package store import ( "context" "errors" "fmt" "github.com/google/uuid" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" "messenger/internal/attachment" "messenger/internal/platform/apperr" "messenger/internal/platform/postgres" ) type Attachments struct { pool *pgxpool.Pool } var _ attachment.AttachmentRepository = (*Attachments)(nil) func NewAttachments(pool *pgxpool.Pool) *Attachments { return &Attachments{pool: pool} } // Publication and garbage collection use the same hash lock. The transaction // spans only publication, never client transfer or image decoding. func (r *Attachments) WithPublication(ctx context.Context, a attachment.Attachment, fn func(attachment.Publication) error) error { return postgres.Classify(pgx.BeginFunc(ctx, r.pool, func(tx pgx.Tx) error { if _, err := tx.Exec(ctx, `SET LOCAL idle_in_transaction_session_timeout = '35s'`); err != nil { return err } if err := attachment.LockHash(ctx, tx, a.FileHash); err != nil { return err } var status attachment.FileStatus err := tx.QueryRow(ctx, `SELECT status FROM files WHERE hash = $1 FOR UPDATE`, a.FileHash).Scan(&status) if err != nil && !errors.Is(err, pgx.ErrNoRows) { return err } return fn(publication{tx: tx, attachment: a, ready: status == attachment.FileReady}) })) } type publication struct { tx pgx.Tx attachment attachment.Attachment ready bool } func (p publication) FileReady() bool { return p.ready } func (p publication) SaveReady(ctx context.Context) error { a := p.attachment _, err := p.tx.Exec(ctx, ` INSERT INTO files (hash, size_bytes, mime_type, status) VALUES ($1, $2, $3, $4) ON CONFLICT (hash) DO UPDATE SET size_bytes = excluded.size_bytes, mime_type = excluded.mime_type, status = excluded.status`, a.FileHash, a.SizeBytes, a.MIMEType, attachment.FileReady) if err != nil { return fmt.Errorf("publish file: %w", err) } _, err = p.tx.Exec(ctx, ` INSERT INTO attachments (id, chat_id, owner_id, filename, file_hash, created_at) VALUES ($1, $2, $3, $4, $5, $6)`, a.ID, a.ChatID, a.OwnerID, a.Filename, a.FileHash, a.CreatedAt) return err } func (r *Attachments) GetForMember(ctx context.Context, id, actor uuid.UUID) (attachment.Attachment, error) { var a attachment.Attachment err := r.pool.QueryRow(ctx, ` SELECT a.id, a.chat_id, a.owner_id, a.filename, a.file_hash, f.size_bytes, f.mime_type, f.status, a.created_at FROM attachments a JOIN files f ON f.hash = a.file_hash WHERE a.id = $1 AND EXISTS ( SELECT 1 FROM chat_members m WHERE m.chat_id = a.chat_id AND m.user_id = $2 )`, id, actor). Scan(&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.FileHash, &a.SizeBytes, &a.MIMEType, &a.Status, &a.CreatedAt) if errors.Is(err, pgx.ErrNoRows) { return attachment.Attachment{}, apperr.NotFound("attachment not found") } return a, postgres.Classify(err) }