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)