package store import ( "context" "encoding/hex" "errors" "time" "gitflic.ru/project/bulla-max/mtusi2026lab/internal/common" "gitflic.ru/project/bulla-max/mtusi2026lab/internal/model" "github.com/google/uuid" "github.com/jackc/pgx/v5" ) // CreatePendingAttachment records the intent to store an object before the S3 // PUT happens. Committing this row first is what makes the reconciler able to // distinguish "never uploaded" from "uploaded but process died". func (s *Store) CreatePendingAttachment(ctx context.Context, att model.Attachment) error { ctx, cancel := s.withTimeout(ctx) defer cancel() hash, err := hex.DecodeString(att.SHA256) if err != nil { return common.BadRequest("invalid sha256") } _, err = s.pool.Exec(ctx, ` INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key, status, error_code, created_at, updated_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'pending', NULL, $9, $9)`, att.ID, att.ChatID, att.OwnerID, att.Filename, att.ContentType, att.SizeBytes, hash, att.ObjectKey, time.Time(att.CreatedAt)) return dbError(err) } // MarkAttachmentReady publishes metadata only after the object bytes are known // to be in S3. A 201 is therefore a promise about both stores. func (s *Store) MarkAttachmentReady(ctx context.Context, id uuid.UUID) (time.Time, error) { ctx, cancel := s.withTimeout(ctx) defer cancel() updatedAt := time.Now().UTC() tag, err := s.pool.Exec(ctx, ` UPDATE attachments SET status = 'ready', updated_at = $2 WHERE id = $1 AND status = 'pending'`, id, updatedAt) if err != nil { return time.Time{}, dbError(err) } if tag.RowsAffected() == 0 { return time.Time{}, common.Conflict("attachment is not pending") } return updatedAt, nil } // DeletePendingAttachment removes a row only while it is still pending. The // status guard is the safety property: if an upload completed concurrently, the // compensation or reconciler pass must not delete a ready attachment. func (s *Store) DeletePendingAttachment(ctx context.Context, id uuid.UUID) error { ctx, cancel := s.withTimeout(ctx) defer cancel() _, err := s.pool.Exec(ctx, `DELETE FROM attachments WHERE id = $1 AND status = 'pending'`, id) return dbError(err) } func (s *Store) GetAttachmentForUser(ctx context.Context, userID, attachmentID uuid.UUID) (model.Attachment, error) { ctx, cancel := s.withTimeout(ctx) defer cancel() att, err := scanAttachment(s.pool.QueryRow(ctx, ` SELECT a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes, a.sha256, a.status, a.error_code, a.created_at, a.updated_at, a.object_key FROM attachments a JOIN chat_members cm ON cm.chat_id = a.chat_id AND cm.user_id = $2 WHERE a.id = $1`, attachmentID, userID)) if err != nil { return model.Attachment{}, err } return att, nil } // ListStalePendingAttachments is the entry point for crash recovery. cutoff is // an instant, not a duration: rows created before it are eligible. The caller // computes it as now - grace so the boundary can be tuned and tested. func (s *Store) ListStalePendingAttachments(ctx context.Context, cutoff time.Time, limit int) ([]model.Attachment, error) { ctx, cancel := s.withTimeout(ctx) defer cancel() rows, err := s.pool.Query(ctx, ` SELECT a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes, a.sha256, a.status, a.error_code, a.created_at, a.updated_at, a.object_key FROM attachments a WHERE a.status = 'pending' AND a.created_at < $1 ORDER BY a.created_at LIMIT $2`, cutoff, limit) if err != nil { return nil, dbError(err) } defer rows.Close() var result []model.Attachment for rows.Next() { att, scanErr := scanAttachment(rows) if scanErr != nil { return nil, dbError(scanErr) } result = append(result, att) } if err = rows.Err(); err != nil { return nil, dbError(err) } return result, nil } func (s *Store) ListAttachmentObjectKeys(ctx context.Context) (map[string]struct{}, error) { ctx, cancel := s.withTimeout(ctx) defer cancel() rows, err := s.pool.Query(ctx, `SELECT object_key FROM attachments`) if err != nil { return nil, dbError(err) } defer rows.Close() keys := make(map[string]struct{}) for rows.Next() { var key string if err = rows.Scan(&key); err != nil { return nil, dbError(err) } keys[key] = struct{}{} } if err = rows.Err(); err != nil { return nil, dbError(err) } return keys, nil } func scanAttachment(row rowScanner) (model.Attachment, error) { var ( att model.Attachment hash []byte errCode *string createdAt time.Time updatedAt time.Time ) if err := row.Scan( &att.ID, &att.ChatID, &att.OwnerID, &att.Filename, &att.ContentType, &att.SizeBytes, &hash, &att.Status, &errCode, &createdAt, &updatedAt, &att.ObjectKey, ); err != nil { if errors.Is(err, pgx.ErrNoRows) { return model.Attachment{}, common.NotFound("attachment not found") } return model.Attachment{}, dbError(err) } att.SHA256 = hex.EncodeToString(hash) att.ErrorCode = errCode att.Variants = []model.Variant{} att.CreatedAt = common.RFCFormTime(createdAt.UTC()) att.UpdatedAt = common.RFCFormTime(updatedAt.UTC()) return att, nil }