This commit is contained in:
@@ -0,0 +1,193 @@
|
||||
package broker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
neturl "net/url"
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab7/internal/domain"
|
||||
"mtusi2026lab7/internal/security"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
const QueueName = "attachment.process.v1"
|
||||
|
||||
type RabbitMQ struct {
|
||||
connection *amqp.Connection
|
||||
channel *amqp.Channel
|
||||
confirms <-chan amqp.Confirmation
|
||||
publishMu sync.Mutex
|
||||
}
|
||||
|
||||
func Open(url string, prefetch int) (*RabbitMQ, error) {
|
||||
if url == "" {
|
||||
return nil, fmt.Errorf("broker URL is required")
|
||||
}
|
||||
parsedURL, err := neturl.Parse(url)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse broker URL: %w", err)
|
||||
}
|
||||
connectionConfig := amqp.Config{Heartbeat: 10 * time.Second, Locale: "en_US"}
|
||||
if parsedURL.Scheme == "amqps" {
|
||||
serverName := os.Getenv("BROKER_TLS_SERVER_NAME")
|
||||
if serverName == "" {
|
||||
serverName = "dependency-gateway"
|
||||
}
|
||||
connectionConfig.TLSClientConfig, err = security.ClientMTLSConfig(
|
||||
os.Getenv("CLIENT_TLS_CA_FILE"),
|
||||
os.Getenv("CLIENT_TLS_CERT_FILE"),
|
||||
os.Getenv("CLIENT_TLS_KEY_FILE"),
|
||||
serverName,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("configure broker mTLS: %w", err)
|
||||
}
|
||||
}
|
||||
connection, err := amqp.DialConfig(url, connectionConfig)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("connect RabbitMQ: %w", err)
|
||||
}
|
||||
channel, err := connection.Channel()
|
||||
if err != nil {
|
||||
_ = connection.Close()
|
||||
return nil, fmt.Errorf("open RabbitMQ channel: %w", err)
|
||||
}
|
||||
if _, err = channel.QueueDeclare(QueueName, true, false, false, false, nil); err != nil {
|
||||
_ = channel.Close()
|
||||
_ = connection.Close()
|
||||
return nil, fmt.Errorf("declare RabbitMQ queue: %w", err)
|
||||
}
|
||||
if prefetch > 0 {
|
||||
if err = channel.Qos(prefetch, 0, false); err != nil {
|
||||
_ = channel.Close()
|
||||
_ = connection.Close()
|
||||
return nil, fmt.Errorf("set RabbitMQ prefetch: %w", err)
|
||||
}
|
||||
}
|
||||
client := &RabbitMQ{connection: connection, channel: channel}
|
||||
if err = channel.Confirm(false); err != nil {
|
||||
client.Close()
|
||||
return nil, fmt.Errorf("enable RabbitMQ publisher confirms: %w", err)
|
||||
}
|
||||
client.confirms = channel.NotifyPublish(make(chan amqp.Confirmation, 1))
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func (client *RabbitMQ) Publish(ctx context.Context, job domain.AttachmentJob) (err error) {
|
||||
parentCarrier := propagation.MapCarrier{}
|
||||
if job.TraceParent != "" {
|
||||
parentCarrier.Set("traceparent", job.TraceParent)
|
||||
}
|
||||
if job.TraceState != "" {
|
||||
parentCarrier.Set("tracestate", job.TraceState)
|
||||
}
|
||||
ctx = otel.GetTextMapPropagator().Extract(ctx, parentCarrier)
|
||||
ctx, span := otel.Tracer("mtusi2026lab7/broker").Start(
|
||||
ctx,
|
||||
QueueName+" publish",
|
||||
trace.WithSpanKind(trace.SpanKindProducer),
|
||||
trace.WithAttributes(
|
||||
attribute.String("messaging.system", "rabbitmq"),
|
||||
attribute.String("messaging.destination.name", QueueName),
|
||||
attribute.String("messaging.operation.name", "publish"),
|
||||
attribute.Int("job.attempt", job.Attempt),
|
||||
),
|
||||
)
|
||||
defer func() {
|
||||
if err != nil {
|
||||
span.SetStatus(codes.Error, "broker publish failed")
|
||||
} else {
|
||||
span.SetStatus(codes.Ok, "")
|
||||
}
|
||||
span.End()
|
||||
}()
|
||||
|
||||
body, err := json.Marshal(job.Message())
|
||||
if err != nil {
|
||||
return fmt.Errorf("encode attachment job: %w", err)
|
||||
}
|
||||
traceCarrier := propagation.MapCarrier{}
|
||||
otel.GetTextMapPropagator().Inject(ctx, traceCarrier)
|
||||
headers := amqp.Table{}
|
||||
for _, key := range traceCarrier.Keys() {
|
||||
headers[key] = traceCarrier.Get(key)
|
||||
}
|
||||
|
||||
client.publishMu.Lock()
|
||||
defer client.publishMu.Unlock()
|
||||
if err = client.channel.PublishWithContext(ctx, "", QueueName, false, false, amqp.Publishing{
|
||||
DeliveryMode: amqp.Persistent,
|
||||
ContentType: "application/json",
|
||||
Type: domain.AttachmentJobType,
|
||||
MessageId: job.JobID,
|
||||
Timestamp: time.Now().UTC(),
|
||||
Headers: headers,
|
||||
Body: body,
|
||||
}); err != nil {
|
||||
return fmt.Errorf("publish attachment job: %w", err)
|
||||
}
|
||||
select {
|
||||
case confirmation, ok := <-client.confirms:
|
||||
if !ok {
|
||||
return fmt.Errorf("publisher confirm channel closed")
|
||||
}
|
||||
if !confirmation.Ack {
|
||||
return fmt.Errorf("broker rejected attachment job")
|
||||
}
|
||||
return nil
|
||||
case <-ctx.Done():
|
||||
return fmt.Errorf("wait for publisher confirm: %w", ctx.Err())
|
||||
}
|
||||
}
|
||||
|
||||
func ContextFromDelivery(ctx context.Context, delivery amqp.Delivery) context.Context {
|
||||
carrier := propagation.MapCarrier{}
|
||||
for key, value := range delivery.Headers {
|
||||
if text, ok := value.(string); ok {
|
||||
carrier.Set(key, text)
|
||||
}
|
||||
}
|
||||
return otel.GetTextMapPropagator().Extract(ctx, carrier)
|
||||
}
|
||||
|
||||
func (client *RabbitMQ) Consume(consumerName string) (<-chan amqp.Delivery, error) {
|
||||
deliveries, err := client.channel.Consume(QueueName, consumerName, false, false, false, false, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("consume attachment jobs: %w", err)
|
||||
}
|
||||
return deliveries, nil
|
||||
}
|
||||
|
||||
func Decode(delivery amqp.Delivery) (domain.AttachmentJobMessage, error) {
|
||||
var message domain.AttachmentJobMessage
|
||||
if err := json.Unmarshal(delivery.Body, &message); err != nil {
|
||||
return message, fmt.Errorf("decode attachment job: %w", err)
|
||||
}
|
||||
if message.SchemaVersion != 1 || message.Type != domain.AttachmentJobType || message.JobID == "" || message.AttachmentID == "" || message.PipelineVersion < 1 || message.Attempt < 1 {
|
||||
return message, fmt.Errorf("attachment job has invalid required fields")
|
||||
}
|
||||
return message, nil
|
||||
}
|
||||
|
||||
func (client *RabbitMQ) Close() error {
|
||||
if client == nil {
|
||||
return nil
|
||||
}
|
||||
if client.channel != nil {
|
||||
_ = client.channel.Close()
|
||||
}
|
||||
if client.connection != nil {
|
||||
return client.connection.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Vendored
+110
@@ -0,0 +1,110 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log"
|
||||
|
||||
"mtusi2026lab7/internal/adapter/redis"
|
||||
"mtusi2026lab7/internal/application"
|
||||
"mtusi2026lab7/internal/domain"
|
||||
)
|
||||
|
||||
// CachedRepository декорирует основной Repository. Все операции, кроме чтения
|
||||
// и создания чата, автоматически делегируются встроенному Repository.
|
||||
type CachedRepository struct {
|
||||
application.Repository
|
||||
chatCache redis.ChatCache
|
||||
logger *log.Logger
|
||||
}
|
||||
|
||||
func NewCachedRepository(
|
||||
repository application.Repository,
|
||||
chatCache redis.ChatCache,
|
||||
logger *log.Logger,
|
||||
) *CachedRepository {
|
||||
if logger == nil {
|
||||
logger = log.Default()
|
||||
}
|
||||
|
||||
return &CachedRepository{
|
||||
Repository: repository,
|
||||
chatCache: chatCache,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *CachedRepository) CreateQueuedAttachment(
|
||||
ctx context.Context,
|
||||
attachment domain.Attachment,
|
||||
job domain.AttachmentJob,
|
||||
) (domain.Attachment, error) {
|
||||
queueRepository, ok := r.Repository.(application.AttachmentQueueRepository)
|
||||
if !ok {
|
||||
return domain.Attachment{}, errors.New("attachment queue repository is not configured")
|
||||
}
|
||||
return queueRepository.CreateQueuedAttachment(ctx, attachment, job)
|
||||
}
|
||||
func (r *CachedRepository) CreateChat(
|
||||
ctx context.Context,
|
||||
title string,
|
||||
memberIDs []string,
|
||||
) (domain.Chat, error) {
|
||||
chat, err := r.Repository.CreateChat(ctx, title, memberIDs)
|
||||
if err != nil {
|
||||
return domain.Chat{}, err
|
||||
}
|
||||
|
||||
// Запись в PostgreSQL уже подтверждена. Ошибка необязательного кэша не
|
||||
// должна превращать успешную бизнес-операцию в 503.
|
||||
if err = r.chatCache.Set(ctx, chat); err != nil {
|
||||
r.logger.Printf("[WARN] Redis chat cache write failed: %v", err)
|
||||
}
|
||||
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func (r *CachedRepository) GetChatByID(
|
||||
ctx context.Context,
|
||||
chatID string,
|
||||
callerID string,
|
||||
) (domain.Chat, error) {
|
||||
chat, err := r.chatCache.Get(ctx, chatID)
|
||||
if err == nil {
|
||||
if !containsMember(chat.MemberIDs, callerID) {
|
||||
return domain.Chat{}, domain.ErrNotFound
|
||||
}
|
||||
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
shouldFillCache := errors.Is(err, redis.ErrMiss)
|
||||
if !shouldFillCache {
|
||||
r.logger.Printf("[WARN] Redis chat cache read failed: %v", err)
|
||||
}
|
||||
|
||||
chat, err = r.Repository.GetChatByID(ctx, chatID, callerID)
|
||||
if err != nil {
|
||||
return domain.Chat{}, err
|
||||
}
|
||||
|
||||
if shouldFillCache {
|
||||
if err = r.chatCache.Set(ctx, chat); err != nil {
|
||||
r.logger.Printf("[WARN] Redis chat cache fill failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func containsMember(memberIDs []string, callerID string) bool {
|
||||
for _, memberID := range memberIDs {
|
||||
if memberID == callerID {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
var _ application.Repository = (*CachedRepository)(nil)
|
||||
+183
@@ -0,0 +1,183 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
"testing"
|
||||
|
||||
"mtusi2026lab7/internal/adapter/memory"
|
||||
"mtusi2026lab7/internal/adapter/redis"
|
||||
"mtusi2026lab7/internal/application"
|
||||
"mtusi2026lab7/internal/domain"
|
||||
)
|
||||
|
||||
type fakeChatCache struct {
|
||||
chats map[string]domain.Chat
|
||||
getErr error
|
||||
setErr error
|
||||
sets int
|
||||
}
|
||||
|
||||
func (c *fakeChatCache) Get(
|
||||
_ context.Context,
|
||||
chatID string,
|
||||
) (domain.Chat, error) {
|
||||
if c.getErr != nil {
|
||||
return domain.Chat{}, c.getErr
|
||||
}
|
||||
|
||||
chat, exists := c.chats[chatID]
|
||||
if !exists {
|
||||
return domain.Chat{}, redis.ErrMiss
|
||||
}
|
||||
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func (c *fakeChatCache) Set(
|
||||
_ context.Context,
|
||||
chat domain.Chat,
|
||||
) error {
|
||||
c.sets++
|
||||
if c.setErr != nil {
|
||||
return c.setErr
|
||||
}
|
||||
c.chats[chat.ID] = chat
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
type countingRepository struct {
|
||||
application.Repository
|
||||
getChatCalls int
|
||||
}
|
||||
|
||||
func (r *countingRepository) GetChatByID(
|
||||
ctx context.Context,
|
||||
chatID string,
|
||||
callerID string,
|
||||
) (domain.Chat, error) {
|
||||
r.getChatCalls++
|
||||
return r.Repository.GetChatByID(ctx, chatID, callerID)
|
||||
}
|
||||
|
||||
func cachedRepositoryFixture(
|
||||
t *testing.T,
|
||||
) (*countingRepository, *fakeChatCache, domain.User, domain.User, domain.Chat) {
|
||||
t.Helper()
|
||||
|
||||
legacy := memory.NewMemoryStore()
|
||||
member, err := legacy.CreateUser("cache_member", "Участник")
|
||||
if err != nil {
|
||||
t.Fatalf("create member: %v", err)
|
||||
}
|
||||
outsider, err := legacy.CreateUser("cache_outsider", "Посторонний")
|
||||
if err != nil {
|
||||
t.Fatalf("create outsider: %v", err)
|
||||
}
|
||||
chat, err := legacy.CreateChat("Кешируемый чат", []string{member.ID})
|
||||
if err != nil {
|
||||
t.Fatalf("create chat: %v", err)
|
||||
}
|
||||
|
||||
repository := &countingRepository{
|
||||
Repository: memory.NewMemoryRepository(legacy),
|
||||
}
|
||||
chatCache := &fakeChatCache{
|
||||
chats: make(map[string]domain.Chat),
|
||||
}
|
||||
|
||||
return repository, chatCache, member, outsider, chat
|
||||
}
|
||||
|
||||
func TestCachedRepositoryMissThenHit(t *testing.T) {
|
||||
repository, chatCache, member, _, expected := cachedRepositoryFixture(t)
|
||||
cached := NewCachedRepository(
|
||||
repository,
|
||||
chatCache,
|
||||
log.New(io.Discard, "", 0),
|
||||
)
|
||||
|
||||
first, err := cached.GetChatByID(context.Background(), expected.ID, member.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("first read: %v", err)
|
||||
}
|
||||
second, err := cached.GetChatByID(context.Background(), expected.ID, member.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("second read: %v", err)
|
||||
}
|
||||
|
||||
if repository.getChatCalls != 1 {
|
||||
t.Fatalf("expected one source read, got %d", repository.getChatCalls)
|
||||
}
|
||||
if chatCache.sets != 1 {
|
||||
t.Fatalf("expected one cache fill, got %d", chatCache.sets)
|
||||
}
|
||||
if first.ID != expected.ID || second.ID != expected.ID {
|
||||
t.Fatal("cache changed chat identity")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCachedRepositoryFallsBackWhenCacheUnavailable(t *testing.T) {
|
||||
repository, chatCache, member, _, expected := cachedRepositoryFixture(t)
|
||||
chatCache.getErr = errors.New("redis unavailable")
|
||||
chatCache.setErr = errors.New("redis unavailable")
|
||||
cached := NewCachedRepository(
|
||||
repository,
|
||||
chatCache,
|
||||
log.New(io.Discard, "", 0),
|
||||
)
|
||||
|
||||
chat, err := cached.GetChatByID(context.Background(), expected.ID, member.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("fallback read: %v", err)
|
||||
}
|
||||
if chat.ID != expected.ID || repository.getChatCalls != 1 {
|
||||
t.Fatal("source repository was not used after cache failure")
|
||||
}
|
||||
if chatCache.sets != 0 {
|
||||
t.Fatal("failed cache read must not trigger another cache operation")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCachedRepositoryChecksMembershipOnHit(t *testing.T) {
|
||||
repository, chatCache, _, outsider, expected := cachedRepositoryFixture(t)
|
||||
chatCache.chats[expected.ID] = expected
|
||||
cached := NewCachedRepository(
|
||||
repository,
|
||||
chatCache,
|
||||
log.New(io.Discard, "", 0),
|
||||
)
|
||||
|
||||
_, err := cached.GetChatByID(context.Background(), expected.ID, outsider.ID)
|
||||
if !errors.Is(err, domain.ErrNotFound) {
|
||||
t.Fatalf("expected ErrNotFound for outsider, got %v", err)
|
||||
}
|
||||
if repository.getChatCalls != 0 {
|
||||
t.Fatal("cache hit unexpectedly queried source repository")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCachedRepositoryIgnoresWriteFailure(t *testing.T) {
|
||||
repository, chatCache, member, _, _ := cachedRepositoryFixture(t)
|
||||
chatCache.setErr = errors.New("redis unavailable")
|
||||
cached := NewCachedRepository(
|
||||
repository,
|
||||
chatCache,
|
||||
log.New(io.Discard, "", 0),
|
||||
)
|
||||
|
||||
chat, err := cached.CreateChat(
|
||||
context.Background(),
|
||||
"Новый чат",
|
||||
[]string{member.ID},
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("create chat with unavailable cache: %v", err)
|
||||
}
|
||||
if chat.ID == "" || chatCache.sets != 1 {
|
||||
t.Fatal("chat was not created before best-effort cache write")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package health
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type Checker interface {
|
||||
Ping(ctx context.Context) error
|
||||
}
|
||||
|
||||
type MultiChecker struct {
|
||||
checkers []Checker
|
||||
}
|
||||
|
||||
func NewMultiChecker(checkers ...Checker) *MultiChecker {
|
||||
filtered := make([]Checker, 0, len(checkers))
|
||||
for _, checker := range checkers {
|
||||
if checker != nil {
|
||||
filtered = append(filtered, checker)
|
||||
}
|
||||
}
|
||||
return &MultiChecker{checkers: filtered}
|
||||
}
|
||||
|
||||
func (checker *MultiChecker) Ping(ctx context.Context) error {
|
||||
for index, dependency := range checker.checkers {
|
||||
if err := dependency.Ping(ctx); err != nil {
|
||||
return fmt.Errorf("dependency %d: %w", index, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package memory
|
||||
|
||||
import "mtusi2026lab7/internal/domain"
|
||||
|
||||
var (
|
||||
ErrNotFound = domain.ErrNotFound
|
||||
ErrConflict = domain.ErrConflict
|
||||
)
|
||||
@@ -0,0 +1,401 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab7/internal/application"
|
||||
"mtusi2026lab7/internal/domain"
|
||||
)
|
||||
|
||||
type memorySession struct {
|
||||
userID string
|
||||
expiresAt time.Time
|
||||
}
|
||||
|
||||
type memoryIdempotencyScope struct {
|
||||
actorID string
|
||||
method string
|
||||
canonicalPath string
|
||||
key string
|
||||
}
|
||||
|
||||
type memoryIdempotencyResult struct {
|
||||
requestHash [32]byte
|
||||
message domain.Message
|
||||
expiresAt time.Time
|
||||
}
|
||||
|
||||
type MemoryRepository struct {
|
||||
legacy *MemoryStore
|
||||
|
||||
mu sync.RWMutex
|
||||
passwordByUserID map[string]string
|
||||
userIDByUsername map[string]string
|
||||
sessionsByHashKey map[[32]byte]memorySession
|
||||
idempotencyByScope map[memoryIdempotencyScope]memoryIdempotencyResult
|
||||
}
|
||||
|
||||
func NewMemoryRepository(legacy *MemoryStore) *MemoryRepository {
|
||||
return &MemoryRepository{
|
||||
legacy: legacy,
|
||||
passwordByUserID: make(map[string]string),
|
||||
userIDByUsername: make(map[string]string),
|
||||
sessionsByHashKey: make(map[[32]byte]memorySession),
|
||||
idempotencyByScope: make(map[memoryIdempotencyScope]memoryIdempotencyResult),
|
||||
}
|
||||
}
|
||||
|
||||
func (r *MemoryRepository) CreateUser(
|
||||
ctx context.Context,
|
||||
username string,
|
||||
displayName string,
|
||||
passwordHash string,
|
||||
) (domain.User, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
|
||||
user, err := r.legacy.CreateUser(username, displayName)
|
||||
if err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
|
||||
r.mu.Lock()
|
||||
r.passwordByUserID[user.ID] = passwordHash
|
||||
r.userIDByUsername[user.Username] = user.ID
|
||||
r.mu.Unlock()
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (r *MemoryRepository) GetUserByID(
|
||||
ctx context.Context,
|
||||
userID string,
|
||||
) (domain.User, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
|
||||
return r.legacy.GetUserByID(userID)
|
||||
}
|
||||
|
||||
func (r *MemoryRepository) GetUserByUsername(
|
||||
ctx context.Context,
|
||||
username string,
|
||||
) (domain.User, string, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return domain.User{}, "", err
|
||||
}
|
||||
|
||||
r.mu.RLock()
|
||||
userID, exists := r.userIDByUsername[username]
|
||||
passwordHash := r.passwordByUserID[userID]
|
||||
r.mu.RUnlock()
|
||||
|
||||
if !exists {
|
||||
return domain.User{}, "", ErrNotFound
|
||||
}
|
||||
|
||||
user, err := r.legacy.GetUserByID(userID)
|
||||
if err != nil {
|
||||
return domain.User{}, "", err
|
||||
}
|
||||
|
||||
return user, passwordHash, nil
|
||||
}
|
||||
|
||||
func (r *MemoryRepository) UpdatePasswordHash(
|
||||
ctx context.Context,
|
||||
userID string,
|
||||
previousHash string,
|
||||
newHash string,
|
||||
) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if current, exists := r.passwordByUserID[userID]; exists && current == previousHash {
|
||||
r.passwordByUserID[userID] = newHash
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *MemoryRepository) CreateChat(
|
||||
ctx context.Context,
|
||||
title string,
|
||||
memberIDs []string,
|
||||
) (domain.Chat, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return domain.Chat{}, err
|
||||
}
|
||||
|
||||
return r.legacy.CreateChat(title, memberIDs)
|
||||
}
|
||||
|
||||
func (r *MemoryRepository) GetChatByID(
|
||||
ctx context.Context,
|
||||
chatID string,
|
||||
callerID string,
|
||||
) (domain.Chat, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return domain.Chat{}, err
|
||||
}
|
||||
|
||||
return r.legacy.GetChatByID(chatID, callerID)
|
||||
}
|
||||
|
||||
func (r *MemoryRepository) GetChatsForUser(
|
||||
ctx context.Context,
|
||||
userID string,
|
||||
limit int,
|
||||
cursor *domain.ChatCursor,
|
||||
) ([]domain.Chat, bool, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
|
||||
return r.legacy.GetChatsForUser(userID, limit, cursor)
|
||||
}
|
||||
|
||||
func (r *MemoryRepository) CreateMessageIdempotently(
|
||||
ctx context.Context,
|
||||
write application.IdempotentMessageWrite,
|
||||
) (domain.Message, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return domain.Message{}, err
|
||||
}
|
||||
|
||||
scope := memoryIdempotencyScope{
|
||||
actorID: write.ActorID,
|
||||
method: write.Method,
|
||||
canonicalPath: write.CanonicalPath,
|
||||
key: write.Key,
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
|
||||
if _, err := r.legacy.GetChatByID(write.ChatID, write.ActorID); err != nil {
|
||||
return domain.Message{}, err
|
||||
}
|
||||
for _, attachmentID := range write.AttachmentIDs {
|
||||
attachment, err := r.legacy.GetAttachmentByID(attachmentID)
|
||||
if err != nil || attachment.ChatID != write.ChatID {
|
||||
return domain.Message{}, ErrNotFound
|
||||
}
|
||||
if attachment.Status != domain.AttachmentStatusReady {
|
||||
return domain.Message{}, application.ErrAttachmentNotReady
|
||||
}
|
||||
}
|
||||
|
||||
if stored, exists := r.idempotencyByScope[scope]; exists {
|
||||
if stored.expiresAt.After(now) {
|
||||
if stored.requestHash != write.RequestHash {
|
||||
return domain.Message{}, application.ErrIdempotencyConflict
|
||||
}
|
||||
return stored.message, nil
|
||||
}
|
||||
delete(r.idempotencyByScope, scope)
|
||||
}
|
||||
|
||||
message, err := r.legacy.CreateMessage(
|
||||
write.ChatID,
|
||||
write.ActorID,
|
||||
write.Text,
|
||||
write.AttachmentIDs,
|
||||
)
|
||||
if err != nil {
|
||||
return domain.Message{}, err
|
||||
}
|
||||
r.idempotencyByScope[scope] = memoryIdempotencyResult{
|
||||
requestHash: write.RequestHash,
|
||||
message: message,
|
||||
expiresAt: now.Add(write.TTL),
|
||||
}
|
||||
return message, nil
|
||||
}
|
||||
|
||||
func (r *MemoryRepository) GetMessages(
|
||||
ctx context.Context,
|
||||
chatID string,
|
||||
callerID string,
|
||||
limit int,
|
||||
cursor *domain.MessageCursor,
|
||||
) ([]domain.Message, bool, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
|
||||
return r.legacy.GetMessages(
|
||||
chatID,
|
||||
callerID,
|
||||
limit,
|
||||
cursor,
|
||||
)
|
||||
}
|
||||
|
||||
func (r *MemoryRepository) CreateSession(
|
||||
ctx context.Context,
|
||||
tokenHash []byte,
|
||||
userID string,
|
||||
expiresAt time.Time,
|
||||
) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
key, err := memoryTokenHashKey(tokenHash)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
r.mu.Lock()
|
||||
r.sessionsByHashKey[key] = memorySession{
|
||||
userID: userID,
|
||||
expiresAt: expiresAt,
|
||||
}
|
||||
r.mu.Unlock()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *MemoryRepository) GetUserBySession(
|
||||
ctx context.Context,
|
||||
tokenHash []byte,
|
||||
) (domain.User, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
|
||||
key, err := memoryTokenHashKey(tokenHash)
|
||||
if err != nil {
|
||||
return domain.User{}, ErrNotFound
|
||||
}
|
||||
|
||||
r.mu.RLock()
|
||||
session, exists := r.sessionsByHashKey[key]
|
||||
r.mu.RUnlock()
|
||||
|
||||
if !exists || !session.expiresAt.After(time.Now().UTC()) {
|
||||
return domain.User{}, ErrNotFound
|
||||
}
|
||||
|
||||
return r.legacy.GetUserByID(session.userID)
|
||||
}
|
||||
|
||||
func (r *MemoryRepository) DeleteSession(
|
||||
ctx context.Context,
|
||||
tokenHash []byte,
|
||||
) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
key, err := memoryTokenHashKey(tokenHash)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
r.mu.Lock()
|
||||
delete(r.sessionsByHashKey, key)
|
||||
r.mu.Unlock()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *MemoryRepository) CreateQueuedAttachment(
|
||||
ctx context.Context,
|
||||
attachment domain.Attachment,
|
||||
_ domain.AttachmentJob,
|
||||
) (domain.Attachment, error) {
|
||||
return r.CreateAttachment(ctx, attachment)
|
||||
}
|
||||
func (r *MemoryRepository) CreateAttachment(
|
||||
ctx context.Context,
|
||||
attachment domain.Attachment,
|
||||
) (domain.Attachment, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
if err := r.legacy.PutAttachment(attachment); err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
return attachment, nil
|
||||
}
|
||||
|
||||
func (r *MemoryRepository) MarkAttachmentReady(
|
||||
ctx context.Context,
|
||||
attachmentID string,
|
||||
updatedAt time.Time,
|
||||
) (domain.Attachment, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
return r.legacy.UpdateAttachmentStatus(
|
||||
attachmentID,
|
||||
domain.AttachmentStatusReady,
|
||||
nil,
|
||||
updatedAt,
|
||||
)
|
||||
}
|
||||
|
||||
func (r *MemoryRepository) MarkAttachmentFailed(
|
||||
ctx context.Context,
|
||||
attachmentID string,
|
||||
errorCode string,
|
||||
updatedAt time.Time,
|
||||
) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := r.legacy.UpdateAttachmentStatus(
|
||||
attachmentID,
|
||||
domain.AttachmentStatusFailed,
|
||||
&errorCode,
|
||||
updatedAt,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *MemoryRepository) GetAttachment(
|
||||
ctx context.Context,
|
||||
attachmentID string,
|
||||
callerID string,
|
||||
) (domain.Attachment, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
attachment, err := r.legacy.GetAttachmentByID(attachmentID)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
if _, err = r.legacy.GetChatByID(attachment.ChatID, callerID); err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
if attachment.Variants == nil {
|
||||
attachment.Variants = make([]domain.AttachmentVariant, 0)
|
||||
}
|
||||
return attachment, nil
|
||||
}
|
||||
|
||||
func memoryTokenHashKey(tokenHash []byte) ([32]byte, error) {
|
||||
var key [32]byte
|
||||
|
||||
if len(tokenHash) != len(key) {
|
||||
return key, fmt.Errorf(
|
||||
"session token hash must contain %d bytes",
|
||||
len(key),
|
||||
)
|
||||
}
|
||||
|
||||
copy(key[:], tokenHash)
|
||||
|
||||
return key, nil
|
||||
}
|
||||
|
||||
var _ application.Repository = (*MemoryRepository)(nil)
|
||||
@@ -0,0 +1,371 @@
|
||||
package memory
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab7/internal/domain"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type MemoryStore struct {
|
||||
mu sync.RWMutex
|
||||
|
||||
usersByID map[string]domain.User //key = user UUID
|
||||
usersByUsername map[string]string //key = username для быстрой проверки уникальности
|
||||
|
||||
chatsByID map[string]domain.Chat //key = chat UUID
|
||||
|
||||
messagesByChatID map[string][]domain.Message // key = chat UUID, value = слайс сообщений
|
||||
|
||||
attachmentsByID map[string]domain.Attachment
|
||||
}
|
||||
|
||||
func NewMemoryStore() *MemoryStore {
|
||||
return &MemoryStore{
|
||||
usersByID: make(map[string]domain.User),
|
||||
usersByUsername: make(map[string]string),
|
||||
chatsByID: make(map[string]domain.Chat),
|
||||
messagesByChatID: make(map[string][]domain.Message),
|
||||
attachmentsByID: make(map[string]domain.Attachment),
|
||||
}
|
||||
}
|
||||
|
||||
// ---пользователи---
|
||||
|
||||
func (s *MemoryStore) CreateUser(username, displayName string) (domain.User, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
// дубликат username -> 409 Conflict
|
||||
if _, exists := s.usersByUsername[username]; exists {
|
||||
return domain.User{}, ErrConflict
|
||||
}
|
||||
|
||||
user := domain.User{
|
||||
ID: uuid.NewString(),
|
||||
Username: username,
|
||||
DisplayName: displayName,
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
|
||||
s.usersByID[user.ID] = user
|
||||
s.usersByUsername[user.Username] = user.ID
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *MemoryStore) GetUserByID(id string) (domain.User, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
user, exists := s.usersByID[id]
|
||||
if !exists {
|
||||
return domain.User{}, ErrNotFound
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// ---чаты---
|
||||
|
||||
func (s *MemoryStore) CreateChat(title string, memberIDs []string) (domain.Chat, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
//все участники рил существуют
|
||||
for _, memberID := range memberIDs {
|
||||
if _, exists := s.usersByID[memberID]; !exists {
|
||||
return domain.Chat{}, fmt.Errorf(
|
||||
"%w: member %s",
|
||||
ErrNotFound,
|
||||
memberID,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
chat := domain.Chat{
|
||||
ID: uuid.NewString(),
|
||||
Title: title,
|
||||
MemberIDs: append([]string(nil), memberIDs...), //копирую слайс для изоляции
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
|
||||
s.chatsByID[chat.ID] = chat
|
||||
s.messagesByChatID[chat.ID] = make([]domain.Message, 0)
|
||||
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func (s *MemoryStore) GetChatByID(chatID, callerID string) (domain.Chat, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
chat, exists := s.chatsByID[chatID]
|
||||
if !exists {
|
||||
return domain.Chat{}, ErrNotFound
|
||||
}
|
||||
|
||||
// Требование безопасности: посторонний получает 404, а не 403
|
||||
isMember := false
|
||||
for _, m := range chat.MemberIDs {
|
||||
if m == callerID {
|
||||
isMember = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if !isMember {
|
||||
return domain.Chat{}, ErrNotFound
|
||||
}
|
||||
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func (s *MemoryStore) GetChatsForUser(
|
||||
userID string,
|
||||
limit int,
|
||||
cursorData *domain.ChatCursor,
|
||||
) ([]domain.Chat, bool, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
chats := make([]domain.Chat, 0)
|
||||
|
||||
for _, chat := range s.chatsByID {
|
||||
for _, memberID := range chat.MemberIDs {
|
||||
if memberID == userID {
|
||||
chats = append(chats, chat)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sort.Slice(chats, func(i, j int) bool {
|
||||
if chats[i].CreatedAt.Equal(chats[j].CreatedAt) {
|
||||
return chats[i].ID < chats[j].ID
|
||||
}
|
||||
|
||||
return chats[i].CreatedAt.Before(chats[j].CreatedAt)
|
||||
})
|
||||
|
||||
start := 0
|
||||
|
||||
if cursorData != nil {
|
||||
start = sort.Search(len(chats), func(index int) bool {
|
||||
chat := chats[index]
|
||||
|
||||
if chat.CreatedAt.After(cursorData.CreatedAt) {
|
||||
return true
|
||||
}
|
||||
|
||||
return chat.CreatedAt.Equal(cursorData.CreatedAt) &&
|
||||
chat.ID > cursorData.ChatID
|
||||
})
|
||||
}
|
||||
|
||||
if start >= len(chats) {
|
||||
return make([]domain.Chat, 0), false, nil
|
||||
}
|
||||
|
||||
end := start + limit
|
||||
if end > len(chats) {
|
||||
end = len(chats)
|
||||
}
|
||||
|
||||
items := make([]domain.Chat, end-start)
|
||||
copy(items, chats[start:end])
|
||||
return items, end < len(chats), nil
|
||||
}
|
||||
|
||||
// PutAttachment stores metadata for adapter and application tests. Binary
|
||||
// content intentionally does not belong to this in-memory metadata store.
|
||||
func (s *MemoryStore) PutAttachment(attachment domain.Attachment) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if _, exists := s.attachmentsByID[attachment.ID]; exists {
|
||||
return ErrConflict
|
||||
}
|
||||
|
||||
chat, exists := s.chatsByID[attachment.ChatID]
|
||||
if !exists {
|
||||
return ErrNotFound
|
||||
}
|
||||
|
||||
ownerIsMember := false
|
||||
for _, memberID := range chat.MemberIDs {
|
||||
if memberID == attachment.OwnerID {
|
||||
ownerIsMember = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !ownerIsMember {
|
||||
return ErrNotFound
|
||||
}
|
||||
|
||||
s.attachmentsByID[attachment.ID] = attachment
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *MemoryStore) GetAttachmentByID(
|
||||
attachmentID string,
|
||||
) (domain.Attachment, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
attachment, exists := s.attachmentsByID[attachmentID]
|
||||
if !exists {
|
||||
return domain.Attachment{}, ErrNotFound
|
||||
}
|
||||
return attachment, nil
|
||||
}
|
||||
|
||||
func (s *MemoryStore) UpdateAttachmentStatus(
|
||||
attachmentID string,
|
||||
status domain.AttachmentStatus,
|
||||
errorCode *string,
|
||||
updatedAt time.Time,
|
||||
) (domain.Attachment, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
attachment, exists := s.attachmentsByID[attachmentID]
|
||||
if !exists {
|
||||
return domain.Attachment{}, ErrNotFound
|
||||
}
|
||||
if attachment.Status != domain.AttachmentStatusPending {
|
||||
return domain.Attachment{}, ErrConflict
|
||||
}
|
||||
attachment.Status = status
|
||||
attachment.ErrorCode = errorCode
|
||||
attachment.UpdatedAt = updatedAt
|
||||
if attachment.Variants == nil {
|
||||
attachment.Variants = make([]domain.AttachmentVariant, 0)
|
||||
}
|
||||
s.attachmentsByID[attachmentID] = attachment
|
||||
return attachment, nil
|
||||
}
|
||||
|
||||
// ---Сообщения---
|
||||
|
||||
func (s *MemoryStore) CreateMessage(
|
||||
chatID, senderID, text string,
|
||||
attachmentLists ...[]string,
|
||||
) (domain.Message, error) {
|
||||
messageID := uuid.NewString()
|
||||
attachmentIDs := make([]string, 0)
|
||||
if len(attachmentLists) > 0 {
|
||||
attachmentIDs = append(attachmentIDs, attachmentLists[0]...)
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
chat, exists := s.chatsByID[chatID]
|
||||
if !exists {
|
||||
return domain.Message{}, ErrNotFound
|
||||
}
|
||||
|
||||
isMember := false
|
||||
for _, memberID := range chat.MemberIDs {
|
||||
if memberID == senderID {
|
||||
isMember = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !isMember {
|
||||
return domain.Message{}, ErrNotFound
|
||||
}
|
||||
|
||||
createdAt := time.Now().UTC()
|
||||
|
||||
messages := s.messagesByChatID[chatID]
|
||||
if len(messages) > 0 {
|
||||
lastCreatedAt := messages[len(messages)-1].CreatedAt
|
||||
|
||||
// Обеспечиваем строго возрастающее время внутри каждого чата.
|
||||
if !createdAt.After(lastCreatedAt) {
|
||||
createdAt = lastCreatedAt.Add(time.Nanosecond)
|
||||
}
|
||||
}
|
||||
|
||||
message := domain.Message{
|
||||
ID: messageID,
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
AttachmentIDs: attachmentIDs,
|
||||
CreatedAt: createdAt,
|
||||
}
|
||||
|
||||
s.messagesByChatID[chatID] = append(messages, message)
|
||||
|
||||
return message, nil
|
||||
}
|
||||
|
||||
func (s *MemoryStore) GetMessages(
|
||||
chatID, callerID string,
|
||||
limit int,
|
||||
cursorData *domain.MessageCursor,
|
||||
) ([]domain.Message, bool, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
chat, exists := s.chatsByID[chatID]
|
||||
if !exists {
|
||||
return nil, false, ErrNotFound
|
||||
}
|
||||
|
||||
isMember := false
|
||||
for _, memberID := range chat.MemberIDs {
|
||||
if memberID == callerID {
|
||||
isMember = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !isMember {
|
||||
return nil, false, ErrNotFound
|
||||
}
|
||||
|
||||
messages := s.messagesByChatID[chatID]
|
||||
|
||||
start := 0
|
||||
|
||||
if cursorData != nil {
|
||||
// Срез уже упорядочен во время записи, поэтому вместо
|
||||
// полного прохода используем бинарный поиск.
|
||||
start = sort.Search(len(messages), func(index int) bool {
|
||||
message := messages[index]
|
||||
|
||||
if message.CreatedAt.After(cursorData.CreatedAt) {
|
||||
return true
|
||||
}
|
||||
|
||||
return message.CreatedAt.Equal(cursorData.CreatedAt) &&
|
||||
message.ID > cursorData.MessageID
|
||||
})
|
||||
}
|
||||
|
||||
if start >= len(messages) {
|
||||
return make([]domain.Message, 0), false, nil
|
||||
}
|
||||
|
||||
end := len(messages)
|
||||
if limit > 0 && end-start > limit {
|
||||
end = start + limit
|
||||
}
|
||||
|
||||
// копируем только возвращаемую страницу, а не всю историю, изменяя внутренний срез
|
||||
items := make([]domain.Message, end-start)
|
||||
for index, message := range messages[start:end] {
|
||||
message.AttachmentIDs = append(
|
||||
make([]string, 0, len(message.AttachmentIDs)),
|
||||
message.AttachmentIDs...,
|
||||
)
|
||||
items[index] = message
|
||||
}
|
||||
return items, end < len(messages), nil
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
package objectstore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab7/internal/application"
|
||||
|
||||
minio "github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/credentials"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
type MinIOStore struct {
|
||||
client *minio.Client
|
||||
bucket string
|
||||
operationTimeout time.Duration
|
||||
}
|
||||
|
||||
type StoredObject struct {
|
||||
Key string
|
||||
SizeBytes int64
|
||||
LastModified time.Time
|
||||
}
|
||||
|
||||
func NewMinIOStore(
|
||||
endpoint string,
|
||||
region string,
|
||||
bucket string,
|
||||
accessKeyID string,
|
||||
secretAccessKey string,
|
||||
operationTimeout time.Duration,
|
||||
) (*MinIOStore, error) {
|
||||
parsedEndpoint, err := url.Parse(endpoint)
|
||||
if err != nil || parsedEndpoint.Host == "" {
|
||||
return nil, fmt.Errorf("S3 endpoint must be an absolute HTTP(S) URL")
|
||||
}
|
||||
if parsedEndpoint.Scheme != "http" && parsedEndpoint.Scheme != "https" {
|
||||
return nil, fmt.Errorf("S3 endpoint scheme must be http or https")
|
||||
}
|
||||
if parsedEndpoint.Path != "" && parsedEndpoint.Path != "/" {
|
||||
return nil, fmt.Errorf("S3 endpoint must not contain a path")
|
||||
}
|
||||
if parsedEndpoint.RawQuery != "" || parsedEndpoint.Fragment != "" || parsedEndpoint.User != nil {
|
||||
return nil, fmt.Errorf("S3 endpoint must not contain credentials, query or fragment")
|
||||
}
|
||||
if strings.TrimSpace(bucket) == "" || strings.TrimSpace(accessKeyID) == "" ||
|
||||
strings.TrimSpace(secretAccessKey) == "" {
|
||||
return nil, fmt.Errorf("S3 bucket and credentials are required")
|
||||
}
|
||||
if operationTimeout <= 0 {
|
||||
return nil, fmt.Errorf("S3 operation timeout must be positive")
|
||||
}
|
||||
|
||||
client, err := minio.New(parsedEndpoint.Host, &minio.Options{
|
||||
Creds: credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
|
||||
Secure: parsedEndpoint.Scheme == "https",
|
||||
Region: region,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create MinIO client: %w", err)
|
||||
}
|
||||
return &MinIOStore{client: client, bucket: bucket, operationTimeout: operationTimeout}, nil
|
||||
}
|
||||
|
||||
func (store *MinIOStore) Put(ctx context.Context, object application.ObjectPut) error {
|
||||
ctx, span := startObjectSpan(ctx, "put")
|
||||
defer span.End()
|
||||
operationContext, cancel := context.WithTimeout(ctx, store.operationTimeout)
|
||||
defer cancel()
|
||||
upload, err := store.client.PutObject(
|
||||
operationContext,
|
||||
store.bucket,
|
||||
object.Key,
|
||||
object.Body,
|
||||
object.SizeBytes,
|
||||
minio.PutObjectOptions{ContentType: object.ContentType},
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("put MinIO object: %w", err)
|
||||
}
|
||||
if upload.Size != object.SizeBytes {
|
||||
return fmt.Errorf("put MinIO object: stored %d bytes, want %d", upload.Size, object.SizeBytes)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *MinIOStore) Get(
|
||||
ctx context.Context,
|
||||
key string,
|
||||
) (application.ObjectContent, error) {
|
||||
ctx, span := startObjectSpan(ctx, "get")
|
||||
defer span.End()
|
||||
operationContext, cancel := context.WithTimeout(ctx, store.operationTimeout)
|
||||
stat, err := store.client.StatObject(
|
||||
operationContext,
|
||||
store.bucket,
|
||||
key,
|
||||
minio.StatObjectOptions{},
|
||||
)
|
||||
if err != nil {
|
||||
cancel()
|
||||
return application.ObjectContent{}, fmt.Errorf("stat MinIO object: %w", err)
|
||||
}
|
||||
object, err := store.client.GetObject(
|
||||
operationContext,
|
||||
store.bucket,
|
||||
key,
|
||||
minio.GetObjectOptions{},
|
||||
)
|
||||
if err != nil {
|
||||
cancel()
|
||||
return application.ObjectContent{}, fmt.Errorf("get MinIO object: %w", err)
|
||||
}
|
||||
firstByte := make([]byte, 1)
|
||||
readCount, readError := object.Read(firstByte)
|
||||
if readError != nil && readCount == 0 {
|
||||
_ = object.Close()
|
||||
cancel()
|
||||
return application.ObjectContent{}, fmt.Errorf("read MinIO object: %w", readError)
|
||||
}
|
||||
if readCount != 1 {
|
||||
_ = object.Close()
|
||||
cancel()
|
||||
return application.ObjectContent{}, fmt.Errorf("read MinIO object: expected non-empty object")
|
||||
}
|
||||
return application.ObjectContent{
|
||||
Body: &cancelingReadCloser{
|
||||
Reader: io.MultiReader(bytes.NewReader(firstByte), object),
|
||||
Closer: object,
|
||||
cancel: cancel,
|
||||
},
|
||||
SizeBytes: stat.Size,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (store *MinIOStore) List(
|
||||
ctx context.Context,
|
||||
prefix string,
|
||||
) ([]StoredObject, error) {
|
||||
ctx, span := startObjectSpan(ctx, "list")
|
||||
defer span.End()
|
||||
operationContext, cancel := context.WithTimeout(ctx, store.operationTimeout)
|
||||
defer cancel()
|
||||
|
||||
objects := make([]StoredObject, 0)
|
||||
for object := range store.client.ListObjects(
|
||||
operationContext,
|
||||
store.bucket,
|
||||
minio.ListObjectsOptions{Prefix: prefix, Recursive: true},
|
||||
) {
|
||||
if object.Err != nil {
|
||||
return nil, fmt.Errorf("list MinIO objects: %w", object.Err)
|
||||
}
|
||||
objects = append(objects, StoredObject{
|
||||
Key: object.Key,
|
||||
SizeBytes: object.Size,
|
||||
LastModified: object.LastModified.UTC(),
|
||||
})
|
||||
}
|
||||
return objects, nil
|
||||
}
|
||||
|
||||
func (store *MinIOStore) Delete(ctx context.Context, key string) error {
|
||||
ctx, span := startObjectSpan(ctx, "delete")
|
||||
defer span.End()
|
||||
operationContext, cancel := context.WithTimeout(ctx, store.operationTimeout)
|
||||
defer cancel()
|
||||
if err := store.client.RemoveObject(
|
||||
operationContext,
|
||||
store.bucket,
|
||||
key,
|
||||
minio.RemoveObjectOptions{},
|
||||
); err != nil {
|
||||
return fmt.Errorf("delete MinIO object: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *MinIOStore) Ping(ctx context.Context) error {
|
||||
ctx, span := startObjectSpan(ctx, "bucket_exists")
|
||||
defer span.End()
|
||||
operationContext, cancel := context.WithTimeout(ctx, store.operationTimeout)
|
||||
defer cancel()
|
||||
exists, err := store.client.BucketExists(operationContext, store.bucket)
|
||||
if err != nil {
|
||||
return fmt.Errorf("check MinIO bucket: %w", err)
|
||||
}
|
||||
if !exists {
|
||||
return fmt.Errorf("MinIO bucket %q does not exist", store.bucket)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func startObjectSpan(ctx context.Context, operation string) (context.Context, trace.Span) {
|
||||
return otel.Tracer("mtusi2026lab7/s3").Start(
|
||||
ctx,
|
||||
"s3."+operation,
|
||||
trace.WithSpanKind(trace.SpanKindClient),
|
||||
trace.WithAttributes(
|
||||
attribute.String("storage.system", "s3"),
|
||||
attribute.String("storage.operation", operation),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
type cancelingReadCloser struct {
|
||||
io.Reader
|
||||
io.Closer
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func (reader *cancelingReadCloser) Close() error {
|
||||
err := reader.Closer.Close()
|
||||
reader.cancel()
|
||||
return err
|
||||
}
|
||||
|
||||
var _ application.ObjectStore = (*MinIOStore)(nil)
|
||||
@@ -0,0 +1,37 @@
|
||||
package objectstore
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestNewMinIOStoreValidatesConfiguration(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
endpoint string
|
||||
bucket string
|
||||
accessKey string
|
||||
secretKey string
|
||||
timeout time.Duration
|
||||
wantError bool
|
||||
}{
|
||||
{name: "valid HTTP", endpoint: "http://minio:9000", bucket: "attachments", accessKey: "api", secretKey: "secret", timeout: time.Second},
|
||||
{name: "valid HTTPS", endpoint: "https://s3.example.test", bucket: "attachments", accessKey: "api", secretKey: "secret", timeout: time.Second},
|
||||
{name: "relative endpoint", endpoint: "minio:9000", bucket: "attachments", accessKey: "api", secretKey: "secret", timeout: time.Second, wantError: true},
|
||||
{name: "endpoint path", endpoint: "http://minio:9000/path", bucket: "attachments", accessKey: "api", secretKey: "secret", timeout: time.Second, wantError: true},
|
||||
{name: "embedded credentials", endpoint: "http://user:pass@minio:9000", bucket: "attachments", accessKey: "api", secretKey: "secret", timeout: time.Second, wantError: true},
|
||||
{name: "empty bucket", endpoint: "http://minio:9000", accessKey: "api", secretKey: "secret", timeout: time.Second, wantError: true},
|
||||
{name: "empty credentials", endpoint: "http://minio:9000", bucket: "attachments", timeout: time.Second, wantError: true},
|
||||
{name: "invalid timeout", endpoint: "http://minio:9000", bucket: "attachments", accessKey: "api", secretKey: "secret", wantError: true},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
_, err := NewMinIOStore(testCase.endpoint, "us-east-1", testCase.bucket,
|
||||
testCase.accessKey, testCase.secretKey, testCase.timeout)
|
||||
if (err != nil) != testCase.wantError {
|
||||
t.Fatalf("NewMinIOStore() error = %v, wantError %v", err, testCase.wantError)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,906 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab7/internal/domain"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
const attachmentJobColumns = `
|
||||
schema_version, job_id::text, job_type, attachment_id::text,
|
||||
pipeline_version, attempt, max_attempts, status, error_code,
|
||||
available_at, lease_until, leased_by, replay_count, created_at, updated_at,
|
||||
COALESCE(traceparent, ''), COALESCE(tracestate, '')
|
||||
`
|
||||
|
||||
type scanner interface {
|
||||
Scan(dest ...any) error
|
||||
}
|
||||
|
||||
func scanAttachmentJob(row scanner, job *domain.AttachmentJob) error {
|
||||
return row.Scan(
|
||||
&job.SchemaVersion,
|
||||
&job.JobID,
|
||||
&job.Type,
|
||||
&job.AttachmentID,
|
||||
&job.PipelineVersion,
|
||||
&job.Attempt,
|
||||
&job.MaxAttempts,
|
||||
&job.Status,
|
||||
&job.ErrorCode,
|
||||
&job.AvailableAt,
|
||||
&job.LeaseUntil,
|
||||
&job.LeasedBy,
|
||||
&job.ReplayCount,
|
||||
&job.CreatedAt,
|
||||
&job.UpdatedAt,
|
||||
&job.TraceParent,
|
||||
&job.TraceState,
|
||||
)
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) CreateQueuedAttachment(ctx context.Context, attachment domain.Attachment, job domain.AttachmentJob) (domain.Attachment, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
tx, err := s.pool.Begin(queryContext)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("begin queued attachment transaction: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(queryContext) }()
|
||||
|
||||
err = tx.QueryRow(queryContext, `
|
||||
INSERT INTO attachments (
|
||||
id, chat_id, owner_id, object_key, staging_key, filename, content_type,
|
||||
size_bytes, sha256, width, height, pipeline_version, status, error_code,
|
||||
created_at, updated_at
|
||||
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,decode($9,'hex'),$10,$11,$12,$13,NULL,$14,$15)
|
||||
RETURNING created_at, updated_at
|
||||
`, attachment.ID, attachment.ChatID, attachment.OwnerID, attachment.ObjectKey,
|
||||
attachment.StagingKey, attachment.Filename, attachment.ContentType, attachment.SizeBytes,
|
||||
attachment.SHA256, attachment.Width, attachment.Height, attachment.PipelineVersion,
|
||||
attachment.Status, attachment.CreatedAt, attachment.UpdatedAt,
|
||||
).Scan(&attachment.CreatedAt, &attachment.UpdatedAt)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("insert queued attachment: %w", err)
|
||||
}
|
||||
if job.AvailableAt.IsZero() {
|
||||
job.AvailableAt = job.CreatedAt
|
||||
}
|
||||
_, err = tx.Exec(queryContext, `
|
||||
INSERT INTO attachment_jobs (
|
||||
job_id, attachment_id, schema_version, job_type, pipeline_version,
|
||||
attempt, max_attempts, status, available_at, created_at, updated_at,
|
||||
traceparent, tracestate
|
||||
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)
|
||||
`, job.JobID, job.AttachmentID, job.SchemaVersion, job.Type, job.PipelineVersion,
|
||||
job.Attempt, job.MaxAttempts, job.Status, job.AvailableAt, job.CreatedAt, job.UpdatedAt,
|
||||
job.TraceParent, job.TraceState)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("insert attachment job: %w", err)
|
||||
}
|
||||
if err = tx.Commit(queryContext); err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("commit queued attachment: %w", err)
|
||||
}
|
||||
attachment.Variants = make([]domain.AttachmentVariant, 0)
|
||||
return attachment, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) ListUnpublishedAttachmentJobs(ctx context.Context, limit int) ([]domain.AttachmentJob, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
rows, err := s.pool.Query(queryContext, `
|
||||
SELECT `+attachmentJobColumns+`
|
||||
FROM attachment_jobs
|
||||
WHERE status = 'queued' AND published_at IS NULL
|
||||
AND available_at <= CURRENT_TIMESTAMP
|
||||
ORDER BY available_at, created_at, job_id
|
||||
LIMIT $1
|
||||
`, limit)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list unpublished attachment jobs: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
jobs := make([]domain.AttachmentJob, 0)
|
||||
for rows.Next() {
|
||||
var job domain.AttachmentJob
|
||||
if err = scanAttachmentJob(rows, &job); err != nil {
|
||||
return nil, fmt.Errorf("scan unpublished attachment job: %w", err)
|
||||
}
|
||||
jobs = append(jobs, job)
|
||||
}
|
||||
return jobs, rows.Err()
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) MarkAttachmentJobPublished(ctx context.Context, jobID string, attempt int, publishedAt time.Time) error {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
_, err := s.pool.Exec(queryContext, `
|
||||
UPDATE attachment_jobs SET published_at = $3, updated_at = $3
|
||||
WHERE job_id = $1 AND attempt = $2 AND status = 'queued'
|
||||
`, jobID, attempt, publishedAt)
|
||||
if err != nil {
|
||||
return fmt.Errorf("mark attachment job published: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) ClaimAttachmentJob(
|
||||
ctx context.Context,
|
||||
message domain.AttachmentJobMessage,
|
||||
workerID string,
|
||||
leaseUntil time.Time,
|
||||
) (domain.AttachmentJob, bool, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
tx, err := s.pool.Begin(queryContext)
|
||||
if err != nil {
|
||||
return domain.AttachmentJob{}, false, fmt.Errorf("begin claim attachment job: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(queryContext) }()
|
||||
|
||||
var job domain.AttachmentJob
|
||||
err = scanAttachmentJob(tx.QueryRow(queryContext, `
|
||||
UPDATE attachment_jobs
|
||||
SET status = 'processing', lease_until = $5, leased_by = $6,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE job_id = $1 AND attachment_id = $2 AND pipeline_version = $3
|
||||
AND attempt = $4 AND status = 'queued'
|
||||
AND available_at <= CURRENT_TIMESTAMP
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM attachments a
|
||||
WHERE a.id = attachment_jobs.attachment_id
|
||||
AND a.pipeline_version = attachment_jobs.pipeline_version
|
||||
AND a.status = 'queued'
|
||||
)
|
||||
RETURNING `+attachmentJobColumns+`
|
||||
`, message.JobID, message.AttachmentID, message.PipelineVersion, message.Attempt,
|
||||
leaseUntil, workerID), &job)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
var status domain.AttachmentJobStatus
|
||||
var attachmentStatus domain.AttachmentStatus
|
||||
var attempt, activeVersion, jobVersion int
|
||||
lookupErr := tx.QueryRow(queryContext, `
|
||||
SELECT j.status, j.attempt, a.status, a.pipeline_version, j.pipeline_version
|
||||
FROM attachment_jobs j
|
||||
JOIN attachments a ON a.id=j.attachment_id
|
||||
WHERE j.job_id=$1
|
||||
FOR UPDATE OF a,j
|
||||
`, message.JobID).Scan(
|
||||
&status,
|
||||
&attempt,
|
||||
&attachmentStatus,
|
||||
&activeVersion,
|
||||
&jobVersion,
|
||||
)
|
||||
if errors.Is(lookupErr, pgx.ErrNoRows) {
|
||||
return domain.AttachmentJob{}, false, ErrNotFound
|
||||
}
|
||||
if lookupErr != nil {
|
||||
return domain.AttachmentJob{}, false, fmt.Errorf("inspect unclaimed attachment job: %w", lookupErr)
|
||||
}
|
||||
err = nil
|
||||
switch {
|
||||
case status == domain.AttachmentJobQueued &&
|
||||
activeVersion == jobVersion &&
|
||||
attachmentStatus == domain.AttachmentStatusReady:
|
||||
_, err = tx.Exec(queryContext, `
|
||||
UPDATE attachment_jobs
|
||||
SET status='succeeded', error_code=NULL, published_at=COALESCE(published_at,CURRENT_TIMESTAMP),
|
||||
lease_until=NULL, leased_by=NULL, updated_at=CURRENT_TIMESTAMP
|
||||
WHERE job_id=$1
|
||||
`, message.JobID)
|
||||
status = domain.AttachmentJobSucceeded
|
||||
case status == domain.AttachmentJobQueued && activeVersion != jobVersion:
|
||||
_, err = tx.Exec(queryContext, `
|
||||
UPDATE attachment_jobs
|
||||
SET status='superseded', error_code='superseded_pipeline',
|
||||
lease_until=NULL, leased_by=NULL, updated_at=CURRENT_TIMESTAMP
|
||||
WHERE job_id=$1
|
||||
`, message.JobID)
|
||||
status = domain.AttachmentJobSuperseded
|
||||
}
|
||||
if err != nil {
|
||||
return domain.AttachmentJob{}, false, fmt.Errorf("normalize unclaimed attachment job: %w", err)
|
||||
}
|
||||
if err = tx.Commit(queryContext); err != nil {
|
||||
return domain.AttachmentJob{}, false, fmt.Errorf("commit unclaimed attachment job: %w", err)
|
||||
}
|
||||
return domain.AttachmentJob{JobID: message.JobID, Status: status, Attempt: attempt}, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return domain.AttachmentJob{}, false, fmt.Errorf("claim attachment job: %w", err)
|
||||
}
|
||||
_, err = tx.Exec(queryContext, `
|
||||
UPDATE attachments SET status = 'processing', updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = $1 AND pipeline_version = $2 AND status = 'queued'
|
||||
`, message.AttachmentID, message.PipelineVersion)
|
||||
if err != nil {
|
||||
return domain.AttachmentJob{}, false, fmt.Errorf("mark attachment processing: %w", err)
|
||||
}
|
||||
if err = tx.Commit(queryContext); err != nil {
|
||||
return domain.AttachmentJob{}, false, fmt.Errorf("commit claimed attachment job: %w", err)
|
||||
}
|
||||
return job, true, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) GetAttachmentForProcessing(ctx context.Context, attachmentID string) (domain.Attachment, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
var attachment domain.Attachment
|
||||
var digest []byte
|
||||
var stagingKey *string
|
||||
err := s.pool.QueryRow(queryContext, `
|
||||
SELECT id::text, chat_id::text, owner_id::text, object_key, staging_key,
|
||||
filename, content_type, size_bytes, sha256, width, height,
|
||||
pipeline_version, status, error_code, created_at, updated_at
|
||||
FROM attachments WHERE id = $1
|
||||
`, attachmentID).Scan(&attachment.ID, &attachment.ChatID, &attachment.OwnerID,
|
||||
&attachment.ObjectKey, &stagingKey, &attachment.Filename,
|
||||
&attachment.ContentType, &attachment.SizeBytes, &digest, &attachment.Width,
|
||||
&attachment.Height, &attachment.PipelineVersion, &attachment.Status,
|
||||
&attachment.ErrorCode, &attachment.CreatedAt, &attachment.UpdatedAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.Attachment{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("get attachment for processing: %w", err)
|
||||
}
|
||||
attachment.SHA256 = fmt.Sprintf("%x", digest)
|
||||
if stagingKey != nil {
|
||||
attachment.StagingKey = *stagingKey
|
||||
}
|
||||
return attachment, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) CompleteAttachmentJob(
|
||||
ctx context.Context,
|
||||
job domain.AttachmentJob,
|
||||
variants []domain.AttachmentVariant,
|
||||
updatedAt time.Time,
|
||||
) (bool, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
tx, err := s.pool.Begin(queryContext)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("begin complete attachment job: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(queryContext) }()
|
||||
|
||||
var attachmentStatus domain.AttachmentStatus
|
||||
var pipelineVersion int
|
||||
var jobStatus domain.AttachmentJobStatus
|
||||
err = tx.QueryRow(queryContext, `
|
||||
SELECT a.status, a.pipeline_version, j.status
|
||||
FROM attachments a
|
||||
JOIN attachment_jobs j ON j.attachment_id = a.id
|
||||
WHERE a.id = $1 AND j.job_id = $2
|
||||
FOR UPDATE OF a, j
|
||||
`, job.AttachmentID, job.JobID).Scan(&attachmentStatus, &pipelineVersion, &jobStatus)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("lock attachment completion: %w", err)
|
||||
}
|
||||
if pipelineVersion != job.PipelineVersion || jobStatus == domain.AttachmentJobSuperseded {
|
||||
if jobStatus != domain.AttachmentJobSuperseded {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
UPDATE attachment_jobs
|
||||
SET status='superseded', error_code='superseded_pipeline',
|
||||
lease_until=NULL, leased_by=NULL, updated_at=$2
|
||||
WHERE job_id=$1
|
||||
`, job.JobID, updatedAt)
|
||||
if err == nil {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
INSERT INTO attachment_job_events
|
||||
(job_id, event_type, previous_status, new_status, attempt, error_code, created_at)
|
||||
VALUES ($1, 'superseded', $2, 'superseded', $3, 'superseded_pipeline', $4)
|
||||
`, job.JobID, jobStatus, job.Attempt, updatedAt)
|
||||
}
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("supersede stale pipeline completion: %w", err)
|
||||
}
|
||||
}
|
||||
if err = tx.Commit(queryContext); err != nil {
|
||||
return false, fmt.Errorf("commit stale pipeline completion: %w", err)
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
if attachmentStatus == domain.AttachmentStatusReady || jobStatus == domain.AttachmentJobSucceeded {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
UPDATE attachment_jobs
|
||||
SET status='succeeded', error_code=NULL, lease_until=NULL, leased_by=NULL, updated_at=$2
|
||||
WHERE job_id=$1
|
||||
`, job.JobID, updatedAt)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("normalize completed job: %w", err)
|
||||
}
|
||||
if err = tx.Commit(queryContext); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
if len(variants) != 3 {
|
||||
return false, fmt.Errorf("complete attachment requires three variants: %w", ErrConflict)
|
||||
}
|
||||
for _, variant := range variants {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
INSERT INTO attachment_variants (
|
||||
attachment_id, pipeline_version, name, object_key, content_type,
|
||||
size_bytes, width, height, sha256, created_at
|
||||
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,decode($9,'hex'),$10)
|
||||
ON CONFLICT (attachment_id, pipeline_version, name) DO UPDATE SET
|
||||
object_key = EXCLUDED.object_key, content_type = EXCLUDED.content_type,
|
||||
size_bytes = EXCLUDED.size_bytes, width = EXCLUDED.width,
|
||||
height = EXCLUDED.height, sha256 = EXCLUDED.sha256
|
||||
`, job.AttachmentID, job.PipelineVersion, variant.Name, variant.ObjectKey,
|
||||
variant.ContentType, variant.SizeBytes, variant.Width, variant.Height,
|
||||
variant.SHA256, updatedAt)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("upsert attachment variant %s: %w", variant.Name, err)
|
||||
}
|
||||
}
|
||||
tag, err := tx.Exec(queryContext, `
|
||||
UPDATE attachments SET status = 'ready', error_code = NULL, updated_at = $3
|
||||
WHERE id = $1 AND pipeline_version = $2 AND status IN ('queued','processing')
|
||||
`, job.AttachmentID, job.PipelineVersion, updatedAt)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("mark attachment ready: %w", err)
|
||||
}
|
||||
if tag.RowsAffected() != 1 {
|
||||
return false, fmt.Errorf("active pipeline changed during completion: %w", ErrConflict)
|
||||
}
|
||||
_, err = tx.Exec(queryContext, `
|
||||
UPDATE attachment_jobs
|
||||
SET status = 'succeeded', error_code = NULL, lease_until = NULL,
|
||||
leased_by = NULL, updated_at = $2
|
||||
WHERE job_id = $1
|
||||
`, job.JobID, updatedAt)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("mark attachment job succeeded: %w", err)
|
||||
}
|
||||
_, err = tx.Exec(queryContext, `
|
||||
INSERT INTO attachment_job_events
|
||||
(job_id, event_type, previous_status, new_status, attempt, created_at)
|
||||
VALUES ($1, 'completed', $2, 'succeeded', $3, $4)
|
||||
`, job.JobID, jobStatus, job.Attempt, updatedAt)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("record attachment completion: %w", err)
|
||||
}
|
||||
if err = tx.Commit(queryContext); err != nil {
|
||||
return false, fmt.Errorf("commit completed attachment job: %w", err)
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) RetryAttachmentJob(
|
||||
ctx context.Context,
|
||||
jobID string,
|
||||
errorCode string,
|
||||
availableAt time.Time,
|
||||
updatedAt time.Time,
|
||||
eventType string,
|
||||
) (domain.AttachmentJob, bool, error) {
|
||||
if eventType != "retry_scheduled" && eventType != "lease_recovered" {
|
||||
return domain.AttachmentJob{}, false, fmt.Errorf("unsupported retry event type")
|
||||
}
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
tx, err := s.pool.Begin(queryContext)
|
||||
if err != nil {
|
||||
return domain.AttachmentJob{}, false, fmt.Errorf("begin retry attachment job: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(queryContext) }()
|
||||
|
||||
var job domain.AttachmentJob
|
||||
err = scanAttachmentJob(tx.QueryRow(queryContext, `
|
||||
SELECT `+attachmentJobColumns+`
|
||||
FROM attachment_jobs WHERE job_id = $1 FOR UPDATE
|
||||
`, jobID), &job)
|
||||
if err != nil {
|
||||
return domain.AttachmentJob{}, false, fmt.Errorf("lock attachment job for retry: %w", err)
|
||||
}
|
||||
var attachmentStatus domain.AttachmentStatus
|
||||
var activePipelineVersion int
|
||||
if err = tx.QueryRow(queryContext,
|
||||
`SELECT status, pipeline_version FROM attachments WHERE id = $1 FOR UPDATE`,
|
||||
job.AttachmentID,
|
||||
).Scan(&attachmentStatus, &activePipelineVersion); err != nil {
|
||||
return domain.AttachmentJob{}, false, fmt.Errorf("lock attachment for retry: %w", err)
|
||||
}
|
||||
if activePipelineVersion != job.PipelineVersion || job.Status == domain.AttachmentJobSuperseded {
|
||||
previousStatus := job.Status
|
||||
if job.Status != domain.AttachmentJobSuperseded {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
UPDATE attachment_jobs
|
||||
SET status='superseded', error_code='superseded_pipeline',
|
||||
lease_until=NULL, leased_by=NULL, updated_at=$2
|
||||
WHERE job_id=$1
|
||||
`, jobID, updatedAt)
|
||||
if err == nil {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
INSERT INTO attachment_job_events
|
||||
(job_id, event_type, previous_status, new_status, attempt, error_code, created_at)
|
||||
VALUES ($1, 'superseded', $2, 'superseded', $3, 'superseded_pipeline', $4)
|
||||
`, jobID, previousStatus, job.Attempt, updatedAt)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return domain.AttachmentJob{}, false, err
|
||||
}
|
||||
if err = tx.Commit(queryContext); err != nil {
|
||||
return domain.AttachmentJob{}, false, err
|
||||
}
|
||||
job.Status = domain.AttachmentJobSuperseded
|
||||
job.ErrorCode = stringPointer("superseded_pipeline")
|
||||
job.LeaseUntil = nil
|
||||
job.LeasedBy = nil
|
||||
return job, true, nil
|
||||
}
|
||||
if attachmentStatus == domain.AttachmentStatusReady || job.Status == domain.AttachmentJobSucceeded {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
UPDATE attachment_jobs
|
||||
SET status='succeeded', error_code=NULL, lease_until=NULL, leased_by=NULL, updated_at=$2
|
||||
WHERE job_id=$1
|
||||
`, jobID, updatedAt)
|
||||
if err != nil {
|
||||
return domain.AttachmentJob{}, false, err
|
||||
}
|
||||
if err = tx.Commit(queryContext); err != nil {
|
||||
return domain.AttachmentJob{}, false, err
|
||||
}
|
||||
job.Status = domain.AttachmentJobSucceeded
|
||||
return job, true, nil
|
||||
}
|
||||
if job.Status != domain.AttachmentJobProcessing {
|
||||
if err = tx.Commit(queryContext); err != nil {
|
||||
return domain.AttachmentJob{}, false, err
|
||||
}
|
||||
return job, job.Status == domain.AttachmentJobFailed || job.Status == domain.AttachmentJobSuperseded, nil
|
||||
}
|
||||
if job.Attempt >= job.MaxAttempts {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
UPDATE attachment_jobs
|
||||
SET status='failed', error_code=$2, lease_until=NULL, leased_by=NULL, updated_at=$3
|
||||
WHERE job_id=$1
|
||||
`, jobID, errorCode, updatedAt)
|
||||
if err == nil {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
UPDATE attachments
|
||||
SET status='failed', error_code='retry_exhausted', updated_at=$3
|
||||
WHERE id=$1 AND pipeline_version=$2 AND status <> 'ready'
|
||||
`, job.AttachmentID, job.PipelineVersion, updatedAt)
|
||||
}
|
||||
if err == nil {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
INSERT INTO attachment_job_events
|
||||
(job_id, event_type, previous_status, new_status, attempt, error_code, created_at)
|
||||
VALUES ($1, 'permanent_failure', 'processing', 'failed', $2, $3, $4)
|
||||
`, jobID, job.Attempt, errorCode, updatedAt)
|
||||
}
|
||||
if err != nil {
|
||||
return domain.AttachmentJob{}, false, err
|
||||
}
|
||||
if err = tx.Commit(queryContext); err != nil {
|
||||
return domain.AttachmentJob{}, false, err
|
||||
}
|
||||
job.Status = domain.AttachmentJobFailed
|
||||
job.ErrorCode = &errorCode
|
||||
job.LeaseUntil = nil
|
||||
job.LeasedBy = nil
|
||||
return job, true, nil
|
||||
}
|
||||
|
||||
job.Attempt++
|
||||
_, err = tx.Exec(queryContext, `
|
||||
UPDATE attachment_jobs
|
||||
SET attempt=$2, status='queued', error_code=$3, available_at=$4,
|
||||
published_at=NULL, lease_until=NULL, leased_by=NULL, updated_at=$5
|
||||
WHERE job_id=$1
|
||||
`, jobID, job.Attempt, errorCode, availableAt, updatedAt)
|
||||
if err == nil {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
UPDATE attachments
|
||||
SET status='queued', error_code=NULL, updated_at=$3
|
||||
WHERE id=$1 AND pipeline_version=$2 AND status <> 'ready'
|
||||
`, job.AttachmentID, job.PipelineVersion, updatedAt)
|
||||
}
|
||||
if err == nil {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
INSERT INTO attachment_job_events
|
||||
(job_id, event_type, previous_status, new_status, attempt, error_code, created_at)
|
||||
VALUES ($1, $2, 'processing', 'queued', $3, $4, $5)
|
||||
`, jobID, eventType, job.Attempt, errorCode, updatedAt)
|
||||
}
|
||||
if err != nil {
|
||||
return domain.AttachmentJob{}, false, err
|
||||
}
|
||||
if err = tx.Commit(queryContext); err != nil {
|
||||
return domain.AttachmentJob{}, false, err
|
||||
}
|
||||
job.Status = domain.AttachmentJobQueued
|
||||
job.ErrorCode = &errorCode
|
||||
job.AvailableAt = availableAt
|
||||
job.LeaseUntil = nil
|
||||
job.LeasedBy = nil
|
||||
job.UpdatedAt = updatedAt
|
||||
return job, false, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) FailAttachmentJob(ctx context.Context, jobID, errorCode string, updatedAt time.Time) error {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
tx, err := s.pool.Begin(queryContext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = tx.Rollback(queryContext) }()
|
||||
|
||||
var attachmentID string
|
||||
var attachmentStatus domain.AttachmentStatus
|
||||
var activePipelineVersion, jobPipelineVersion, attempt int
|
||||
var jobStatus domain.AttachmentJobStatus
|
||||
err = tx.QueryRow(queryContext, `
|
||||
SELECT a.id::text, a.status, a.pipeline_version, j.pipeline_version, j.status, j.attempt
|
||||
FROM attachment_jobs j
|
||||
JOIN attachments a ON a.id=j.attachment_id
|
||||
WHERE j.job_id=$1 FOR UPDATE OF a,j
|
||||
`, jobID).Scan(
|
||||
&attachmentID,
|
||||
&attachmentStatus,
|
||||
&activePipelineVersion,
|
||||
&jobPipelineVersion,
|
||||
&jobStatus,
|
||||
&attempt,
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if activePipelineVersion != jobPipelineVersion || jobStatus == domain.AttachmentJobSuperseded {
|
||||
if jobStatus != domain.AttachmentJobSuperseded {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
UPDATE attachment_jobs
|
||||
SET status='superseded', error_code='superseded_pipeline',
|
||||
lease_until=NULL, leased_by=NULL, updated_at=$2
|
||||
WHERE job_id=$1
|
||||
`, jobID, updatedAt)
|
||||
if err == nil {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
INSERT INTO attachment_job_events
|
||||
(job_id, event_type, previous_status, new_status, attempt, error_code, created_at)
|
||||
VALUES ($1, 'superseded', $2, 'superseded', $3, 'superseded_pipeline', $4)
|
||||
`, jobID, jobStatus, attempt, updatedAt)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit(queryContext)
|
||||
}
|
||||
if attachmentStatus == domain.AttachmentStatusReady || jobStatus == domain.AttachmentJobSucceeded {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
UPDATE attachment_jobs
|
||||
SET status='succeeded', error_code=NULL, lease_until=NULL, leased_by=NULL, updated_at=$2
|
||||
WHERE job_id=$1
|
||||
`, jobID, updatedAt)
|
||||
} else {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
UPDATE attachment_jobs
|
||||
SET status='failed', error_code=$2, lease_until=NULL, leased_by=NULL, updated_at=$3
|
||||
WHERE job_id=$1
|
||||
`, jobID, errorCode, updatedAt)
|
||||
if err == nil {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
UPDATE attachments
|
||||
SET status='failed', error_code=$3, updated_at=$4
|
||||
WHERE id=$1 AND pipeline_version=$2
|
||||
`, attachmentID, jobPipelineVersion, errorCode, updatedAt)
|
||||
}
|
||||
if err == nil {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
INSERT INTO attachment_job_events
|
||||
(job_id, event_type, previous_status, new_status, attempt, error_code, created_at)
|
||||
VALUES ($1, 'permanent_failure', $2, 'failed', $3, $4, $5)
|
||||
`, jobID, jobStatus, attempt, errorCode, updatedAt)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit(queryContext)
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) ListExpiredAttachmentJobs(ctx context.Context, now time.Time, limit int) ([]domain.AttachmentJob, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
rows, err := s.pool.Query(queryContext, `
|
||||
SELECT `+attachmentJobColumns+`
|
||||
FROM attachment_jobs
|
||||
WHERE status='processing' AND lease_until <= $1
|
||||
ORDER BY lease_until, job_id
|
||||
LIMIT $2
|
||||
`, now, limit)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list expired attachment jobs: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
jobs := make([]domain.AttachmentJob, 0)
|
||||
for rows.Next() {
|
||||
var job domain.AttachmentJob
|
||||
if err = scanAttachmentJob(rows, &job); err != nil {
|
||||
return nil, fmt.Errorf("scan expired attachment job: %w", err)
|
||||
}
|
||||
jobs = append(jobs, job)
|
||||
}
|
||||
return jobs, rows.Err()
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) ReplayFailedAttachmentJob(ctx context.Context, jobID string, replayedAt time.Time) (domain.AttachmentJob, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
tx, err := s.pool.Begin(queryContext)
|
||||
if err != nil {
|
||||
return domain.AttachmentJob{}, fmt.Errorf("begin attachment replay: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(queryContext) }()
|
||||
|
||||
var job domain.AttachmentJob
|
||||
err = scanAttachmentJob(tx.QueryRow(queryContext, `
|
||||
SELECT `+attachmentJobColumns+`
|
||||
FROM attachment_jobs WHERE job_id=$1 FOR UPDATE
|
||||
`, jobID), &job)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.AttachmentJob{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return domain.AttachmentJob{}, fmt.Errorf("lock failed job for replay: %w", err)
|
||||
}
|
||||
var attachmentStatus domain.AttachmentStatus
|
||||
var activePipelineVersion int
|
||||
var stagingKey *string
|
||||
if err = tx.QueryRow(queryContext, `
|
||||
SELECT status, staging_key, pipeline_version FROM attachments WHERE id=$1 FOR UPDATE
|
||||
`, job.AttachmentID).Scan(&attachmentStatus, &stagingKey, &activePipelineVersion); err != nil {
|
||||
return domain.AttachmentJob{}, err
|
||||
}
|
||||
if job.Status != domain.AttachmentJobFailed ||
|
||||
attachmentStatus != domain.AttachmentStatusFailed ||
|
||||
activePipelineVersion != job.PipelineVersion {
|
||||
return domain.AttachmentJob{}, fmt.Errorf("only the active failed pipeline can be replayed: %w", ErrConflict)
|
||||
}
|
||||
if stagingKey == nil || *stagingKey == "" {
|
||||
return domain.AttachmentJob{}, fmt.Errorf("failed job staging is no longer retained: %w", ErrConflict)
|
||||
}
|
||||
_, err = tx.Exec(queryContext, `
|
||||
UPDATE attachment_jobs
|
||||
SET attempt=1, status='queued', error_code=NULL, available_at=$2,
|
||||
published_at=NULL, lease_until=NULL, leased_by=NULL,
|
||||
replay_count=replay_count+1, updated_at=$2
|
||||
WHERE job_id=$1
|
||||
`, jobID, replayedAt)
|
||||
if err == nil {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
UPDATE attachments SET status='queued', error_code=NULL, updated_at=$2 WHERE id=$1
|
||||
`, job.AttachmentID, replayedAt)
|
||||
}
|
||||
if err == nil {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
INSERT INTO attachment_job_events
|
||||
(job_id, event_type, previous_status, new_status, attempt, created_at)
|
||||
VALUES ($1, 'operator_replay', 'failed', 'queued', 1, $2)
|
||||
`, jobID, replayedAt)
|
||||
}
|
||||
if err != nil {
|
||||
return domain.AttachmentJob{}, fmt.Errorf("replay failed job: %w", err)
|
||||
}
|
||||
if err = tx.Commit(queryContext); err != nil {
|
||||
return domain.AttachmentJob{}, fmt.Errorf("commit attachment replay: %w", err)
|
||||
}
|
||||
job.Attempt = 1
|
||||
job.Status = domain.AttachmentJobQueued
|
||||
job.ErrorCode = nil
|
||||
job.AvailableAt = replayedAt
|
||||
job.ReplayCount++
|
||||
job.UpdatedAt = replayedAt
|
||||
return job, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) ListFailedAttachmentJobs(ctx context.Context, limit int) ([]domain.AttachmentJob, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
rows, err := s.pool.Query(queryContext, `
|
||||
SELECT `+attachmentJobColumns+`
|
||||
FROM attachment_jobs
|
||||
WHERE status='failed'
|
||||
ORDER BY updated_at, job_id
|
||||
LIMIT $1
|
||||
`, limit)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list failed attachment jobs: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
jobs := make([]domain.AttachmentJob, 0)
|
||||
for rows.Next() {
|
||||
var job domain.AttachmentJob
|
||||
if err = scanAttachmentJob(rows, &job); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
jobs = append(jobs, job)
|
||||
}
|
||||
return jobs, rows.Err()
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) LookupAttachmentByStagingKey(
|
||||
ctx context.Context,
|
||||
stagingKey string,
|
||||
) (string, domain.AttachmentStatus, time.Time, bool, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
var attachmentID string
|
||||
var status domain.AttachmentStatus
|
||||
var updatedAt time.Time
|
||||
err := s.pool.QueryRow(queryContext, `
|
||||
SELECT id::text, status, updated_at FROM attachments WHERE staging_key=$1
|
||||
`, stagingKey).Scan(&attachmentID, &status, &updatedAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return "", "", time.Time{}, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return "", "", time.Time{}, false, err
|
||||
}
|
||||
return attachmentID, status, updatedAt, true, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) ClearAttachmentStagingKey(ctx context.Context, attachmentID, stagingKey string) error {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
_, err := s.pool.Exec(queryContext, `
|
||||
UPDATE attachments SET staging_key=NULL
|
||||
WHERE id=$1 AND staging_key=$2 AND status IN ('ready','failed')
|
||||
`, attachmentID, stagingKey)
|
||||
if err != nil {
|
||||
return fmt.Errorf("clear attachment staging key: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) ListReadyStagingKeys(
|
||||
ctx context.Context,
|
||||
limit int,
|
||||
) (map[string]string, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
rows, err := s.pool.Query(queryContext, `
|
||||
SELECT staging_key, id::text
|
||||
FROM attachments
|
||||
WHERE status='ready' AND staging_key IS NOT NULL
|
||||
ORDER BY updated_at, id
|
||||
LIMIT $1
|
||||
`, limit)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list ready staging keys: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
keys := make(map[string]string)
|
||||
for rows.Next() {
|
||||
var key, attachmentID string
|
||||
if err = rows.Scan(&key, &attachmentID); err != nil {
|
||||
return nil, fmt.Errorf("scan ready staging key: %w", err)
|
||||
}
|
||||
keys[key] = attachmentID
|
||||
}
|
||||
return keys, rows.Err()
|
||||
}
|
||||
|
||||
func stringPointer(value string) *string { return &value }
|
||||
|
||||
func (s *PostgreSQLStore) GetAttachmentJob(ctx context.Context, jobID string) (domain.AttachmentJob, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
var job domain.AttachmentJob
|
||||
err := scanAttachmentJob(s.pool.QueryRow(queryContext, `
|
||||
SELECT `+attachmentJobColumns+`
|
||||
FROM attachment_jobs WHERE job_id=$1
|
||||
`, jobID), &job)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.AttachmentJob{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return domain.AttachmentJob{}, fmt.Errorf("get attachment job: %w", err)
|
||||
}
|
||||
return job, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) UpgradeAttachmentPipeline(
|
||||
ctx context.Context,
|
||||
attachmentID string,
|
||||
targetVersion int,
|
||||
stagingKey string,
|
||||
job domain.AttachmentJob,
|
||||
upgradedAt time.Time,
|
||||
) (domain.AttachmentJob, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
tx, err := s.pool.Begin(queryContext)
|
||||
if err != nil {
|
||||
return domain.AttachmentJob{}, fmt.Errorf("begin pipeline upgrade: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(queryContext) }()
|
||||
|
||||
var status domain.AttachmentStatus
|
||||
var currentVersion int
|
||||
err = tx.QueryRow(queryContext, `
|
||||
SELECT status, pipeline_version
|
||||
FROM attachments WHERE id=$1 FOR UPDATE
|
||||
`, attachmentID).Scan(&status, ¤tVersion)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.AttachmentJob{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return domain.AttachmentJob{}, fmt.Errorf("lock attachment for pipeline upgrade: %w", err)
|
||||
}
|
||||
if targetVersion != currentVersion+1 ||
|
||||
(status != domain.AttachmentStatusReady && status != domain.AttachmentStatusProcessing) {
|
||||
return domain.AttachmentJob{}, fmt.Errorf("pipeline upgrade requires ready/processing current version and next target version: %w", ErrConflict)
|
||||
}
|
||||
|
||||
_, err = tx.Exec(queryContext, `
|
||||
INSERT INTO attachment_job_events
|
||||
(job_id, event_type, previous_status, new_status, attempt, error_code, created_at)
|
||||
SELECT job_id, 'superseded', status, 'superseded', attempt, 'superseded_pipeline', $3
|
||||
FROM attachment_jobs
|
||||
WHERE attachment_id=$1 AND pipeline_version < $2
|
||||
AND status IN ('queued','processing')
|
||||
`, attachmentID, targetVersion, upgradedAt)
|
||||
if err == nil {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
UPDATE attachment_jobs
|
||||
SET status='superseded', error_code='superseded_pipeline',
|
||||
lease_until=NULL, leased_by=NULL, updated_at=$3
|
||||
WHERE attachment_id=$1 AND pipeline_version < $2
|
||||
AND status IN ('queued','processing')
|
||||
`, attachmentID, targetVersion, upgradedAt)
|
||||
}
|
||||
if err == nil {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
UPDATE attachments
|
||||
SET pipeline_version=$2, staging_key=$3, status='queued',
|
||||
error_code=NULL, updated_at=$4
|
||||
WHERE id=$1
|
||||
`, attachmentID, targetVersion, stagingKey, upgradedAt)
|
||||
}
|
||||
if job.AvailableAt.IsZero() {
|
||||
job.AvailableAt = upgradedAt
|
||||
}
|
||||
if err == nil {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
INSERT INTO attachment_jobs (
|
||||
job_id, attachment_id, schema_version, job_type, pipeline_version,
|
||||
attempt, max_attempts, status, available_at, created_at, updated_at,
|
||||
traceparent, tracestate
|
||||
) VALUES ($1,$2,$3,$4,$5,$6,$7,'queued',$8,$9,$10,$11,$12)
|
||||
`, job.JobID, attachmentID, job.SchemaVersion, job.Type, targetVersion,
|
||||
job.Attempt, job.MaxAttempts, job.AvailableAt, job.CreatedAt, job.UpdatedAt,
|
||||
job.TraceParent, job.TraceState)
|
||||
}
|
||||
if err == nil {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
INSERT INTO attachment_job_events
|
||||
(job_id, event_type, previous_status, new_status, attempt, created_at)
|
||||
VALUES ($1, 'version_upgrade', 'queued', 'queued', $2, $3)
|
||||
`, job.JobID, job.Attempt, upgradedAt)
|
||||
}
|
||||
if err != nil {
|
||||
return domain.AttachmentJob{}, fmt.Errorf("apply pipeline upgrade: %w", err)
|
||||
}
|
||||
if err = tx.Commit(queryContext); err != nil {
|
||||
return domain.AttachmentJob{}, fmt.Errorf("commit pipeline upgrade: %w", err)
|
||||
}
|
||||
job.Status = domain.AttachmentJobQueued
|
||||
job.PipelineVersion = targetVersion
|
||||
job.AvailableAt = upgradedAt
|
||||
job.UpdatedAt = upgradedAt
|
||||
return job, nil
|
||||
}
|
||||
@@ -0,0 +1,372 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab7/internal/domain"
|
||||
"mtusi2026lab7/internal/reconcile"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (s *PostgreSQLStore) CreateAttachment(
|
||||
ctx context.Context,
|
||||
attachment domain.Attachment,
|
||||
) (domain.Attachment, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
err := s.pool.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
INSERT INTO attachments (
|
||||
id, chat_id, owner_id, object_key, filename, content_type,
|
||||
size_bytes, sha256, width, height, status, error_code,
|
||||
created_at, updated_at
|
||||
)
|
||||
VALUES (
|
||||
$1, $2, $3, $4, $5, $6,
|
||||
$7, decode($8, 'hex'), $9, $10, $11, $12,
|
||||
$13, $14
|
||||
)
|
||||
RETURNING created_at, updated_at
|
||||
`,
|
||||
attachment.ID,
|
||||
attachment.ChatID,
|
||||
attachment.OwnerID,
|
||||
attachment.ObjectKey,
|
||||
attachment.Filename,
|
||||
attachment.ContentType,
|
||||
attachment.SizeBytes,
|
||||
attachment.SHA256,
|
||||
attachment.Width,
|
||||
attachment.Height,
|
||||
attachment.Status,
|
||||
attachment.ErrorCode,
|
||||
attachment.CreatedAt,
|
||||
attachment.UpdatedAt,
|
||||
).Scan(&attachment.CreatedAt, &attachment.UpdatedAt)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("insert attachment metadata: %w", err)
|
||||
}
|
||||
if attachment.Variants == nil {
|
||||
attachment.Variants = make([]domain.AttachmentVariant, 0)
|
||||
}
|
||||
return attachment, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) MarkAttachmentReady(
|
||||
ctx context.Context,
|
||||
attachmentID string,
|
||||
updatedAt time.Time,
|
||||
) (domain.Attachment, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var attachment domain.Attachment
|
||||
var sha256Bytes []byte
|
||||
err := s.pool.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
UPDATE attachments
|
||||
SET status = 'ready', error_code = NULL, updated_at = $2
|
||||
WHERE id = $1 AND status IN ('queued', 'processing')
|
||||
RETURNING
|
||||
id::text, chat_id::text, owner_id::text, object_key,
|
||||
filename, content_type, size_bytes, sha256, width, height,
|
||||
pipeline_version, status, error_code, created_at, updated_at
|
||||
`,
|
||||
attachmentID,
|
||||
updatedAt,
|
||||
).Scan(
|
||||
&attachment.ID,
|
||||
&attachment.ChatID,
|
||||
&attachment.OwnerID,
|
||||
&attachment.ObjectKey,
|
||||
&attachment.Filename,
|
||||
&attachment.ContentType,
|
||||
&attachment.SizeBytes,
|
||||
&sha256Bytes,
|
||||
&attachment.Width,
|
||||
&attachment.Height,
|
||||
&attachment.PipelineVersion,
|
||||
&attachment.Status,
|
||||
&attachment.ErrorCode,
|
||||
&attachment.CreatedAt,
|
||||
&attachment.UpdatedAt,
|
||||
)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.Attachment{}, ErrConflict
|
||||
}
|
||||
if err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("mark attachment ready: %w", err)
|
||||
}
|
||||
attachment.SHA256 = fmt.Sprintf("%x", sha256Bytes)
|
||||
attachment.Variants, err = s.listAttachmentVariants(queryContext, attachment.ID, attachment.PipelineVersion)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
return attachment, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) MarkAttachmentFailed(
|
||||
ctx context.Context,
|
||||
attachmentID string,
|
||||
errorCode string,
|
||||
updatedAt time.Time,
|
||||
) error {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
commandTag, err := s.pool.Exec(
|
||||
queryContext,
|
||||
`
|
||||
UPDATE attachments
|
||||
SET status = 'failed', error_code = $2, updated_at = $3
|
||||
WHERE id = $1 AND status IN ('queued', 'processing')
|
||||
`,
|
||||
attachmentID,
|
||||
errorCode,
|
||||
updatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("mark attachment failed: %w", err)
|
||||
}
|
||||
if commandTag.RowsAffected() != 1 {
|
||||
return ErrConflict
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) GetAttachment(
|
||||
ctx context.Context,
|
||||
attachmentID string,
|
||||
callerID string,
|
||||
) (domain.Attachment, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var attachment domain.Attachment
|
||||
var sha256Bytes []byte
|
||||
err := s.pool.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
SELECT
|
||||
a.id::text, a.chat_id::text, a.owner_id::text, a.object_key,
|
||||
a.filename, a.content_type, a.size_bytes, a.sha256,
|
||||
a.width, a.height, a.pipeline_version, a.status, a.error_code,
|
||||
a.created_at, a.updated_at
|
||||
FROM attachments AS a
|
||||
JOIN chat_members AS cm
|
||||
ON cm.chat_id = a.chat_id AND cm.user_id = $2
|
||||
WHERE a.id = $1
|
||||
`,
|
||||
attachmentID,
|
||||
callerID,
|
||||
).Scan(
|
||||
&attachment.ID,
|
||||
&attachment.ChatID,
|
||||
&attachment.OwnerID,
|
||||
&attachment.ObjectKey,
|
||||
&attachment.Filename,
|
||||
&attachment.ContentType,
|
||||
&attachment.SizeBytes,
|
||||
&sha256Bytes,
|
||||
&attachment.Width,
|
||||
&attachment.Height,
|
||||
&attachment.PipelineVersion,
|
||||
&attachment.Status,
|
||||
&attachment.ErrorCode,
|
||||
&attachment.CreatedAt,
|
||||
&attachment.UpdatedAt,
|
||||
)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.Attachment{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("get attachment metadata: %w", err)
|
||||
}
|
||||
attachment.SHA256 = fmt.Sprintf("%x", sha256Bytes)
|
||||
attachment.Variants, err = s.listAttachmentVariants(queryContext, attachment.ID, attachment.PipelineVersion)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
return attachment, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) ListAttachmentInventory(
|
||||
ctx context.Context,
|
||||
) ([]reconcile.AttachmentRecord, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
rows, err := s.pool.Query(
|
||||
queryContext,
|
||||
`
|
||||
SELECT
|
||||
a.id::text,
|
||||
a.object_key,
|
||||
a.status,
|
||||
a.updated_at,
|
||||
EXISTS (
|
||||
SELECT 1
|
||||
FROM message_attachments AS ma
|
||||
WHERE ma.attachment_id = a.id
|
||||
) AS referenced,
|
||||
COALESCE(a.staging_key, ''),
|
||||
COALESCE(av.object_key, '')
|
||||
FROM attachments AS a
|
||||
LEFT JOIN attachment_variants AS av ON av.attachment_id = a.id
|
||||
ORDER BY a.id, av.pipeline_version, av.name
|
||||
`,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("query attachment inventory: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
records := make([]reconcile.AttachmentRecord, 0)
|
||||
recordIndexes := make(map[string]int)
|
||||
for rows.Next() {
|
||||
var record reconcile.AttachmentRecord
|
||||
var stagingKey string
|
||||
var variantKey string
|
||||
if err = rows.Scan(
|
||||
&record.ID,
|
||||
&record.ObjectKey,
|
||||
&record.Status,
|
||||
&record.UpdatedAt,
|
||||
&record.Referenced,
|
||||
&stagingKey,
|
||||
&variantKey,
|
||||
); err != nil {
|
||||
return nil, fmt.Errorf("scan attachment inventory: %w", err)
|
||||
}
|
||||
if recordIndex, exists := recordIndexes[record.ID]; exists {
|
||||
if variantKey != "" {
|
||||
records[recordIndex].AdditionalObjectKeys = append(
|
||||
records[recordIndex].AdditionalObjectKeys,
|
||||
variantKey,
|
||||
)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if stagingKey != "" {
|
||||
record.AdditionalObjectKeys = append(record.AdditionalObjectKeys, stagingKey)
|
||||
}
|
||||
if variantKey != "" {
|
||||
record.AdditionalObjectKeys = append(record.AdditionalObjectKeys, variantKey)
|
||||
}
|
||||
recordIndexes[record.ID] = len(records)
|
||||
records = append(records, record)
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("iterate attachment inventory: %w", err)
|
||||
}
|
||||
return records, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) MarkAttachmentFailedIfUnreferenced(
|
||||
ctx context.Context,
|
||||
attachmentID string,
|
||||
expectedStatus domain.AttachmentStatus,
|
||||
updatedBefore time.Time,
|
||||
errorCode string,
|
||||
updatedAt time.Time,
|
||||
) (bool, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
transaction, err := s.pool.BeginTx(queryContext, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("begin attachment reconciliation transaction: %w", err)
|
||||
}
|
||||
defer func() { _ = transaction.Rollback(queryContext) }()
|
||||
|
||||
var lockedAttachmentID string
|
||||
err = transaction.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
SELECT id::text
|
||||
FROM attachments
|
||||
WHERE id = $1
|
||||
FOR UPDATE
|
||||
`,
|
||||
attachmentID,
|
||||
).Scan(&lockedAttachmentID)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("lock attachment during reconciliation: %w", err)
|
||||
}
|
||||
|
||||
// This is deliberately a second statement. Under READ COMMITTED it gets a
|
||||
// fresh snapshot after the row lock was acquired, so a message transaction
|
||||
// that linked this attachment while we waited is visible to NOT EXISTS.
|
||||
commandTag, err := transaction.Exec(
|
||||
queryContext,
|
||||
`
|
||||
UPDATE attachments AS a
|
||||
SET status = 'failed', error_code = $4, updated_at = $5
|
||||
WHERE a.id = $1
|
||||
AND a.status = $2
|
||||
AND a.updated_at <= $3
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM message_attachments AS ma
|
||||
WHERE ma.attachment_id = a.id
|
||||
)
|
||||
`,
|
||||
attachmentID,
|
||||
expectedStatus,
|
||||
updatedBefore,
|
||||
errorCode,
|
||||
updatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("mark attachment failed during reconciliation: %w", err)
|
||||
}
|
||||
if err = transaction.Commit(queryContext); err != nil {
|
||||
return false, fmt.Errorf("commit attachment reconciliation: %w", err)
|
||||
}
|
||||
return commandTag.RowsAffected() == 1, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) listAttachmentVariants(
|
||||
ctx context.Context,
|
||||
attachmentID string,
|
||||
pipelineVersion int,
|
||||
) ([]domain.AttachmentVariant, error) {
|
||||
if pipelineVersion < 1 {
|
||||
pipelineVersion = 1
|
||||
}
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT name, object_key, content_type, size_bytes, width, height, sha256, pipeline_version
|
||||
FROM attachment_variants
|
||||
WHERE attachment_id = $1 AND pipeline_version = $2
|
||||
ORDER BY name
|
||||
`, attachmentID, pipelineVersion)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("query attachment variants: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
variants := make([]domain.AttachmentVariant, 0)
|
||||
for rows.Next() {
|
||||
var variant domain.AttachmentVariant
|
||||
var digest []byte
|
||||
if err = rows.Scan(&variant.Name, &variant.ObjectKey, &variant.ContentType, &variant.SizeBytes, &variant.Width, &variant.Height, &digest, &variant.PipelineVersion); err != nil {
|
||||
return nil, fmt.Errorf("scan attachment variant: %w", err)
|
||||
}
|
||||
variant.SHA256 = fmt.Sprintf("%x", digest)
|
||||
variants = append(variants, variant)
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("iterate attachment variants: %w", err)
|
||||
}
|
||||
return variants, nil
|
||||
}
|
||||
|
||||
var _ reconcile.MetadataStore = (*PostgreSQLStore)(nil)
|
||||
@@ -0,0 +1,278 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"mtusi2026lab7/internal/domain"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (s *PostgreSQLStore) CreateChat(
|
||||
ctx context.Context,
|
||||
title string,
|
||||
memberIDs []string,
|
||||
) (domain.Chat, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
transaction, err := s.pool.Begin(queryContext)
|
||||
if err != nil {
|
||||
return domain.Chat{}, fmt.Errorf(
|
||||
"begin create chat transaction: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
_ = transaction.Rollback(queryContext)
|
||||
}()
|
||||
|
||||
chat := domain.Chat{
|
||||
ID: uuid.NewString(),
|
||||
Title: title,
|
||||
MemberIDs: append([]string(nil), memberIDs...),
|
||||
}
|
||||
|
||||
err = transaction.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
INSERT INTO chats (
|
||||
id,
|
||||
title
|
||||
)
|
||||
VALUES ($1, $2)
|
||||
RETURNING created_at
|
||||
`,
|
||||
chat.ID,
|
||||
chat.Title,
|
||||
).Scan(&chat.CreatedAt)
|
||||
if err != nil {
|
||||
return domain.Chat{}, fmt.Errorf("insert chat: %w", err)
|
||||
}
|
||||
|
||||
for position, memberID := range memberIDs {
|
||||
commandTag, insertErr := transaction.Exec(
|
||||
queryContext,
|
||||
`
|
||||
INSERT INTO chat_members (
|
||||
chat_id,
|
||||
user_id,
|
||||
position
|
||||
)
|
||||
SELECT
|
||||
$1,
|
||||
id,
|
||||
$3
|
||||
FROM users
|
||||
WHERE id = $2
|
||||
`,
|
||||
chat.ID,
|
||||
memberID,
|
||||
position,
|
||||
)
|
||||
if insertErr != nil {
|
||||
return domain.Chat{}, fmt.Errorf(
|
||||
"insert chat member %s: %w",
|
||||
memberID,
|
||||
insertErr,
|
||||
)
|
||||
}
|
||||
|
||||
// INSERT ... SELECT не вставляет строку, если пользователя нет.
|
||||
// Возврат из функции активирует deferred Rollback: уже созданные
|
||||
// chat и предыдущие membership-строки не останутся в базе.
|
||||
if commandTag.RowsAffected() != 1 {
|
||||
return domain.Chat{}, fmt.Errorf(
|
||||
"%w: member %s",
|
||||
ErrNotFound,
|
||||
memberID,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if err = transaction.Commit(queryContext); err != nil {
|
||||
return domain.Chat{}, fmt.Errorf(
|
||||
"commit create chat transaction: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) GetChatByID(
|
||||
ctx context.Context,
|
||||
chatID string,
|
||||
callerID string,
|
||||
) (domain.Chat, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var chat domain.Chat
|
||||
|
||||
err := s.pool.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
SELECT
|
||||
chat.id::text,
|
||||
chat.title,
|
||||
chat.created_at,
|
||||
array_agg(
|
||||
member.user_id::text
|
||||
ORDER BY member.position
|
||||
)
|
||||
FROM chats AS chat
|
||||
JOIN chat_members AS caller
|
||||
ON caller.chat_id = chat.id
|
||||
AND caller.user_id = $2
|
||||
JOIN chat_members AS member
|
||||
ON member.chat_id = chat.id
|
||||
WHERE chat.id = $1
|
||||
GROUP BY
|
||||
chat.id,
|
||||
chat.title,
|
||||
chat.created_at
|
||||
`,
|
||||
chatID,
|
||||
callerID,
|
||||
).Scan(
|
||||
&chat.ID,
|
||||
&chat.Title,
|
||||
&chat.CreatedAt,
|
||||
&chat.MemberIDs,
|
||||
)
|
||||
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.Chat{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return domain.Chat{}, fmt.Errorf("select chat by id: %w", err)
|
||||
}
|
||||
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) GetChatsForUser(
|
||||
ctx context.Context,
|
||||
userID string,
|
||||
limit int,
|
||||
cursor *domain.ChatCursor,
|
||||
) ([]domain.Chat, bool, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var (
|
||||
rows pgx.Rows
|
||||
err error
|
||||
)
|
||||
|
||||
if cursor == nil {
|
||||
rows, err = s.pool.Query(
|
||||
queryContext,
|
||||
`
|
||||
SELECT
|
||||
chat.id::text,
|
||||
chat.title,
|
||||
chat.created_at,
|
||||
array_agg(
|
||||
member.user_id::text
|
||||
ORDER BY member.position
|
||||
)
|
||||
FROM chat_members AS own_membership
|
||||
JOIN chats AS chat
|
||||
ON chat.id = own_membership.chat_id
|
||||
JOIN chat_members AS member
|
||||
ON member.chat_id = chat.id
|
||||
WHERE own_membership.user_id = $1
|
||||
GROUP BY
|
||||
chat.id,
|
||||
chat.title,
|
||||
chat.created_at
|
||||
ORDER BY
|
||||
chat.created_at,
|
||||
chat.id
|
||||
LIMIT $2
|
||||
`,
|
||||
userID,
|
||||
limit+1,
|
||||
)
|
||||
} else {
|
||||
rows, err = s.pool.Query(
|
||||
queryContext,
|
||||
`
|
||||
SELECT
|
||||
chat.id::text,
|
||||
chat.title,
|
||||
chat.created_at,
|
||||
array_agg(
|
||||
member.user_id::text
|
||||
ORDER BY member.position
|
||||
)
|
||||
FROM chat_members AS own_membership
|
||||
JOIN chats AS chat
|
||||
ON chat.id = own_membership.chat_id
|
||||
JOIN chat_members AS member
|
||||
ON member.chat_id = chat.id
|
||||
WHERE own_membership.user_id = $1
|
||||
AND (chat.created_at, chat.id) > ($2, $3)
|
||||
GROUP BY
|
||||
chat.id,
|
||||
chat.title,
|
||||
chat.created_at
|
||||
ORDER BY
|
||||
chat.created_at,
|
||||
chat.id
|
||||
LIMIT $4
|
||||
`,
|
||||
userID,
|
||||
cursor.CreatedAt,
|
||||
cursor.ChatID,
|
||||
limit+1,
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf(
|
||||
"query chats for user: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
items := make([]domain.Chat, 0, limit+1)
|
||||
|
||||
for rows.Next() {
|
||||
var chat domain.Chat
|
||||
|
||||
if err := rows.Scan(
|
||||
&chat.ID,
|
||||
&chat.Title,
|
||||
&chat.CreatedAt,
|
||||
&chat.MemberIDs,
|
||||
); err != nil {
|
||||
return nil, false, fmt.Errorf(
|
||||
"scan chat page: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
items = append(items, chat)
|
||||
}
|
||||
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, false, fmt.Errorf(
|
||||
"iterate chat page: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
hasMore := len(items) > limit
|
||||
if hasMore {
|
||||
items = items[:limit]
|
||||
}
|
||||
return items, hasMore, nil
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package postgres
|
||||
|
||||
import "mtusi2026lab7/internal/application"
|
||||
|
||||
var _ application.Repository = (*PostgreSQLStore)(nil)
|
||||
@@ -0,0 +1,8 @@
|
||||
package postgres
|
||||
|
||||
import "mtusi2026lab7/internal/domain"
|
||||
|
||||
var (
|
||||
ErrNotFound = domain.ErrNotFound
|
||||
ErrConflict = domain.ErrConflict
|
||||
)
|
||||
@@ -0,0 +1,75 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (s *PostgreSQLStore) AllowLoginAttempt(
|
||||
ctx context.Context,
|
||||
identifierHash [32]byte,
|
||||
now time.Time,
|
||||
window time.Duration,
|
||||
limit int,
|
||||
) (bool, time.Duration, error) {
|
||||
if err := s.maybePruneExpiredState(ctx, now); err != nil {
|
||||
return false, 0, err
|
||||
}
|
||||
if err := s.maybePruneExpiredLoginRateState(ctx, now, window); err != nil {
|
||||
return false, 0, err
|
||||
}
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var attempts int
|
||||
var windowStartedAt time.Time
|
||||
err := s.pool.QueryRow(queryContext, `
|
||||
INSERT INTO login_rate_limits (
|
||||
identifier_hash, window_started_at, attempts
|
||||
)
|
||||
VALUES ($1, $2, 1)
|
||||
ON CONFLICT (identifier_hash) DO UPDATE
|
||||
SET
|
||||
window_started_at = CASE
|
||||
WHEN login_rate_limits.window_started_at <= $3
|
||||
THEN EXCLUDED.window_started_at
|
||||
ELSE login_rate_limits.window_started_at
|
||||
END,
|
||||
attempts = CASE
|
||||
WHEN login_rate_limits.window_started_at <= $3 THEN 1
|
||||
ELSE login_rate_limits.attempts + 1
|
||||
END
|
||||
RETURNING attempts, window_started_at
|
||||
`, identifierHash[:], now.UTC(), now.UTC().Add(-window)).Scan(
|
||||
&attempts,
|
||||
&windowStartedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return false, 0, fmt.Errorf("update login rate limit: %w", err)
|
||||
}
|
||||
if attempts <= limit {
|
||||
return true, 0, nil
|
||||
}
|
||||
retryAfter := windowStartedAt.Add(window).Sub(now.UTC())
|
||||
if retryAfter < time.Second {
|
||||
retryAfter = time.Second
|
||||
}
|
||||
return false, retryAfter, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) ResetLoginAttempts(
|
||||
ctx context.Context,
|
||||
identifierHash [32]byte,
|
||||
) error {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
if _, err := s.pool.Exec(
|
||||
queryContext,
|
||||
`DELETE FROM login_rate_limits WHERE identifier_hash = $1`,
|
||||
identifierHash[:],
|
||||
); err != nil {
|
||||
return fmt.Errorf("reset login rate limit: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
expiredStatePruneEvery = 128
|
||||
expiredStatePruneBatch = 256
|
||||
)
|
||||
|
||||
// maybePruneExpiredState bounds session/idempotency table growth without adding
|
||||
// a cleanup round trip to every request. The first operation after process
|
||||
// start prunes immediately; later operations amortize one bounded indexed
|
||||
// delete per expiredStatePruneEvery writes.
|
||||
func (s *PostgreSQLStore) maybePruneExpiredState(ctx context.Context, now time.Time) error {
|
||||
iteration := s.expiredStatePruneCounter.Add(1)
|
||||
if iteration != 1 && iteration%expiredStatePruneEvery != 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
_, err := s.pool.Exec(queryContext, `
|
||||
WITH stale_sessions AS (
|
||||
SELECT token_hash
|
||||
FROM sessions
|
||||
WHERE expires_at <= $1
|
||||
ORDER BY expires_at
|
||||
LIMIT $2
|
||||
FOR UPDATE SKIP LOCKED
|
||||
), deleted_sessions AS (
|
||||
DELETE FROM sessions AS target
|
||||
USING stale_sessions AS stale
|
||||
WHERE target.token_hash = stale.token_hash
|
||||
RETURNING 1
|
||||
), stale_idempotency AS (
|
||||
SELECT user_id, method, canonical_path, idempotency_key
|
||||
FROM message_idempotency
|
||||
WHERE expires_at <= $1
|
||||
ORDER BY expires_at
|
||||
LIMIT $2
|
||||
FOR UPDATE SKIP LOCKED
|
||||
), deleted_idempotency AS (
|
||||
DELETE FROM message_idempotency AS target
|
||||
USING stale_idempotency AS stale
|
||||
WHERE target.user_id = stale.user_id
|
||||
AND target.method = stale.method
|
||||
AND target.canonical_path = stale.canonical_path
|
||||
AND target.idempotency_key = stale.idempotency_key
|
||||
RETURNING 1
|
||||
)
|
||||
SELECT
|
||||
(SELECT count(*) FROM deleted_sessions),
|
||||
(SELECT count(*) FROM deleted_idempotency)
|
||||
`, now.UTC(), expiredStatePruneBatch)
|
||||
if err != nil {
|
||||
return fmt.Errorf("prune expired auth state: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// maybePruneExpiredLoginRateState uses the configured limiter window as the
|
||||
// cutoff. Comparing with now directly would delete active windows and weaken
|
||||
// the limiter whenever maintenance runs.
|
||||
func (s *PostgreSQLStore) maybePruneExpiredLoginRateState(
|
||||
ctx context.Context,
|
||||
now time.Time,
|
||||
window time.Duration,
|
||||
) error {
|
||||
iteration := s.loginRatePruneCounter.Add(1)
|
||||
if iteration != 1 && iteration%expiredStatePruneEvery != 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
_, err := s.pool.Exec(queryContext, `
|
||||
WITH stale_login_limits AS (
|
||||
SELECT identifier_hash
|
||||
FROM login_rate_limits
|
||||
WHERE window_started_at <= $1
|
||||
ORDER BY window_started_at
|
||||
LIMIT $2
|
||||
FOR UPDATE SKIP LOCKED
|
||||
)
|
||||
DELETE FROM login_rate_limits AS target
|
||||
USING stale_login_limits AS stale
|
||||
WHERE target.identifier_hash = stale.identifier_hash
|
||||
`, now.UTC().Add(-window), expiredStatePruneBatch)
|
||||
if err != nil {
|
||||
return fmt.Errorf("prune expired login rate state: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,426 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab7/internal/application"
|
||||
"mtusi2026lab7/internal/domain"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (s *PostgreSQLStore) CreateMessageIdempotently(
|
||||
ctx context.Context,
|
||||
write application.IdempotentMessageWrite,
|
||||
) (domain.Message, error) {
|
||||
if err := s.maybePruneExpiredState(ctx, time.Now()); err != nil {
|
||||
return domain.Message{}, err
|
||||
}
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
transaction, err := s.pool.BeginTx(queryContext, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return domain.Message{}, fmt.Errorf("begin idempotent message transaction: %w", err)
|
||||
}
|
||||
defer func() { _ = transaction.Rollback(queryContext) }()
|
||||
|
||||
var isMember bool
|
||||
err = transaction.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM chat_members
|
||||
WHERE chat_id = $1
|
||||
AND user_id = $2
|
||||
)
|
||||
`,
|
||||
write.ChatID,
|
||||
write.ActorID,
|
||||
).Scan(&isMember)
|
||||
if err != nil {
|
||||
return domain.Message{}, fmt.Errorf("check chat membership: %w", err)
|
||||
}
|
||||
if !isMember {
|
||||
return domain.Message{}, ErrNotFound
|
||||
}
|
||||
|
||||
attachmentUUIDs := make([]uuid.UUID, len(write.AttachmentIDs))
|
||||
for index, attachmentID := range write.AttachmentIDs {
|
||||
parsedID, parseErr := uuid.Parse(attachmentID)
|
||||
if parseErr != nil {
|
||||
return domain.Message{}, fmt.Errorf("parse validated attachment id: %w", parseErr)
|
||||
}
|
||||
attachmentUUIDs[index] = parsedID
|
||||
}
|
||||
|
||||
if len(attachmentUUIDs) > 0 {
|
||||
rows, queryError := transaction.Query(
|
||||
queryContext,
|
||||
`
|
||||
SELECT id::text, status
|
||||
FROM attachments
|
||||
WHERE chat_id = $1
|
||||
AND id = ANY($2::uuid[])
|
||||
ORDER BY id
|
||||
FOR UPDATE
|
||||
`,
|
||||
write.ChatID,
|
||||
attachmentUUIDs,
|
||||
)
|
||||
if queryError != nil {
|
||||
return domain.Message{}, fmt.Errorf("lock message attachments: %w", queryError)
|
||||
}
|
||||
availableCount := 0
|
||||
eligibleCount := 0
|
||||
for rows.Next() {
|
||||
var attachmentID string
|
||||
var status domain.AttachmentStatus
|
||||
if queryError = rows.Scan(&attachmentID, &status); queryError != nil {
|
||||
rows.Close()
|
||||
return domain.Message{}, fmt.Errorf("scan locked message attachment: %w", queryError)
|
||||
}
|
||||
availableCount++
|
||||
if status != domain.AttachmentStatusFailed {
|
||||
eligibleCount++
|
||||
}
|
||||
}
|
||||
queryError = rows.Err()
|
||||
rows.Close()
|
||||
if queryError != nil {
|
||||
return domain.Message{}, fmt.Errorf("iterate locked message attachments: %w", queryError)
|
||||
}
|
||||
if availableCount != len(attachmentUUIDs) {
|
||||
return domain.Message{}, ErrNotFound
|
||||
}
|
||||
if eligibleCount != len(attachmentUUIDs) {
|
||||
return domain.Message{}, application.ErrAttachmentNotReady
|
||||
}
|
||||
}
|
||||
|
||||
_, err = transaction.Exec(
|
||||
queryContext,
|
||||
`
|
||||
DELETE FROM message_idempotency
|
||||
WHERE user_id = $1
|
||||
AND method = $2
|
||||
AND canonical_path = $3
|
||||
AND idempotency_key = $4
|
||||
AND expires_at <= CURRENT_TIMESTAMP
|
||||
`,
|
||||
write.ActorID,
|
||||
write.Method,
|
||||
write.CanonicalPath,
|
||||
write.Key,
|
||||
)
|
||||
if err != nil {
|
||||
return domain.Message{}, fmt.Errorf("delete expired idempotency key: %w", err)
|
||||
}
|
||||
|
||||
message := domain.Message{
|
||||
ID: uuid.NewString(),
|
||||
ChatID: write.ChatID,
|
||||
SenderID: write.ActorID,
|
||||
Text: write.Text,
|
||||
AttachmentIDs: append([]string(nil), write.AttachmentIDs...),
|
||||
}
|
||||
|
||||
var storedHash []byte
|
||||
var storedMessageID string
|
||||
err = transaction.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
INSERT INTO message_idempotency (
|
||||
user_id,
|
||||
method,
|
||||
canonical_path,
|
||||
idempotency_key,
|
||||
request_hash,
|
||||
message_id,
|
||||
expires_at
|
||||
)
|
||||
VALUES (
|
||||
$1,
|
||||
$2,
|
||||
$3,
|
||||
$4,
|
||||
$5,
|
||||
$6,
|
||||
CURRENT_TIMESTAMP + $7 * INTERVAL '1 second'
|
||||
)
|
||||
ON CONFLICT DO NOTHING
|
||||
RETURNING request_hash, message_id::text
|
||||
`,
|
||||
write.ActorID,
|
||||
write.Method,
|
||||
write.CanonicalPath,
|
||||
write.Key,
|
||||
write.RequestHash[:],
|
||||
message.ID,
|
||||
int64(write.TTL/time.Second),
|
||||
).Scan(&storedHash, &storedMessageID)
|
||||
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
err = transaction.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
SELECT request_hash, message_id::text
|
||||
FROM message_idempotency
|
||||
WHERE user_id = $1
|
||||
AND method = $2
|
||||
AND canonical_path = $3
|
||||
AND idempotency_key = $4
|
||||
`,
|
||||
write.ActorID,
|
||||
write.Method,
|
||||
write.CanonicalPath,
|
||||
write.Key,
|
||||
).Scan(&storedHash, &storedMessageID)
|
||||
if err != nil {
|
||||
return domain.Message{}, fmt.Errorf("read idempotency result: %w", err)
|
||||
}
|
||||
|
||||
if !bytes.Equal(storedHash, write.RequestHash[:]) {
|
||||
return domain.Message{}, application.ErrIdempotencyConflict
|
||||
}
|
||||
|
||||
err = transaction.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
SELECT
|
||||
id::text,
|
||||
chat_id::text,
|
||||
sender_id::text,
|
||||
text,
|
||||
created_at,
|
||||
COALESCE(
|
||||
ARRAY(
|
||||
SELECT attachment_id::text
|
||||
FROM message_attachments
|
||||
WHERE message_id = messages.id
|
||||
ORDER BY position
|
||||
), ARRAY[]::text[]
|
||||
)
|
||||
FROM messages
|
||||
WHERE id = $1
|
||||
`,
|
||||
storedMessageID,
|
||||
).Scan(
|
||||
&message.ID,
|
||||
&message.ChatID,
|
||||
&message.SenderID,
|
||||
&message.Text,
|
||||
&message.CreatedAt,
|
||||
&message.AttachmentIDs,
|
||||
)
|
||||
if err != nil {
|
||||
return domain.Message{}, fmt.Errorf("read idempotent message: %w", err)
|
||||
}
|
||||
|
||||
if err = transaction.Commit(queryContext); err != nil {
|
||||
return domain.Message{}, fmt.Errorf("commit idempotency replay: %w", err)
|
||||
}
|
||||
return message, nil
|
||||
}
|
||||
if err != nil {
|
||||
return domain.Message{}, fmt.Errorf("claim idempotency key: %w", err)
|
||||
}
|
||||
|
||||
err = transaction.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
INSERT INTO messages (
|
||||
id,
|
||||
chat_id,
|
||||
sender_id,
|
||||
text
|
||||
)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING created_at
|
||||
`,
|
||||
message.ID,
|
||||
message.ChatID,
|
||||
message.SenderID,
|
||||
message.Text,
|
||||
).Scan(&message.CreatedAt)
|
||||
if err != nil {
|
||||
return domain.Message{}, fmt.Errorf("insert message: %w", err)
|
||||
}
|
||||
|
||||
if len(attachmentUUIDs) > 0 {
|
||||
_, err = transaction.Exec(
|
||||
queryContext,
|
||||
`
|
||||
INSERT INTO message_attachments (
|
||||
message_id,
|
||||
chat_id,
|
||||
attachment_id,
|
||||
position
|
||||
)
|
||||
SELECT $1, $2, attachment_id, (ordinality - 1)::smallint
|
||||
FROM unnest($3::uuid[]) WITH ORDINALITY AS input(attachment_id, ordinality)
|
||||
`,
|
||||
message.ID,
|
||||
message.ChatID,
|
||||
attachmentUUIDs,
|
||||
)
|
||||
if err != nil {
|
||||
return domain.Message{}, fmt.Errorf("link message attachments: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if err = transaction.Commit(queryContext); err != nil {
|
||||
return domain.Message{}, fmt.Errorf("commit idempotent message: %w", err)
|
||||
}
|
||||
|
||||
return message, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) GetMessages(
|
||||
ctx context.Context,
|
||||
chatID string,
|
||||
callerID string,
|
||||
limit int,
|
||||
cursor *domain.MessageCursor,
|
||||
) ([]domain.Message, bool, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var isMember bool
|
||||
|
||||
err := s.pool.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM chat_members
|
||||
WHERE chat_id = $1
|
||||
AND user_id = $2
|
||||
)
|
||||
`,
|
||||
chatID,
|
||||
callerID,
|
||||
).Scan(&isMember)
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf(
|
||||
"check chat membership: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
if !isMember {
|
||||
return nil, false, ErrNotFound
|
||||
}
|
||||
|
||||
var rows pgx.Rows
|
||||
|
||||
if cursor == nil {
|
||||
rows, err = s.pool.Query(
|
||||
queryContext,
|
||||
`
|
||||
SELECT
|
||||
id::text,
|
||||
chat_id::text,
|
||||
sender_id::text,
|
||||
text,
|
||||
created_at,
|
||||
COALESCE(
|
||||
ARRAY(
|
||||
SELECT attachment_id::text
|
||||
FROM message_attachments
|
||||
WHERE message_id = messages.id
|
||||
ORDER BY position
|
||||
), ARRAY[]::text[]
|
||||
)
|
||||
FROM messages
|
||||
WHERE chat_id = $1
|
||||
ORDER BY
|
||||
created_at,
|
||||
id
|
||||
LIMIT $2
|
||||
`,
|
||||
chatID,
|
||||
limit+1,
|
||||
)
|
||||
} else {
|
||||
rows, err = s.pool.Query(
|
||||
queryContext,
|
||||
`
|
||||
SELECT
|
||||
id::text,
|
||||
chat_id::text,
|
||||
sender_id::text,
|
||||
text,
|
||||
created_at,
|
||||
COALESCE(
|
||||
ARRAY(
|
||||
SELECT attachment_id::text
|
||||
FROM message_attachments
|
||||
WHERE message_id = messages.id
|
||||
ORDER BY position
|
||||
), ARRAY[]::text[]
|
||||
)
|
||||
FROM messages
|
||||
WHERE chat_id = $1
|
||||
AND (created_at, id) > ($2, $3)
|
||||
ORDER BY
|
||||
created_at,
|
||||
id
|
||||
LIMIT $4
|
||||
`,
|
||||
chatID,
|
||||
cursor.CreatedAt,
|
||||
cursor.MessageID,
|
||||
limit+1,
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf(
|
||||
"query messages: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
items := make([]domain.Message, 0, limit+1)
|
||||
|
||||
for rows.Next() {
|
||||
var message domain.Message
|
||||
|
||||
if err := rows.Scan(
|
||||
&message.ID,
|
||||
&message.ChatID,
|
||||
&message.SenderID,
|
||||
&message.Text,
|
||||
&message.CreatedAt,
|
||||
&message.AttachmentIDs,
|
||||
); err != nil {
|
||||
return nil, false, fmt.Errorf(
|
||||
"scan message page: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
items = append(items, message)
|
||||
}
|
||||
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, false, fmt.Errorf(
|
||||
"iterate message page: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
hasMore := len(items) > limit
|
||||
if hasMore {
|
||||
items = items[:limit]
|
||||
}
|
||||
return items, hasMore, nil
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (s *PostgreSQLStore) AttachmentQueueStats(
|
||||
ctx context.Context,
|
||||
now time.Time,
|
||||
) (int64, float64, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
var depth int64
|
||||
var oldestAge float64
|
||||
err := s.pool.QueryRow(queryContext, `
|
||||
SELECT
|
||||
COUNT(*),
|
||||
COALESCE(EXTRACT(EPOCH FROM ($1::timestamptz - MIN(created_at))), 0)
|
||||
FROM attachment_jobs
|
||||
WHERE status = 'queued'
|
||||
`, now).Scan(&depth, &oldestAge)
|
||||
if err != nil {
|
||||
return 0, 0, fmt.Errorf("read attachment queue stats: %w", err)
|
||||
}
|
||||
if oldestAge < 0 {
|
||||
oldestAge = 0
|
||||
}
|
||||
return depth, oldestAge, nil
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab7/internal/domain"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (s *PostgreSQLStore) CreateSession(
|
||||
ctx context.Context,
|
||||
tokenHash []byte,
|
||||
userID string,
|
||||
expiresAt time.Time,
|
||||
) error {
|
||||
if err := s.maybePruneExpiredState(ctx, time.Now()); err != nil {
|
||||
return err
|
||||
}
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
_, err := s.pool.Exec(
|
||||
queryContext,
|
||||
`
|
||||
INSERT INTO sessions (
|
||||
token_hash,
|
||||
user_id,
|
||||
expires_at
|
||||
)
|
||||
VALUES ($1, $2, $3)
|
||||
`,
|
||||
tokenHash,
|
||||
userID,
|
||||
expiresAt,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("insert session: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) GetUserBySession(
|
||||
ctx context.Context,
|
||||
tokenHash []byte,
|
||||
) (domain.User, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var user domain.User
|
||||
|
||||
err := s.pool.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
SELECT
|
||||
app_user.id::text,
|
||||
app_user.username,
|
||||
app_user.display_name,
|
||||
app_user.created_at
|
||||
FROM sessions AS session
|
||||
JOIN users AS app_user
|
||||
ON app_user.id = session.user_id
|
||||
WHERE session.token_hash = $1
|
||||
AND session.expires_at > CURRENT_TIMESTAMP
|
||||
`,
|
||||
tokenHash,
|
||||
).Scan(
|
||||
&user.ID,
|
||||
&user.Username,
|
||||
&user.DisplayName,
|
||||
&user.CreatedAt,
|
||||
)
|
||||
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.User{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return domain.User{}, fmt.Errorf(
|
||||
"select user by session: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) DeleteSession(
|
||||
ctx context.Context,
|
||||
tokenHash []byte,
|
||||
) error {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
_, err := s.pool.Exec(
|
||||
queryContext,
|
||||
`
|
||||
DELETE FROM sessions
|
||||
WHERE token_hash = $1
|
||||
`,
|
||||
tokenHash,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("delete session: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type PostgreSQLStore struct {
|
||||
pool *pgxpool.Pool
|
||||
queryTimeout time.Duration
|
||||
expiredStatePruneCounter atomic.Uint64
|
||||
loginRatePruneCounter atomic.Uint64
|
||||
}
|
||||
|
||||
func NewPostgreSQLStore(
|
||||
pool *pgxpool.Pool,
|
||||
queryTimeout time.Duration,
|
||||
) *PostgreSQLStore {
|
||||
return &PostgreSQLStore{
|
||||
pool: pool,
|
||||
queryTimeout: queryTimeout,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) Ping(ctx context.Context) error {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
return s.pool.Ping(queryContext)
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) Close() {
|
||||
s.pool.Close()
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) withTimeout(
|
||||
ctx context.Context,
|
||||
) (context.Context, context.CancelFunc) {
|
||||
return context.WithTimeout(ctx, s.queryTimeout)
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"mtusi2026lab7/internal/domain"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
)
|
||||
|
||||
func (s *PostgreSQLStore) CreateUser(
|
||||
ctx context.Context,
|
||||
username string,
|
||||
displayName string,
|
||||
passwordHash string,
|
||||
) (domain.User, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
user := domain.User{
|
||||
ID: uuid.NewString(),
|
||||
Username: username,
|
||||
DisplayName: displayName,
|
||||
}
|
||||
|
||||
err := s.pool.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
INSERT INTO users (
|
||||
id,
|
||||
username,
|
||||
display_name,
|
||||
password_hash
|
||||
)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING created_at
|
||||
`,
|
||||
user.ID,
|
||||
user.Username,
|
||||
user.DisplayName,
|
||||
passwordHash,
|
||||
).Scan(&user.CreatedAt)
|
||||
|
||||
if err == nil {
|
||||
return user, nil
|
||||
}
|
||||
|
||||
var postgresError *pgconn.PgError
|
||||
if errors.As(err, &postgresError) &&
|
||||
postgresError.Code == "23505" &&
|
||||
postgresError.ConstraintName == "users_username_unique" {
|
||||
return domain.User{}, ErrConflict
|
||||
}
|
||||
|
||||
return domain.User{}, fmt.Errorf("insert user: %w", err)
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) GetUserByID(
|
||||
ctx context.Context,
|
||||
userID string,
|
||||
) (domain.User, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var user domain.User
|
||||
|
||||
err := s.pool.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
SELECT
|
||||
id::text,
|
||||
username,
|
||||
display_name,
|
||||
created_at
|
||||
FROM users
|
||||
WHERE id = $1
|
||||
`,
|
||||
userID,
|
||||
).Scan(
|
||||
&user.ID,
|
||||
&user.Username,
|
||||
&user.DisplayName,
|
||||
&user.CreatedAt,
|
||||
)
|
||||
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.User{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return domain.User{}, fmt.Errorf("select user by id: %w", err)
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) GetUserByUsername(
|
||||
ctx context.Context,
|
||||
username string,
|
||||
) (domain.User, string, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var (
|
||||
user domain.User
|
||||
passwordHash string
|
||||
)
|
||||
|
||||
err := s.pool.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
SELECT
|
||||
id::text,
|
||||
username,
|
||||
display_name,
|
||||
created_at,
|
||||
password_hash
|
||||
FROM users
|
||||
WHERE username = $1
|
||||
`,
|
||||
username,
|
||||
).Scan(
|
||||
&user.ID,
|
||||
&user.Username,
|
||||
&user.DisplayName,
|
||||
&user.CreatedAt,
|
||||
&passwordHash,
|
||||
)
|
||||
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.User{}, "", ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return domain.User{}, "", fmt.Errorf(
|
||||
"select user by username: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
return user, passwordHash, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) UpdatePasswordHash(
|
||||
ctx context.Context,
|
||||
userID string,
|
||||
previousHash string,
|
||||
newHash string,
|
||||
) error {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
_, err := s.pool.Exec(
|
||||
queryContext,
|
||||
`UPDATE users SET password_hash = $1 WHERE id = $2 AND password_hash = $3`,
|
||||
newHash,
|
||||
userID,
|
||||
previousHash,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("update password hash: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab7/internal/domain"
|
||||
|
||||
"github.com/google/uuid"
|
||||
goredis "github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
const chatKeyPrefix = "chat:v2:"
|
||||
|
||||
var ErrMiss = errors.New("cache miss")
|
||||
|
||||
// ChatCache хранит только производную копию неизменяемых данных чата.
|
||||
// PostgreSQL остаётся источником истины.
|
||||
type ChatCache interface {
|
||||
Get(ctx context.Context, chatID string) (domain.Chat, error)
|
||||
Set(ctx context.Context, chat domain.Chat) error
|
||||
}
|
||||
|
||||
type RedisChatCache struct {
|
||||
client *goredis.Client
|
||||
ttl time.Duration
|
||||
operationTimeout time.Duration
|
||||
}
|
||||
|
||||
func NewRedisChatCache(
|
||||
redisURL string,
|
||||
ttl time.Duration,
|
||||
operationTimeout time.Duration,
|
||||
poolSize int,
|
||||
) (*RedisChatCache, error) {
|
||||
options, err := goredis.ParseURL(strings.TrimSpace(redisURL))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse Redis URL: %w", err)
|
||||
}
|
||||
|
||||
options.DialTimeout = operationTimeout
|
||||
options.ReadTimeout = operationTimeout
|
||||
options.WriteTimeout = operationTimeout
|
||||
options.PoolTimeout = operationTimeout
|
||||
options.PoolSize = poolSize
|
||||
options.MaxRetries = -1
|
||||
|
||||
return &RedisChatCache{
|
||||
client: goredis.NewClient(options),
|
||||
ttl: ttl,
|
||||
operationTimeout: operationTimeout,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *RedisChatCache) Ping(ctx context.Context) error {
|
||||
operationContext, cancel := c.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
if err := c.client.Ping(operationContext).Err(); err != nil {
|
||||
return fmt.Errorf("ping Redis: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *RedisChatCache) Close() error {
|
||||
return c.client.Close()
|
||||
}
|
||||
|
||||
func (c *RedisChatCache) Get(
|
||||
ctx context.Context,
|
||||
chatID string,
|
||||
) (domain.Chat, error) {
|
||||
operationContext, cancel := c.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
payload, err := c.client.Get(
|
||||
operationContext,
|
||||
chatKey(chatID),
|
||||
).Bytes()
|
||||
if errors.Is(err, goredis.Nil) {
|
||||
return domain.Chat{}, ErrMiss
|
||||
}
|
||||
if err != nil {
|
||||
return domain.Chat{}, fmt.Errorf("get cached chat: %w", err)
|
||||
}
|
||||
|
||||
var chat domain.Chat
|
||||
if err = json.Unmarshal(payload, &chat); err != nil {
|
||||
c.deleteInvalidValue(operationContext, chatID)
|
||||
return domain.Chat{}, fmt.Errorf("decode cached chat: %w", err)
|
||||
}
|
||||
|
||||
if err = validateCachedChat(chat, chatID); err != nil {
|
||||
c.deleteInvalidValue(operationContext, chatID)
|
||||
return domain.Chat{}, err
|
||||
}
|
||||
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func (c *RedisChatCache) Set(
|
||||
ctx context.Context,
|
||||
chat domain.Chat,
|
||||
) error {
|
||||
payload, err := json.Marshal(chat)
|
||||
if err != nil {
|
||||
return fmt.Errorf("encode chat for cache: %w", err)
|
||||
}
|
||||
|
||||
operationContext, cancel := c.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
if err = c.client.Set(
|
||||
operationContext,
|
||||
chatKey(chat.ID),
|
||||
payload,
|
||||
c.ttl,
|
||||
).Err(); err != nil {
|
||||
return fmt.Errorf("cache chat: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *RedisChatCache) withTimeout(
|
||||
ctx context.Context,
|
||||
) (context.Context, context.CancelFunc) {
|
||||
return context.WithTimeout(ctx, c.operationTimeout)
|
||||
}
|
||||
|
||||
func (c *RedisChatCache) deleteInvalidValue(
|
||||
ctx context.Context,
|
||||
chatID string,
|
||||
) {
|
||||
_ = c.client.Del(ctx, chatKey(chatID)).Err()
|
||||
}
|
||||
|
||||
func chatKey(chatID string) string {
|
||||
return chatKeyPrefix + chatID
|
||||
}
|
||||
|
||||
func validateCachedChat(chat domain.Chat, expectedID string) error {
|
||||
if chat.ID != expectedID {
|
||||
return errors.New("cached chat id does not match cache key")
|
||||
}
|
||||
if _, err := uuid.Parse(chat.ID); err != nil {
|
||||
return errors.New("cached chat contains invalid id")
|
||||
}
|
||||
if strings.TrimSpace(chat.Title) == "" || chat.CreatedAt.IsZero() {
|
||||
return errors.New("cached chat is incomplete")
|
||||
}
|
||||
if len(chat.MemberIDs) == 0 {
|
||||
return errors.New("cached chat has no members")
|
||||
}
|
||||
|
||||
seenMembers := make(map[string]struct{}, len(chat.MemberIDs))
|
||||
for _, memberID := range chat.MemberIDs {
|
||||
if _, err := uuid.Parse(memberID); err != nil {
|
||||
return errors.New("cached chat contains invalid member id")
|
||||
}
|
||||
if _, exists := seenMembers[memberID]; exists {
|
||||
return errors.New("cached chat contains duplicate member id")
|
||||
}
|
||||
seenMembers[memberID] = struct{}{}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
var _ ChatCache = (*RedisChatCache)(nil)
|
||||
@@ -0,0 +1,67 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"mtusi2026lab7/internal/domain"
|
||||
)
|
||||
|
||||
type AttachmentDownload struct {
|
||||
Body io.ReadCloser
|
||||
ContentType string
|
||||
Filename string
|
||||
SizeBytes int64
|
||||
}
|
||||
|
||||
func (s *Service) GetAttachment(ctx context.Context, attachmentID, actorID string) (domain.Attachment, error) {
|
||||
return s.repository.GetAttachment(ctx, attachmentID, actorID)
|
||||
}
|
||||
|
||||
func (s *Service) DownloadAttachment(ctx context.Context, attachmentID, actorID, variantName string) (AttachmentDownload, error) {
|
||||
attachment, err := s.repository.GetAttachment(ctx, attachmentID, actorID)
|
||||
if err != nil {
|
||||
return AttachmentDownload{}, err
|
||||
}
|
||||
if attachment.Status != domain.AttachmentStatusReady {
|
||||
return AttachmentDownload{}, ErrAttachmentNotReady
|
||||
}
|
||||
if s.objectStore == nil {
|
||||
return AttachmentDownload{}, ErrStorageUnavailable
|
||||
}
|
||||
if variantName == "" {
|
||||
variantName = "original"
|
||||
}
|
||||
key := attachment.ObjectKey
|
||||
contentType := attachment.ContentType
|
||||
sizeBytes := attachment.SizeBytes
|
||||
filename := attachment.Filename
|
||||
if variantName != "original" {
|
||||
found := false
|
||||
for _, variant := range attachment.Variants {
|
||||
if variant.Name == variantName {
|
||||
key = variant.ObjectKey
|
||||
contentType = variant.ContentType
|
||||
sizeBytes = variant.SizeBytes
|
||||
filename = variant.Name + ".jpg"
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return AttachmentDownload{}, domain.ErrNotFound
|
||||
}
|
||||
}
|
||||
object, err := s.objectStore.Get(ctx, key)
|
||||
if err != nil {
|
||||
return AttachmentDownload{}, fmt.Errorf("%w: get object", ErrStorageUnavailable)
|
||||
}
|
||||
if object.Body == nil || object.SizeBytes != sizeBytes {
|
||||
if object.Body != nil {
|
||||
_ = object.Body.Close()
|
||||
}
|
||||
return AttachmentDownload{}, fmt.Errorf("%w: object metadata mismatch", ErrStorageUnavailable)
|
||||
}
|
||||
return AttachmentDownload{Body: object.Body, ContentType: contentType, Filename: filename, SizeBytes: sizeBytes}, nil
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"image"
|
||||
_ "image/jpeg"
|
||||
_ "image/png"
|
||||
"io"
|
||||
"os"
|
||||
|
||||
"mtusi2026lab7/internal/domain"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
)
|
||||
|
||||
const currentAttachmentPipelineVersion = 1
|
||||
|
||||
func (s *Service) UploadAttachment(ctx context.Context, command UploadAttachmentCommand) (domain.Attachment, error) {
|
||||
if s.objectStore == nil {
|
||||
return domain.Attachment{}, ErrStorageUnavailable
|
||||
}
|
||||
queueRepository, ok := s.repository.(AttachmentQueueRepository)
|
||||
if !ok {
|
||||
return domain.Attachment{}, fmt.Errorf("attachment queue repository is not configured")
|
||||
}
|
||||
if command.Body == nil {
|
||||
return domain.Attachment{}, fmt.Errorf("%w: attachment body is required", ErrInvalidInput)
|
||||
}
|
||||
if err := domain.ValidateAttachmentFilename(command.Filename); err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("%w: %v", ErrInvalidInput, err)
|
||||
}
|
||||
if err := domain.ValidateAttachmentContentType(command.DeclaredContentType); err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("%w: %v", ErrUnsupportedMediaType, err)
|
||||
}
|
||||
if _, err := s.repository.GetChatByID(ctx, command.ChatID, command.ActorID); err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
if err := acquireAttachmentSlot(ctx, s.attachmentUploadSlots); err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("%w: wait for upload capacity", ErrStorageUnavailable)
|
||||
}
|
||||
defer releaseAttachmentSlot(s.attachmentUploadSlots)
|
||||
|
||||
stagedFile, err := os.CreateTemp("", "mtusi-attachment-*")
|
||||
if err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("create bounded upload staging file: %w", err)
|
||||
}
|
||||
stagedPath := stagedFile.Name()
|
||||
defer func() {
|
||||
_ = stagedFile.Close()
|
||||
_ = os.Remove(stagedPath)
|
||||
}()
|
||||
|
||||
hasher := sha256.New()
|
||||
sizeBytes, err := io.Copy(io.MultiWriter(stagedFile, hasher), io.LimitReader(command.Body, domain.MaxAttachmentSizeBytes+1))
|
||||
if err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("%w: read attachment body", ErrInvalidInput)
|
||||
}
|
||||
if sizeBytes > domain.MaxAttachmentSizeBytes {
|
||||
return domain.Attachment{}, ErrPayloadTooLarge
|
||||
}
|
||||
if _, err = stagedFile.Seek(0, io.SeekStart); err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("rewind staged attachment: %w", err)
|
||||
}
|
||||
imageConfig, format, err := image.DecodeConfig(stagedFile)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("%w: decode image header", ErrInvalidImage)
|
||||
}
|
||||
actualContentType, supported := contentTypeForImageFormat(format)
|
||||
if !supported || actualContentType != command.DeclaredContentType {
|
||||
return domain.Attachment{}, ErrUnsupportedMediaType
|
||||
}
|
||||
if imageConfig.Width < 1 || imageConfig.Height < 1 {
|
||||
return domain.Attachment{}, ErrInvalidImage
|
||||
}
|
||||
if int64(imageConfig.Width) > int64(domain.MaxAttachmentPixels)/int64(imageConfig.Height) {
|
||||
return domain.Attachment{}, ErrPayloadTooLarge
|
||||
}
|
||||
sha256Hex := hex.EncodeToString(hasher.Sum(nil))
|
||||
if err = domain.ValidateReadyAttachmentMetadata(command.Filename, actualContentType, sizeBytes, sha256Hex, imageConfig.Width, imageConfig.Height); err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("%w: %v", ErrInvalidImage, err)
|
||||
}
|
||||
if _, err = stagedFile.Seek(0, io.SeekStart); err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("rewind staged attachment for validation: %w", err)
|
||||
}
|
||||
if err = s.validateCompleteImage(ctx, stagedFile); err != nil {
|
||||
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
|
||||
return domain.Attachment{}, fmt.Errorf("%w: wait for image decoder", ErrStorageUnavailable)
|
||||
}
|
||||
return domain.Attachment{}, fmt.Errorf("%w: decode complete image", ErrInvalidImage)
|
||||
}
|
||||
|
||||
now := s.now().UTC()
|
||||
attachmentID := uuid.NewString()
|
||||
attachment := domain.Attachment{
|
||||
ID: attachmentID,
|
||||
ChatID: command.ChatID,
|
||||
OwnerID: command.ActorID,
|
||||
Filename: command.Filename,
|
||||
ObjectKey: "attachments/" + command.ChatID + "/" + attachmentID + "/original",
|
||||
StagingKey: "staging/" + attachmentID + "/original",
|
||||
ContentType: actualContentType,
|
||||
SizeBytes: sizeBytes,
|
||||
SHA256: sha256Hex,
|
||||
Width: imageConfig.Width,
|
||||
Height: imageConfig.Height,
|
||||
PipelineVersion: currentAttachmentPipelineVersion,
|
||||
Status: domain.AttachmentStatusQueued,
|
||||
Variants: make([]domain.AttachmentVariant, 0),
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
}
|
||||
if _, err = stagedFile.Seek(0, io.SeekStart); err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("rewind staged attachment for storage: %w", err)
|
||||
}
|
||||
if err = s.objectStore.Put(ctx, ObjectPut{Key: attachment.StagingKey, ContentType: attachment.ContentType, SizeBytes: attachment.SizeBytes, Body: stagedFile}); err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("%w: put durable staging object", ErrStorageUnavailable)
|
||||
}
|
||||
traceCarrier := propagation.MapCarrier{}
|
||||
otel.GetTextMapPropagator().Inject(ctx, traceCarrier)
|
||||
job := domain.AttachmentJob{
|
||||
SchemaVersion: 1,
|
||||
JobID: uuid.NewString(),
|
||||
Type: domain.AttachmentJobType,
|
||||
AttachmentID: attachment.ID,
|
||||
PipelineVersion: attachment.PipelineVersion,
|
||||
Attempt: 1,
|
||||
MaxAttempts: s.jobMaxAttempts,
|
||||
Status: domain.AttachmentJobQueued,
|
||||
AvailableAt: now,
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
TraceParent: traceCarrier.Get("traceparent"),
|
||||
TraceState: traceCarrier.Get("tracestate"),
|
||||
}
|
||||
attachment, err = queueRepository.CreateQueuedAttachment(ctx, attachment, job)
|
||||
if err != nil {
|
||||
// A failed COMMIT response is ambiguous. Preserve staging so a committed
|
||||
// job can still finish and an uncommitted orphan can be retained/cleaned.
|
||||
return domain.Attachment{}, fmt.Errorf("persist queued attachment: %w", err)
|
||||
}
|
||||
if attachment.Variants == nil {
|
||||
attachment.Variants = make([]domain.AttachmentVariant, 0)
|
||||
}
|
||||
return attachment, nil
|
||||
}
|
||||
|
||||
func acquireAttachmentSlot(ctx context.Context, slots chan struct{}) error {
|
||||
select {
|
||||
case slots <- struct{}{}:
|
||||
return nil
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
func releaseAttachmentSlot(slots chan struct{}) { <-slots }
|
||||
|
||||
func (s *Service) validateCompleteImage(ctx context.Context, body io.Reader) error {
|
||||
if err := acquireAttachmentSlot(ctx, s.attachmentDecodeSlots); err != nil {
|
||||
return err
|
||||
}
|
||||
defer releaseAttachmentSlot(s.attachmentDecodeSlots)
|
||||
_, _, err := image.Decode(body)
|
||||
return err
|
||||
}
|
||||
|
||||
func contentTypeForImageFormat(format string) (string, bool) {
|
||||
switch format {
|
||||
case "png":
|
||||
return "image/png", true
|
||||
case "jpeg":
|
||||
return "image/jpeg", true
|
||||
default:
|
||||
return "", false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
package application_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/png"
|
||||
"io"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab7/internal/adapter/memory"
|
||||
. "mtusi2026lab7/internal/application"
|
||||
"mtusi2026lab7/internal/domain"
|
||||
)
|
||||
|
||||
type fakeObjectStore struct {
|
||||
mu sync.Mutex
|
||||
objects map[string][]byte
|
||||
putError error
|
||||
}
|
||||
|
||||
func newFakeObjectStore() *fakeObjectStore { return &fakeObjectStore{objects: make(map[string][]byte)} }
|
||||
func (store *fakeObjectStore) Put(_ context.Context, object ObjectPut) error {
|
||||
if store.putError != nil {
|
||||
return store.putError
|
||||
}
|
||||
payload, err := io.ReadAll(object.Body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
store.mu.Lock()
|
||||
store.objects[object.Key] = payload
|
||||
store.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
func (store *fakeObjectStore) Get(_ context.Context, key string) (ObjectContent, error) {
|
||||
store.mu.Lock()
|
||||
defer store.mu.Unlock()
|
||||
payload, ok := store.objects[key]
|
||||
if !ok {
|
||||
return ObjectContent{}, errors.New("not found")
|
||||
}
|
||||
return ObjectContent{Body: io.NopCloser(bytes.NewReader(payload)), SizeBytes: int64(len(payload))}, nil
|
||||
}
|
||||
func (store *fakeObjectStore) Delete(_ context.Context, key string) error {
|
||||
store.mu.Lock()
|
||||
delete(store.objects, key)
|
||||
store.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
type interruptedReader struct{}
|
||||
|
||||
func (interruptedReader) Read([]byte) (int, error) { return 0, errors.New("injected read failure") }
|
||||
|
||||
func newAttachmentService(t *testing.T, objects ObjectStore) (*Service, string, string) {
|
||||
t.Helper()
|
||||
legacy := memory.NewMemoryStore()
|
||||
repository := memory.NewMemoryRepository(legacy)
|
||||
user, err := repository.CreateUser(context.Background(), "uploader", "Uploader", "hash")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
chat, err := repository.CreateChat(context.Background(), "Images", []string{user.ID})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
codec, err := NewCursorCodec("attachment-test-key-with-more-than-thirty-two-bytes")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service, err := NewService(repository, codec, time.Hour, WithObjectStore(objects), WithJobMaxAttempts(5))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return service, user.ID, chat.ID
|
||||
}
|
||||
|
||||
func testPNG(t *testing.T) []byte {
|
||||
t.Helper()
|
||||
var payload bytes.Buffer
|
||||
img := image.NewRGBA(image.Rect(0, 0, 320, 200))
|
||||
img.Set(0, 0, color.RGBA{R: 255, A: 255})
|
||||
if err := png.Encode(&payload, img); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return payload.Bytes()
|
||||
}
|
||||
|
||||
func TestUploadAttachmentDurablyQueuesStagingObject(t *testing.T) {
|
||||
objects := newFakeObjectStore()
|
||||
service, actorID, chatID := newAttachmentService(t, objects)
|
||||
payload := testPNG(t)
|
||||
attachment, err := service.UploadAttachment(context.Background(), UploadAttachmentCommand{
|
||||
ActorID: actorID, ChatID: chatID, Filename: "photo.png",
|
||||
DeclaredContentType: "image/png", Body: bytes.NewReader(payload),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if attachment.Status != domain.AttachmentStatusQueued {
|
||||
t.Fatalf("status=%s, want queued", attachment.Status)
|
||||
}
|
||||
if attachment.StagingKey == "" || attachment.ObjectKey == attachment.StagingKey {
|
||||
t.Fatalf("staging/final keys are not separated: %+v", attachment)
|
||||
}
|
||||
objects.mu.Lock()
|
||||
staged := append([]byte(nil), objects.objects[attachment.StagingKey]...)
|
||||
objects.mu.Unlock()
|
||||
if !bytes.Equal(staged, payload) {
|
||||
t.Fatal("durable staging bytes differ")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUploadAttachmentRejectsInvalidInputBeforeStaging(t *testing.T) {
|
||||
objects := newFakeObjectStore()
|
||||
service, actorID, chatID := newAttachmentService(t, objects)
|
||||
cases := []struct {
|
||||
name string
|
||||
command UploadAttachmentCommand
|
||||
target error
|
||||
}{
|
||||
{"unsafe filename", UploadAttachmentCommand{ActorID: actorID, ChatID: chatID, Filename: "../x.png", DeclaredContentType: "image/png", Body: bytes.NewReader(testPNG(t))}, ErrInvalidInput},
|
||||
{"mime", UploadAttachmentCommand{ActorID: actorID, ChatID: chatID, Filename: "x.png", DeclaredContentType: "image/jpeg", Body: bytes.NewReader(testPNG(t))}, ErrUnsupportedMediaType},
|
||||
{"corrupt", UploadAttachmentCommand{ActorID: actorID, ChatID: chatID, Filename: "x.png", DeclaredContentType: "image/png", Body: bytes.NewReader([]byte("broken"))}, ErrInvalidImage},
|
||||
{"interrupted", UploadAttachmentCommand{ActorID: actorID, ChatID: chatID, Filename: "x.png", DeclaredContentType: "image/png", Body: interruptedReader{}}, ErrInvalidInput},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if _, err := service.UploadAttachment(context.Background(), tc.command); !errors.Is(err, tc.target) {
|
||||
t.Fatalf("error=%v, want %v", err, tc.target)
|
||||
}
|
||||
})
|
||||
}
|
||||
objects.mu.Lock()
|
||||
count := len(objects.objects)
|
||||
objects.mu.Unlock()
|
||||
if count != 0 {
|
||||
t.Fatalf("invalid requests staged %d objects", count)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUploadAttachmentStorageFailureDoesNotCreateQueuedMetadata(t *testing.T) {
|
||||
objects := newFakeObjectStore()
|
||||
objects.putError = errors.New("storage down")
|
||||
service, actorID, chatID := newAttachmentService(t, objects)
|
||||
_, err := service.UploadAttachment(context.Background(), UploadAttachmentCommand{ActorID: actorID, ChatID: chatID, Filename: "x.png", DeclaredContentType: "image/png", Body: bytes.NewReader(testPNG(t))})
|
||||
if !errors.Is(err, ErrStorageUnavailable) {
|
||||
t.Fatalf("error=%v, want storage unavailable", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"mtusi2026lab7/internal/domain"
|
||||
)
|
||||
|
||||
func (s *Service) CreateChat(ctx context.Context, command CreateChatCommand) (domain.Chat, error) {
|
||||
if err := domain.ValidateChatInput(command.Title, command.MemberIDs, command.ActorID); err != nil {
|
||||
return domain.Chat{}, fmt.Errorf("%w: %v", ErrInvalidInput, err)
|
||||
}
|
||||
return s.repository.CreateChat(ctx, command.Title, command.MemberIDs)
|
||||
}
|
||||
|
||||
func (s *Service) GetChat(ctx context.Context, actorID, chatID string) (domain.Chat, error) {
|
||||
return s.repository.GetChatByID(ctx, chatID, actorID)
|
||||
}
|
||||
|
||||
func (s *Service) ListChats(
|
||||
ctx context.Context,
|
||||
actorID string,
|
||||
limit int,
|
||||
cursorToken string,
|
||||
) (domain.ChatPage, error) {
|
||||
var cursor *domain.ChatCursor
|
||||
if cursorToken != "" {
|
||||
decoded, err := s.cursors.DecodeChat(cursorToken, actorID)
|
||||
if err != nil {
|
||||
return domain.ChatPage{}, ErrInvalidCursor
|
||||
}
|
||||
cursor = decoded
|
||||
}
|
||||
|
||||
items, hasMore, err := s.repository.GetChatsForUser(ctx, actorID, limit, cursor)
|
||||
if err != nil {
|
||||
return domain.ChatPage{}, err
|
||||
}
|
||||
page := domain.ChatPage{Items: items}
|
||||
if page.Items == nil {
|
||||
page.Items = make([]domain.Chat, 0)
|
||||
}
|
||||
if hasMore {
|
||||
last := page.Items[len(page.Items)-1]
|
||||
next, encodeErr := s.cursors.EncodeChat(domain.ChatCursor{
|
||||
CreatedAt: last.CreatedAt, ChatID: last.ID, UserID: actorID,
|
||||
})
|
||||
if encodeErr != nil {
|
||||
return domain.ChatPage{}, encodeErr
|
||||
}
|
||||
page.NextCursor = &next
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package application
|
||||
|
||||
import "io"
|
||||
|
||||
type CreateUserCommand struct {
|
||||
Username string
|
||||
DisplayName string
|
||||
Password string
|
||||
}
|
||||
|
||||
type CreateSessionCommand struct {
|
||||
Username string
|
||||
Password string
|
||||
}
|
||||
|
||||
type CreateChatCommand struct {
|
||||
ActorID string
|
||||
Title string
|
||||
MemberIDs []string
|
||||
}
|
||||
|
||||
type SendMessageCommand struct {
|
||||
ActorID string
|
||||
ChatID string
|
||||
Text string
|
||||
AttachmentIDs []string
|
||||
Method string
|
||||
CanonicalPath string
|
||||
IdempotencyKey string
|
||||
}
|
||||
|
||||
type UploadAttachmentCommand struct {
|
||||
ActorID string
|
||||
ChatID string
|
||||
Filename string
|
||||
DeclaredContentType string
|
||||
Body io.Reader
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab7/internal/domain"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const cursorVersion = 1
|
||||
|
||||
type CursorCodec struct {
|
||||
key []byte
|
||||
}
|
||||
|
||||
type cursorPayload struct {
|
||||
Version int `json:"v"`
|
||||
Kind string `json:"kind"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
ID string `json:"id"`
|
||||
ScopeID string `json:"scope_id"`
|
||||
}
|
||||
|
||||
func NewCursorCodec(key string) (*CursorCodec, error) {
|
||||
if len(key) < 32 {
|
||||
return nil, fmt.Errorf("cursor signing key must contain at least 32 bytes")
|
||||
}
|
||||
return &CursorCodec{key: []byte(key)}, nil
|
||||
}
|
||||
|
||||
func (c *CursorCodec) EncodeChat(cursor domain.ChatCursor) (string, error) {
|
||||
return c.encode(cursorPayload{
|
||||
Version: cursorVersion, Kind: "chat", CreatedAt: cursor.CreatedAt.UTC().Format(time.RFC3339Nano),
|
||||
ID: cursor.ChatID, ScopeID: cursor.UserID,
|
||||
})
|
||||
}
|
||||
|
||||
func (c *CursorCodec) DecodeChat(token, expectedUserID string) (*domain.ChatCursor, error) {
|
||||
payload, err := c.decode(token, "chat", expectedUserID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &domain.ChatCursor{CreatedAt: payload.createdAt, ChatID: payload.id, UserID: payload.scopeID}, nil
|
||||
}
|
||||
|
||||
func (c *CursorCodec) EncodeMessage(cursor domain.MessageCursor) (string, error) {
|
||||
return c.encode(cursorPayload{
|
||||
Version: cursorVersion, Kind: "message", CreatedAt: cursor.CreatedAt.UTC().Format(time.RFC3339Nano),
|
||||
ID: cursor.MessageID, ScopeID: cursor.ChatID,
|
||||
})
|
||||
}
|
||||
|
||||
func (c *CursorCodec) DecodeMessage(token, expectedChatID string) (*domain.MessageCursor, error) {
|
||||
payload, err := c.decode(token, "message", expectedChatID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &domain.MessageCursor{CreatedAt: payload.createdAt, MessageID: payload.id, ChatID: payload.scopeID}, nil
|
||||
}
|
||||
|
||||
func (c *CursorCodec) encode(payload cursorPayload) (string, error) {
|
||||
encodedPayload, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("encode cursor payload: %w", err)
|
||||
}
|
||||
mac := hmac.New(sha256.New, c.key)
|
||||
_, _ = mac.Write(encodedPayload)
|
||||
return base64.RawURLEncoding.EncodeToString(encodedPayload) + "." +
|
||||
base64.RawURLEncoding.EncodeToString(mac.Sum(nil)), nil
|
||||
}
|
||||
|
||||
type decodedCursor struct {
|
||||
createdAt time.Time
|
||||
id string
|
||||
scopeID string
|
||||
}
|
||||
|
||||
func (c *CursorCodec) decode(token, expectedKind, expectedScopeID string) (decodedCursor, error) {
|
||||
parts := strings.Split(token, ".")
|
||||
if len(parts) != 2 {
|
||||
return decodedCursor{}, ErrInvalidCursor
|
||||
}
|
||||
payloadBytes, err := base64.RawURLEncoding.DecodeString(parts[0])
|
||||
if err != nil {
|
||||
return decodedCursor{}, ErrInvalidCursor
|
||||
}
|
||||
signature, err := base64.RawURLEncoding.DecodeString(parts[1])
|
||||
if err != nil {
|
||||
return decodedCursor{}, ErrInvalidCursor
|
||||
}
|
||||
mac := hmac.New(sha256.New, c.key)
|
||||
_, _ = mac.Write(payloadBytes)
|
||||
if !hmac.Equal(signature, mac.Sum(nil)) {
|
||||
return decodedCursor{}, ErrInvalidCursor
|
||||
}
|
||||
|
||||
var payload cursorPayload
|
||||
if err = json.Unmarshal(payloadBytes, &payload); err != nil ||
|
||||
payload.Version != cursorVersion || payload.Kind != expectedKind ||
|
||||
payload.ScopeID != expectedScopeID {
|
||||
return decodedCursor{}, ErrInvalidCursor
|
||||
}
|
||||
createdAt, err := time.Parse(time.RFC3339Nano, payload.CreatedAt)
|
||||
if err != nil {
|
||||
return decodedCursor{}, ErrInvalidCursor
|
||||
}
|
||||
if _, err = uuid.Parse(payload.ID); err != nil {
|
||||
return decodedCursor{}, ErrInvalidCursor
|
||||
}
|
||||
if _, err = uuid.Parse(payload.ScopeID); err != nil {
|
||||
return decodedCursor{}, ErrInvalidCursor
|
||||
}
|
||||
return decodedCursor{createdAt: createdAt.UTC(), id: payload.ID, scopeID: payload.ScopeID}, nil
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab7/internal/domain"
|
||||
)
|
||||
|
||||
const cursorTestKey = "cursor-test-key-with-more-than-thirty-two-bytes"
|
||||
|
||||
func TestCursorCodecRoundTrip(t *testing.T) {
|
||||
codec, err := NewCursorCodec(cursorTestKey)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
expected := domain.MessageCursor{
|
||||
CreatedAt: time.Date(2026, 10, 18, 12, 30, 0, 123, time.UTC),
|
||||
MessageID: "42eea32e-d9b5-4bc6-b4fc-94e9b0477adf",
|
||||
ChatID: "9fa3f49c-e62e-4209-8414-d6d5f69805bf",
|
||||
}
|
||||
token, err := codec.EncodeMessage(expected)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
actual, err := codec.DecodeMessage(token, expected.ChatID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if *actual != expected {
|
||||
t.Fatalf("cursor changed after round trip: got %#v, want %#v", *actual, expected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCursorCodecRejectsTamperingAndWrongScope(t *testing.T) {
|
||||
codec, err := NewCursorCodec(cursorTestKey)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
token, err := codec.EncodeChat(domain.ChatCursor{
|
||||
CreatedAt: time.Now().UTC(),
|
||||
ChatID: "42eea32e-d9b5-4bc6-b4fc-94e9b0477adf",
|
||||
UserID: "9fa3f49c-e62e-4209-8414-d6d5f69805bf",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
parts := strings.Split(token, ".")
|
||||
signature, err := base64.RawURLEncoding.DecodeString(parts[1])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
signature[0] ^= 1
|
||||
tampered := parts[0] + "." + base64.RawURLEncoding.EncodeToString(signature)
|
||||
if _, err = codec.DecodeChat(tampered, "9fa3f49c-e62e-4209-8414-d6d5f69805bf"); !errors.Is(err, ErrInvalidCursor) {
|
||||
t.Fatalf("tampered cursor: got %v, want ErrInvalidCursor", err)
|
||||
}
|
||||
if _, err = codec.DecodeChat(token, "e6ca4af0-69ed-4784-8ce0-ee035299fe08"); !errors.Is(err, ErrInvalidCursor) {
|
||||
t.Fatalf("wrong scope: got %v, want ErrInvalidCursor", err)
|
||||
}
|
||||
if _, err = codec.DecodeMessage(token, "9fa3f49c-e62e-4209-8414-d6d5f69805bf"); !errors.Is(err, ErrInvalidCursor) {
|
||||
t.Fatalf("wrong cursor kind: got %v, want ErrInvalidCursor", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCursorCodecRequiresStrongSharedKey(t *testing.T) {
|
||||
if _, err := NewCursorCodec("too-short"); err == nil {
|
||||
t.Fatal("expected short cursor signing key to be rejected")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCursorCodecRejectsSignedInvalidFieldTypesBeforeSQL(t *testing.T) {
|
||||
codec, err := NewCursorCodec(cursorTestKey)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
chatID := "9fa3f49c-e62e-4209-8414-d6d5f69805bf"
|
||||
validMessageID := "42eea32e-d9b5-4bc6-b4fc-94e9b0477adf"
|
||||
testCases := []cursorPayload{
|
||||
{Version: cursorVersion, Kind: "message", CreatedAt: "not-a-time", ID: validMessageID, ScopeID: chatID},
|
||||
{Version: cursorVersion, Kind: "message", CreatedAt: time.Now().UTC().Format(time.RFC3339Nano), ID: "not-a-uuid", ScopeID: chatID},
|
||||
}
|
||||
for _, payload := range testCases {
|
||||
token, encodeErr := codec.encode(payload)
|
||||
if encodeErr != nil {
|
||||
t.Fatal(encodeErr)
|
||||
}
|
||||
if _, decodeErr := codec.DecodeMessage(token, chatID); !errors.Is(decodeErr, ErrInvalidCursor) {
|
||||
t.Fatalf("invalid signed cursor returned %v, want ErrInvalidCursor", decodeErr)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package application
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrInvalidCursor = errors.New("invalid cursor")
|
||||
ErrInvalidCredentials = errors.New("invalid credentials")
|
||||
ErrInvalidInput = errors.New("invalid input")
|
||||
ErrCredentialState = errors.New("invalid stored credential state")
|
||||
ErrIdempotencyConflict = errors.New("idempotency key is already used for another request")
|
||||
ErrAttachmentNotReady = errors.New("attachment is not ready")
|
||||
ErrPayloadTooLarge = errors.New("payload too large")
|
||||
ErrUnsupportedMediaType = errors.New("unsupported media type")
|
||||
ErrInvalidImage = errors.New("invalid image")
|
||||
ErrStorageUnavailable = errors.New("object storage unavailable")
|
||||
)
|
||||
@@ -0,0 +1,88 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"mtusi2026lab7/internal/domain"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type canonicalMessageRequest struct {
|
||||
Text string `json:"text"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
}
|
||||
|
||||
func (s *Service) SendMessage(ctx context.Context, command SendMessageCommand) (domain.Message, error) {
|
||||
attachmentIDs := append([]string(nil), command.AttachmentIDs...)
|
||||
if attachmentIDs == nil {
|
||||
attachmentIDs = make([]string, 0)
|
||||
}
|
||||
|
||||
if err := domain.ValidateMessageInput(command.Text, attachmentIDs); err != nil {
|
||||
return domain.Message{}, fmt.Errorf("%w: %v", ErrInvalidInput, err)
|
||||
}
|
||||
for index, attachmentID := range attachmentIDs {
|
||||
attachmentIDs[index] = uuid.MustParse(attachmentID).String()
|
||||
}
|
||||
|
||||
canonicalBody, err := json.Marshal(canonicalMessageRequest{
|
||||
Text: command.Text,
|
||||
AttachmentIDs: attachmentIDs,
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Message{}, fmt.Errorf("canonicalize message request: %w", err)
|
||||
}
|
||||
|
||||
return s.repository.CreateMessageIdempotently(ctx, IdempotentMessageWrite{
|
||||
ActorID: command.ActorID,
|
||||
ChatID: command.ChatID,
|
||||
Text: command.Text,
|
||||
AttachmentIDs: attachmentIDs,
|
||||
Method: command.Method,
|
||||
CanonicalPath: command.CanonicalPath,
|
||||
Key: command.IdempotencyKey,
|
||||
RequestHash: sha256.Sum256(canonicalBody),
|
||||
TTL: s.idempotencyTTL,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) ListMessages(
|
||||
ctx context.Context,
|
||||
actorID string,
|
||||
chatID string,
|
||||
limit int,
|
||||
cursorToken string,
|
||||
) (domain.MessagePage, error) {
|
||||
var cursor *domain.MessageCursor
|
||||
if cursorToken != "" {
|
||||
decoded, err := s.cursors.DecodeMessage(cursorToken, chatID)
|
||||
if err != nil {
|
||||
return domain.MessagePage{}, ErrInvalidCursor
|
||||
}
|
||||
cursor = decoded
|
||||
}
|
||||
|
||||
items, hasMore, err := s.repository.GetMessages(ctx, chatID, actorID, limit, cursor)
|
||||
if err != nil {
|
||||
return domain.MessagePage{}, err
|
||||
}
|
||||
page := domain.MessagePage{Items: items}
|
||||
if page.Items == nil {
|
||||
page.Items = make([]domain.Message, 0)
|
||||
}
|
||||
if hasMore {
|
||||
last := page.Items[len(page.Items)-1]
|
||||
next, encodeErr := s.cursors.EncodeMessage(domain.MessageCursor{
|
||||
CreatedAt: last.CreatedAt, MessageID: last.ID, ChatID: chatID,
|
||||
})
|
||||
if encodeErr != nil {
|
||||
return domain.MessagePage{}, encodeErr
|
||||
}
|
||||
page.NextCursor = &next
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab7/internal/domain"
|
||||
)
|
||||
|
||||
type UserRepository interface {
|
||||
CreateUser(ctx context.Context, username, displayName, passwordHash string) (domain.User, error)
|
||||
GetUserByUsername(ctx context.Context, username string) (domain.User, string, error)
|
||||
UpdatePasswordHash(ctx context.Context, userID, previousHash, newHash string) error
|
||||
}
|
||||
|
||||
type SessionRepository interface {
|
||||
CreateSession(ctx context.Context, tokenHash []byte, userID string, expiresAt time.Time) error
|
||||
GetUserBySession(ctx context.Context, tokenHash []byte) (domain.User, error)
|
||||
DeleteSession(ctx context.Context, tokenHash []byte) error
|
||||
}
|
||||
|
||||
type ChatRepository interface {
|
||||
CreateChat(ctx context.Context, title string, memberIDs []string) (domain.Chat, error)
|
||||
GetChatByID(ctx context.Context, chatID, callerID string) (domain.Chat, error)
|
||||
GetChatsForUser(ctx context.Context, userID string, limit int, cursor *domain.ChatCursor) ([]domain.Chat, bool, error)
|
||||
}
|
||||
|
||||
type IdempotentMessageWrite struct {
|
||||
ActorID string
|
||||
ChatID string
|
||||
Text string
|
||||
AttachmentIDs []string
|
||||
Method string
|
||||
CanonicalPath string
|
||||
Key string
|
||||
RequestHash [32]byte
|
||||
TTL time.Duration
|
||||
}
|
||||
|
||||
type MessageRepository interface {
|
||||
CreateMessageIdempotently(ctx context.Context, write IdempotentMessageWrite) (domain.Message, error)
|
||||
GetMessages(ctx context.Context, chatID, callerID string, limit int, cursor *domain.MessageCursor) ([]domain.Message, bool, error)
|
||||
}
|
||||
|
||||
type AttachmentRepository interface {
|
||||
CreateAttachment(ctx context.Context, attachment domain.Attachment) (domain.Attachment, error)
|
||||
MarkAttachmentReady(ctx context.Context, attachmentID string, updatedAt time.Time) (domain.Attachment, error)
|
||||
MarkAttachmentFailed(ctx context.Context, attachmentID, errorCode string, updatedAt time.Time) error
|
||||
GetAttachment(ctx context.Context, attachmentID, callerID string) (domain.Attachment, error)
|
||||
}
|
||||
|
||||
type AttachmentQueueRepository interface {
|
||||
CreateQueuedAttachment(ctx context.Context, attachment domain.Attachment, job domain.AttachmentJob) (domain.Attachment, error)
|
||||
}
|
||||
|
||||
type Repository interface {
|
||||
UserRepository
|
||||
SessionRepository
|
||||
ChatRepository
|
||||
MessageRepository
|
||||
AttachmentRepository
|
||||
}
|
||||
|
||||
type ObjectPut struct {
|
||||
Key string
|
||||
ContentType string
|
||||
SizeBytes int64
|
||||
Body io.Reader
|
||||
}
|
||||
|
||||
type ObjectContent struct {
|
||||
Body io.ReadCloser
|
||||
SizeBytes int64
|
||||
}
|
||||
|
||||
type ObjectStore interface {
|
||||
Put(ctx context.Context, object ObjectPut) error
|
||||
Get(ctx context.Context, key string) (ObjectContent, error)
|
||||
Delete(ctx context.Context, key string) error
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
const MinimumIdempotencyTTL = 24 * time.Hour
|
||||
const defaultAttachmentCleanupTimeout = time.Second
|
||||
const defaultAttachmentUploadConcurrency = 4
|
||||
const defaultAttachmentDecodeConcurrency = 1
|
||||
const defaultJobMaxAttempts = 5
|
||||
|
||||
type ServiceOption func(*Service) error
|
||||
|
||||
type Service struct {
|
||||
repository Repository
|
||||
cursors *CursorCodec
|
||||
sessionTTL time.Duration
|
||||
idempotencyTTL time.Duration
|
||||
now func() time.Time
|
||||
objectStore ObjectStore
|
||||
attachmentCleanupTimeout time.Duration
|
||||
attachmentUploadSlots chan struct{}
|
||||
attachmentDecodeSlots chan struct{}
|
||||
jobMaxAttempts int
|
||||
}
|
||||
|
||||
func NewService(repository Repository, cursors *CursorCodec, sessionTTL time.Duration, options ...ServiceOption) (*Service, error) {
|
||||
if repository == nil {
|
||||
return nil, fmt.Errorf("repository is required")
|
||||
}
|
||||
if cursors == nil {
|
||||
return nil, fmt.Errorf("cursor codec is required")
|
||||
}
|
||||
if sessionTTL <= 0 {
|
||||
return nil, fmt.Errorf("session TTL must be positive")
|
||||
}
|
||||
service := &Service{
|
||||
repository: repository,
|
||||
cursors: cursors,
|
||||
sessionTTL: sessionTTL,
|
||||
idempotencyTTL: MinimumIdempotencyTTL,
|
||||
now: func() time.Time { return time.Now().UTC() },
|
||||
attachmentCleanupTimeout: defaultAttachmentCleanupTimeout,
|
||||
attachmentUploadSlots: make(chan struct{}, defaultAttachmentUploadConcurrency),
|
||||
attachmentDecodeSlots: make(chan struct{}, defaultAttachmentDecodeConcurrency),
|
||||
jobMaxAttempts: defaultJobMaxAttempts,
|
||||
}
|
||||
for _, option := range options {
|
||||
if err := option(service); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return service, nil
|
||||
}
|
||||
|
||||
func WithIdempotencyTTL(ttl time.Duration) ServiceOption {
|
||||
return func(service *Service) error {
|
||||
if ttl < MinimumIdempotencyTTL {
|
||||
return fmt.Errorf("idempotency TTL must be at least %s", MinimumIdempotencyTTL)
|
||||
}
|
||||
service.idempotencyTTL = ttl
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func WithObjectStore(objectStore ObjectStore) ServiceOption {
|
||||
return func(service *Service) error {
|
||||
if objectStore == nil {
|
||||
return fmt.Errorf("object store is required")
|
||||
}
|
||||
service.objectStore = objectStore
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func WithJobMaxAttempts(attempts int) ServiceOption {
|
||||
return func(service *Service) error {
|
||||
if attempts < 1 {
|
||||
return fmt.Errorf("job max attempts must be positive")
|
||||
}
|
||||
service.jobMaxAttempts = attempts
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"mtusi2026lab7/internal/domain"
|
||||
"mtusi2026lab7/internal/security"
|
||||
)
|
||||
|
||||
const dummyPasswordHash = "$argon2id$v=19$m=19456,t=2,p=1$" +
|
||||
"AAAAAAAAAAAAAAAAAAAAAA$" +
|
||||
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
|
||||
|
||||
func (s *Service) CreateSession(ctx context.Context, command CreateSessionCommand) (domain.Session, error) {
|
||||
user, passwordHash, err := s.repository.GetUserByUsername(ctx, command.Username)
|
||||
userNotFound := errors.Is(err, domain.ErrNotFound)
|
||||
if userNotFound {
|
||||
passwordHash = dummyPasswordHash
|
||||
} else if err != nil {
|
||||
return domain.Session{}, err
|
||||
}
|
||||
|
||||
passwordMatches, verifyErr := security.VerifyPassword(command.Password, passwordHash)
|
||||
if verifyErr != nil {
|
||||
return domain.Session{}, fmt.Errorf("%w: %v", ErrCredentialState, verifyErr)
|
||||
}
|
||||
if userNotFound || !passwordMatches {
|
||||
return domain.Session{}, ErrInvalidCredentials
|
||||
}
|
||||
needsRehash, rehashErr := security.NeedsPasswordRehash(passwordHash)
|
||||
if rehashErr != nil {
|
||||
return domain.Session{}, fmt.Errorf("%w: password hash policy", ErrCredentialState)
|
||||
}
|
||||
if needsRehash {
|
||||
newHash, hashErr := security.HashPassword(command.Password)
|
||||
if hashErr != nil {
|
||||
return domain.Session{}, fmt.Errorf("%w: password rehash", ErrCredentialState)
|
||||
}
|
||||
if updateErr := s.repository.UpdatePasswordHash(ctx, user.ID, passwordHash, newHash); updateErr != nil {
|
||||
return domain.Session{}, fmt.Errorf("%w: password rehash update", ErrCredentialState)
|
||||
}
|
||||
}
|
||||
|
||||
token, tokenHash, err := security.GenerateSessionToken()
|
||||
if err != nil {
|
||||
return domain.Session{}, fmt.Errorf("generate session token: %w", err)
|
||||
}
|
||||
expiresAt := s.now().Add(s.sessionTTL)
|
||||
if err = s.repository.CreateSession(ctx, tokenHash, user.ID, expiresAt); err != nil {
|
||||
return domain.Session{}, err
|
||||
}
|
||||
return domain.Session{
|
||||
Token: token, TokenType: "Bearer", ExpiresAt: expiresAt, User: user,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *Service) Authenticate(ctx context.Context, token string) (domain.User, []byte, error) {
|
||||
tokenHash := security.HashSessionToken(token)
|
||||
user, err := s.repository.GetUserBySession(ctx, tokenHash)
|
||||
if err != nil {
|
||||
return domain.User{}, nil, err
|
||||
}
|
||||
return user, tokenHash, nil
|
||||
}
|
||||
|
||||
func (s *Service) DeleteSession(ctx context.Context, tokenHash []byte) error {
|
||||
return s.repository.DeleteSession(ctx, tokenHash)
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"mtusi2026lab7/internal/domain"
|
||||
"mtusi2026lab7/internal/security"
|
||||
)
|
||||
|
||||
func (s *Service) CreateUser(ctx context.Context, command CreateUserCommand) (domain.User, error) {
|
||||
if err := domain.ValidateUser(command.Username, command.DisplayName); err != nil {
|
||||
return domain.User{}, fmt.Errorf("%w: %v", ErrInvalidInput, err)
|
||||
}
|
||||
if err := security.ValidatePassword(command.Password); err != nil {
|
||||
return domain.User{}, fmt.Errorf("%w: %v", ErrInvalidInput, err)
|
||||
}
|
||||
|
||||
passwordHash, err := security.HashPassword(command.Password)
|
||||
if err != nil {
|
||||
return domain.User{}, fmt.Errorf("hash password: %w", err)
|
||||
}
|
||||
return s.repository.CreateUser(
|
||||
ctx,
|
||||
command.Username,
|
||||
command.DisplayName,
|
||||
passwordHash,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,554 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
HTTPHost string
|
||||
HTTPPort string
|
||||
InstanceID string
|
||||
|
||||
SessionTTL time.Duration
|
||||
IdempotencyTTL time.Duration
|
||||
SessionCookieSecure bool
|
||||
CursorSigningKey string
|
||||
LoginRateLimit int
|
||||
LoginRateWindow time.Duration
|
||||
|
||||
DatabaseURL string
|
||||
DatabaseMaxConns int32
|
||||
DatabaseMinConns int32
|
||||
DatabaseMaxConnLifetime time.Duration
|
||||
DatabaseMaxConnIdleTime time.Duration
|
||||
DatabaseHealthCheckPeriod time.Duration
|
||||
DatabaseConnectTimeout time.Duration
|
||||
DatabaseQueryTimeout time.Duration
|
||||
|
||||
RedisURL string
|
||||
RedisCacheTTL time.Duration
|
||||
RedisOperationTimeout time.Duration
|
||||
RedisPoolSize int
|
||||
|
||||
S3Endpoint string
|
||||
S3Region string
|
||||
S3Bucket string
|
||||
S3AccessKeyID string
|
||||
S3SecretAccessKey string
|
||||
S3OperationTimeout time.Duration
|
||||
|
||||
BrokerURL string
|
||||
WorkerConcurrency int
|
||||
JobMaxAttempts int
|
||||
JobTimeout time.Duration
|
||||
JobRetryBase time.Duration
|
||||
JobRetryMax time.Duration
|
||||
JobLease time.Duration
|
||||
StagingRetention time.Duration
|
||||
StagingCleanupInterval time.Duration
|
||||
|
||||
ReadinessTimeout time.Duration
|
||||
ShutdownDrainDelay time.Duration
|
||||
ShutdownTimeout time.Duration
|
||||
}
|
||||
|
||||
func Load() (Config, error) { return load(true, true) }
|
||||
|
||||
func LoadWorker() (Config, error) { return load(false, true) }
|
||||
|
||||
func LoadDispatcher() (Config, error) { return load(false, false) }
|
||||
|
||||
func load(requireCursor, requireS3 bool) (Config, error) {
|
||||
instanceID, err := instanceIDFromEnv()
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
sessionTTL, err := secondsDurationFromEnv(
|
||||
"SESSION_TTL_SECONDS",
|
||||
3600,
|
||||
)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
idempotencyTTL, err := secondsDurationFromEnv(
|
||||
"IDEMPOTENCY_TTL_SECONDS",
|
||||
86400,
|
||||
)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
loginRateLimit, err := int32FromEnv("LOGIN_RATE_LIMIT", 5, 1)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
loginRateWindow, err := secondsDurationFromEnv("LOGIN_RATE_WINDOW_SECONDS", 60)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
sessionCookieSecure, err := boolFromEnv("SESSION_COOKIE_SECURE", false)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
databaseURL, err := requiredValueOrFile(
|
||||
"DATABASE_URL",
|
||||
"DATABASE_URL_FILE",
|
||||
)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
cursorSigningKey, err := roleValueOrFile(requireCursor,
|
||||
"CURSOR_SIGNING_KEY",
|
||||
"CURSOR_SIGNING_KEY_FILE",
|
||||
)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
s3AccessKeyID, err := roleValueOrFile(requireS3,
|
||||
"S3_ACCESS_KEY_ID",
|
||||
"S3_ACCESS_KEY_ID_FILE",
|
||||
)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
s3SecretAccessKey, err := roleValueOrFile(requireS3,
|
||||
"S3_SECRET_ACCESS_KEY",
|
||||
"S3_SECRET_ACCESS_KEY_FILE",
|
||||
)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
s3OperationTimeout, err := durationFromEnv("S3_OPERATION_TIMEOUT", 5*time.Second)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
brokerURL, err := optionalValueOrFile("BROKER_URL", "BROKER_URL_FILE")
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
workerConcurrency, err := int32FromEnv("WORKER_CONCURRENCY", 2, 1)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
jobMaxAttempts, err := int32FromEnv("JOB_MAX_ATTEMPTS", 5, 1)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
jobTimeout, err := secondsDurationFromEnv("JOB_TIMEOUT_SECONDS", 60)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
jobRetryBase, err := durationFromEnv("JOB_RETRY_BASE", 250*time.Millisecond)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
jobRetryMax, err := durationFromEnv("JOB_RETRY_MAX", 4*time.Second)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
jobLease, err := secondsDurationFromEnv("JOB_LEASE_SECONDS", 75)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
stagingRetention, err := secondsDurationFromEnv("STAGING_RETENTION_SECONDS", 86400)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
stagingCleanupInterval, err := secondsDurationFromEnv("STAGING_CLEANUP_INTERVAL_SECONDS", 30)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
databaseMaxConns, err := int32FromEnv("DB_MAX_CONNS", 10, 1)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
databaseMinConns, err := int32FromEnv("DB_MIN_CONNS", 2, 0)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
databaseMaxConnLifetime, err := durationFromEnv(
|
||||
"DB_MAX_CONN_LIFETIME",
|
||||
30*time.Minute,
|
||||
)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
databaseMaxConnIdleTime, err := durationFromEnv(
|
||||
"DB_MAX_CONN_IDLE_TIME",
|
||||
5*time.Minute,
|
||||
)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
databaseHealthCheckPeriod, err := durationFromEnv(
|
||||
"DB_HEALTH_CHECK_PERIOD",
|
||||
30*time.Second,
|
||||
)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
databaseConnectTimeout, err := durationFromEnv(
|
||||
"DB_CONNECT_TIMEOUT",
|
||||
5*time.Second,
|
||||
)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
databaseQueryTimeout, err := durationFromEnv(
|
||||
"DB_QUERY_TIMEOUT",
|
||||
3*time.Second,
|
||||
)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
redisURL, err := optionalValueOrFile("CACHE_URL", "CACHE_URL_FILE")
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
redisCacheTTL, err := durationFromEnv(
|
||||
"CACHE_TTL",
|
||||
5*time.Minute,
|
||||
)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
redisOperationTimeout, err := durationFromEnv(
|
||||
"CACHE_OPERATION_TIMEOUT",
|
||||
250*time.Millisecond,
|
||||
)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
redisPoolSize, err := int32FromEnv("CACHE_POOL_SIZE", 10, 1)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
readinessTimeout, err := durationFromEnv(
|
||||
"READINESS_TIMEOUT",
|
||||
2*time.Second,
|
||||
)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
shutdownDrainDelay, err := durationFromEnv(
|
||||
"SHUTDOWN_DRAIN_DELAY",
|
||||
2*time.Second,
|
||||
)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
shutdownTimeout, err := durationFromEnv(
|
||||
"SHUTDOWN_TIMEOUT",
|
||||
10*time.Second,
|
||||
)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
if databaseMinConns > databaseMaxConns {
|
||||
return Config{}, errors.New(
|
||||
"DB_MIN_CONNS must not be greater than DB_MAX_CONNS",
|
||||
)
|
||||
}
|
||||
|
||||
if idempotencyTTL < 24*time.Hour {
|
||||
return Config{}, errors.New(
|
||||
"IDEMPOTENCY_TTL_SECONDS must be at least 86400",
|
||||
)
|
||||
}
|
||||
|
||||
if shutdownDrainDelay >= shutdownTimeout {
|
||||
return Config{}, errors.New(
|
||||
"SHUTDOWN_DRAIN_DELAY must be less than SHUTDOWN_TIMEOUT",
|
||||
)
|
||||
}
|
||||
|
||||
if jobRetryMax < jobRetryBase {
|
||||
return Config{}, errors.New("JOB_RETRY_MAX must not be less than JOB_RETRY_BASE")
|
||||
}
|
||||
if jobLease <= jobTimeout {
|
||||
return Config{}, errors.New("JOB_LEASE_SECONDS must be greater than JOB_TIMEOUT_SECONDS")
|
||||
}
|
||||
|
||||
return Config{
|
||||
HTTPHost: envOrDefault("APP_HOST", "0.0.0.0"),
|
||||
HTTPPort: envOrDefault("APP_PORT", "8080"),
|
||||
InstanceID: instanceID,
|
||||
SessionTTL: sessionTTL,
|
||||
IdempotencyTTL: idempotencyTTL,
|
||||
SessionCookieSecure: sessionCookieSecure,
|
||||
CursorSigningKey: cursorSigningKey,
|
||||
LoginRateLimit: int(loginRateLimit),
|
||||
LoginRateWindow: loginRateWindow,
|
||||
|
||||
DatabaseURL: databaseURL,
|
||||
DatabaseMaxConns: databaseMaxConns,
|
||||
DatabaseMinConns: databaseMinConns,
|
||||
DatabaseMaxConnLifetime: databaseMaxConnLifetime,
|
||||
DatabaseMaxConnIdleTime: databaseMaxConnIdleTime,
|
||||
DatabaseHealthCheckPeriod: databaseHealthCheckPeriod,
|
||||
DatabaseConnectTimeout: databaseConnectTimeout,
|
||||
DatabaseQueryTimeout: databaseQueryTimeout,
|
||||
|
||||
RedisURL: redisURL,
|
||||
RedisCacheTTL: redisCacheTTL,
|
||||
RedisOperationTimeout: redisOperationTimeout,
|
||||
RedisPoolSize: int(redisPoolSize),
|
||||
|
||||
S3Endpoint: envOrDefault("S3_ENDPOINT", "http://minio:9000"),
|
||||
S3Region: envOrDefault("S3_REGION", "us-east-1"),
|
||||
S3Bucket: envOrDefault("S3_BUCKET", "messenger-attachments"),
|
||||
S3AccessKeyID: s3AccessKeyID,
|
||||
S3SecretAccessKey: s3SecretAccessKey,
|
||||
S3OperationTimeout: s3OperationTimeout,
|
||||
|
||||
BrokerURL: brokerURL,
|
||||
WorkerConcurrency: int(workerConcurrency),
|
||||
JobMaxAttempts: int(jobMaxAttempts),
|
||||
JobTimeout: jobTimeout,
|
||||
JobRetryBase: jobRetryBase,
|
||||
JobRetryMax: jobRetryMax,
|
||||
JobLease: jobLease,
|
||||
StagingRetention: stagingRetention,
|
||||
StagingCleanupInterval: stagingCleanupInterval,
|
||||
ReadinessTimeout: readinessTimeout,
|
||||
ShutdownDrainDelay: shutdownDrainDelay,
|
||||
ShutdownTimeout: shutdownTimeout,
|
||||
}, nil
|
||||
}
|
||||
|
||||
var instanceIDPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$`)
|
||||
|
||||
func instanceIDFromEnv() (string, error) {
|
||||
instanceID := strings.TrimSpace(os.Getenv("INSTANCE_ID"))
|
||||
if instanceID == "" {
|
||||
randomBytes := make([]byte, 6)
|
||||
if _, err := rand.Read(randomBytes); err != nil {
|
||||
return "", fmt.Errorf("generate opaque instance id: %w", err)
|
||||
}
|
||||
instanceID = "api-" + hex.EncodeToString(randomBytes)
|
||||
}
|
||||
|
||||
if !instanceIDPattern.MatchString(instanceID) {
|
||||
return "", errors.New(
|
||||
"INSTANCE_ID or hostname must match [A-Za-z0-9][A-Za-z0-9._-]{0,127}",
|
||||
)
|
||||
}
|
||||
|
||||
return instanceID, nil
|
||||
}
|
||||
|
||||
func (c Config) HTTPAddress() string {
|
||||
return net.JoinHostPort(c.HTTPHost, c.HTTPPort)
|
||||
}
|
||||
|
||||
func roleValueOrFile(required bool, valueEnv, fileEnv string) (string, error) {
|
||||
if required {
|
||||
return requiredValueOrFile(valueEnv, fileEnv)
|
||||
}
|
||||
return optionalValueOrFile(valueEnv, fileEnv)
|
||||
}
|
||||
func requiredValueOrFile(valueEnv, fileEnv string) (string, error) {
|
||||
value, valueExists := os.LookupEnv(valueEnv)
|
||||
filePath, fileExists := os.LookupEnv(fileEnv)
|
||||
|
||||
if valueExists && fileExists {
|
||||
return "", fmt.Errorf(
|
||||
"%s and %s must not be set at the same time",
|
||||
valueEnv,
|
||||
fileEnv,
|
||||
)
|
||||
}
|
||||
|
||||
if valueExists {
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "" {
|
||||
return "", fmt.Errorf("%s must not be empty", valueEnv)
|
||||
}
|
||||
|
||||
return value, nil
|
||||
}
|
||||
|
||||
if fileExists {
|
||||
filePath = strings.TrimSpace(filePath)
|
||||
if filePath == "" {
|
||||
return "", fmt.Errorf("%s must not be empty", fileEnv)
|
||||
}
|
||||
|
||||
data, err := os.ReadFile(filePath)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("read %s: %w", fileEnv, err)
|
||||
}
|
||||
|
||||
value = strings.TrimSpace(string(data))
|
||||
if value == "" {
|
||||
return "", fmt.Errorf("file from %s must not be empty", fileEnv)
|
||||
}
|
||||
|
||||
return value, nil
|
||||
}
|
||||
|
||||
return "", fmt.Errorf("%s or %s must be set", valueEnv, fileEnv)
|
||||
}
|
||||
|
||||
func optionalValueOrFile(valueEnv, fileEnv string) (string, error) {
|
||||
value, valueExists := os.LookupEnv(valueEnv)
|
||||
filePath, fileExists := os.LookupEnv(fileEnv)
|
||||
|
||||
if valueExists && fileExists {
|
||||
return "", fmt.Errorf(
|
||||
"%s and %s must not be set at the same time",
|
||||
valueEnv,
|
||||
fileEnv,
|
||||
)
|
||||
}
|
||||
|
||||
if valueExists {
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "" {
|
||||
return "", fmt.Errorf("%s must not be empty", valueEnv)
|
||||
}
|
||||
|
||||
return value, nil
|
||||
}
|
||||
|
||||
if fileExists {
|
||||
filePath = strings.TrimSpace(filePath)
|
||||
if filePath == "" {
|
||||
return "", fmt.Errorf("%s must not be empty", fileEnv)
|
||||
}
|
||||
|
||||
data, err := os.ReadFile(filePath)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("read %s: %w", fileEnv, err)
|
||||
}
|
||||
|
||||
value = strings.TrimSpace(string(data))
|
||||
if value == "" {
|
||||
return "", fmt.Errorf("file from %s must not be empty", fileEnv)
|
||||
}
|
||||
|
||||
return value, nil
|
||||
}
|
||||
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func envOrDefault(name, fallback string) string {
|
||||
value := strings.TrimSpace(os.Getenv(name))
|
||||
if value == "" {
|
||||
return fallback
|
||||
}
|
||||
|
||||
return value
|
||||
}
|
||||
|
||||
func int32FromEnv(name string, fallback, minimum int32) (int32, error) {
|
||||
raw := strings.TrimSpace(os.Getenv(name))
|
||||
if raw == "" {
|
||||
return fallback, nil
|
||||
}
|
||||
|
||||
value, err := strconv.ParseInt(raw, 10, 32)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("%s must be an integer: %w", name, err)
|
||||
}
|
||||
|
||||
if value < int64(minimum) {
|
||||
return 0, fmt.Errorf("%s must be at least %d", name, minimum)
|
||||
}
|
||||
|
||||
return int32(value), nil
|
||||
}
|
||||
|
||||
func boolFromEnv(name string, fallback bool) (bool, error) {
|
||||
raw := strings.TrimSpace(os.Getenv(name))
|
||||
if raw == "" {
|
||||
return fallback, nil
|
||||
}
|
||||
|
||||
value, err := strconv.ParseBool(raw)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("%s must be true or false: %w", name, err)
|
||||
}
|
||||
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func durationFromEnv(name string, fallback time.Duration) (time.Duration, error) {
|
||||
raw := strings.TrimSpace(os.Getenv(name))
|
||||
if raw == "" {
|
||||
return fallback, nil
|
||||
}
|
||||
|
||||
value, err := time.ParseDuration(raw)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf(
|
||||
"%s must be a Go duration such as 3s or 5m: %w",
|
||||
name,
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
if value <= 0 {
|
||||
return 0, fmt.Errorf("%s must be positive", name)
|
||||
}
|
||||
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func secondsDurationFromEnv(
|
||||
name string,
|
||||
fallbackSeconds int64,
|
||||
) (time.Duration, error) {
|
||||
raw := strings.TrimSpace(os.Getenv(name))
|
||||
if raw == "" {
|
||||
raw = strconv.FormatInt(fallbackSeconds, 10)
|
||||
}
|
||||
|
||||
seconds, err := strconv.ParseInt(raw, 10, 64)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf(
|
||||
"%s must be an integer number of seconds: %w",
|
||||
name,
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
if seconds <= 0 {
|
||||
return 0, fmt.Errorf("%s must be positive", name)
|
||||
}
|
||||
|
||||
duration, err := time.ParseDuration(raw + "s")
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("%s is too large: %w", name, err)
|
||||
}
|
||||
|
||||
return duration, nil
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package config
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestInstanceIDFromEnvironment(t *testing.T) {
|
||||
t.Setenv("INSTANCE_ID", "api-replica_01")
|
||||
|
||||
instanceID, err := instanceIDFromEnv()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if instanceID != "api-replica_01" {
|
||||
t.Fatalf("got %q, want api-replica_01", instanceID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstanceIDRejectsUnsafeHeaderValue(t *testing.T) {
|
||||
t.Setenv("INSTANCE_ID", "api-1\r\nX-Forged: true")
|
||||
|
||||
if _, err := instanceIDFromEnv(); err == nil {
|
||||
t.Fatal("expected unsafe instance ID to be rejected")
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstanceIDGeneratesOpaqueAlias(t *testing.T) {
|
||||
t.Setenv("INSTANCE_ID", "")
|
||||
|
||||
instanceID, err := instanceIDFromEnv()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if instanceID == "" {
|
||||
t.Fatal("random alias returned an empty instance ID")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package config
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestBoolFromEnv(t *testing.T) {
|
||||
t.Run("fallback", func(t *testing.T) {
|
||||
t.Setenv("TEST_BOOL", "")
|
||||
value, err := boolFromEnv("TEST_BOOL", true)
|
||||
if err != nil || !value {
|
||||
t.Fatalf("boolFromEnv() = %v, %v; want true, nil", value, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("explicit false", func(t *testing.T) {
|
||||
t.Setenv("TEST_BOOL", "false")
|
||||
value, err := boolFromEnv("TEST_BOOL", true)
|
||||
if err != nil || value {
|
||||
t.Fatalf("boolFromEnv() = %v, %v; want false, nil", value, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("invalid", func(t *testing.T) {
|
||||
t.Setenv("TEST_BOOL", "sometimes")
|
||||
_, err := boolFromEnv("TEST_BOOL", false)
|
||||
if err == nil {
|
||||
t.Fatal("boolFromEnv() error = nil, want validation error")
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"mtusi2026lab7/internal/config"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
func Open(
|
||||
ctx context.Context,
|
||||
cfg config.Config,
|
||||
) (*pgxpool.Pool, error) {
|
||||
poolConfig, err := pgxpool.ParseConfig(cfg.DatabaseURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse PostgreSQL configuration: %w", err)
|
||||
}
|
||||
|
||||
poolConfig.MaxConns = cfg.DatabaseMaxConns
|
||||
poolConfig.MinConns = cfg.DatabaseMinConns
|
||||
poolConfig.MaxConnLifetime = cfg.DatabaseMaxConnLifetime
|
||||
poolConfig.MaxConnIdleTime = cfg.DatabaseMaxConnIdleTime
|
||||
poolConfig.HealthCheckPeriod = cfg.DatabaseHealthCheckPeriod
|
||||
poolConfig.ConnConfig.Tracer = pgxQueryTracer{}
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(ctx, poolConfig)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create PostgreSQL pool: %w", err)
|
||||
}
|
||||
|
||||
// NewWithConfig создаёт структуру пула, но не гарантирует,
|
||||
// что PostgreSQL уже доступен. Ping обеспечивает fail-fast.
|
||||
if err := pool.Ping(ctx); err != nil {
|
||||
pool.Close()
|
||||
return nil, fmt.Errorf("ping PostgreSQL: %w", err)
|
||||
}
|
||||
|
||||
return pool, nil
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
type pgxQueryTracer struct{}
|
||||
|
||||
func (pgxQueryTracer) TraceAcquireStart(
|
||||
ctx context.Context,
|
||||
_ *pgxpool.Pool,
|
||||
_ pgxpool.TraceAcquireStartData,
|
||||
) context.Context {
|
||||
ctx, _ = otel.Tracer("mtusi2026lab7/postgresql").Start(
|
||||
ctx,
|
||||
"postgresql.acquire",
|
||||
trace.WithSpanKind(trace.SpanKindClient),
|
||||
trace.WithAttributes(
|
||||
attribute.String("db.system.name", "postgresql"),
|
||||
attribute.String("db.operation.name", "ACQUIRE"),
|
||||
),
|
||||
)
|
||||
return ctx
|
||||
}
|
||||
|
||||
func (pgxQueryTracer) TraceAcquireEnd(
|
||||
ctx context.Context,
|
||||
_ *pgxpool.Pool,
|
||||
data pgxpool.TraceAcquireEndData,
|
||||
) {
|
||||
span := trace.SpanFromContext(ctx)
|
||||
if data.Err != nil {
|
||||
span.SetStatus(codes.Error, "database connection acquisition failed")
|
||||
} else {
|
||||
span.SetStatus(codes.Ok, "")
|
||||
}
|
||||
span.End()
|
||||
}
|
||||
|
||||
func (pgxQueryTracer) TraceQueryStart(
|
||||
ctx context.Context,
|
||||
_ *pgx.Conn,
|
||||
data pgx.TraceQueryStartData,
|
||||
) context.Context {
|
||||
operation := databaseOperation(data.SQL)
|
||||
ctx, _ = otel.Tracer("mtusi2026lab7/postgresql").Start(
|
||||
ctx,
|
||||
"postgresql."+strings.ToLower(operation),
|
||||
trace.WithSpanKind(trace.SpanKindClient),
|
||||
trace.WithAttributes(
|
||||
attribute.String("db.system.name", "postgresql"),
|
||||
attribute.String("db.operation.name", operation),
|
||||
),
|
||||
)
|
||||
return ctx
|
||||
}
|
||||
|
||||
func (pgxQueryTracer) TraceQueryEnd(
|
||||
ctx context.Context,
|
||||
_ *pgx.Conn,
|
||||
data pgx.TraceQueryEndData,
|
||||
) {
|
||||
span := trace.SpanFromContext(ctx)
|
||||
if data.Err != nil {
|
||||
span.SetStatus(codes.Error, "database operation failed")
|
||||
} else {
|
||||
span.SetStatus(codes.Ok, "")
|
||||
}
|
||||
span.End()
|
||||
}
|
||||
|
||||
func databaseOperation(sql string) string {
|
||||
fields := strings.Fields(sql)
|
||||
if len(fields) == 0 {
|
||||
return "QUERY"
|
||||
}
|
||||
operation := strings.ToUpper(fields[0])
|
||||
switch operation {
|
||||
case "SELECT", "INSERT", "UPDATE", "DELETE", "BEGIN", "COMMIT", "ROLLBACK":
|
||||
return operation
|
||||
default:
|
||||
return "QUERY"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
const (
|
||||
MaxAttachmentFilenameCodePoints = 255
|
||||
MaxAttachmentSizeBytes = 10 * 1024 * 1024
|
||||
MaxAttachmentPixels = 40_000_000
|
||||
)
|
||||
|
||||
type AttachmentVariant struct {
|
||||
Name string
|
||||
ContentType string
|
||||
SizeBytes int64
|
||||
Width int
|
||||
Height int
|
||||
SHA256 string
|
||||
ObjectKey string
|
||||
PipelineVersion int
|
||||
}
|
||||
|
||||
type AttachmentStatus string
|
||||
|
||||
const (
|
||||
AttachmentStatusQueued AttachmentStatus = "queued"
|
||||
AttachmentStatusProcessing AttachmentStatus = "processing"
|
||||
AttachmentStatusReady AttachmentStatus = "ready"
|
||||
AttachmentStatusFailed AttachmentStatus = "failed"
|
||||
// Source-compatible alias for the lab4 reconciliation code.
|
||||
AttachmentStatusPending = AttachmentStatusQueued
|
||||
)
|
||||
|
||||
// Attachment contains metadata only. ObjectKey points to bytes in the
|
||||
// private object store and must never be derived from Filename.
|
||||
type Attachment struct {
|
||||
ID string
|
||||
ChatID string
|
||||
OwnerID string
|
||||
Filename string
|
||||
ObjectKey string
|
||||
ContentType string
|
||||
SizeBytes int64
|
||||
SHA256 string
|
||||
Width int
|
||||
Height int
|
||||
StagingKey string
|
||||
PipelineVersion int
|
||||
Status AttachmentStatus
|
||||
Variants []AttachmentVariant
|
||||
ErrorCode *string
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
func ValidateAttachmentFilename(filename string) error {
|
||||
if !utf8.ValidString(filename) {
|
||||
return fmt.Errorf("filename must be valid UTF-8")
|
||||
}
|
||||
filenameLength := utf8.RuneCountInString(filename)
|
||||
if filenameLength < 1 || filenameLength > MaxAttachmentFilenameCodePoints {
|
||||
return fmt.Errorf("filename length must be between 1 and %d code points", MaxAttachmentFilenameCodePoints)
|
||||
}
|
||||
if strings.TrimSpace(filename) == "" || filename == "." || filename == ".." {
|
||||
return fmt.Errorf("filename is unsafe")
|
||||
}
|
||||
if strings.ContainsAny(filename, `/\\`) {
|
||||
return fmt.Errorf("filename must not contain path separators")
|
||||
}
|
||||
for _, character := range filename {
|
||||
if unicode.IsControl(character) {
|
||||
return fmt.Errorf("filename must not contain control characters")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func ValidateAttachmentContentType(contentType string) error {
|
||||
if contentType != "image/png" && contentType != "image/jpeg" {
|
||||
return fmt.Errorf("content type must be image/png or image/jpeg")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ValidateReadyAttachmentMetadata checks the bounded metadata produced after
|
||||
// the upload stream has been identified, decoded and hashed. It deliberately
|
||||
// does not trust an HTTP Content-Type header.
|
||||
func ValidateReadyAttachmentMetadata(
|
||||
filename string,
|
||||
contentType string,
|
||||
sizeBytes int64,
|
||||
sha256Hex string,
|
||||
width int,
|
||||
height int,
|
||||
) error {
|
||||
if err := ValidateAttachmentFilename(filename); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := ValidateAttachmentContentType(contentType); err != nil {
|
||||
return err
|
||||
}
|
||||
if sizeBytes < 1 || sizeBytes > MaxAttachmentSizeBytes {
|
||||
return fmt.Errorf("attachment size must be between 1 and %d bytes", MaxAttachmentSizeBytes)
|
||||
}
|
||||
if width < 1 || height < 1 {
|
||||
return fmt.Errorf("image dimensions must be positive and contain at most %d pixels", MaxAttachmentPixels)
|
||||
}
|
||||
if int64(width) > int64(MaxAttachmentPixels)/int64(height) {
|
||||
return fmt.Errorf("image dimensions must be positive and contain at most %d pixels", MaxAttachmentPixels)
|
||||
}
|
||||
if len(sha256Hex) != 64 || sha256Hex != strings.ToLower(sha256Hex) {
|
||||
return fmt.Errorf("sha256 must contain 64 lowercase hexadecimal characters")
|
||||
}
|
||||
decodedHash, err := hex.DecodeString(sha256Hex)
|
||||
if err != nil || len(decodedHash) != 32 {
|
||||
return fmt.Errorf("sha256 must contain 64 lowercase hexadecimal characters")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package domain
|
||||
|
||||
import "time"
|
||||
|
||||
const AttachmentJobType = "attachment.process.v1"
|
||||
|
||||
type AttachmentJobStatus string
|
||||
|
||||
const (
|
||||
AttachmentJobQueued AttachmentJobStatus = "queued"
|
||||
AttachmentJobProcessing AttachmentJobStatus = "processing"
|
||||
AttachmentJobSucceeded AttachmentJobStatus = "succeeded"
|
||||
AttachmentJobFailed AttachmentJobStatus = "failed"
|
||||
AttachmentJobSuperseded AttachmentJobStatus = "superseded"
|
||||
)
|
||||
|
||||
type AttachmentJob struct {
|
||||
SchemaVersion int
|
||||
JobID string
|
||||
Type string
|
||||
AttachmentID string
|
||||
PipelineVersion int
|
||||
Attempt int
|
||||
MaxAttempts int
|
||||
Status AttachmentJobStatus
|
||||
ErrorCode *string
|
||||
AvailableAt time.Time
|
||||
LeaseUntil *time.Time
|
||||
LeasedBy *string
|
||||
ReplayCount int
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
TraceParent string
|
||||
TraceState string
|
||||
}
|
||||
|
||||
type AttachmentJobMessage struct {
|
||||
SchemaVersion int `json:"schema_version"`
|
||||
JobID string `json:"job_id"`
|
||||
Type string `json:"type"`
|
||||
AttachmentID string `json:"attachment_id"`
|
||||
PipelineVersion int `json:"pipeline_version"`
|
||||
Attempt int `json:"attempt"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
func (job AttachmentJob) Message() AttachmentJobMessage {
|
||||
return AttachmentJobMessage{
|
||||
SchemaVersion: job.SchemaVersion,
|
||||
JobID: job.JobID,
|
||||
Type: job.Type,
|
||||
AttachmentID: job.AttachmentID,
|
||||
PipelineVersion: job.PipelineVersion,
|
||||
Attempt: job.Attempt,
|
||||
CreatedAt: job.CreatedAt.UTC(),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"math"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestValidateReadyAttachmentMetadata(t *testing.T) {
|
||||
validHash := strings.Repeat("ab", 32)
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
filename string
|
||||
contentType string
|
||||
sizeBytes int64
|
||||
sha256 string
|
||||
width int
|
||||
height int
|
||||
wantError bool
|
||||
}{
|
||||
{name: "png", filename: "кот.png", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1},
|
||||
{name: "jpeg at limits", filename: strings.Repeat("界", 255), contentType: "image/jpeg", sizeBytes: MaxAttachmentSizeBytes, sha256: validHash, width: 8_000, height: 5_000},
|
||||
{name: "empty filename", filename: "", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true},
|
||||
{name: "blank filename", filename: " ", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true},
|
||||
{name: "dot segment", filename: "..", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true},
|
||||
{name: "forward slash", filename: "folder/image.png", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true},
|
||||
{name: "backslash", filename: `folder\\image.png`, contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true},
|
||||
{name: "control character", filename: "image\n.png", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true},
|
||||
{name: "C1 control character", filename: "image\u0085.png", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true},
|
||||
{name: "invalid UTF-8", filename: string([]byte{'x', 0xff, '.', 'p', 'n', 'g'}), contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true},
|
||||
{name: "filename too long", filename: strings.Repeat("a", 256), contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true},
|
||||
{name: "unsupported MIME", filename: "image.gif", contentType: "image/gif", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true},
|
||||
{name: "empty file", filename: "image.png", contentType: "image/png", sizeBytes: 0, sha256: validHash, width: 1, height: 1, wantError: true},
|
||||
{name: "file too large", filename: "image.png", contentType: "image/png", sizeBytes: MaxAttachmentSizeBytes + 1, sha256: validHash, width: 1, height: 1, wantError: true},
|
||||
{name: "zero width", filename: "image.png", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 0, height: 1, wantError: true},
|
||||
{name: "too many pixels", filename: "image.png", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 8_001, height: 5_000, wantError: true},
|
||||
{name: "dimension multiplication cannot overflow", filename: "image.png", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: math.MaxInt, height: math.MaxInt, wantError: true},
|
||||
{name: "short hash", filename: "image.png", contentType: "image/png", sizeBytes: 1, sha256: "ab", width: 1, height: 1, wantError: true},
|
||||
{name: "uppercase hash", filename: "image.png", contentType: "image/png", sizeBytes: 1, sha256: strings.ToUpper(validHash), width: 1, height: 1, wantError: true},
|
||||
{name: "non-hex hash", filename: "image.png", contentType: "image/png", sizeBytes: 1, sha256: strings.Repeat("zz", 32), width: 1, height: 1, wantError: true},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
err := ValidateReadyAttachmentMetadata(
|
||||
testCase.filename,
|
||||
testCase.contentType,
|
||||
testCase.sizeBytes,
|
||||
testCase.sha256,
|
||||
testCase.width,
|
||||
testCase.height,
|
||||
)
|
||||
if (err != nil) != testCase.wantError {
|
||||
t.Fatalf("ValidateReadyAttachmentMetadata() error = %v, wantError %v", err, testCase.wantError)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package domain
|
||||
|
||||
import "time"
|
||||
|
||||
type Chat struct {
|
||||
ID string
|
||||
Title string
|
||||
MemberIDs []string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type ChatCursor struct {
|
||||
CreatedAt time.Time
|
||||
ChatID string
|
||||
UserID string
|
||||
}
|
||||
|
||||
type ChatPage struct {
|
||||
Items []Chat
|
||||
NextCursor *string
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package domain
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrNotFound = errors.New("not found")
|
||||
ErrConflict = errors.New("conflict")
|
||||
)
|
||||
@@ -0,0 +1,23 @@
|
||||
package domain
|
||||
|
||||
import "time"
|
||||
|
||||
type Message struct {
|
||||
ID string
|
||||
ChatID string
|
||||
SenderID string
|
||||
Text string
|
||||
AttachmentIDs []string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type MessageCursor struct {
|
||||
CreatedAt time.Time
|
||||
MessageID string
|
||||
ChatID string
|
||||
}
|
||||
|
||||
type MessagePage struct {
|
||||
Items []Message
|
||||
NextCursor *string
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestValidateMessageInput(t *testing.T) {
|
||||
validAttachment := "11111111-1111-4111-8111-111111111111"
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
text string
|
||||
attachmentIDs []string
|
||||
wantError bool
|
||||
}{
|
||||
{name: "text only", text: "hello"},
|
||||
{name: "attachment only", attachmentIDs: []string{validAttachment}},
|
||||
{name: "whitespace with attachment", text: " ", attachmentIDs: []string{validAttachment}},
|
||||
{name: "empty", wantError: true},
|
||||
{name: "whitespace only", text: " ", wantError: true},
|
||||
{name: "text too long", text: strings.Repeat("界", 4001), wantError: true},
|
||||
{name: "invalid attachment uuid", text: "hello", attachmentIDs: []string{"not-a-uuid"}, wantError: true},
|
||||
{
|
||||
name: "duplicate attachment uuid ignores case",
|
||||
text: "hello",
|
||||
attachmentIDs: []string{
|
||||
"AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA",
|
||||
"aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
|
||||
},
|
||||
wantError: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
err := ValidateMessageInput(testCase.text, testCase.attachmentIDs)
|
||||
if (err != nil) != testCase.wantError {
|
||||
t.Fatalf("ValidateMessageInput() error = %v, wantError %v", err, testCase.wantError)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateMessageInputAttachmentLimit(t *testing.T) {
|
||||
attachmentIDs := []string{
|
||||
"00000000-0000-4000-8000-000000000001",
|
||||
"00000000-0000-4000-8000-000000000002",
|
||||
"00000000-0000-4000-8000-000000000003",
|
||||
"00000000-0000-4000-8000-000000000004",
|
||||
"00000000-0000-4000-8000-000000000005",
|
||||
"00000000-0000-4000-8000-000000000006",
|
||||
"00000000-0000-4000-8000-000000000007",
|
||||
"00000000-0000-4000-8000-000000000008",
|
||||
"00000000-0000-4000-8000-000000000009",
|
||||
"00000000-0000-4000-8000-000000000010",
|
||||
}
|
||||
|
||||
if err := ValidateMessageInput("", attachmentIDs); err != nil {
|
||||
t.Fatalf("10 attachments must be accepted: %v", err)
|
||||
}
|
||||
|
||||
attachmentIDs = append(
|
||||
attachmentIDs,
|
||||
"00000000-0000-4000-8000-000000000011",
|
||||
)
|
||||
if err := ValidateMessageInput("hello", attachmentIDs); err == nil {
|
||||
t.Fatal("11 attachments must be rejected")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package domain
|
||||
|
||||
import "time"
|
||||
|
||||
type Session struct {
|
||||
Token string
|
||||
TokenType string
|
||||
ExpiresAt time.Time
|
||||
User User
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package domain
|
||||
|
||||
import "time"
|
||||
|
||||
// User is the transport-independent representation of a messenger user.
|
||||
type User struct {
|
||||
ID string
|
||||
Username string
|
||||
DisplayName string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const MaxMessageAttachments = 10
|
||||
|
||||
var usernameRegex = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
|
||||
func ValidateUser(username, displayName string) error {
|
||||
if !usernameRegex.MatchString(username) {
|
||||
return fmt.Errorf("username must match [a-z0-9_]{3,32}")
|
||||
}
|
||||
|
||||
nameRunes := utf8.RuneCountInString(displayName)
|
||||
if nameRunes < 1 || nameRunes > 100 {
|
||||
return fmt.Errorf("display_name length must be between 1 and 100 code points")
|
||||
}
|
||||
if strings.TrimSpace(displayName) == "" {
|
||||
return fmt.Errorf("display_name cannot be only whitespace")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Validate remains as a compatibility convenience for existing callers.
|
||||
func (u User) Validate() error {
|
||||
return ValidateUser(u.Username, u.DisplayName)
|
||||
}
|
||||
|
||||
func ValidateChatInput(title string, memberIDs []string, callerID string) error {
|
||||
titleRunes := utf8.RuneCountInString(title)
|
||||
if titleRunes < 1 || titleRunes > 100 || strings.TrimSpace(title) == "" {
|
||||
return fmt.Errorf("invalid chat title")
|
||||
}
|
||||
if len(memberIDs) == 0 {
|
||||
return fmt.Errorf("member_ids cannot be empty")
|
||||
}
|
||||
if len(memberIDs) > 100 {
|
||||
return fmt.Errorf("member_ids must contain at most 100 users")
|
||||
}
|
||||
|
||||
hasCaller := false
|
||||
seen := make(map[string]struct{}, len(memberIDs))
|
||||
for _, id := range memberIDs {
|
||||
if _, err := uuid.Parse(id); err != nil {
|
||||
return fmt.Errorf("invalid member uuid: %s", id)
|
||||
}
|
||||
if _, exists := seen[id]; exists {
|
||||
return fmt.Errorf("duplicate member_id: %s", id)
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
if id == callerID {
|
||||
hasCaller = true
|
||||
}
|
||||
}
|
||||
|
||||
if !hasCaller {
|
||||
return fmt.Errorf("caller must be in member_ids")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func ValidateMessageInput(text string, attachmentIDs []string) error {
|
||||
textRunes := utf8.RuneCountInString(text)
|
||||
if textRunes > 4000 {
|
||||
return fmt.Errorf("message text length must be at most 4000 code points")
|
||||
}
|
||||
if len(attachmentIDs) > MaxMessageAttachments {
|
||||
return fmt.Errorf("attachment_ids must contain at most %d items", MaxMessageAttachments)
|
||||
}
|
||||
|
||||
seen := make(map[string]struct{}, len(attachmentIDs))
|
||||
for _, attachmentID := range attachmentIDs {
|
||||
parsedID, err := uuid.Parse(attachmentID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid attachment uuid: %s", attachmentID)
|
||||
}
|
||||
canonicalID := parsedID.String()
|
||||
if _, exists := seen[canonicalID]; exists {
|
||||
return fmt.Errorf("duplicate attachment_id: %s", attachmentID)
|
||||
}
|
||||
seen[canonicalID] = struct{}{}
|
||||
}
|
||||
|
||||
if strings.TrimSpace(text) == "" && len(attachmentIDs) == 0 {
|
||||
return fmt.Errorf("message must contain non-blank text or at least one attachment")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ValidateMessageText remains for callers that create text-only messages.
|
||||
func ValidateMessageText(text string) error {
|
||||
return ValidateMessageInput(text, nil)
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
package reconcile
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab7/internal/adapter/objectstore"
|
||||
"mtusi2026lab7/internal/domain"
|
||||
)
|
||||
|
||||
const (
|
||||
IssueOrphanObject = "orphan_object"
|
||||
IssueMissingObject = "missing_object"
|
||||
IssueFailedObject = "failed_object"
|
||||
IssueReferencedMissing = "referenced_missing_object"
|
||||
)
|
||||
|
||||
type AttachmentRecord struct {
|
||||
ID string
|
||||
ObjectKey string
|
||||
AdditionalObjectKeys []string
|
||||
Status domain.AttachmentStatus
|
||||
UpdatedAt time.Time
|
||||
Referenced bool
|
||||
}
|
||||
|
||||
type MetadataStore interface {
|
||||
ListAttachmentInventory(ctx context.Context) ([]AttachmentRecord, error)
|
||||
MarkAttachmentFailedIfUnreferenced(
|
||||
ctx context.Context,
|
||||
attachmentID string,
|
||||
expectedStatus domain.AttachmentStatus,
|
||||
updatedBefore time.Time,
|
||||
errorCode string,
|
||||
updatedAt time.Time,
|
||||
) (bool, error)
|
||||
}
|
||||
|
||||
type ObjectInventory interface {
|
||||
List(ctx context.Context, prefix string) ([]objectstore.StoredObject, error)
|
||||
Delete(ctx context.Context, key string) error
|
||||
}
|
||||
|
||||
type Issue struct {
|
||||
Kind string `json:"kind"`
|
||||
AttachmentID string `json:"attachment_id,omitempty"`
|
||||
ObjectKey string `json:"object_key"`
|
||||
Protected bool `json:"protected,omitempty"`
|
||||
Action string `json:"action"`
|
||||
}
|
||||
|
||||
type Result struct {
|
||||
DryRun bool `json:"dry_run"`
|
||||
GracePeriod time.Duration `json:"-"`
|
||||
GracePeriodSeconds int64 `json:"grace_period_seconds"`
|
||||
ScannedAttachments int `json:"scanned_attachments"`
|
||||
ScannedObjects int `json:"scanned_objects"`
|
||||
Issues []Issue `json:"issues"`
|
||||
DeletedObjects int `json:"deleted_objects"`
|
||||
FailedAttachments int `json:"failed_attachments"`
|
||||
Duration time.Duration `json:"-"`
|
||||
DurationMillis int64 `json:"duration_ms"`
|
||||
}
|
||||
|
||||
type Reconciler struct {
|
||||
metadata MetadataStore
|
||||
objects ObjectInventory
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func New(metadata MetadataStore, objects ObjectInventory) (*Reconciler, error) {
|
||||
if metadata == nil || objects == nil {
|
||||
return nil, fmt.Errorf("metadata and object stores are required")
|
||||
}
|
||||
return &Reconciler{
|
||||
metadata: metadata,
|
||||
objects: objects,
|
||||
now: func() time.Time { return time.Now().UTC() },
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *Reconciler) Run(
|
||||
ctx context.Context,
|
||||
gracePeriod time.Duration,
|
||||
apply bool,
|
||||
) (Result, error) {
|
||||
if gracePeriod <= 0 {
|
||||
return Result{}, fmt.Errorf("grace period must be positive")
|
||||
}
|
||||
startedAt := r.now().UTC()
|
||||
cutoff := startedAt.Add(-gracePeriod)
|
||||
result := Result{
|
||||
DryRun: !apply,
|
||||
GracePeriod: gracePeriod,
|
||||
GracePeriodSeconds: int64(gracePeriod / time.Second),
|
||||
Issues: make([]Issue, 0),
|
||||
}
|
||||
|
||||
attachments, err := r.metadata.ListAttachmentInventory(ctx)
|
||||
if err != nil {
|
||||
return Result{}, fmt.Errorf("list attachment metadata: %w", err)
|
||||
}
|
||||
objects, err := r.objects.List(ctx, "attachments/")
|
||||
if err != nil {
|
||||
return Result{}, fmt.Errorf("list attachment objects: %w", err)
|
||||
}
|
||||
result.ScannedAttachments = len(attachments)
|
||||
result.ScannedObjects = len(objects)
|
||||
|
||||
attachmentsByKey := make(map[string]AttachmentRecord, len(attachments))
|
||||
for _, attachment := range attachments {
|
||||
attachmentsByKey[attachment.ObjectKey] = attachment
|
||||
for _, objectKey := range attachment.AdditionalObjectKeys {
|
||||
if objectKey != "" {
|
||||
attachmentsByKey[objectKey] = attachment
|
||||
}
|
||||
}
|
||||
}
|
||||
objectsByKey := make(map[string]objectstore.StoredObject, len(objects))
|
||||
for _, object := range objects {
|
||||
objectsByKey[object.Key] = object
|
||||
if _, exists := attachmentsByKey[object.Key]; exists {
|
||||
continue
|
||||
}
|
||||
if object.LastModified.IsZero() || object.LastModified.After(cutoff) {
|
||||
continue
|
||||
}
|
||||
issue := Issue{Kind: IssueOrphanObject, ObjectKey: object.Key, Action: "would_delete"}
|
||||
if apply {
|
||||
if err = r.objects.Delete(ctx, object.Key); err != nil {
|
||||
return result, fmt.Errorf("delete orphan object %q: %w", object.Key, err)
|
||||
}
|
||||
issue.Action = "deleted"
|
||||
result.DeletedObjects++
|
||||
}
|
||||
result.Issues = append(result.Issues, issue)
|
||||
}
|
||||
|
||||
for _, attachment := range attachments {
|
||||
if attachment.UpdatedAt.After(cutoff) {
|
||||
continue
|
||||
}
|
||||
_, objectExists := objectsByKey[attachment.ObjectKey]
|
||||
switch {
|
||||
case attachment.Status == domain.AttachmentStatusReady && !objectExists:
|
||||
issue := Issue{
|
||||
Kind: IssueMissingObject,
|
||||
AttachmentID: attachment.ID,
|
||||
ObjectKey: attachment.ObjectKey,
|
||||
Protected: attachment.Referenced,
|
||||
Action: "would_mark_failed",
|
||||
}
|
||||
if attachment.Referenced {
|
||||
issue.Kind = IssueReferencedMissing
|
||||
issue.Action = "manual_repair_required"
|
||||
} else if apply {
|
||||
changed, markError := r.metadata.MarkAttachmentFailedIfUnreferenced(
|
||||
ctx, attachment.ID, attachment.Status, cutoff,
|
||||
"reconciler_missing_object", startedAt,
|
||||
)
|
||||
if markError != nil {
|
||||
return result, fmt.Errorf("mark missing attachment %q failed: %w", attachment.ID, markError)
|
||||
}
|
||||
if changed {
|
||||
issue.Action = "marked_failed"
|
||||
result.FailedAttachments++
|
||||
} else {
|
||||
issue.Action = "skipped_concurrent_change"
|
||||
}
|
||||
}
|
||||
result.Issues = append(result.Issues, issue)
|
||||
|
||||
case attachment.Status == domain.AttachmentStatusFailed && objectExists:
|
||||
issue := Issue{
|
||||
Kind: IssueFailedObject, AttachmentID: attachment.ID,
|
||||
ObjectKey: attachment.ObjectKey, Protected: attachment.Referenced,
|
||||
Action: "would_delete",
|
||||
}
|
||||
if attachment.Referenced {
|
||||
issue.Action = "manual_repair_required"
|
||||
} else if apply {
|
||||
if err = r.objects.Delete(ctx, attachment.ObjectKey); err != nil {
|
||||
return result, fmt.Errorf("delete failed attachment object %q: %w", attachment.ObjectKey, err)
|
||||
}
|
||||
issue.Action = "deleted"
|
||||
result.DeletedObjects++
|
||||
}
|
||||
result.Issues = append(result.Issues, issue)
|
||||
}
|
||||
}
|
||||
|
||||
sort.Slice(result.Issues, func(i, j int) bool {
|
||||
if result.Issues[i].ObjectKey == result.Issues[j].ObjectKey {
|
||||
return result.Issues[i].Kind < result.Issues[j].Kind
|
||||
}
|
||||
return result.Issues[i].ObjectKey < result.Issues[j].ObjectKey
|
||||
})
|
||||
result.Duration = r.now().UTC().Sub(startedAt)
|
||||
result.DurationMillis = result.Duration.Milliseconds()
|
||||
return result, nil
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
package reconcile
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab7/internal/adapter/objectstore"
|
||||
"mtusi2026lab7/internal/domain"
|
||||
)
|
||||
|
||||
type fakeMetadataStore struct {
|
||||
records []AttachmentRecord
|
||||
markError error
|
||||
skipMark bool
|
||||
}
|
||||
|
||||
func (store *fakeMetadataStore) ListAttachmentInventory(
|
||||
context.Context,
|
||||
) ([]AttachmentRecord, error) {
|
||||
return append([]AttachmentRecord(nil), store.records...), nil
|
||||
}
|
||||
|
||||
func (store *fakeMetadataStore) MarkAttachmentFailedIfUnreferenced(
|
||||
_ context.Context,
|
||||
attachmentID string,
|
||||
expectedStatus domain.AttachmentStatus,
|
||||
updatedBefore time.Time,
|
||||
errorCode string,
|
||||
updatedAt time.Time,
|
||||
) (bool, error) {
|
||||
if store.markError != nil {
|
||||
return false, store.markError
|
||||
}
|
||||
if store.skipMark {
|
||||
return false, nil
|
||||
}
|
||||
for index := range store.records {
|
||||
record := &store.records[index]
|
||||
if record.ID != attachmentID || record.Status != expectedStatus ||
|
||||
record.UpdatedAt.After(updatedBefore) || record.Referenced {
|
||||
continue
|
||||
}
|
||||
record.Status = domain.AttachmentStatusFailed
|
||||
record.UpdatedAt = updatedAt
|
||||
_ = errorCode
|
||||
return true, nil
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func TestReconcilerDoesNotTouchActiveAttachments(t *testing.T) {
|
||||
old := time.Now().UTC().Add(-2 * time.Hour)
|
||||
metadata := &fakeMetadataStore{
|
||||
records: []AttachmentRecord{
|
||||
{
|
||||
ID: "queued-old", ObjectKey: "attachments/queued-old",
|
||||
AdditionalObjectKeys: []string{"attachments/queued-old-staging"},
|
||||
Status: domain.AttachmentStatusQueued, UpdatedAt: old,
|
||||
},
|
||||
{
|
||||
ID: "processing-old", ObjectKey: "attachments/processing-old",
|
||||
Status: domain.AttachmentStatusProcessing, UpdatedAt: old,
|
||||
},
|
||||
},
|
||||
}
|
||||
objects := &fakeObjectInventory{objects: map[string]objectstore.StoredObject{
|
||||
"attachments/queued-old": {Key: "attachments/queued-old", LastModified: old},
|
||||
"attachments/queued-old-staging": {Key: "attachments/queued-old-staging", LastModified: old},
|
||||
"attachments/processing-old": {Key: "attachments/processing-old", LastModified: old},
|
||||
}}
|
||||
reconciler, err := New(metadata, objects)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
result, err := reconciler.Run(context.Background(), time.Hour, true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if result.DeletedObjects != 0 || result.FailedAttachments != 0 {
|
||||
t.Fatalf("active attachments must not be reconciled as stale: %+v", result)
|
||||
}
|
||||
if len(result.Issues) != 0 {
|
||||
t.Fatalf("active attachments must not produce reconciliation issues: %+v", result.Issues)
|
||||
}
|
||||
if len(objects.objects) != 3 {
|
||||
t.Fatal("reconciler deleted an object belonging to an active attachment")
|
||||
}
|
||||
}
|
||||
|
||||
type fakeObjectInventory struct {
|
||||
objects map[string]objectstore.StoredObject
|
||||
deleteError error
|
||||
}
|
||||
|
||||
func (store *fakeObjectInventory) List(
|
||||
context.Context,
|
||||
string,
|
||||
) ([]objectstore.StoredObject, error) {
|
||||
objects := make([]objectstore.StoredObject, 0, len(store.objects))
|
||||
for _, object := range store.objects {
|
||||
objects = append(objects, object)
|
||||
}
|
||||
return objects, nil
|
||||
}
|
||||
|
||||
func (store *fakeObjectInventory) Delete(_ context.Context, key string) error {
|
||||
if store.deleteError != nil {
|
||||
return store.deleteError
|
||||
}
|
||||
delete(store.objects, key)
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestReconcilerDryRunApplyAndRepeat(t *testing.T) {
|
||||
now := time.Now().UTC()
|
||||
old := now.Add(-2 * time.Hour)
|
||||
fresh := now.Add(-5 * time.Minute)
|
||||
metadata := &fakeMetadataStore{records: []AttachmentRecord{
|
||||
{
|
||||
ID: "ready-present", ObjectKey: "attachments/ready-present",
|
||||
AdditionalObjectKeys: []string{"attachments/ready-present-thumbnail"},
|
||||
Status: domain.AttachmentStatusReady, UpdatedAt: old,
|
||||
},
|
||||
{ID: "ready-missing", ObjectKey: "attachments/ready-missing", Status: domain.AttachmentStatusReady, UpdatedAt: old},
|
||||
{ID: "ready-used-missing", ObjectKey: "attachments/ready-used-missing", Status: domain.AttachmentStatusReady, UpdatedAt: old, Referenced: true},
|
||||
{ID: "queued-old", ObjectKey: "attachments/queued-old", Status: domain.AttachmentStatusQueued, UpdatedAt: old},
|
||||
{ID: "failed-old", ObjectKey: "attachments/failed-old", Status: domain.AttachmentStatusFailed, UpdatedAt: old},
|
||||
{ID: "queued-fresh", ObjectKey: "attachments/queued-fresh", Status: domain.AttachmentStatusQueued, UpdatedAt: fresh},
|
||||
}}
|
||||
objects := &fakeObjectInventory{objects: map[string]objectstore.StoredObject{
|
||||
"attachments/ready-present": {Key: "attachments/ready-present", LastModified: old},
|
||||
"attachments/ready-present-thumbnail": {Key: "attachments/ready-present-thumbnail", LastModified: old},
|
||||
"attachments/queued-old": {Key: "attachments/queued-old", LastModified: old},
|
||||
"attachments/failed-old": {Key: "attachments/failed-old", LastModified: old},
|
||||
"attachments/orphan-old": {Key: "attachments/orphan-old", LastModified: old},
|
||||
"attachments/orphan-fresh": {Key: "attachments/orphan-fresh", LastModified: fresh},
|
||||
}}
|
||||
reconciler, err := New(metadata, objects)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
dryRun, err := reconciler.Run(context.Background(), time.Hour, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !dryRun.DryRun || len(dryRun.Issues) != 4 ||
|
||||
dryRun.DeletedObjects != 0 || dryRun.FailedAttachments != 0 {
|
||||
t.Fatalf("unexpected dry-run result: %+v", dryRun)
|
||||
}
|
||||
if len(objects.objects) != 6 {
|
||||
t.Fatal("dry-run changed object storage")
|
||||
}
|
||||
for _, record := range metadata.records {
|
||||
if record.ID == "ready-missing" && record.Status != domain.AttachmentStatusReady {
|
||||
t.Fatal("dry-run changed metadata")
|
||||
}
|
||||
}
|
||||
|
||||
applied, err := reconciler.Run(context.Background(), time.Hour, true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if applied.DeletedObjects != 2 || applied.FailedAttachments != 1 {
|
||||
t.Fatalf("unexpected apply result: %+v", applied)
|
||||
}
|
||||
if _, exists := objects.objects["attachments/orphan-old"]; exists {
|
||||
t.Fatal("old orphan was not deleted")
|
||||
}
|
||||
if _, exists := objects.objects["attachments/orphan-fresh"]; !exists {
|
||||
t.Fatal("fresh orphan must be protected by grace period")
|
||||
}
|
||||
if _, exists := objects.objects["attachments/ready-present"]; !exists {
|
||||
t.Fatal("healthy object was deleted")
|
||||
}
|
||||
if _, exists := objects.objects["attachments/ready-present-thumbnail"]; !exists {
|
||||
t.Fatal("managed variant object was deleted as an orphan")
|
||||
}
|
||||
if _, exists := objects.objects["attachments/queued-old"]; !exists {
|
||||
t.Fatal("active queued attachment object was deleted")
|
||||
}
|
||||
for _, issue := range applied.Issues {
|
||||
if issue.AttachmentID == "ready-used-missing" &&
|
||||
(!issue.Protected || issue.Action != "manual_repair_required") {
|
||||
t.Fatalf("referenced attachment was not protected: %+v", issue)
|
||||
}
|
||||
}
|
||||
|
||||
repeated, err := reconciler.Run(context.Background(), time.Hour, true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if repeated.DeletedObjects != 0 || repeated.FailedAttachments != 0 {
|
||||
t.Fatalf("repeat must be mutation-idempotent: %+v", repeated)
|
||||
}
|
||||
if len(repeated.Issues) != 1 || !repeated.Issues[0].Protected {
|
||||
t.Fatalf("repeat should retain only protected manual issue: %+v", repeated)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReconcilerReportsMutationFailures(t *testing.T) {
|
||||
old := time.Now().UTC().Add(-2 * time.Hour)
|
||||
metadata := &fakeMetadataStore{records: []AttachmentRecord{
|
||||
{ID: "missing", ObjectKey: "attachments/missing", Status: domain.AttachmentStatusReady, UpdatedAt: old},
|
||||
}}
|
||||
metadata.markError = errors.New("injected database failure")
|
||||
objects := &fakeObjectInventory{objects: make(map[string]objectstore.StoredObject)}
|
||||
reconciler, err := New(metadata, objects)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = reconciler.Run(context.Background(), time.Hour, true); err == nil {
|
||||
t.Fatal("injected database mutation failure was hidden")
|
||||
}
|
||||
|
||||
metadata.records = nil
|
||||
metadata.markError = nil
|
||||
objects.objects["attachments/orphan"] = objectstore.StoredObject{
|
||||
Key: "attachments/orphan", LastModified: old,
|
||||
}
|
||||
objects.deleteError = errors.New("injected object-store failure")
|
||||
if _, err = reconciler.Run(context.Background(), time.Hour, true); err == nil {
|
||||
t.Fatal("injected object-store mutation failure was hidden")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package security
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ClientMTLSConfig builds a TLS 1.3 client configuration with an explicit
|
||||
// workload certificate. The service name is verified against the server
|
||||
// certificate; neither InsecureSkipVerify nor the host trust store is used.
|
||||
func ClientMTLSConfig(caFile, certFile, keyFile, serverName string) (*tls.Config, error) {
|
||||
caFile = strings.TrimSpace(caFile)
|
||||
certFile = strings.TrimSpace(certFile)
|
||||
keyFile = strings.TrimSpace(keyFile)
|
||||
serverName = strings.TrimSpace(serverName)
|
||||
if caFile == "" || certFile == "" || keyFile == "" || serverName == "" {
|
||||
return nil, errors.New("client CA, certificate, key, and server name are required")
|
||||
}
|
||||
|
||||
caPEM, err := os.ReadFile(caFile)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read client TLS CA: %w", err)
|
||||
}
|
||||
roots := x509.NewCertPool()
|
||||
if !roots.AppendCertsFromPEM(caPEM) {
|
||||
return nil, errors.New("client TLS CA file contains no certificate")
|
||||
}
|
||||
certificate, err := tls.LoadX509KeyPair(certFile, keyFile)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load client TLS identity: %w", err)
|
||||
}
|
||||
|
||||
return &tls.Config{
|
||||
MinVersion: tls.VersionTLS13,
|
||||
RootCAs: roots,
|
||||
Certificates: []tls.Certificate{certificate},
|
||||
ServerName: serverName,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package security
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func ServerMTLSConfig(clientCAFile string, allowedClientURI string, allowedClientURIFile string) (*tls.Config, error) {
|
||||
clientCAFile = strings.TrimSpace(clientCAFile)
|
||||
allowedClientURI = strings.TrimSpace(allowedClientURI)
|
||||
allowedClientURIFile = strings.TrimSpace(allowedClientURIFile)
|
||||
if clientCAFile == "" || (allowedClientURI == "" && allowedClientURIFile == "") {
|
||||
return nil, errors.New("TLS_CLIENT_CA_FILE and an allowed client URI source are required")
|
||||
}
|
||||
allowedClientURIs := make(map[string]struct{})
|
||||
if allowedClientURI != "" {
|
||||
allowedClientURIs[allowedClientURI] = struct{}{}
|
||||
}
|
||||
if allowedClientURIFile != "" {
|
||||
allowedPEM, readErr := os.ReadFile(allowedClientURIFile)
|
||||
if readErr != nil {
|
||||
return nil, fmt.Errorf("read allowed client URI file: %w", readErr)
|
||||
}
|
||||
for _, line := range strings.Split(string(allowedPEM), "\n") {
|
||||
line = strings.TrimSpace(line)
|
||||
if line != "" && !strings.HasPrefix(line, "#") {
|
||||
allowedClientURIs[line] = struct{}{}
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(allowedClientURIs) == 0 {
|
||||
return nil, errors.New("allowed client URI set is empty")
|
||||
}
|
||||
caPEM, err := os.ReadFile(clientCAFile)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read client CA: %w", err)
|
||||
}
|
||||
clientRoots := x509.NewCertPool()
|
||||
if !clientRoots.AppendCertsFromPEM(caPEM) {
|
||||
return nil, errors.New("client CA file contains no certificate")
|
||||
}
|
||||
return &tls.Config{
|
||||
MinVersion: tls.VersionTLS13,
|
||||
ClientAuth: tls.RequireAndVerifyClientCert,
|
||||
ClientCAs: clientRoots,
|
||||
NextProtos: []string{"h2", "http/1.1"},
|
||||
VerifyConnection: func(state tls.ConnectionState) error {
|
||||
if len(state.VerifiedChains) == 0 || len(state.PeerCertificates) == 0 {
|
||||
return errors.New("verified client certificate is required")
|
||||
}
|
||||
leaf := state.PeerCertificates[0]
|
||||
for _, identity := range leaf.URIs {
|
||||
if _, allowed := allowedClientURIs[identity.String()]; allowed {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("client certificate URI SAN is not allowed")
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
package security
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultArgonMemory uint32 = 19 * 1024
|
||||
defaultArgonIterations uint32 = 2
|
||||
defaultArgonParallelism uint8 = 1
|
||||
argonSaltLength = 16
|
||||
argonKeyLength uint32 = 32
|
||||
|
||||
minPasswordLength = 12
|
||||
maxPasswordLength = 128
|
||||
)
|
||||
|
||||
var ErrInvalidPasswordHash = errors.New("invalid password hash")
|
||||
|
||||
func ValidatePassword(password string) error {
|
||||
if !utf8.ValidString(password) {
|
||||
return errors.New("password must be valid UTF-8")
|
||||
}
|
||||
|
||||
length := utf8.RuneCountInString(password)
|
||||
if length < minPasswordLength || length > maxPasswordLength {
|
||||
return fmt.Errorf(
|
||||
"password length must be between %d and %d code points",
|
||||
minPasswordLength,
|
||||
maxPasswordLength,
|
||||
)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func HashPassword(password string) (string, error) {
|
||||
if err := ValidatePassword(password); err != nil {
|
||||
return "", err
|
||||
}
|
||||
parameters, err := passwordParametersFromEnvironment()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
salt := make([]byte, argonSaltLength)
|
||||
if _, err = rand.Read(salt); err != nil {
|
||||
return "", fmt.Errorf("generate password salt: %w", err)
|
||||
}
|
||||
|
||||
hash := argon2.IDKey(
|
||||
[]byte(password),
|
||||
salt,
|
||||
parameters.iterations,
|
||||
parameters.memory,
|
||||
parameters.parallelism,
|
||||
argonKeyLength,
|
||||
)
|
||||
|
||||
encodedSalt := base64.RawStdEncoding.EncodeToString(salt)
|
||||
encodedHash := base64.RawStdEncoding.EncodeToString(hash)
|
||||
|
||||
encoded := fmt.Sprintf(
|
||||
"$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
|
||||
argon2.Version,
|
||||
parameters.memory,
|
||||
parameters.iterations,
|
||||
parameters.parallelism,
|
||||
encodedSalt,
|
||||
encodedHash,
|
||||
)
|
||||
|
||||
return encoded, nil
|
||||
}
|
||||
|
||||
func VerifyPassword(
|
||||
password string,
|
||||
encodedHash string,
|
||||
) (bool, error) {
|
||||
parameters, salt, expectedHash, err := decodePasswordHash(encodedHash)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
actualHash := argon2.IDKey(
|
||||
[]byte(password),
|
||||
salt,
|
||||
parameters.iterations,
|
||||
parameters.memory,
|
||||
parameters.parallelism,
|
||||
uint32(len(expectedHash)),
|
||||
)
|
||||
|
||||
matches := subtle.ConstantTimeCompare(
|
||||
actualHash,
|
||||
expectedHash,
|
||||
) == 1
|
||||
|
||||
return matches, nil
|
||||
}
|
||||
|
||||
// NeedsPasswordRehash reports whether a verified stored hash must be upgraded
|
||||
// to the active Argon2id policy. Callers must verify the password first.
|
||||
func NeedsPasswordRehash(encodedHash string) (bool, error) {
|
||||
stored, salt, hash, err := decodePasswordHash(encodedHash)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
active, err := passwordParametersFromEnvironment()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return stored != active || len(salt) != argonSaltLength || uint32(len(hash)) != argonKeyLength, nil
|
||||
}
|
||||
|
||||
type argonParameters struct {
|
||||
memory uint32
|
||||
iterations uint32
|
||||
parallelism uint8
|
||||
}
|
||||
|
||||
func passwordParametersFromEnvironment() (argonParameters, error) {
|
||||
memory, err := boundedUint32Environment(
|
||||
"ARGON2_MEMORY_KIB", defaultArgonMemory, defaultArgonMemory, 256*1024,
|
||||
)
|
||||
if err != nil {
|
||||
return argonParameters{}, err
|
||||
}
|
||||
iterations, err := boundedUint32Environment(
|
||||
"ARGON2_ITERATIONS", defaultArgonIterations, defaultArgonIterations, 10,
|
||||
)
|
||||
if err != nil {
|
||||
return argonParameters{}, err
|
||||
}
|
||||
parallelism, err := boundedUint32Environment(
|
||||
"ARGON2_PARALLELISM", uint32(defaultArgonParallelism), 1, 8,
|
||||
)
|
||||
if err != nil {
|
||||
return argonParameters{}, err
|
||||
}
|
||||
return argonParameters{
|
||||
memory: memory, iterations: iterations, parallelism: uint8(parallelism),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func boundedUint32Environment(
|
||||
name string,
|
||||
fallback uint32,
|
||||
minimum uint32,
|
||||
maximum uint32,
|
||||
) (uint32, error) {
|
||||
raw := strings.TrimSpace(os.Getenv(name))
|
||||
if raw == "" {
|
||||
return fallback, nil
|
||||
}
|
||||
value, err := strconv.ParseUint(raw, 10, 32)
|
||||
if err != nil || value < uint64(minimum) || value > uint64(maximum) {
|
||||
return 0, fmt.Errorf("%s must be an integer from %d to %d", name, minimum, maximum)
|
||||
}
|
||||
return uint32(value), nil
|
||||
}
|
||||
|
||||
func decodePasswordHash(
|
||||
encodedHash string,
|
||||
) (argonParameters, []byte, []byte, error) {
|
||||
parts := strings.Split(encodedHash, "$")
|
||||
if len(parts) != 6 ||
|
||||
parts[0] != "" ||
|
||||
parts[1] != "argon2id" {
|
||||
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
|
||||
}
|
||||
|
||||
var version int
|
||||
if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil {
|
||||
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
|
||||
}
|
||||
|
||||
if version != argon2.Version {
|
||||
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
|
||||
}
|
||||
|
||||
var parameters argonParameters
|
||||
if _, err := fmt.Sscanf(
|
||||
parts[3],
|
||||
"m=%d,t=%d,p=%d",
|
||||
¶meters.memory,
|
||||
¶meters.iterations,
|
||||
¶meters.parallelism,
|
||||
); err != nil {
|
||||
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
|
||||
}
|
||||
|
||||
// Ограничения не позволяют повреждённой строке из БД запросить
|
||||
// гигантский объём памяти или процессорного времени.
|
||||
if parameters.memory < 8*1024 ||
|
||||
parameters.memory > 256*1024 ||
|
||||
parameters.iterations < 1 ||
|
||||
parameters.iterations > 10 ||
|
||||
parameters.parallelism < 1 ||
|
||||
parameters.parallelism > 8 {
|
||||
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
|
||||
}
|
||||
|
||||
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
|
||||
if err != nil || len(salt) < 16 || len(salt) > 64 {
|
||||
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
|
||||
}
|
||||
|
||||
hash, err := base64.RawStdEncoding.DecodeString(parts[5])
|
||||
if err != nil || len(hash) < 16 || len(hash) > 64 {
|
||||
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
|
||||
}
|
||||
|
||||
return parameters, salt, hash, nil
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
package security
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func BenchmarkHashPasswordGrade3(b *testing.B) {
|
||||
const password = "benchmark-password-123"
|
||||
for index := 0; index < b.N; index++ {
|
||||
if _, err := HashPassword(password); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkVerifyPasswordGrade4(b *testing.B) {
|
||||
const password = "benchmark-password-123"
|
||||
encodedHash, err := HashPassword(password)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
b.ResetTimer()
|
||||
for index := 0; index < b.N; index++ {
|
||||
matches, verifyErr := VerifyPassword(password, encodedHash)
|
||||
if verifyErr != nil || !matches {
|
||||
b.Fatalf("verify failed: matches=%v err=%v", matches, verifyErr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHashPasswordRejectsWeakConfiguredCost(t *testing.T) {
|
||||
t.Setenv("ARGON2_MEMORY_KIB", "8192")
|
||||
if _, err := HashPassword("valid-password-123"); err == nil {
|
||||
t.Fatal("HashPassword accepted memory below the lab7 minimum")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPasswordHashAndVerify(t *testing.T) {
|
||||
password := "Correct-password-123"
|
||||
|
||||
encodedHash, err := HashPassword(password)
|
||||
if err != nil {
|
||||
t.Fatalf("HashPassword returned error: %v", err)
|
||||
}
|
||||
|
||||
if strings.Contains(encodedHash, password) {
|
||||
t.Fatal("encoded hash contains plaintext password")
|
||||
}
|
||||
|
||||
matches, err := VerifyPassword(password, encodedHash)
|
||||
if err != nil {
|
||||
t.Fatalf("VerifyPassword returned error: %v", err)
|
||||
}
|
||||
if !matches {
|
||||
t.Fatal("correct password did not match")
|
||||
}
|
||||
|
||||
matches, err = VerifyPassword("Wrong-password-123", encodedHash)
|
||||
if err != nil {
|
||||
t.Fatalf("VerifyPassword returned error: %v", err)
|
||||
}
|
||||
if matches {
|
||||
t.Fatal("wrong password matched")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPasswordHashesUseDifferentSalts(t *testing.T) {
|
||||
password := "Correct-password-123"
|
||||
|
||||
firstHash, err := HashPassword(password)
|
||||
if err != nil {
|
||||
t.Fatalf("first HashPassword returned error: %v", err)
|
||||
}
|
||||
|
||||
secondHash, err := HashPassword(password)
|
||||
if err != nil {
|
||||
t.Fatalf("second HashPassword returned error: %v", err)
|
||||
}
|
||||
|
||||
if firstHash == secondHash {
|
||||
t.Fatal("equal passwords produced equal encoded hashes")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPasswordValidation(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
password string
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "minimum length",
|
||||
password: "123456789012",
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "unicode",
|
||||
password: "пароль-проверка-123",
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "colon is allowed",
|
||||
password: "password:with:colon",
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "too short",
|
||||
password: "short",
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
err := ValidatePassword(testCase.password)
|
||||
|
||||
if testCase.wantErr && err == nil {
|
||||
t.Fatal("expected validation error")
|
||||
}
|
||||
if !testCase.wantErr && err != nil {
|
||||
t.Fatalf("unexpected validation error: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMalformedPasswordHash(t *testing.T) {
|
||||
_, err := VerifyPassword(
|
||||
"Correct-password-123",
|
||||
"not-an-argon2-hash",
|
||||
)
|
||||
if err == nil {
|
||||
t.Fatal("expected malformed hash error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNeedsPasswordRehash(t *testing.T) {
|
||||
currentHash, err := HashPassword("Correct-password-123")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
needsRehash, err := NeedsPasswordRehash(currentHash)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if needsRehash {
|
||||
t.Fatal("current policy hash unexpectedly requires rehash")
|
||||
}
|
||||
|
||||
legacyHash := strings.Replace(currentHash, "m=19456,t=2,p=1", "m=8192,t=2,p=1", 1)
|
||||
needsRehash, err = NeedsPasswordRehash(legacyHash)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !needsRehash {
|
||||
t.Fatal("legacy policy hash was not marked for rehash")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package security
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
const sessionTokenBytes = 32
|
||||
|
||||
func GenerateSessionToken() (string, []byte, error) {
|
||||
randomBytes := make([]byte, sessionTokenBytes)
|
||||
|
||||
if _, err := rand.Read(randomBytes); err != nil {
|
||||
return "", nil, fmt.Errorf("generate session token: %w", err)
|
||||
}
|
||||
|
||||
token := base64.RawURLEncoding.EncodeToString(randomBytes)
|
||||
tokenHash := HashSessionToken(token)
|
||||
|
||||
return token, tokenHash, nil
|
||||
}
|
||||
|
||||
func HashSessionToken(token string) []byte {
|
||||
digest := sha256.Sum256([]byte(token))
|
||||
|
||||
hash := make([]byte, len(digest))
|
||||
copy(hash, digest[:])
|
||||
|
||||
return hash
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package security
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGenerateSessionToken(t *testing.T) {
|
||||
firstToken, firstHash, err := GenerateSessionToken()
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateSessionToken returned error: %v", err)
|
||||
}
|
||||
|
||||
secondToken, secondHash, err := GenerateSessionToken()
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateSessionToken returned error: %v", err)
|
||||
}
|
||||
|
||||
if firstToken == secondToken {
|
||||
t.Fatal("generated session tokens are equal")
|
||||
}
|
||||
|
||||
if bytes.Equal(firstHash, secondHash) {
|
||||
t.Fatal("generated session token hashes are equal")
|
||||
}
|
||||
|
||||
if len(firstHash) != 32 {
|
||||
t.Fatalf("expected 32-byte token hash, got %d", len(firstHash))
|
||||
}
|
||||
|
||||
recalculatedHash := HashSessionToken(firstToken)
|
||||
if !bytes.Equal(firstHash, recalculatedHash) {
|
||||
t.Fatal("token hash is not reproducible")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
type JobRecorder struct {
|
||||
runtime *Runtime
|
||||
processed metric.Int64Counter
|
||||
duration metric.Float64Histogram
|
||||
readyDuration metric.Float64Histogram
|
||||
busy atomic.Int64
|
||||
capacity int64
|
||||
}
|
||||
|
||||
type JobAttempt struct {
|
||||
recorder *JobRecorder
|
||||
ctx context.Context
|
||||
span trace.Span
|
||||
started time.Time
|
||||
createdAt time.Time
|
||||
jobType string
|
||||
attempt int
|
||||
ended atomic.Bool
|
||||
}
|
||||
|
||||
func NewJobRecorder(runtime *Runtime, capacity int) (*JobRecorder, error) {
|
||||
if capacity < 1 {
|
||||
return nil, fmt.Errorf("worker capacity must be positive")
|
||||
}
|
||||
processed, err := runtime.Meter.Int64Counter(
|
||||
"messenger.worker.jobs",
|
||||
metric.WithDescription("Number of completed worker processing attempts"),
|
||||
metric.WithUnit("{job}"),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create worker jobs counter: %w", err)
|
||||
}
|
||||
duration, err := runtime.Meter.Float64Histogram(
|
||||
"messenger.worker.job.duration",
|
||||
metric.WithDescription("Worker processing attempt duration"),
|
||||
metric.WithUnit("s"),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create worker duration histogram: %w", err)
|
||||
}
|
||||
readyDuration, err := runtime.Meter.Float64Histogram(
|
||||
"messenger.attachment.ready.duration",
|
||||
metric.WithDescription("Time from durable acceptance until attachment ready"),
|
||||
metric.WithUnit("s"),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create attachment ready duration histogram: %w", err)
|
||||
}
|
||||
busy, err := runtime.Meter.Int64ObservableGauge(
|
||||
"messenger.worker.busy",
|
||||
metric.WithDescription("Number of workers processing jobs"),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create worker busy metric: %w", err)
|
||||
}
|
||||
workerCapacity, err := runtime.Meter.Int64ObservableGauge(
|
||||
"messenger.worker.capacity",
|
||||
metric.WithDescription("Configured worker processing capacity"),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create worker capacity metric: %w", err)
|
||||
}
|
||||
recorder := &JobRecorder{
|
||||
runtime: runtime,
|
||||
processed: processed,
|
||||
duration: duration,
|
||||
readyDuration: readyDuration,
|
||||
capacity: int64(capacity),
|
||||
}
|
||||
_, err = runtime.Meter.RegisterCallback(
|
||||
func(ctx context.Context, observer metric.Observer) error {
|
||||
observer.ObserveInt64(busy, recorder.busy.Load())
|
||||
observer.ObserveInt64(workerCapacity, recorder.capacity)
|
||||
return nil
|
||||
},
|
||||
busy,
|
||||
workerCapacity,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("register worker saturation metrics: %w", err)
|
||||
}
|
||||
return recorder, nil
|
||||
}
|
||||
|
||||
func (recorder *JobRecorder) Start(
|
||||
ctx context.Context,
|
||||
jobType string,
|
||||
destination string,
|
||||
attempt int,
|
||||
createdAt time.Time,
|
||||
) (context.Context, *JobAttempt) {
|
||||
ctx, span := recorder.runtime.Tracer.Start(
|
||||
ctx,
|
||||
"attachment.process",
|
||||
trace.WithSpanKind(trace.SpanKindConsumer),
|
||||
trace.WithAttributes(
|
||||
attribute.String("messaging.system", "rabbitmq"),
|
||||
attribute.String("messaging.destination.name", destination),
|
||||
attribute.String("messaging.operation.name", "process"),
|
||||
attribute.String("job.type", jobType),
|
||||
attribute.Int("job.attempt", attempt),
|
||||
),
|
||||
)
|
||||
recorder.busy.Add(1)
|
||||
return ctx, &JobAttempt{
|
||||
recorder: recorder,
|
||||
ctx: ctx,
|
||||
span: span,
|
||||
started: time.Now(),
|
||||
createdAt: createdAt,
|
||||
jobType: jobType,
|
||||
attempt: attempt,
|
||||
}
|
||||
}
|
||||
|
||||
func (attempt *JobAttempt) End(processErr error) {
|
||||
if !attempt.ended.CompareAndSwap(false, true) {
|
||||
return
|
||||
}
|
||||
defer attempt.recorder.busy.Add(-1)
|
||||
elapsed := time.Since(attempt.started)
|
||||
outcome := "succeeded"
|
||||
event := "attachment_job_completed"
|
||||
if processErr != nil {
|
||||
outcome = "failed"
|
||||
event = "attachment_job_failed"
|
||||
attempt.span.SetStatus(codes.Error, "job processing failed")
|
||||
} else {
|
||||
attempt.span.SetStatus(codes.Ok, "")
|
||||
}
|
||||
labels := metric.WithAttributes(
|
||||
attribute.String("job_type", attempt.jobType),
|
||||
attribute.String("outcome", outcome),
|
||||
)
|
||||
attempt.recorder.processed.Add(attempt.ctx, 1, labels)
|
||||
attempt.recorder.duration.Record(attempt.ctx, elapsed.Seconds(), labels)
|
||||
if processErr == nil && !attempt.createdAt.IsZero() {
|
||||
readySeconds := time.Since(attempt.createdAt).Seconds()
|
||||
if readySeconds >= 0 {
|
||||
attempt.recorder.readyDuration.Record(
|
||||
attempt.ctx,
|
||||
readySeconds,
|
||||
metric.WithAttributes(attribute.String("job_type", attempt.jobType)),
|
||||
)
|
||||
}
|
||||
}
|
||||
fields := Fields{
|
||||
"job_type": attempt.jobType,
|
||||
"outcome": outcome,
|
||||
"attempt": attempt.attempt,
|
||||
"duration_ms": float64(elapsed.Microseconds()) / 1000,
|
||||
}
|
||||
if processErr != nil {
|
||||
attempt.recorder.runtime.Logger.Warn(attempt.ctx, event, fields)
|
||||
} else {
|
||||
attempt.recorder.runtime.Logger.Info(attempt.ctx, event, fields)
|
||||
}
|
||||
attempt.span.End()
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
otellog "go.opentelemetry.io/otel/log"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
type Fields map[string]any
|
||||
|
||||
type Logger struct {
|
||||
logger otellog.Logger
|
||||
serviceName string
|
||||
instanceID string
|
||||
}
|
||||
|
||||
var stdoutMu sync.Mutex
|
||||
|
||||
func NewLogger(logger otellog.Logger, serviceName, instanceID string) *Logger {
|
||||
return &Logger{logger: logger, serviceName: serviceName, instanceID: instanceID}
|
||||
}
|
||||
|
||||
func (logger *Logger) Info(ctx context.Context, event string, fields Fields) {
|
||||
logger.emit(ctx, otellog.SeverityInfo, "INFO", event, fields)
|
||||
}
|
||||
|
||||
func (logger *Logger) Warn(ctx context.Context, event string, fields Fields) {
|
||||
logger.emit(ctx, otellog.SeverityWarn, "WARN", event, fields)
|
||||
}
|
||||
|
||||
func (logger *Logger) emit(
|
||||
ctx context.Context,
|
||||
severity otellog.Severity,
|
||||
severityText string,
|
||||
event string,
|
||||
fields Fields,
|
||||
) {
|
||||
now := time.Now().UTC()
|
||||
spanContext := trace.SpanContextFromContext(ctx)
|
||||
traceID := ""
|
||||
spanID := ""
|
||||
if spanContext.IsValid() {
|
||||
traceID = spanContext.TraceID().String()
|
||||
spanID = spanContext.SpanID().String()
|
||||
}
|
||||
|
||||
line := map[string]any{
|
||||
"timestamp": now.Format(time.RFC3339Nano),
|
||||
"severity": severityText,
|
||||
"service.name": logger.serviceName,
|
||||
"service.instance.id": logger.instanceID,
|
||||
"event": event,
|
||||
"trace_id": traceID,
|
||||
"span_id": spanID,
|
||||
}
|
||||
attributes := []attribute.KeyValue{
|
||||
attribute.String("event", event),
|
||||
attribute.String("trace_id", traceID),
|
||||
attribute.String("span_id", spanID),
|
||||
}
|
||||
for key, value := range fields {
|
||||
if _, protected := line[key]; protected {
|
||||
continue
|
||||
}
|
||||
line[key] = value
|
||||
attributes = append(attributes, logAttribute(key, value))
|
||||
}
|
||||
|
||||
encoded, err := json.Marshal(line)
|
||||
if err == nil {
|
||||
stdoutMu.Lock()
|
||||
_, _ = fmt.Fprintln(os.Stdout, string(encoded))
|
||||
stdoutMu.Unlock()
|
||||
}
|
||||
|
||||
var record otellog.Record
|
||||
record.SetTimestamp(now)
|
||||
record.SetObservedTimestamp(now)
|
||||
record.SetSeverity(severity)
|
||||
record.SetSeverityText(severityText)
|
||||
record.SetEventName(event)
|
||||
record.SetBody(attribute.StringValue(event))
|
||||
record.AddAttributes(attributes...)
|
||||
logger.logger.Emit(ctx, record)
|
||||
}
|
||||
|
||||
func logAttribute(key string, value any) attribute.KeyValue {
|
||||
switch typed := value.(type) {
|
||||
case string:
|
||||
return attribute.String(key, typed)
|
||||
case int:
|
||||
return attribute.Int(key, typed)
|
||||
case int64:
|
||||
return attribute.Int64(key, typed)
|
||||
case float64:
|
||||
return attribute.Float64(key, typed)
|
||||
case bool:
|
||||
return attribute.Bool(key, typed)
|
||||
default:
|
||||
return attribute.String(key, fmt.Sprint(value))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
)
|
||||
|
||||
func registerProcessMetrics(meter metric.Meter) error {
|
||||
cpu, err := meter.Float64ObservableCounter(
|
||||
"messenger.process.cpu.time",
|
||||
metric.WithDescription("CPU time consumed by the process"),
|
||||
metric.WithUnit("s"),
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create process CPU metric: %w", err)
|
||||
}
|
||||
memory, err := meter.Int64ObservableGauge(
|
||||
"messenger.process.memory",
|
||||
metric.WithDescription("Resident memory used by the process"),
|
||||
metric.WithUnit("By"),
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create process memory metric: %w", err)
|
||||
}
|
||||
_, err = meter.RegisterCallback(
|
||||
func(ctx context.Context, observer metric.Observer) error {
|
||||
if seconds, readErr := processCPUSeconds(); readErr == nil {
|
||||
observer.ObserveFloat64(cpu, seconds)
|
||||
}
|
||||
if bytes, readErr := processResidentBytes(); readErr == nil {
|
||||
observer.ObserveInt64(memory, bytes)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
cpu,
|
||||
memory,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("register process metrics: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func processCPUSeconds() (float64, error) {
|
||||
data, err := os.ReadFile("/proc/self/schedstat")
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
fields := strings.Fields(string(data))
|
||||
if len(fields) < 1 {
|
||||
return 0, fmt.Errorf("invalid /proc/self/schedstat")
|
||||
}
|
||||
nanoseconds, err := strconv.ParseUint(fields[0], 10, 64)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return float64(nanoseconds) / 1_000_000_000, nil
|
||||
}
|
||||
|
||||
func processResidentBytes() (int64, error) {
|
||||
data, err := os.ReadFile("/proc/self/statm")
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
fields := strings.Fields(string(data))
|
||||
if len(fields) < 2 {
|
||||
return 0, fmt.Errorf("invalid /proc/self/statm")
|
||||
}
|
||||
pages, err := strconv.ParseInt(fields[1], 10, 64)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return pages * int64(os.Getpagesize()), nil
|
||||
}
|
||||
|
||||
func RegisterDBPool(runtime *Runtime, pool *pgxpool.Pool) error {
|
||||
connections, err := runtime.Meter.Int64ObservableGauge(
|
||||
"messenger.db.pool.connections",
|
||||
metric.WithDescription("PostgreSQL pool connections by state"),
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create DB pool connection metric: %w", err)
|
||||
}
|
||||
waits, err := runtime.Meter.Int64ObservableCounter(
|
||||
"messenger.db.pool.waits",
|
||||
metric.WithDescription("Number of acquisitions that waited for a PostgreSQL connection"),
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create DB pool wait metric: %w", err)
|
||||
}
|
||||
_, err = runtime.Meter.RegisterCallback(
|
||||
func(ctx context.Context, observer metric.Observer) error {
|
||||
stats := pool.Stat()
|
||||
observer.ObserveInt64(
|
||||
connections,
|
||||
int64(stats.AcquiredConns()),
|
||||
metric.WithAttributes(attribute.String("state", "used")),
|
||||
)
|
||||
observer.ObserveInt64(
|
||||
connections,
|
||||
int64(stats.IdleConns()),
|
||||
metric.WithAttributes(attribute.String("state", "idle")),
|
||||
)
|
||||
observer.ObserveInt64(
|
||||
connections,
|
||||
int64(stats.MaxConns()),
|
||||
metric.WithAttributes(attribute.String("state", "capacity")),
|
||||
)
|
||||
observer.ObserveInt64(waits, stats.EmptyAcquireCount())
|
||||
return nil
|
||||
},
|
||||
connections,
|
||||
waits,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("register DB pool metrics: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type QueueRecorder struct {
|
||||
depth metric.Int64Gauge
|
||||
age metric.Float64Gauge
|
||||
}
|
||||
|
||||
func NewQueueRecorder(runtime *Runtime) (*QueueRecorder, error) {
|
||||
depth, err := runtime.Meter.Int64Gauge(
|
||||
"messenger.queue.depth",
|
||||
metric.WithDescription("Number of queued attachment jobs"),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create queue depth metric: %w", err)
|
||||
}
|
||||
age, err := runtime.Meter.Float64Gauge(
|
||||
"messenger.queue.oldest_job_age",
|
||||
metric.WithDescription("Age of the oldest queued attachment job"),
|
||||
metric.WithUnit("s"),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create queue age metric: %w", err)
|
||||
}
|
||||
return &QueueRecorder{depth: depth, age: age}, nil
|
||||
}
|
||||
|
||||
func (recorder *QueueRecorder) Record(ctx context.Context, depth int64, ageSeconds float64) {
|
||||
labels := metric.WithAttributes(attribute.String("queue", "attachment.process.v1"))
|
||||
recorder.depth.Record(ctx, depth, labels)
|
||||
recorder.age.Record(ctx, ageSeconds, labels)
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab7/internal/security"
|
||||
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp"
|
||||
"go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp"
|
||||
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
|
||||
otellogglobal "go.opentelemetry.io/otel/log/global"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
sdklog "go.opentelemetry.io/otel/sdk/log"
|
||||
sdkmetric "go.opentelemetry.io/otel/sdk/metric"
|
||||
"go.opentelemetry.io/otel/sdk/resource"
|
||||
sdktrace "go.opentelemetry.io/otel/sdk/trace"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
const (
|
||||
ServiceVersion = "6.0.0"
|
||||
instrumentationScope = "mtusi2026lab7"
|
||||
)
|
||||
|
||||
type Runtime struct {
|
||||
Tracer trace.Tracer
|
||||
Meter metric.Meter
|
||||
Logger *Logger
|
||||
|
||||
tracerProvider *sdktrace.TracerProvider
|
||||
meterProvider *sdkmetric.MeterProvider
|
||||
loggerProvider *sdklog.LoggerProvider
|
||||
}
|
||||
|
||||
func Start(
|
||||
ctx context.Context,
|
||||
serviceName string,
|
||||
instanceID string,
|
||||
deploymentEnvironment string,
|
||||
) (*Runtime, error) {
|
||||
serverName := os.Getenv("OTEL_TLS_SERVER_NAME")
|
||||
if serverName == "" {
|
||||
serverName = "telemetry-gateway"
|
||||
}
|
||||
clientTLS, err := security.ClientMTLSConfig(
|
||||
os.Getenv("CLIENT_TLS_CA_FILE"),
|
||||
os.Getenv("CLIENT_TLS_CERT_FILE"),
|
||||
os.Getenv("CLIENT_TLS_KEY_FILE"),
|
||||
serverName,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("configure OpenTelemetry mTLS: %w", err)
|
||||
}
|
||||
|
||||
res, err := resource.New(ctx, resource.WithAttributes(
|
||||
attribute.String("service.name", serviceName),
|
||||
attribute.String("service.version", ServiceVersion),
|
||||
attribute.String("service.instance.id", instanceID),
|
||||
attribute.String("deployment.environment.name", deploymentEnvironment),
|
||||
))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create OpenTelemetry resource: %w", err)
|
||||
}
|
||||
|
||||
traceExporter, err := otlptracehttp.New(ctx,
|
||||
otlptracehttp.WithTimeout(3*time.Second),
|
||||
otlptracehttp.WithTLSClientConfig(clientTLS.Clone()),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create OTLP trace exporter: %w", err)
|
||||
}
|
||||
tracerProvider := sdktrace.NewTracerProvider(
|
||||
sdktrace.WithResource(res),
|
||||
sdktrace.WithBatcher(
|
||||
traceExporter,
|
||||
sdktrace.WithBatchTimeout(time.Second),
|
||||
sdktrace.WithExportTimeout(3*time.Second),
|
||||
sdktrace.WithMaxQueueSize(2048),
|
||||
sdktrace.WithMaxExportBatchSize(256),
|
||||
),
|
||||
)
|
||||
|
||||
metricExporter, err := otlpmetrichttp.New(ctx,
|
||||
otlpmetrichttp.WithTimeout(3*time.Second),
|
||||
otlpmetrichttp.WithTLSClientConfig(clientTLS.Clone()),
|
||||
)
|
||||
if err != nil {
|
||||
_ = tracerProvider.Shutdown(context.Background())
|
||||
return nil, fmt.Errorf("create OTLP metric exporter: %w", err)
|
||||
}
|
||||
metricReader := sdkmetric.NewPeriodicReader(
|
||||
metricExporter,
|
||||
sdkmetric.WithInterval(5*time.Second),
|
||||
sdkmetric.WithTimeout(3*time.Second),
|
||||
)
|
||||
meterProvider := sdkmetric.NewMeterProvider(
|
||||
sdkmetric.WithResource(res),
|
||||
sdkmetric.WithReader(metricReader),
|
||||
sdkmetric.WithView(durationHistogramView(
|
||||
"messenger.http.server.duration",
|
||||
[]float64{0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10},
|
||||
)),
|
||||
sdkmetric.WithView(durationHistogramView(
|
||||
"messenger.worker.job.duration",
|
||||
[]float64{0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60},
|
||||
)),
|
||||
sdkmetric.WithView(durationHistogramView(
|
||||
"messenger.attachment.ready.duration",
|
||||
[]float64{0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60, 120},
|
||||
)),
|
||||
)
|
||||
|
||||
logExporter, err := otlploghttp.New(ctx,
|
||||
otlploghttp.WithTimeout(3*time.Second),
|
||||
otlploghttp.WithTLSClientConfig(clientTLS.Clone()),
|
||||
)
|
||||
if err != nil {
|
||||
_ = meterProvider.Shutdown(context.Background())
|
||||
_ = tracerProvider.Shutdown(context.Background())
|
||||
return nil, fmt.Errorf("create OTLP log exporter: %w", err)
|
||||
}
|
||||
loggerProvider := sdklog.NewLoggerProvider(
|
||||
sdklog.WithResource(res),
|
||||
sdklog.WithAttributeCountLimit(32),
|
||||
sdklog.WithAttributeValueLengthLimit(1024),
|
||||
sdklog.WithProcessor(sdklog.NewBatchProcessor(
|
||||
logExporter,
|
||||
sdklog.WithMaxQueueSize(2048),
|
||||
sdklog.WithExportMaxBatchSize(256),
|
||||
sdklog.WithExportInterval(time.Second),
|
||||
sdklog.WithExportTimeout(3*time.Second),
|
||||
)),
|
||||
)
|
||||
|
||||
otel.SetTracerProvider(tracerProvider)
|
||||
otel.SetMeterProvider(meterProvider)
|
||||
otellogglobal.SetLoggerProvider(loggerProvider)
|
||||
otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(
|
||||
propagation.TraceContext{},
|
||||
propagation.Baggage{},
|
||||
))
|
||||
|
||||
runtime := &Runtime{
|
||||
Tracer: tracerProvider.Tracer(instrumentationScope),
|
||||
Meter: meterProvider.Meter(instrumentationScope),
|
||||
Logger: NewLogger(otellogglobal.Logger(instrumentationScope), serviceName, instanceID),
|
||||
tracerProvider: tracerProvider,
|
||||
meterProvider: meterProvider,
|
||||
loggerProvider: loggerProvider,
|
||||
}
|
||||
if err = registerProcessMetrics(runtime.Meter); err != nil {
|
||||
_ = runtime.Shutdown(context.Background())
|
||||
return nil, err
|
||||
}
|
||||
return runtime, nil
|
||||
}
|
||||
|
||||
func durationHistogramView(name string, boundaries []float64) sdkmetric.View {
|
||||
return sdkmetric.NewView(
|
||||
sdkmetric.Instrument{Name: name, Kind: sdkmetric.InstrumentKindHistogram},
|
||||
sdkmetric.Stream{Aggregation: sdkmetric.AggregationExplicitBucketHistogram{
|
||||
Boundaries: boundaries,
|
||||
}},
|
||||
)
|
||||
}
|
||||
|
||||
func (runtime *Runtime) Shutdown(ctx context.Context) error {
|
||||
if runtime == nil {
|
||||
return nil
|
||||
}
|
||||
return errors.Join(
|
||||
runtime.loggerProvider.Shutdown(ctx),
|
||||
runtime.meterProvider.Shutdown(ctx),
|
||||
runtime.tracerProvider.Shutdown(ctx),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"mtusi2026lab7/internal/domain"
|
||||
)
|
||||
|
||||
type AttachmentVariantResponse struct {
|
||||
Name string `json:"name"`
|
||||
ContentType string `json:"content_type"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
Width int `json:"width"`
|
||||
Height int `json:"height"`
|
||||
SHA256 string `json:"sha256"`
|
||||
}
|
||||
|
||||
type AttachmentResponse struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
OwnerID string `json:"owner_id"`
|
||||
Filename string `json:"filename"`
|
||||
ContentType string `json:"content_type"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
SHA256 string `json:"sha256"`
|
||||
Status domain.AttachmentStatus `json:"status"`
|
||||
Variants []AttachmentVariantResponse `json:"variants"`
|
||||
ErrorCode *string `json:"error_code"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
func AttachmentFromDomain(attachment domain.Attachment) AttachmentResponse {
|
||||
variants := make([]AttachmentVariantResponse, 0, len(attachment.Variants))
|
||||
for _, variant := range attachment.Variants {
|
||||
variants = append(variants, AttachmentVariantResponse{
|
||||
Name: variant.Name,
|
||||
ContentType: variant.ContentType,
|
||||
SizeBytes: variant.SizeBytes,
|
||||
Width: variant.Width,
|
||||
Height: variant.Height,
|
||||
SHA256: variant.SHA256,
|
||||
})
|
||||
}
|
||||
return AttachmentResponse{
|
||||
ID: attachment.ID,
|
||||
ChatID: attachment.ChatID,
|
||||
OwnerID: attachment.OwnerID,
|
||||
Filename: attachment.Filename,
|
||||
ContentType: attachment.ContentType,
|
||||
SizeBytes: attachment.SizeBytes,
|
||||
SHA256: attachment.SHA256,
|
||||
Status: attachment.Status,
|
||||
Variants: variants,
|
||||
ErrorCode: attachment.ErrorCode,
|
||||
CreatedAt: attachment.CreatedAt,
|
||||
UpdatedAt: attachment.UpdatedAt,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"mtusi2026lab7/internal/domain"
|
||||
)
|
||||
|
||||
type CreateChatRequest struct {
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
}
|
||||
|
||||
type ChatResponse struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type ChatPageResponse struct {
|
||||
Items []ChatResponse `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
func ChatFromDomain(chat domain.Chat) ChatResponse {
|
||||
return ChatResponse{
|
||||
ID: chat.ID, Title: chat.Title, MemberIDs: chat.MemberIDs, CreatedAt: chat.CreatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func ChatPageFromDomain(page domain.ChatPage) ChatPageResponse {
|
||||
items := make([]ChatResponse, len(page.Items))
|
||||
for index, chat := range page.Items {
|
||||
items[index] = ChatFromDomain(chat)
|
||||
}
|
||||
return ChatPageResponse{Items: items, NextCursor: page.NextCursor}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"mtusi2026lab7/internal/domain"
|
||||
)
|
||||
|
||||
type CreateMessageRequest struct {
|
||||
Text string `json:"text"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
}
|
||||
|
||||
type MessageResponse struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
SenderID string `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type MessagePageResponse struct {
|
||||
Items []MessageResponse `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
func MessageFromDomain(message domain.Message) MessageResponse {
|
||||
attachmentIDs := append([]string(nil), message.AttachmentIDs...)
|
||||
if attachmentIDs == nil {
|
||||
attachmentIDs = make([]string, 0)
|
||||
}
|
||||
|
||||
return MessageResponse{
|
||||
ID: message.ID, ChatID: message.ChatID, SenderID: message.SenderID,
|
||||
Text: message.Text, AttachmentIDs: attachmentIDs, CreatedAt: message.CreatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func MessagePageFromDomain(page domain.MessagePage) MessagePageResponse {
|
||||
items := make([]MessageResponse, len(page.Items))
|
||||
for index, message := range page.Items {
|
||||
items[index] = MessageFromDomain(message)
|
||||
}
|
||||
return MessagePageResponse{Items: items, NextCursor: page.NextCursor}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"mtusi2026lab7/internal/domain"
|
||||
)
|
||||
|
||||
type SessionResponse struct {
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
User UserResponse `json:"user"`
|
||||
}
|
||||
|
||||
func SessionFromDomain(session domain.Session) SessionResponse {
|
||||
return SessionResponse{
|
||||
Token: session.Token, TokenType: session.TokenType, ExpiresAt: session.ExpiresAt,
|
||||
User: UserFromDomain(session.User),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"mtusi2026lab7/internal/domain"
|
||||
)
|
||||
|
||||
type CreateUserRequest struct {
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
type UserResponse struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
func UserFromDomain(user domain.User) UserResponse {
|
||||
return UserResponse{
|
||||
ID: user.ID, Username: user.Username, DisplayName: user.DisplayName, CreatedAt: user.CreatedAt,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"mtusi2026lab7/internal/application"
|
||||
"mtusi2026lab7/internal/domain"
|
||||
"mtusi2026lab7/internal/transport/http/dto"
|
||||
"mtusi2026lab7/internal/transport/http/middleware"
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
)
|
||||
|
||||
func (h *Handler) CreateChat(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
currentUser := middleware.GetCurrentUser(r.Context())
|
||||
|
||||
var request dto.CreateChatRequest
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeDecodeJSONError(w, requestID, err)
|
||||
return
|
||||
}
|
||||
|
||||
chat, err := h.service.CreateChat(r.Context(), application.CreateChatCommand{
|
||||
ActorID: currentUser.ID, Title: request.Title, MemberIDs: request.MemberIDs,
|
||||
})
|
||||
if errors.Is(err, application.ErrInvalidInput) {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
|
||||
strings.TrimPrefix(err.Error(), application.ErrInvalidInput.Error()+": "), requestID)
|
||||
return
|
||||
}
|
||||
if errors.Is(err, domain.ErrNotFound) {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
|
||||
"one or more members do not exist", requestID)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable,
|
||||
"service is temporarily unavailable", requestID)
|
||||
return
|
||||
}
|
||||
response.WriteJSON(w, http.StatusCreated, dto.ChatFromDomain(chat), requestID)
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"mtusi2026lab7/internal/application"
|
||||
"mtusi2026lab7/internal/domain"
|
||||
"mtusi2026lab7/internal/transport/http/dto"
|
||||
"mtusi2026lab7/internal/transport/http/middleware"
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var idempotencyKeyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
|
||||
func (h *Handler) CreateMessage(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
currentUser := middleware.GetCurrentUser(r.Context())
|
||||
parsedChatID, err := uuid.Parse(r.PathValue("chat_id"))
|
||||
if err != nil {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
|
||||
"invalid chat_id uuid", requestID)
|
||||
return
|
||||
}
|
||||
chatID := parsedChatID.String()
|
||||
|
||||
idempotencyKey := r.Header.Get("Idempotency-Key")
|
||||
if !idempotencyKeyPattern.MatchString(idempotencyKey) {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
|
||||
"Idempotency-Key must match [A-Za-z0-9._:-]{1,128}", requestID)
|
||||
return
|
||||
}
|
||||
|
||||
var request dto.CreateMessageRequest
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeDecodeJSONError(w, requestID, err)
|
||||
return
|
||||
}
|
||||
message, err := h.service.SendMessage(r.Context(), application.SendMessageCommand{
|
||||
ActorID: currentUser.ID,
|
||||
ChatID: chatID,
|
||||
Text: request.Text,
|
||||
AttachmentIDs: request.AttachmentIDs,
|
||||
Method: http.MethodPost,
|
||||
CanonicalPath: "/api/v1/chats/" + chatID + "/messages",
|
||||
IdempotencyKey: idempotencyKey,
|
||||
})
|
||||
if errors.Is(err, application.ErrIdempotencyConflict) {
|
||||
response.WriteError(w, http.StatusConflict, response.CodeConflict,
|
||||
"Idempotency-Key is already used for another request", requestID)
|
||||
return
|
||||
}
|
||||
if errors.Is(err, application.ErrAttachmentNotReady) {
|
||||
response.WriteError(w, http.StatusConflict, response.CodeConflict,
|
||||
"attachment is not ready", requestID)
|
||||
return
|
||||
}
|
||||
if errors.Is(err, application.ErrInvalidInput) {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
|
||||
strings.TrimPrefix(err.Error(), application.ErrInvalidInput.Error()+": "), requestID)
|
||||
return
|
||||
}
|
||||
if errors.Is(err, domain.ErrNotFound) {
|
||||
response.WriteError(w, http.StatusNotFound, response.CodeNotFound, "chat not found", requestID)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable,
|
||||
"service is temporarily unavailable", requestID)
|
||||
return
|
||||
}
|
||||
response.WriteJSON(w, http.StatusCreated, dto.MessageFromDomain(message), requestID)
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"mtusi2026lab7/internal/transport/http/middleware"
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
)
|
||||
|
||||
func (h *Handler) DeleteCurrentSession(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
tokenHash := middleware.GetCurrentSessionTokenHash(r.Context())
|
||||
if err := h.service.DeleteSession(r.Context(), tokenHash); err != nil {
|
||||
response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable,
|
||||
"service is temporarily unavailable", requestID)
|
||||
return
|
||||
}
|
||||
h.clearSessionCookie(w)
|
||||
response.WriteJSON(w, http.StatusNoContent, nil, requestID)
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"mtusi2026lab7/internal/application"
|
||||
"mtusi2026lab7/internal/domain"
|
||||
"mtusi2026lab7/internal/transport/http/dto"
|
||||
"mtusi2026lab7/internal/transport/http/middleware"
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func (h *Handler) GetAttachment(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
currentUser := middleware.GetCurrentUser(r.Context())
|
||||
attachmentID, ok := parseAttachmentID(w, r, requestID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
attachment, err := h.service.GetAttachment(r.Context(), attachmentID, currentUser.ID)
|
||||
if errors.Is(err, domain.ErrNotFound) {
|
||||
response.WriteError(w, http.StatusNotFound, response.CodeNotFound,
|
||||
"attachment not found", requestID)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable,
|
||||
"service is temporarily unavailable", requestID)
|
||||
return
|
||||
}
|
||||
response.WriteJSON(w, http.StatusOK, dto.AttachmentFromDomain(attachment), requestID)
|
||||
}
|
||||
|
||||
func (h *Handler) DownloadAttachment(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
currentUser := middleware.GetCurrentUser(r.Context())
|
||||
attachmentID, ok := parseAttachmentID(w, r, requestID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
download, err := h.service.DownloadAttachment(
|
||||
r.Context(), attachmentID, currentUser.ID, r.URL.Query().Get("variant"),
|
||||
)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
response.WriteError(w, http.StatusNotFound, response.CodeNotFound,
|
||||
"attachment or variant not found", requestID)
|
||||
return
|
||||
case errors.Is(err, application.ErrAttachmentNotReady):
|
||||
response.WriteError(w, http.StatusConflict, response.CodeConflict,
|
||||
"attachment is not ready", requestID)
|
||||
return
|
||||
case errors.Is(err, application.ErrStorageUnavailable):
|
||||
response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable,
|
||||
"object storage is temporarily unavailable", requestID)
|
||||
return
|
||||
case err != nil:
|
||||
response.WriteError(w, http.StatusInternalServerError, response.CodeInternalError,
|
||||
"unexpected internal error", requestID)
|
||||
return
|
||||
}
|
||||
defer download.Body.Close()
|
||||
|
||||
w.Header().Set("Content-Type", download.ContentType)
|
||||
w.Header().Set("Content-Length", strconv.FormatInt(download.SizeBytes, 10))
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.Header().Set("Content-Disposition", mime.FormatMediaType(
|
||||
"attachment", map[string]string{"filename": download.Filename},
|
||||
))
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = io.Copy(w, download.Body)
|
||||
}
|
||||
|
||||
func parseAttachmentID(
|
||||
w http.ResponseWriter,
|
||||
r *http.Request,
|
||||
requestID string,
|
||||
) (string, bool) {
|
||||
parsedID, err := uuid.Parse(r.PathValue("attachment_id"))
|
||||
if err != nil {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
|
||||
"invalid attachment_id uuid", requestID)
|
||||
return "", false
|
||||
}
|
||||
return parsedID.String(), true
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"mtusi2026lab7/internal/domain"
|
||||
"mtusi2026lab7/internal/transport/http/dto"
|
||||
"mtusi2026lab7/internal/transport/http/middleware"
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func (h *Handler) GetChat(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
currentUser := middleware.GetCurrentUser(r.Context())
|
||||
chatID := r.PathValue("chat_id")
|
||||
if _, err := uuid.Parse(chatID); err != nil {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
|
||||
"invalid chat_id uuid", requestID)
|
||||
return
|
||||
}
|
||||
|
||||
chat, err := h.service.GetChat(r.Context(), currentUser.ID, chatID)
|
||||
if errors.Is(err, domain.ErrNotFound) {
|
||||
response.WriteError(w, http.StatusNotFound, response.CodeNotFound, "chat not found", requestID)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable,
|
||||
"service is temporarily unavailable", requestID)
|
||||
return
|
||||
}
|
||||
response.WriteJSON(w, http.StatusOK, dto.ChatFromDomain(chat), requestID)
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"mtusi2026lab7/internal/transport/http/dto"
|
||||
"mtusi2026lab7/internal/transport/http/middleware"
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
)
|
||||
|
||||
func (h *Handler) GetMe(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
currentUser := middleware.GetCurrentUser(r.Context())
|
||||
response.WriteJSON(w, http.StatusOK, dto.UserFromDomain(currentUser), requestID)
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"mtusi2026lab7/internal/application"
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
)
|
||||
|
||||
const maxJSONBodyBytes = 1 << 20
|
||||
|
||||
var (
|
||||
errUnsupportedMediaType = errors.New("unsupported media type")
|
||||
errJSONBodyTooLarge = errors.New("JSON body exceeds 1 MiB")
|
||||
)
|
||||
|
||||
type ReadinessChecker interface {
|
||||
Ping(ctx context.Context) error
|
||||
}
|
||||
|
||||
type LoginRateLimiter interface {
|
||||
AllowLoginAttempt(context.Context, [32]byte, time.Time, time.Duration, int) (bool, time.Duration, error)
|
||||
ResetLoginAttempts(context.Context, [32]byte) error
|
||||
}
|
||||
|
||||
type Option func(*Handler)
|
||||
|
||||
type Handler struct {
|
||||
service *application.Service
|
||||
readinessChecker ReadinessChecker
|
||||
readinessTimeout time.Duration
|
||||
sessionCookieSecure bool
|
||||
loginRateLimiter LoginRateLimiter
|
||||
loginRateLimit int
|
||||
loginRateWindow time.Duration
|
||||
}
|
||||
|
||||
func NewHandler(
|
||||
service *application.Service,
|
||||
options ...Option,
|
||||
) *Handler {
|
||||
handler := &Handler{
|
||||
service: service,
|
||||
readinessTimeout: 2 * time.Second,
|
||||
loginRateLimit: 5,
|
||||
loginRateWindow: time.Minute,
|
||||
}
|
||||
|
||||
for _, option := range options {
|
||||
option(handler)
|
||||
}
|
||||
|
||||
return handler
|
||||
}
|
||||
|
||||
func WithLoginRateLimit(
|
||||
limiter LoginRateLimiter,
|
||||
limit int,
|
||||
window time.Duration,
|
||||
) Option {
|
||||
return func(handler *Handler) {
|
||||
handler.loginRateLimiter = limiter
|
||||
handler.loginRateLimit = limit
|
||||
handler.loginRateWindow = window
|
||||
}
|
||||
}
|
||||
|
||||
func WithReadiness(
|
||||
checker ReadinessChecker,
|
||||
timeout time.Duration,
|
||||
) Option {
|
||||
return func(handler *Handler) {
|
||||
handler.readinessChecker = checker
|
||||
handler.readinessTimeout = timeout
|
||||
}
|
||||
}
|
||||
|
||||
func WithSessionCookieSecure(secure bool) Option {
|
||||
return func(handler *Handler) {
|
||||
handler.sessionCookieSecure = secure
|
||||
}
|
||||
}
|
||||
|
||||
func decodeJSON(r *http.Request, destination any) error {
|
||||
mediaType, parameters, err := mime.ParseMediaType(
|
||||
r.Header.Get("Content-Type"),
|
||||
)
|
||||
if err != nil || mediaType != "application/json" {
|
||||
return errUnsupportedMediaType
|
||||
}
|
||||
if charset, exists := parameters["charset"]; exists &&
|
||||
!strings.EqualFold(charset, "utf-8") {
|
||||
return errUnsupportedMediaType
|
||||
}
|
||||
|
||||
if r.Body == nil {
|
||||
return errors.New("request body is empty")
|
||||
}
|
||||
defer r.Body.Close()
|
||||
|
||||
payload, err := io.ReadAll(io.LimitReader(
|
||||
r.Body,
|
||||
maxJSONBodyBytes+1,
|
||||
))
|
||||
if err != nil {
|
||||
return errors.New("read request body")
|
||||
}
|
||||
if len(payload) > maxJSONBodyBytes {
|
||||
return errJSONBodyTooLarge
|
||||
}
|
||||
if !utf8.Valid(payload) {
|
||||
return errors.New("request body must be valid UTF-8")
|
||||
}
|
||||
|
||||
decoder := json.NewDecoder(bytes.NewReader(payload))
|
||||
decoder.DisallowUnknownFields()
|
||||
|
||||
if err := decoder.Decode(destination); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var extra json.RawMessage
|
||||
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
|
||||
return errors.New("extra data after JSON")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func writeDecodeJSONError(
|
||||
w http.ResponseWriter,
|
||||
requestID string,
|
||||
err error,
|
||||
) {
|
||||
switch {
|
||||
case errors.Is(err, errUnsupportedMediaType):
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusUnsupportedMediaType,
|
||||
response.CodeUnsupportedMediaType,
|
||||
"Content-Type must be application/json",
|
||||
requestID,
|
||||
)
|
||||
case errors.Is(err, errJSONBodyTooLarge):
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusRequestEntityTooLarge,
|
||||
response.CodePayloadTooLarge,
|
||||
err.Error(),
|
||||
requestID,
|
||||
)
|
||||
default:
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusBadRequest,
|
||||
response.CodeInvalidRequest,
|
||||
"malformed or invalid JSON: "+err.Error(),
|
||||
requestID,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDecodeJSONRejectsBodyAboveOneMiB(t *testing.T) {
|
||||
request := httptest.NewRequest(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
strings.NewReader(strings.Repeat(" ", maxJSONBodyBytes+1)),
|
||||
)
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
var destination map[string]any
|
||||
err := decodeJSON(request, &destination)
|
||||
if !errors.Is(err, errJSONBodyTooLarge) {
|
||||
t.Fatalf("expected errJSONBodyTooLarge, got %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"mtusi2026lab7/internal/transport/http/middleware"
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
)
|
||||
|
||||
// HealthLive проверяет только то, что HTTP-процесс работает.
|
||||
func (h *Handler) HealthLive(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
|
||||
response.WriteJSON(
|
||||
w,
|
||||
http.StatusOK,
|
||||
map[string]string{"status": "ok"},
|
||||
requestID,
|
||||
)
|
||||
}
|
||||
|
||||
// HealthReady проверяет зависимости, без которых API не может обслуживать трафик.
|
||||
func (h *Handler) HealthReady(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
|
||||
// Этот вариант сохраняет работоспособность изолированных unit-тестов,
|
||||
// в которых PostgreSQL намеренно не создаётся.
|
||||
if h.readinessChecker == nil {
|
||||
response.WriteJSON(
|
||||
w,
|
||||
http.StatusOK,
|
||||
map[string]string{"status": "ok"},
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(
|
||||
r.Context(),
|
||||
h.readinessTimeout,
|
||||
)
|
||||
defer cancel()
|
||||
|
||||
if err := h.readinessChecker.Ping(ctx); err != nil {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusServiceUnavailable,
|
||||
response.CodeUnavailable,
|
||||
"service is not ready",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
response.WriteJSON(
|
||||
w,
|
||||
http.StatusOK,
|
||||
map[string]string{"status": "ok"},
|
||||
requestID,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"mtusi2026lab7/internal/application"
|
||||
"mtusi2026lab7/internal/transport/http/dto"
|
||||
"mtusi2026lab7/internal/transport/http/middleware"
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
)
|
||||
|
||||
func (h *Handler) ListChats(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
currentUser := middleware.GetCurrentUser(r.Context())
|
||||
limit, cursor, ok := parsePagination(w, r, requestID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
page, err := h.service.ListChats(r.Context(), currentUser.ID, limit, cursor)
|
||||
if errors.Is(err, application.ErrInvalidCursor) {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, "invalid cursor", requestID)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable,
|
||||
"service is temporarily unavailable", requestID)
|
||||
return
|
||||
}
|
||||
response.WriteJSON(w, http.StatusOK, dto.ChatPageFromDomain(page), requestID)
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"mtusi2026lab7/internal/application"
|
||||
"mtusi2026lab7/internal/domain"
|
||||
"mtusi2026lab7/internal/transport/http/dto"
|
||||
"mtusi2026lab7/internal/transport/http/middleware"
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func (h *Handler) GetMessages(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
currentUser := middleware.GetCurrentUser(r.Context())
|
||||
chatID := r.PathValue("chat_id")
|
||||
if _, err := uuid.Parse(chatID); err != nil {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
|
||||
"invalid chat_id uuid", requestID)
|
||||
return
|
||||
}
|
||||
limit, cursor, ok := parsePagination(w, r, requestID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
page, err := h.service.ListMessages(r.Context(), currentUser.ID, chatID, limit, cursor)
|
||||
if errors.Is(err, domain.ErrNotFound) {
|
||||
response.WriteError(w, http.StatusNotFound, response.CodeNotFound, "chat not found", requestID)
|
||||
return
|
||||
}
|
||||
if errors.Is(err, application.ErrInvalidCursor) {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, "invalid cursor", requestID)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable,
|
||||
"service is temporarily unavailable", requestID)
|
||||
return
|
||||
}
|
||||
response.WriteJSON(w, http.StatusOK, dto.MessagePageFromDomain(page), requestID)
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
)
|
||||
|
||||
func parsePagination(w http.ResponseWriter, r *http.Request, requestID string) (int, string, bool) {
|
||||
query := r.URL.Query()
|
||||
limit := 50
|
||||
if query.Has("limit") {
|
||||
parsed, err := strconv.Atoi(query.Get("limit"))
|
||||
if err != nil || parsed < 1 || parsed > 100 {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
|
||||
"limit must be an integer between 1 and 100", requestID)
|
||||
return 0, "", false
|
||||
}
|
||||
limit = parsed
|
||||
}
|
||||
cursor := query.Get("cursor")
|
||||
if query.Has("cursor") && cursor == "" {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
|
||||
"cursor must not be empty", requestID)
|
||||
return 0, "", false
|
||||
}
|
||||
return limit, cursor, true
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
const sessionCookieName = "mtusi_session"
|
||||
|
||||
func (h *Handler) setSessionCookie(
|
||||
w http.ResponseWriter,
|
||||
token string,
|
||||
expiresAt time.Time,
|
||||
) {
|
||||
maxAge := int(time.Until(expiresAt).Seconds())
|
||||
if maxAge < 1 {
|
||||
maxAge = 1
|
||||
}
|
||||
|
||||
h.writeSessionCookie(w, token, expiresAt, maxAge)
|
||||
}
|
||||
|
||||
func (h *Handler) clearSessionCookie(w http.ResponseWriter) {
|
||||
h.writeSessionCookie(w, "", time.Unix(1, 0).UTC(), -1)
|
||||
}
|
||||
|
||||
func (h *Handler) writeSessionCookie(
|
||||
w http.ResponseWriter,
|
||||
value string,
|
||||
expiresAt time.Time,
|
||||
maxAge int,
|
||||
) {
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: sessionCookieName, Value: value, Path: "/",
|
||||
Expires: expiresAt, MaxAge: maxAge,
|
||||
HttpOnly: true, Secure: h.sessionCookieSecure,
|
||||
SameSite: http.SameSiteStrictMode,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestSessionCookieIsHardened(t *testing.T) {
|
||||
handler := &Handler{sessionCookieSecure: true}
|
||||
recorder := httptest.NewRecorder()
|
||||
|
||||
handler.setSessionCookie(
|
||||
recorder,
|
||||
"secret-token",
|
||||
time.Now().Add(time.Hour),
|
||||
)
|
||||
|
||||
cookies := recorder.Result().Cookies()
|
||||
if len(cookies) != 1 {
|
||||
t.Fatalf("cookie count = %d, want 1", len(cookies))
|
||||
}
|
||||
|
||||
cookie := cookies[0]
|
||||
if cookie.Name != sessionCookieName || cookie.Value != "secret-token" {
|
||||
t.Fatalf("unexpected cookie: %#v", cookie)
|
||||
}
|
||||
if cookie.Path != "/" || cookie.Domain != "" {
|
||||
t.Fatalf("cookie scope = path %q domain %q", cookie.Path, cookie.Domain)
|
||||
}
|
||||
if !cookie.HttpOnly || !cookie.Secure {
|
||||
t.Fatalf("cookie flags: HttpOnly=%v Secure=%v", cookie.HttpOnly, cookie.Secure)
|
||||
}
|
||||
if cookie.SameSite != http.SameSiteStrictMode {
|
||||
t.Fatalf("SameSite = %v, want Strict", cookie.SameSite)
|
||||
}
|
||||
if cookie.MaxAge < 1 {
|
||||
t.Fatalf("MaxAge = %d, want positive", cookie.MaxAge)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClearSessionCookieExpiresIt(t *testing.T) {
|
||||
handler := &Handler{}
|
||||
recorder := httptest.NewRecorder()
|
||||
|
||||
handler.clearSessionCookie(recorder)
|
||||
|
||||
cookies := recorder.Result().Cookies()
|
||||
if len(cookies) != 1 {
|
||||
t.Fatalf("cookie count = %d, want 1", len(cookies))
|
||||
}
|
||||
|
||||
cookie := cookies[0]
|
||||
if cookie.Value != "" || cookie.MaxAge != -1 {
|
||||
t.Fatalf("clear cookie = value %q MaxAge %d", cookie.Value, cookie.MaxAge)
|
||||
}
|
||||
if !cookie.Expires.Before(time.Now()) {
|
||||
t.Fatalf("clear cookie expiry %v is not in the past", cookie.Expires)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"math"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"mtusi2026lab7/internal/application"
|
||||
"mtusi2026lab7/internal/transport/http/dto"
|
||||
"mtusi2026lab7/internal/transport/http/middleware"
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
)
|
||||
|
||||
const basicChallenge = `Basic realm="messenger", charset="UTF-8"`
|
||||
|
||||
func (h *Handler) CreateSession(
|
||||
w http.ResponseWriter,
|
||||
r *http.Request,
|
||||
) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
|
||||
username, password, ok := r.BasicAuth()
|
||||
if !ok || username == "" ||
|
||||
!utf8.ValidString(username) || !utf8.ValidString(password) {
|
||||
writeBasicUnauthorized(w, requestID)
|
||||
return
|
||||
}
|
||||
identifierHash := sha256.Sum256([]byte(strings.ToLower(username)))
|
||||
if h.loginRateLimiter != nil {
|
||||
allowed, retryAfter, err := h.loginRateLimiter.AllowLoginAttempt(
|
||||
r.Context(), identifierHash, time.Now().UTC(), h.loginRateWindow, h.loginRateLimit,
|
||||
)
|
||||
if err != nil {
|
||||
response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable,
|
||||
"service is temporarily unavailable", requestID)
|
||||
return
|
||||
}
|
||||
if !allowed {
|
||||
seconds := int(math.Ceil(retryAfter.Seconds()))
|
||||
if seconds < 1 {
|
||||
seconds = 1
|
||||
}
|
||||
w.Header().Set("Retry-After", strconv.Itoa(seconds))
|
||||
response.WriteError(w, http.StatusTooManyRequests, response.CodeRateLimited,
|
||||
"too many login attempts", requestID)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
session, err := h.service.CreateSession(r.Context(), application.CreateSessionCommand{
|
||||
Username: username,
|
||||
Password: password,
|
||||
})
|
||||
if errors.Is(err, application.ErrCredentialState) {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusInternalServerError,
|
||||
response.CodeInternalError,
|
||||
"service is temporarily unavailable",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
if errors.Is(err, application.ErrInvalidCredentials) {
|
||||
writeBasicUnauthorized(w, requestID)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusServiceUnavailable,
|
||||
response.CodeUnavailable,
|
||||
"service is temporarily unavailable",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
if h.loginRateLimiter != nil {
|
||||
if err = h.loginRateLimiter.ResetLoginAttempts(r.Context(), identifierHash); err != nil {
|
||||
response.WriteError(w, http.StatusServiceUnavailable, response.CodeUnavailable,
|
||||
"service is temporarily unavailable", requestID)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
h.setSessionCookie(w, session.Token, session.ExpiresAt)
|
||||
|
||||
response.WriteJSON(
|
||||
w,
|
||||
http.StatusCreated,
|
||||
dto.SessionFromDomain(session),
|
||||
requestID,
|
||||
)
|
||||
}
|
||||
func writeBasicUnauthorized(
|
||||
w http.ResponseWriter,
|
||||
requestID string,
|
||||
) {
|
||||
w.Header().Set("WWW-Authenticate", basicChallenge)
|
||||
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusUnauthorized,
|
||||
response.CodeUnauthorized,
|
||||
"invalid username or password",
|
||||
requestID,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"mime"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"mtusi2026lab7/internal/application"
|
||||
"mtusi2026lab7/internal/domain"
|
||||
"mtusi2026lab7/internal/transport/http/dto"
|
||||
"mtusi2026lab7/internal/transport/http/middleware"
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func (h *Handler) UploadAttachment(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
currentUser := middleware.GetCurrentUser(r.Context())
|
||||
|
||||
parsedChatID, err := uuid.Parse(r.PathValue("chat_id"))
|
||||
if err != nil {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
|
||||
"invalid chat_id uuid", requestID)
|
||||
return
|
||||
}
|
||||
filename := r.URL.Query().Get("filename")
|
||||
if filename == "" {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
|
||||
"filename query parameter is required", requestID)
|
||||
return
|
||||
}
|
||||
|
||||
contentType, parameters, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if err != nil || len(parameters) != 0 ||
|
||||
(contentType != "image/png" && contentType != "image/jpeg") {
|
||||
response.WriteError(w, http.StatusUnsupportedMediaType,
|
||||
response.CodeUnsupportedMediaType,
|
||||
"Content-Type must be image/png or image/jpeg", requestID)
|
||||
return
|
||||
}
|
||||
if r.ContentLength > domain.MaxAttachmentSizeBytes {
|
||||
response.WriteError(w, http.StatusRequestEntityTooLarge,
|
||||
response.CodePayloadTooLarge,
|
||||
"attachment exceeds 10 MiB", requestID)
|
||||
return
|
||||
}
|
||||
if r.Body == nil {
|
||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
|
||||
"attachment body is required", requestID)
|
||||
return
|
||||
}
|
||||
defer r.Body.Close()
|
||||
|
||||
attachment, err := h.service.UploadAttachment(
|
||||
r.Context(),
|
||||
application.UploadAttachmentCommand{
|
||||
ActorID: currentUser.ID,
|
||||
ChatID: parsedChatID.String(),
|
||||
Filename: filename,
|
||||
DeclaredContentType: contentType,
|
||||
Body: r.Body,
|
||||
},
|
||||
)
|
||||
switch {
|
||||
case errors.Is(err, application.ErrPayloadTooLarge):
|
||||
response.WriteError(w, http.StatusRequestEntityTooLarge,
|
||||
response.CodePayloadTooLarge,
|
||||
"attachment exceeds 10 MiB or 40 million pixels", requestID)
|
||||
return
|
||||
case errors.Is(err, application.ErrUnsupportedMediaType), errors.Is(err, application.ErrInvalidImage):
|
||||
response.WriteError(w, http.StatusUnsupportedMediaType,
|
||||
response.CodeUnsupportedMediaType,
|
||||
"body is not a valid PNG/JPEG matching the declared Content-Type", requestID)
|
||||
return
|
||||
case errors.Is(err, application.ErrInvalidInput):
|
||||
message := strings.TrimPrefix(err.Error(), application.ErrInvalidInput.Error()+": ")
|
||||
response.WriteError(w, http.StatusBadRequest,
|
||||
response.CodeInvalidRequest, message, requestID)
|
||||
return
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
response.WriteError(w, http.StatusNotFound,
|
||||
response.CodeNotFound, "chat not found", requestID)
|
||||
return
|
||||
case errors.Is(err, application.ErrStorageUnavailable):
|
||||
response.WriteError(w, http.StatusServiceUnavailable,
|
||||
response.CodeUnavailable, "object storage is temporarily unavailable", requestID)
|
||||
return
|
||||
case err != nil:
|
||||
response.WriteError(w, http.StatusServiceUnavailable,
|
||||
response.CodeUnavailable, "service is temporarily unavailable", requestID)
|
||||
return
|
||||
}
|
||||
|
||||
response.WriteJSON(w, http.StatusAccepted, dto.AttachmentFromDomain(attachment), requestID)
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"mtusi2026lab7/internal/application"
|
||||
"mtusi2026lab7/internal/domain"
|
||||
"mtusi2026lab7/internal/transport/http/dto"
|
||||
"mtusi2026lab7/internal/transport/http/middleware"
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
)
|
||||
|
||||
func (h *Handler) CreateUser(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := middleware.GetRequestID(r.Context())
|
||||
|
||||
var request dto.CreateUserRequest
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeDecodeJSONError(w, requestID, err)
|
||||
return
|
||||
}
|
||||
|
||||
createdUser, err := h.service.CreateUser(r.Context(), application.CreateUserCommand{
|
||||
Username: request.Username, DisplayName: request.DisplayName, Password: request.Password,
|
||||
})
|
||||
if errors.Is(err, application.ErrInvalidInput) {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusBadRequest,
|
||||
response.CodeInvalidRequest,
|
||||
strings.TrimPrefix(err.Error(), application.ErrInvalidInput.Error()+": "),
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
if errors.Is(err, domain.ErrConflict) {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusConflict,
|
||||
response.CodeConflict,
|
||||
"username already exists",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusServiceUnavailable,
|
||||
response.CodeUnavailable,
|
||||
"service is temporarily unavailable",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
response.WriteJSON(
|
||||
w,
|
||||
http.StatusCreated,
|
||||
dto.UserFromDomain(createdUser),
|
||||
requestID,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"mtusi2026lab7/internal/domain"
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
)
|
||||
|
||||
const bearerChallenge = `Bearer realm="messenger"`
|
||||
|
||||
const (
|
||||
UserContextKey contextKey = "current_user"
|
||||
sessionTokenHashKey contextKey = "session_token_hash"
|
||||
)
|
||||
|
||||
type SessionAuthenticator interface {
|
||||
Authenticate(
|
||||
ctx context.Context,
|
||||
token string,
|
||||
) (domain.User, []byte, error)
|
||||
}
|
||||
|
||||
func RequireAuth(
|
||||
authenticator SessionAuthenticator,
|
||||
next http.HandlerFunc,
|
||||
) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := GetRequestID(r.Context())
|
||||
|
||||
token, ok := bearerToken(r.Header.Get("Authorization"))
|
||||
if !ok {
|
||||
writeBearerUnauthorized(w, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
user, tokenHash, err := authenticator.Authenticate(
|
||||
r.Context(),
|
||||
token,
|
||||
)
|
||||
if errors.Is(err, domain.ErrNotFound) {
|
||||
writeBearerUnauthorized(w, requestID)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusServiceUnavailable,
|
||||
response.CodeUnavailable,
|
||||
"service is temporarily unavailable",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
ctx := context.WithValue(
|
||||
r.Context(),
|
||||
UserContextKey,
|
||||
user,
|
||||
)
|
||||
ctx = context.WithValue(
|
||||
ctx,
|
||||
sessionTokenHashKey,
|
||||
tokenHash,
|
||||
)
|
||||
|
||||
next(w, r.WithContext(ctx))
|
||||
}
|
||||
}
|
||||
|
||||
func GetCurrentUser(ctx context.Context) domain.User {
|
||||
user, _ := ctx.Value(UserContextKey).(domain.User)
|
||||
return user
|
||||
}
|
||||
|
||||
func GetCurrentSessionTokenHash(ctx context.Context) []byte {
|
||||
tokenHash, _ := ctx.Value(sessionTokenHashKey).([]byte)
|
||||
|
||||
result := make([]byte, len(tokenHash))
|
||||
copy(result, tokenHash)
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
func bearerToken(authorization string) (string, bool) {
|
||||
parts := strings.Fields(authorization)
|
||||
|
||||
if len(parts) != 2 ||
|
||||
!strings.EqualFold(parts[0], "Bearer") ||
|
||||
parts[1] == "" {
|
||||
return "", false
|
||||
}
|
||||
|
||||
return parts[1], true
|
||||
}
|
||||
|
||||
func writeBearerUnauthorized(
|
||||
w http.ResponseWriter,
|
||||
requestID string,
|
||||
) {
|
||||
w.Header().Set("WWW-Authenticate", bearerChallenge)
|
||||
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusUnauthorized,
|
||||
response.CodeUnauthorized,
|
||||
"invalid or expired bearer token",
|
||||
requestID,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
)
|
||||
|
||||
// AvailabilityGate lets a process reject new work before its HTTP listener is
|
||||
// closed. Existing requests are still drained by http.Server.Shutdown.
|
||||
type AvailabilityGate struct {
|
||||
accepting atomic.Bool
|
||||
}
|
||||
|
||||
func NewAvailabilityGate() *AvailabilityGate {
|
||||
gate := &AvailabilityGate{}
|
||||
gate.accepting.Store(true)
|
||||
|
||||
return gate
|
||||
}
|
||||
|
||||
func (g *AvailabilityGate) BeginDrain() {
|
||||
g.accepting.Store(false)
|
||||
}
|
||||
|
||||
func (g *AvailabilityGate) IsAccepting() bool {
|
||||
return g.accepting.Load()
|
||||
}
|
||||
|
||||
func (g *AvailabilityGate) Middleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// Liveness deliberately stays available while the process drains. The
|
||||
// readiness endpoint and all business traffic receive 503 immediately.
|
||||
if g.IsAccepting() || r.URL.Path == "/health/live" {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusServiceUnavailable,
|
||||
response.CodeUnavailable,
|
||||
"service is draining",
|
||||
GetRequestID(r.Context()),
|
||||
)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestAvailabilityGateRejectsNewWorkWhileKeepingLiveness(t *testing.T) {
|
||||
gate := NewAvailabilityGate()
|
||||
next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
})
|
||||
handler := RequestID(gate.Middleware(next))
|
||||
|
||||
before := httptest.NewRecorder()
|
||||
handler.ServeHTTP(before, httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil))
|
||||
if before.Code != http.StatusNoContent {
|
||||
t.Fatalf("before drain status = %d, want %d", before.Code, http.StatusNoContent)
|
||||
}
|
||||
|
||||
gate.BeginDrain()
|
||||
|
||||
draining := httptest.NewRecorder()
|
||||
handler.ServeHTTP(draining, httptest.NewRequest(http.MethodGet, "/health/ready", nil))
|
||||
if draining.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("ready while draining status = %d, want %d", draining.Code, http.StatusServiceUnavailable)
|
||||
}
|
||||
if draining.Header().Get("X-Request-Id") == "" {
|
||||
t.Fatal("draining response is missing X-Request-Id")
|
||||
}
|
||||
|
||||
live := httptest.NewRecorder()
|
||||
handler.ServeHTTP(live, httptest.NewRequest(http.MethodGet, "/health/live", nil))
|
||||
if live.Code != http.StatusNoContent {
|
||||
t.Fatalf("live while draining status = %d, want %d", live.Code, http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package middleware
|
||||
|
||||
import "net/http"
|
||||
|
||||
const InstanceIDHeader = "X-Instance-Id"
|
||||
|
||||
// InstanceID identifies the process that actually produced the response.
|
||||
// It must wrap recovery and routing so even errors, health checks and 404/405
|
||||
// responses carry the same stable process identifier.
|
||||
func InstanceID(instanceID string, next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set(InstanceIDHeader, instanceID)
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestInstanceIDOnSuccessfulAndNotFoundResponses(t *testing.T) {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /ok", func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
})
|
||||
handler := InstanceID("api-01", mux)
|
||||
|
||||
for _, test := range []struct {
|
||||
path string
|
||||
wantStatus int
|
||||
}{
|
||||
{path: "/ok", wantStatus: http.StatusNoContent},
|
||||
{path: "/missing", wantStatus: http.StatusNotFound},
|
||||
} {
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, test.path, nil))
|
||||
|
||||
if recorder.Code != test.wantStatus {
|
||||
t.Fatalf("%s: got status %d, want %d", test.path, recorder.Code, test.wantStatus)
|
||||
}
|
||||
if got := recorder.Header().Get(InstanceIDHeader); got != "api-01" {
|
||||
t.Fatalf("%s: got instance ID %q, want api-01", test.path, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstanceIDSurvivesRecoveredPanic(t *testing.T) {
|
||||
panicking := http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
|
||||
panic("test panic")
|
||||
})
|
||||
handler := InstanceID("api-panic", Recovery(panicking))
|
||||
recorder := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/panic", nil))
|
||||
|
||||
if recorder.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("got status %d, want 500", recorder.Code)
|
||||
}
|
||||
if got := recorder.Header().Get(InstanceIDHeader); got != "api-panic" {
|
||||
t.Fatalf("got instance ID %q, want api-panic", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
apptelemetry "mtusi2026lab7/internal/telemetry"
|
||||
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
type responseWriterInterceptor struct {
|
||||
http.ResponseWriter
|
||||
statusCode int
|
||||
}
|
||||
|
||||
func (w *responseWriterInterceptor) WriteHeader(code int) {
|
||||
w.statusCode = code
|
||||
w.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
func Observability(runtime *apptelemetry.Runtime, next http.Handler) (http.Handler, error) {
|
||||
requests, err := runtime.Meter.Int64Counter(
|
||||
"messenger.http.server.requests",
|
||||
metric.WithDescription("Number of completed HTTP requests"),
|
||||
metric.WithUnit("{request}"),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create HTTP request counter: %w", err)
|
||||
}
|
||||
duration, err := runtime.Meter.Float64Histogram(
|
||||
"messenger.http.server.duration",
|
||||
metric.WithDescription("HTTP server request duration"),
|
||||
metric.WithUnit("s"),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create HTTP duration histogram: %w", err)
|
||||
}
|
||||
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if strings.HasPrefix(r.URL.Path, "/health/") {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
start := time.Now()
|
||||
parent := otel.GetTextMapPropagator().Extract(
|
||||
r.Context(),
|
||||
propagation.HeaderCarrier(r.Header),
|
||||
)
|
||||
ctx, span := runtime.Tracer.Start(
|
||||
parent,
|
||||
r.Method+" HTTP request",
|
||||
trace.WithSpanKind(trace.SpanKindServer),
|
||||
trace.WithAttributes(attribute.String("http.request.method", r.Method)),
|
||||
)
|
||||
defer span.End()
|
||||
interceptor := &responseWriterInterceptor{
|
||||
ResponseWriter: w,
|
||||
statusCode: http.StatusOK,
|
||||
}
|
||||
observedRequest := r.WithContext(ctx)
|
||||
next.ServeHTTP(interceptor, observedRequest)
|
||||
|
||||
route := observedRequest.Pattern
|
||||
if route == "" {
|
||||
route = "unmatched"
|
||||
}
|
||||
statusClass := strconv.Itoa(interceptor.statusCode/100) + "xx"
|
||||
elapsed := time.Since(start)
|
||||
labels := metric.WithAttributes(
|
||||
attribute.String("method", r.Method),
|
||||
attribute.String("route", route),
|
||||
attribute.String("status_class", statusClass),
|
||||
)
|
||||
requests.Add(ctx, 1, labels)
|
||||
duration.Record(ctx, elapsed.Seconds(), labels)
|
||||
|
||||
span.SetName(r.Method + " " + route)
|
||||
span.SetAttributes(
|
||||
attribute.String("http.route", route),
|
||||
attribute.Int("http.response.status_code", interceptor.statusCode),
|
||||
)
|
||||
if interceptor.statusCode >= http.StatusInternalServerError {
|
||||
span.SetStatus(codes.Error, "server error")
|
||||
} else {
|
||||
span.SetStatus(codes.Ok, "")
|
||||
}
|
||||
|
||||
runtime.Logger.Info(ctx, "http_request_completed", apptelemetry.Fields{
|
||||
"method": r.Method,
|
||||
"route": route,
|
||||
"status_code": interceptor.statusCode,
|
||||
"status_class": statusClass,
|
||||
"duration_ms": float64(elapsed.Microseconds()) / 1000,
|
||||
"request_id": GetRequestID(ctx),
|
||||
})
|
||||
}), nil
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"mtusi2026lab7/internal/transport/http/response"
|
||||
)
|
||||
|
||||
// Recovery перехватывает панику и возвращает клиенту валидный JSON 500
|
||||
func Recovery(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
reqID := GetRequestID(r.Context())
|
||||
//из контракта: не раскрывать stack trace и внутренности
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusInternalServerError,
|
||||
response.CodeInternalError,
|
||||
"internal server error",
|
||||
reqID,
|
||||
)
|
||||
}
|
||||
}()
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type contextKey string
|
||||
|
||||
const RequestIDKey contextKey = "request_id"
|
||||
|
||||
// RequestID извлекает или генерирует X-Request-Id и кладет его в контекст и заголовок ответа
|
||||
func RequestID(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
reqID := r.Header.Get("X-Request-Id")
|
||||
if reqID == "" {
|
||||
reqID = uuid.NewString()
|
||||
}
|
||||
|
||||
w.Header().Set("X-Request-Id", reqID)
|
||||
|
||||
ctx := context.WithValue(r.Context(), RequestIDKey, reqID)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
// GetRequestID достает ID запроса из контекста
|
||||
func GetRequestID(ctx context.Context) string {
|
||||
if val, ok := ctx.Value(RequestIDKey).(string); ok {
|
||||
return val
|
||||
}
|
||||
return uuid.NewString()
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package response
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// коды ошибок по контракту
|
||||
const (
|
||||
CodeInvalidRequest = "invalid_request"
|
||||
CodePayloadTooLarge = "payload_too_large"
|
||||
CodeUnsupportedMediaType = "unsupported_media_type"
|
||||
CodeUnauthorized = "unauthorized"
|
||||
CodeNotFound = "not_found"
|
||||
CodeConflict = "conflict"
|
||||
CodeRateLimited = "rate_limited"
|
||||
CodeUnavailable = "unavailable"
|
||||
CodeInternalError = "internal_error"
|
||||
)
|
||||
|
||||
type ErrorPayload struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
|
||||
// ErrorResponse — строгое тело ответа при любой ошибке
|
||||
type ErrorResponse struct {
|
||||
Error ErrorPayload `json:"error"`
|
||||
}
|
||||
|
||||
// WriteJSON отправляет любой успешный ответ с правильными заголовками
|
||||
func WriteJSON(w http.ResponseWriter, statusCode int, data any, requestID string) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
if requestID != "" {
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
}
|
||||
|
||||
w.WriteHeader(statusCode)
|
||||
|
||||
if data != nil {
|
||||
_ = json.NewEncoder(w).Encode(data)
|
||||
}
|
||||
}
|
||||
|
||||
// WriteError формирует стандартизированную ошибку с совпадением request_id в теле и заголовке
|
||||
func WriteError(w http.ResponseWriter, statusCode int, code string, message string, requestID string) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
if requestID != "" {
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
}
|
||||
|
||||
w.WriteHeader(statusCode)
|
||||
|
||||
resp := ErrorResponse{
|
||||
Error: ErrorPayload{
|
||||
Code: code,
|
||||
Message: message,
|
||||
RequestID: requestID,
|
||||
},
|
||||
}
|
||||
|
||||
_ = json.NewEncoder(w).Encode(resp)
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
// RetryDelay returns exponential backoff with deterministic per-job jitter in
|
||||
// [0.5, 1.5). Determinism makes retries reproducible while still avoiding a
|
||||
// synchronized retry wave across different jobs.
|
||||
func RetryDelay(jobID string, nextAttempt int, base, maximum time.Duration) time.Duration {
|
||||
if base <= 0 {
|
||||
base = time.Millisecond
|
||||
}
|
||||
if maximum < base {
|
||||
maximum = base
|
||||
}
|
||||
exponent := nextAttempt - 2
|
||||
if exponent < 0 {
|
||||
exponent = 0
|
||||
}
|
||||
delay := base
|
||||
for index := 0; index < exponent && delay < maximum; index++ {
|
||||
if delay > maximum/2 {
|
||||
delay = maximum
|
||||
break
|
||||
}
|
||||
delay *= 2
|
||||
}
|
||||
if delay > maximum {
|
||||
delay = maximum
|
||||
}
|
||||
sum := sha256.Sum256([]byte(jobID + ":" + strconv.Itoa(nextAttempt)))
|
||||
fraction := float64(binary.BigEndian.Uint64(sum[:8])) / float64(^uint64(0))
|
||||
jittered := time.Duration(float64(delay) * (0.5 + fraction))
|
||||
if jittered > maximum {
|
||||
return maximum
|
||||
}
|
||||
if jittered < time.Millisecond {
|
||||
return time.Millisecond
|
||||
}
|
||||
return jittered
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestRetryDelayUsesBoundedExponentialJitter(t *testing.T) {
|
||||
base := 200 * time.Millisecond
|
||||
maximum := 2 * time.Second
|
||||
previousCeiling := time.Duration(0)
|
||||
for attempt := 2; attempt <= 8; attempt++ {
|
||||
delay := RetryDelay("job-a", attempt, base, maximum)
|
||||
if delay < time.Millisecond || delay > maximum {
|
||||
t.Fatalf("attempt %d delay out of bounds: %v", attempt, delay)
|
||||
}
|
||||
ceiling := base << (attempt - 2)
|
||||
if ceiling > maximum {
|
||||
ceiling = maximum
|
||||
}
|
||||
upper := ceiling + ceiling/2
|
||||
if upper > maximum {
|
||||
upper = maximum
|
||||
}
|
||||
if delay < ceiling/2 || delay > upper {
|
||||
t.Fatalf("attempt %d delay %v outside jitter range [%v,%v]", attempt, delay, ceiling/2, upper)
|
||||
}
|
||||
if ceiling < previousCeiling {
|
||||
t.Fatalf("backoff ceiling decreased")
|
||||
}
|
||||
previousCeiling = ceiling
|
||||
}
|
||||
if first, second := RetryDelay("job-a", 3, base, maximum), RetryDelay("job-a", 3, base, maximum); first != second {
|
||||
t.Fatalf("jitter must be reproducible: %v != %v", first, second)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab7/internal/adapter/objectstore"
|
||||
"mtusi2026lab7/internal/domain"
|
||||
)
|
||||
|
||||
type StagingCleanupStore interface {
|
||||
LookupAttachmentByStagingKey(ctx context.Context, stagingKey string) (
|
||||
attachmentID string,
|
||||
status domain.AttachmentStatus,
|
||||
updatedAt time.Time,
|
||||
found bool,
|
||||
err error,
|
||||
)
|
||||
ListReadyStagingKeys(ctx context.Context, limit int) (map[string]string, error)
|
||||
ClearAttachmentStagingKey(ctx context.Context, attachmentID, stagingKey string) error
|
||||
}
|
||||
|
||||
type StagingObjectStore interface {
|
||||
List(ctx context.Context, prefix string) ([]objectstore.StoredObject, error)
|
||||
Delete(ctx context.Context, key string) error
|
||||
}
|
||||
|
||||
type StagingCleaner struct {
|
||||
store StagingCleanupStore
|
||||
objects StagingObjectStore
|
||||
retention time.Duration
|
||||
}
|
||||
|
||||
func NewStagingCleaner(
|
||||
store StagingCleanupStore,
|
||||
objects StagingObjectStore,
|
||||
retention time.Duration,
|
||||
) (*StagingCleaner, error) {
|
||||
if store == nil || objects == nil {
|
||||
return nil, fmt.Errorf("cleanup store and object store are required")
|
||||
}
|
||||
if retention <= 0 {
|
||||
return nil, fmt.Errorf("staging retention must be positive")
|
||||
}
|
||||
return &StagingCleaner{store: store, objects: objects, retention: retention}, nil
|
||||
}
|
||||
|
||||
func (cleaner *StagingCleaner) RunOnce(ctx context.Context, now time.Time) (int, error) {
|
||||
objects, err := cleaner.objects.List(ctx, "staging/")
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
present := make(map[string]struct{}, len(objects))
|
||||
for _, object := range objects {
|
||||
present[object.Key] = struct{}{}
|
||||
}
|
||||
|
||||
// A previous worker may have deleted the object and crashed before clearing
|
||||
// metadata. Once the result is ready, clearing such a stale pointer is safe.
|
||||
readyKeys, err := cleaner.store.ListReadyStagingKeys(ctx, 1000)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
for key, attachmentID := range readyKeys {
|
||||
if _, exists := present[key]; exists {
|
||||
continue
|
||||
}
|
||||
if err = cleaner.store.ClearAttachmentStagingKey(ctx, attachmentID, key); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
|
||||
cutoff := now.UTC().Add(-cleaner.retention)
|
||||
deleted := 0
|
||||
for _, object := range objects {
|
||||
attachmentID, status, updatedAt, found, lookupErr :=
|
||||
cleaner.store.LookupAttachmentByStagingKey(ctx, object.Key)
|
||||
if lookupErr != nil {
|
||||
return deleted, lookupErr
|
||||
}
|
||||
safeToDelete := false
|
||||
switch {
|
||||
case found && status == domain.AttachmentStatusReady:
|
||||
// Result metadata is already committed, so staging is redundant.
|
||||
safeToDelete = true
|
||||
case found && status == domain.AttachmentStatusFailed &&
|
||||
!updatedAt.After(cutoff) && !object.LastModified.After(cutoff):
|
||||
safeToDelete = true
|
||||
case !found && !object.LastModified.After(cutoff):
|
||||
// An old object without DB metadata is an orphan from a failed or
|
||||
// ambiguous upload transaction.
|
||||
safeToDelete = true
|
||||
}
|
||||
if !safeToDelete {
|
||||
continue
|
||||
}
|
||||
if err = cleaner.objects.Delete(ctx, object.Key); err != nil {
|
||||
return deleted, err
|
||||
}
|
||||
if found {
|
||||
if err = cleaner.store.ClearAttachmentStagingKey(
|
||||
ctx,
|
||||
attachmentID,
|
||||
object.Key,
|
||||
); err != nil {
|
||||
return deleted, err
|
||||
}
|
||||
}
|
||||
deleted++
|
||||
}
|
||||
return deleted, nil
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab7/internal/adapter/objectstore"
|
||||
"mtusi2026lab7/internal/domain"
|
||||
)
|
||||
|
||||
type cleanupReference struct {
|
||||
id string
|
||||
status domain.AttachmentStatus
|
||||
updatedAt time.Time
|
||||
}
|
||||
|
||||
type cleanupStoreFake struct {
|
||||
references map[string]cleanupReference
|
||||
cleared map[string]bool
|
||||
}
|
||||
|
||||
func (store *cleanupStoreFake) LookupAttachmentByStagingKey(
|
||||
_ context.Context,
|
||||
key string,
|
||||
) (string, domain.AttachmentStatus, time.Time, bool, error) {
|
||||
reference, found := store.references[key]
|
||||
return reference.id, reference.status, reference.updatedAt, found, nil
|
||||
}
|
||||
|
||||
func (store *cleanupStoreFake) ListReadyStagingKeys(
|
||||
_ context.Context,
|
||||
_ int,
|
||||
) (map[string]string, error) {
|
||||
keys := make(map[string]string)
|
||||
for key, reference := range store.references {
|
||||
if reference.status == domain.AttachmentStatusReady {
|
||||
keys[key] = reference.id
|
||||
}
|
||||
}
|
||||
return keys, nil
|
||||
}
|
||||
func (store *cleanupStoreFake) ClearAttachmentStagingKey(
|
||||
_ context.Context,
|
||||
_ string,
|
||||
key string,
|
||||
) error {
|
||||
store.cleared[key] = true
|
||||
return nil
|
||||
}
|
||||
|
||||
type cleanupObjectsFake struct {
|
||||
objects []objectstore.StoredObject
|
||||
deleted map[string]bool
|
||||
}
|
||||
|
||||
func (objects *cleanupObjectsFake) List(
|
||||
context.Context,
|
||||
string,
|
||||
) ([]objectstore.StoredObject, error) {
|
||||
return objects.objects, nil
|
||||
}
|
||||
|
||||
func (objects *cleanupObjectsFake) Delete(_ context.Context, key string) error {
|
||||
objects.deleted[key] = true
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestStagingCleanerPreservesActiveWorkAndAppliesRetention(t *testing.T) {
|
||||
now := time.Date(2026, time.November, 5, 12, 0, 0, 0, time.UTC)
|
||||
old := now.Add(-25 * time.Hour)
|
||||
recent := now.Add(-time.Hour)
|
||||
store := &cleanupStoreFake{
|
||||
references: map[string]cleanupReference{
|
||||
"staging/ready": {id: "ready", status: domain.AttachmentStatusReady, updatedAt: recent},
|
||||
"staging/ready-missing": {id: "ready-missing", status: domain.AttachmentStatusReady, updatedAt: recent},
|
||||
"staging/failed-old": {id: "failed-old", status: domain.AttachmentStatusFailed, updatedAt: old},
|
||||
"staging/failed-recent": {id: "failed-recent", status: domain.AttachmentStatusFailed, updatedAt: recent},
|
||||
"staging/queued-old": {id: "queued-old", status: domain.AttachmentStatusQueued, updatedAt: old},
|
||||
},
|
||||
cleared: make(map[string]bool),
|
||||
}
|
||||
objects := &cleanupObjectsFake{
|
||||
objects: []objectstore.StoredObject{
|
||||
{Key: "staging/ready", LastModified: recent},
|
||||
{Key: "staging/failed-old", LastModified: old},
|
||||
{Key: "staging/failed-recent", LastModified: recent},
|
||||
{Key: "staging/queued-old", LastModified: old},
|
||||
{Key: "staging/orphan-old", LastModified: old},
|
||||
{Key: "staging/orphan-recent", LastModified: recent},
|
||||
},
|
||||
deleted: make(map[string]bool),
|
||||
}
|
||||
cleaner, err := NewStagingCleaner(store, objects, 24*time.Hour)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
deleted, err := cleaner.RunOnce(context.Background(), now)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if deleted != 3 {
|
||||
t.Fatalf("deleted %d objects, want 3", deleted)
|
||||
}
|
||||
for _, key := range []string{"staging/ready", "staging/failed-old", "staging/orphan-old"} {
|
||||
if !objects.deleted[key] {
|
||||
t.Errorf("expected %s to be deleted", key)
|
||||
}
|
||||
}
|
||||
for _, key := range []string{"staging/failed-recent", "staging/queued-old", "staging/orphan-recent"} {
|
||||
if objects.deleted[key] {
|
||||
t.Errorf("active/recent %s was deleted", key)
|
||||
}
|
||||
}
|
||||
if !store.cleared["staging/ready"] || !store.cleared["staging/ready-missing"] ||
|
||||
!store.cleared["staging/failed-old"] {
|
||||
t.Fatal("deleted referenced staging keys were not cleared")
|
||||
}
|
||||
if store.cleared["staging/orphan-old"] {
|
||||
t.Fatal("orphan must not clear nonexistent metadata")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/draw"
|
||||
"image/jpeg"
|
||||
"io"
|
||||
"math"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab7/internal/application"
|
||||
"mtusi2026lab7/internal/domain"
|
||||
|
||||
"github.com/disintegration/imaging"
|
||||
webp "github.com/mayahiro/go-webp"
|
||||
)
|
||||
|
||||
type pipelineProfile struct {
|
||||
thumbnailJPEGQuality int
|
||||
cropJPEGQuality int
|
||||
optimizedWebPQuality int
|
||||
}
|
||||
|
||||
func profileForPipeline(version int) (pipelineProfile, bool) {
|
||||
switch version {
|
||||
case 1:
|
||||
return pipelineProfile{thumbnailJPEGQuality: 85, cropJPEGQuality: 85, optimizedWebPQuality: 80}, true
|
||||
case 2:
|
||||
return pipelineProfile{thumbnailJPEGQuality: 90, cropJPEGQuality: 90, optimizedWebPQuality: 85}, true
|
||||
default:
|
||||
return pipelineProfile{}, false
|
||||
}
|
||||
}
|
||||
|
||||
type JobStore interface {
|
||||
GetAttachmentForProcessing(ctx context.Context, attachmentID string) (domain.Attachment, error)
|
||||
CompleteAttachmentJob(
|
||||
ctx context.Context,
|
||||
job domain.AttachmentJob,
|
||||
variants []domain.AttachmentVariant,
|
||||
updatedAt time.Time,
|
||||
) (bool, error)
|
||||
ClearAttachmentStagingKey(ctx context.Context, attachmentID, stagingKey string) error
|
||||
}
|
||||
|
||||
type FaultHook func(job domain.AttachmentJob) error
|
||||
|
||||
type ProcessorHooks struct {
|
||||
BeforeObjects FaultHook
|
||||
AfterObjects FaultHook
|
||||
}
|
||||
|
||||
type Processor struct {
|
||||
store JobStore
|
||||
objects application.ObjectStore
|
||||
now func() time.Time
|
||||
beforeObjects FaultHook
|
||||
afterObjects FaultHook
|
||||
}
|
||||
|
||||
type PermanentError struct {
|
||||
Code string
|
||||
Err error
|
||||
}
|
||||
|
||||
func (err *PermanentError) Error() string { return err.Code + ": " + err.Err.Error() }
|
||||
func (err *PermanentError) Unwrap() error { return err.Err }
|
||||
|
||||
func NewProcessor(
|
||||
store JobStore,
|
||||
objects application.ObjectStore,
|
||||
hooks ...ProcessorHooks,
|
||||
) (*Processor, error) {
|
||||
if store == nil || objects == nil {
|
||||
return nil, fmt.Errorf("job store and object store are required")
|
||||
}
|
||||
var configured ProcessorHooks
|
||||
if len(hooks) > 0 {
|
||||
configured = hooks[0]
|
||||
}
|
||||
return &Processor{
|
||||
store: store,
|
||||
objects: objects,
|
||||
now: func() time.Time { return time.Now().UTC() },
|
||||
beforeObjects: configured.BeforeObjects,
|
||||
afterObjects: configured.AfterObjects,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (processor *Processor) Process(ctx context.Context, job domain.AttachmentJob) error {
|
||||
attachment, err := processor.store.GetAttachmentForProcessing(ctx, job.AttachmentID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("load attachment metadata: %w", err)
|
||||
}
|
||||
if attachment.PipelineVersion != job.PipelineVersion {
|
||||
return &PermanentError{Code: "stale_pipeline", Err: fmt.Errorf("pipeline version mismatch")}
|
||||
}
|
||||
profile, supported := profileForPipeline(job.PipelineVersion)
|
||||
if !supported {
|
||||
return &PermanentError{Code: "unsupported_pipeline", Err: fmt.Errorf("pipeline version %d is not supported", job.PipelineVersion)}
|
||||
}
|
||||
if attachment.StagingKey == "" {
|
||||
return &PermanentError{Code: "staging_expired", Err: fmt.Errorf("staging object is no longer retained")}
|
||||
}
|
||||
|
||||
object, err := processor.objects.Get(ctx, attachment.StagingKey)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read staging object: %w", err)
|
||||
}
|
||||
defer object.Body.Close()
|
||||
|
||||
staged, err := os.CreateTemp("", "mtusi-worker-original-*")
|
||||
if err != nil {
|
||||
return fmt.Errorf("create worker staging file: %w", err)
|
||||
}
|
||||
stagedPath := staged.Name()
|
||||
defer func() {
|
||||
_ = staged.Close()
|
||||
_ = os.Remove(stagedPath)
|
||||
}()
|
||||
|
||||
hasher := sha256.New()
|
||||
copied, err := io.Copy(
|
||||
io.MultiWriter(staged, hasher),
|
||||
io.LimitReader(object.Body, domain.MaxAttachmentSizeBytes+1),
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("copy staging object: %w", err)
|
||||
}
|
||||
if copied != attachment.SizeBytes ||
|
||||
object.SizeBytes != attachment.SizeBytes ||
|
||||
hex.EncodeToString(hasher.Sum(nil)) != attachment.SHA256 {
|
||||
return &PermanentError{Code: "invalid_image", Err: fmt.Errorf("staging object integrity mismatch")}
|
||||
}
|
||||
if err = ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = staged.Seek(0, io.SeekStart); err != nil {
|
||||
return fmt.Errorf("rewind staged image: %w", err)
|
||||
}
|
||||
config, _, err := image.DecodeConfig(staged)
|
||||
if err != nil {
|
||||
return &PermanentError{Code: "invalid_image", Err: fmt.Errorf("decode staged image config: %w", err)}
|
||||
}
|
||||
if config.Width < 1 || config.Height < 1 ||
|
||||
int64(config.Width) > int64(domain.MaxAttachmentPixels)/int64(config.Height) {
|
||||
return &PermanentError{Code: "invalid_image", Err: fmt.Errorf("decoded image dimensions are unsafe")}
|
||||
}
|
||||
if _, err = staged.Seek(0, io.SeekStart); err != nil {
|
||||
return fmt.Errorf("rewind staged image: %w", err)
|
||||
}
|
||||
decoded, err := imaging.Decode(staged, imaging.AutoOrientation(true))
|
||||
if err != nil {
|
||||
return &PermanentError{Code: "invalid_image", Err: fmt.Errorf("decode staged image: %w", err)}
|
||||
}
|
||||
if err = ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
bounds := decoded.Bounds()
|
||||
width, height := bounds.Dx(), bounds.Dy()
|
||||
if width < 1 || height < 1 ||
|
||||
int64(width) > int64(domain.MaxAttachmentPixels)/int64(height) {
|
||||
return &PermanentError{Code: "invalid_image", Err: fmt.Errorf("oriented image dimensions are unsafe")}
|
||||
}
|
||||
|
||||
opaque := image.NewRGBA(image.Rect(0, 0, width, height))
|
||||
draw.Draw(opaque, opaque.Bounds(), &image.Uniform{C: color.White}, image.Point{}, draw.Src)
|
||||
draw.Draw(opaque, opaque.Bounds(), decoded, bounds.Min, draw.Over)
|
||||
|
||||
thumbnailWidth, thumbnailHeight := fitDimensions(width, height, 256)
|
||||
thumbnail := imaging.Resize(opaque, thumbnailWidth, thumbnailHeight, imaging.Lanczos)
|
||||
thumbnailBytes, err := encodeJPEG(thumbnail, profile.thumbnailJPEGQuality)
|
||||
if err != nil {
|
||||
return fmt.Errorf("encode thumbnail: %w", err)
|
||||
}
|
||||
|
||||
cropSide := width
|
||||
if height < cropSide {
|
||||
cropSide = height
|
||||
}
|
||||
cropped := imaging.CropCenter(opaque, cropSide, cropSide)
|
||||
cropped = imaging.Resize(cropped, 128, 128, imaging.Lanczos)
|
||||
cropBytes, err := encodeJPEG(cropped, profile.cropJPEGQuality)
|
||||
if err != nil {
|
||||
return fmt.Errorf("encode crop: %w", err)
|
||||
}
|
||||
|
||||
optimizedWidth, optimizedHeight := fitDimensions(width, height, 1280)
|
||||
optimized := decoded
|
||||
if optimizedWidth != width || optimizedHeight != height {
|
||||
optimized = imaging.Resize(decoded, optimizedWidth, optimizedHeight, imaging.Lanczos)
|
||||
}
|
||||
var optimizedBuffer bytes.Buffer
|
||||
if err = webp.EncodeContext(ctx, &optimizedBuffer, optimized, &webp.Options{
|
||||
Compression: webp.CompressionLossy,
|
||||
Quality: profile.optimizedWebPQuality,
|
||||
}); err != nil {
|
||||
return fmt.Errorf("encode optimized WebP: %w", err)
|
||||
}
|
||||
optimizedBytes := optimizedBuffer.Bytes()
|
||||
|
||||
baseKey := strings.TrimSuffix(attachment.ObjectKey, "/original") +
|
||||
fmt.Sprintf("/v%d/", job.PipelineVersion)
|
||||
variants := []domain.AttachmentVariant{
|
||||
newVariant("thumbnail", "image/jpeg", baseKey+"thumbnail.jpg",
|
||||
thumbnailBytes, thumbnailWidth, thumbnailHeight, job.PipelineVersion),
|
||||
newVariant("crop", "image/jpeg", baseKey+"crop.jpg",
|
||||
cropBytes, 128, 128, job.PipelineVersion),
|
||||
newVariant("optimized", "image/webp", baseKey+"optimized.webp",
|
||||
optimizedBytes, optimizedWidth, optimizedHeight, job.PipelineVersion),
|
||||
}
|
||||
|
||||
if processor.beforeObjects != nil {
|
||||
if err = processor.beforeObjects(job); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if _, err = staged.Seek(0, io.SeekStart); err != nil {
|
||||
return fmt.Errorf("rewind original for publication: %w", err)
|
||||
}
|
||||
if err = processor.objects.Put(ctx, application.ObjectPut{
|
||||
Key: attachment.ObjectKey,
|
||||
ContentType: attachment.ContentType,
|
||||
SizeBytes: attachment.SizeBytes,
|
||||
Body: staged,
|
||||
}); err != nil {
|
||||
return fmt.Errorf("publish original: %w", err)
|
||||
}
|
||||
variantBodies := [][]byte{thumbnailBytes, cropBytes, optimizedBytes}
|
||||
for index, variant := range variants {
|
||||
if err = processor.objects.Put(ctx, application.ObjectPut{
|
||||
Key: variant.ObjectKey,
|
||||
ContentType: variant.ContentType,
|
||||
SizeBytes: variant.SizeBytes,
|
||||
Body: bytes.NewReader(variantBodies[index]),
|
||||
}); err != nil {
|
||||
return fmt.Errorf("publish %s: %w", variant.Name, err)
|
||||
}
|
||||
}
|
||||
if processor.afterObjects != nil {
|
||||
if err = processor.afterObjects(job); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
applied, err := processor.store.CompleteAttachmentJob(
|
||||
ctx,
|
||||
job,
|
||||
variants,
|
||||
processor.now(),
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("commit attachment result: %w", err)
|
||||
}
|
||||
if !applied {
|
||||
return nil
|
||||
}
|
||||
|
||||
cleanupContext, cancel := context.WithTimeout(context.WithoutCancel(ctx), 3*time.Second)
|
||||
defer cancel()
|
||||
if err = processor.objects.Delete(cleanupContext, attachment.StagingKey); err == nil {
|
||||
_ = processor.store.ClearAttachmentStagingKey(
|
||||
cleanupContext,
|
||||
attachment.ID,
|
||||
attachment.StagingKey,
|
||||
)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func fitDimensions(width, height, maximum int) (int, int) {
|
||||
scale := math.Min(1, math.Min(float64(maximum)/float64(width), float64(maximum)/float64(height)))
|
||||
resultWidth := int(math.Floor(float64(width) * scale))
|
||||
resultHeight := int(math.Floor(float64(height) * scale))
|
||||
if resultWidth < 1 {
|
||||
resultWidth = 1
|
||||
}
|
||||
if resultHeight < 1 {
|
||||
resultHeight = 1
|
||||
}
|
||||
return resultWidth, resultHeight
|
||||
}
|
||||
|
||||
func encodeJPEG(source image.Image, quality int) ([]byte, error) {
|
||||
var encoded bytes.Buffer
|
||||
if err := jpeg.Encode(&encoded, source, &jpeg.Options{Quality: quality}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return encoded.Bytes(), nil
|
||||
}
|
||||
|
||||
func newVariant(
|
||||
name string,
|
||||
contentType string,
|
||||
objectKey string,
|
||||
body []byte,
|
||||
width int,
|
||||
height int,
|
||||
pipelineVersion int,
|
||||
) domain.AttachmentVariant {
|
||||
digest := sha256.Sum256(body)
|
||||
return domain.AttachmentVariant{
|
||||
Name: name,
|
||||
ContentType: contentType,
|
||||
SizeBytes: int64(len(body)),
|
||||
Width: width,
|
||||
Height: height,
|
||||
SHA256: hex.EncodeToString(digest[:]),
|
||||
ObjectKey: objectKey,
|
||||
PipelineVersion: pipelineVersion,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"io"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab7/internal/application"
|
||||
"mtusi2026lab7/internal/domain"
|
||||
|
||||
xwebp "golang.org/x/image/webp"
|
||||
)
|
||||
|
||||
type processorStoreFake struct {
|
||||
attachment domain.Attachment
|
||||
variants []domain.AttachmentVariant
|
||||
cleared bool
|
||||
}
|
||||
|
||||
func (store *processorStoreFake) GetAttachmentForProcessing(
|
||||
context.Context,
|
||||
string,
|
||||
) (domain.Attachment, error) {
|
||||
return store.attachment, nil
|
||||
}
|
||||
|
||||
func (store *processorStoreFake) CompleteAttachmentJob(
|
||||
_ context.Context,
|
||||
_ domain.AttachmentJob,
|
||||
variants []domain.AttachmentVariant,
|
||||
_ time.Time,
|
||||
) (bool, error) {
|
||||
store.variants = append([]domain.AttachmentVariant(nil), variants...)
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (store *processorStoreFake) ClearAttachmentStagingKey(
|
||||
context.Context,
|
||||
string,
|
||||
string,
|
||||
) error {
|
||||
store.cleared = true
|
||||
return nil
|
||||
}
|
||||
|
||||
type objectStoreFake struct {
|
||||
objects map[string][]byte
|
||||
}
|
||||
|
||||
func (store *objectStoreFake) Put(_ context.Context, object application.ObjectPut) error {
|
||||
body, err := io.ReadAll(object.Body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
store.objects[object.Key] = body
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *objectStoreFake) Get(
|
||||
_ context.Context,
|
||||
key string,
|
||||
) (application.ObjectContent, error) {
|
||||
body := store.objects[key]
|
||||
return application.ObjectContent{
|
||||
Body: io.NopCloser(bytes.NewReader(body)),
|
||||
SizeBytes: int64(len(body)),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (store *objectStoreFake) Delete(_ context.Context, key string) error {
|
||||
delete(store.objects, key)
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestProcessorCompositesAlphaAndStripsMetadata(t *testing.T) {
|
||||
source := image.NewNRGBA(image.Rect(0, 0, 32, 16))
|
||||
for y := 0; y < 16; y++ {
|
||||
for x := 0; x < 32; x++ {
|
||||
if x < 16 {
|
||||
source.SetNRGBA(x, y, color.NRGBA{R: 255, A: 0})
|
||||
} else {
|
||||
source.SetNRGBA(x, y, color.NRGBA{A: 255})
|
||||
}
|
||||
}
|
||||
}
|
||||
var encoded bytes.Buffer
|
||||
if err := png.Encode(&encoded, source); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store, objects, processor, job := processorFixture(t, encoded.Bytes(), "image/png", 32, 16)
|
||||
if err := processor.Process(context.Background(), job); err != nil {
|
||||
t.Fatalf("process transparent PNG: %v", err)
|
||||
}
|
||||
|
||||
thumbnail := decodeJPEG(t, objects.objects[variantKey(store.variants, "thumbnail")])
|
||||
if got := thumbnail.Bounds().Size(); got.X != 32 || got.Y != 16 {
|
||||
t.Fatalf("thumbnail size = %v, want 32x16 without upscale", got)
|
||||
}
|
||||
white := color.RGBAModel.Convert(thumbnail.At(2, 8)).(color.RGBA)
|
||||
black := color.RGBAModel.Convert(thumbnail.At(29, 8)).(color.RGBA)
|
||||
if white.R < 220 || white.G < 220 || white.B < 220 {
|
||||
t.Fatalf("transparent pixel was not composited on white: %#v", white)
|
||||
}
|
||||
if black.R > 40 || black.G > 40 || black.B > 40 {
|
||||
t.Fatalf("opaque black pixel changed unexpectedly: %#v", black)
|
||||
}
|
||||
|
||||
optimizedBytes := objects.objects[variantKey(store.variants, "optimized")]
|
||||
optimized, err := xwebp.Decode(bytes.NewReader(optimizedBytes))
|
||||
if err != nil {
|
||||
t.Fatalf("decode optimized WebP: %v", err)
|
||||
}
|
||||
if got := optimized.Bounds().Size(); got.X != 32 || got.Y != 16 {
|
||||
t.Fatalf("optimized size = %v, want 32x16 without upscale", got)
|
||||
}
|
||||
_, _, _, alpha := optimized.At(2, 8).RGBA()
|
||||
if alpha > 0x0800 {
|
||||
t.Fatalf("optimized WebP did not preserve transparent alpha: %d", alpha)
|
||||
}
|
||||
for _, metadataChunk := range [][]byte{[]byte("EXIF"), []byte("XMP "), []byte("ICCP")} {
|
||||
if bytes.Contains(optimizedBytes, metadataChunk) {
|
||||
t.Fatalf("optimized WebP unexpectedly contains metadata chunk %q", metadataChunk)
|
||||
}
|
||||
}
|
||||
if !store.cleared {
|
||||
t.Fatal("successful processing did not clear staging metadata")
|
||||
}
|
||||
if _, exists := objects.objects[store.attachment.StagingKey]; exists {
|
||||
t.Fatal("successful processing did not delete staging object")
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessorAppliesEXIFOrientation(t *testing.T) {
|
||||
source := image.NewRGBA(image.Rect(0, 0, 40, 20))
|
||||
var raw bytes.Buffer
|
||||
if err := jpeg.Encode(&raw, source, &jpeg.Options{Quality: 90}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
oriented := injectEXIFOrientation(t, raw.Bytes(), 6)
|
||||
store, objects, processor, job := processorFixture(t, oriented, "image/jpeg", 40, 20)
|
||||
if err := processor.Process(context.Background(), job); err != nil {
|
||||
t.Fatalf("process oriented JPEG: %v", err)
|
||||
}
|
||||
thumbnail := decodeJPEG(t, objects.objects[variantKey(store.variants, "thumbnail")])
|
||||
if got := thumbnail.Bounds().Size(); got.X != 20 || got.Y != 40 {
|
||||
t.Fatalf("thumbnail size after orientation = %v, want 20x40", got)
|
||||
}
|
||||
optimized, err := xwebp.Decode(bytes.NewReader(
|
||||
objects.objects[variantKey(store.variants, "optimized")],
|
||||
))
|
||||
if err != nil {
|
||||
t.Fatalf("decode optimized WebP: %v", err)
|
||||
}
|
||||
if got := optimized.Bounds().Size(); got.X != 20 || got.Y != 40 {
|
||||
t.Fatalf("optimized size after orientation = %v, want 20x40", got)
|
||||
}
|
||||
crop := decodeJPEG(t, objects.objects[variantKey(store.variants, "crop")])
|
||||
if got := crop.Bounds().Size(); got.X != 128 || got.Y != 128 {
|
||||
t.Fatalf("crop size = %v, want 128x128", got)
|
||||
}
|
||||
}
|
||||
|
||||
func processorFixture(
|
||||
t *testing.T,
|
||||
body []byte,
|
||||
contentType string,
|
||||
width int,
|
||||
height int,
|
||||
) (*processorStoreFake, *objectStoreFake, *Processor, domain.AttachmentJob) {
|
||||
t.Helper()
|
||||
digest := sha256.Sum256(body)
|
||||
attachment := domain.Attachment{
|
||||
ID: "attachment",
|
||||
ChatID: "chat",
|
||||
OwnerID: "owner",
|
||||
ObjectKey: "attachments/chat/attachment/original",
|
||||
StagingKey: "staging/attachment/original",
|
||||
ContentType: contentType,
|
||||
SizeBytes: int64(len(body)),
|
||||
SHA256: hex.EncodeToString(digest[:]),
|
||||
Width: width,
|
||||
Height: height,
|
||||
PipelineVersion: 1,
|
||||
Status: domain.AttachmentStatusProcessing,
|
||||
}
|
||||
store := &processorStoreFake{attachment: attachment}
|
||||
objects := &objectStoreFake{objects: map[string][]byte{attachment.StagingKey: body}}
|
||||
processor, err := NewProcessor(store, objects)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return store, objects, processor, domain.AttachmentJob{
|
||||
JobID: "job",
|
||||
AttachmentID: attachment.ID,
|
||||
PipelineVersion: 1,
|
||||
Attempt: 1,
|
||||
MaxAttempts: 5,
|
||||
Status: domain.AttachmentJobProcessing,
|
||||
}
|
||||
}
|
||||
|
||||
func variantKey(variants []domain.AttachmentVariant, name string) string {
|
||||
for _, variant := range variants {
|
||||
if variant.Name == name {
|
||||
return variant.ObjectKey
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func decodeJPEG(t *testing.T, body []byte) image.Image {
|
||||
t.Helper()
|
||||
decoded, err := jpeg.Decode(bytes.NewReader(body))
|
||||
if err != nil {
|
||||
t.Fatalf("decode JPEG: %v", err)
|
||||
}
|
||||
return decoded
|
||||
}
|
||||
|
||||
func injectEXIFOrientation(t *testing.T, source []byte, orientation uint16) []byte {
|
||||
t.Helper()
|
||||
if len(source) < 2 || source[0] != 0xFF || source[1] != 0xD8 {
|
||||
t.Fatal("source is not JPEG")
|
||||
}
|
||||
var tiff bytes.Buffer
|
||||
tiff.WriteString("II")
|
||||
_ = binary.Write(&tiff, binary.LittleEndian, uint16(42))
|
||||
_ = binary.Write(&tiff, binary.LittleEndian, uint32(8))
|
||||
_ = binary.Write(&tiff, binary.LittleEndian, uint16(1))
|
||||
_ = binary.Write(&tiff, binary.LittleEndian, uint16(0x0112))
|
||||
_ = binary.Write(&tiff, binary.LittleEndian, uint16(3))
|
||||
_ = binary.Write(&tiff, binary.LittleEndian, uint32(1))
|
||||
_ = binary.Write(&tiff, binary.LittleEndian, orientation)
|
||||
_ = binary.Write(&tiff, binary.LittleEndian, uint16(0))
|
||||
_ = binary.Write(&tiff, binary.LittleEndian, uint32(0))
|
||||
payload := append([]byte("Exif\x00\x00"), tiff.Bytes()...)
|
||||
var segment bytes.Buffer
|
||||
segment.Write([]byte{0xFF, 0xE1})
|
||||
if err := binary.Write(&segment, binary.BigEndian, uint16(len(payload)+2)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
segment.Write(payload)
|
||||
result := append([]byte(nil), source[:2]...)
|
||||
result = append(result, segment.Bytes()...)
|
||||
result = append(result, source[2:]...)
|
||||
return result
|
||||
}
|
||||
Reference in New Issue
Block a user