на оценку 4
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
2026-11-22 23:33:11 +03:00
parent 20afc2c790
commit cc41f601e3
207 changed files with 22098 additions and 120 deletions
+193
View File
@@ -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
}
+110
View File
@@ -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
View File
@@ -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")
}
}
+33
View File
@@ -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
}
+8
View File
@@ -0,0 +1,8 @@
package memory
import "mtusi2026lab7/internal/domain"
var (
ErrNotFound = domain.ErrNotFound
ErrConflict = domain.ErrConflict
)
+401
View File
@@ -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)
+371
View File
@@ -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
}
+226
View File
@@ -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, &currentVersion)
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
}
+372
View File
@@ -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)
+278
View File
@@ -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
}
+5
View File
@@ -0,0 +1,5 @@
package postgres
import "mtusi2026lab7/internal/application"
var _ application.Repository = (*PostgreSQLStore)(nil)
+8
View File
@@ -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
}
+99
View File
@@ -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
}
+426
View File
@@ -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
}
+31
View File
@@ -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
}
+111
View File
@@ -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
}
+43
View File
@@ -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)
}
+165
View File
@@ -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
}
+175
View File
@@ -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)