package storage import ( "context" "time" "github.com/google/uuid" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" "gitea.privcloud.tech/mtusi2026/internal/gen/contracts" "gitea.privcloud.tech/mtusi2026/internal/pkg/apperr" ) type AttachmentRecord struct { Public contracts.Attachment Key string Missing bool } type AttachmentsRepo struct{ Pool *pgxpool.Pool } const AttachmentColumns = "id,chat_id,owner_id,filename,content_type,size_bytes,sha256,created_at,updated_at,object_key,integrity_missing" func ScanAttachment(row pgx.Row) (*AttachmentRecord, error) { a := new(AttachmentRecord) p := &a.Public if err := row.Scan(&p.Id, &p.ChatId, &p.OwnerId, &p.Filename, &p.ContentType, &p.SizeBytes, &p.Sha256, &p.CreatedAt, &p.UpdatedAt, &a.Key, &a.Missing); err != nil { return nil, apperr.WrapPostgres(err, "attachment unavailable") } p.Status = "ready" p.Variants = []contracts.Variant{} return a, nil } func (r *AttachmentsRepo) Get(ctx context.Context, id uuid.UUID) (*AttachmentRecord, error) { return ScanAttachment(r.Pool.QueryRow(ctx, "SELECT "+AttachmentColumns+" FROM attachments WHERE id=$1", id)) } func (r *AttachmentsRepo) Save(ctx context.Context, conn *pgxpool.Conn, a *AttachmentRecord) error { p := a.Public _, e := conn.Exec(ctx, `INSERT INTO attachments(id,chat_id,owner_id,filename,content_type,size_bytes,sha256,created_at,updated_at,object_key) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)`, p.Id, p.ChatId, p.OwnerId, p.Filename, p.ContentType, p.SizeBytes, p.Sha256, p.CreatedAt, p.UpdatedAt, a.Key) if e != nil { return apperr.WrapPostgres(e, "failed to save attachment") } return nil } // Session locks span S3 work and the database commit. A lost connection releases // the lock; the mandatory grace period also exceeds the maximum upload lifetime. func (r *AttachmentsRepo) Lock(ctx context.Context, key string) (*pgxpool.Conn, func(), error) { c, e := r.Pool.Acquire(ctx) if e != nil { return nil, nil, apperr.WrapPostgres(e, "database unavailable") } if _, e = c.Exec(ctx, "SELECT pg_advisory_lock(hashtextextended($1, 42))", key); e != nil { // The server may have acquired the session lock before cancellation was // observed by the client. Never return that uncertain session to the pool. clean, cancel := context.WithTimeout(context.Background(), 2*time.Second) _ = c.Conn().Close(clean) cancel() c.Release() return nil, nil, apperr.WrapPostgres(e, "lock unavailable") } return c, func() { // Close rather than return a possibly locked session when unlock fails. clean, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() if _, e := c.Exec(clean, "SELECT pg_advisory_unlock(hashtextextended($1, 42))", key); e != nil { _ = c.Conn().Close(clean) } c.Release() }, nil }