package repositories import ( "context" "errors" "fmt" "time" "github.com/google/uuid" "github.com/jackc/pgx/v5" ) // ReserveUpload is committed before any S3 PUT, so an interrupted request is tracked. func (s *AttachmentStore) ReserveUpload(ctx context.Context, a Attachment, grace time.Duration) error { ctx, cancel := boundedQuery(ctx) defer cancel() _, err := s.db.Exec(ctx, `INSERT INTO upload_attempts(id,object_key,cleanup_after) VALUES($1,$2,clock_timestamp()+$3*interval '1 second')`, a.ID, a.ObjectKey, grace.Seconds()) return err } // PublishUpload holds the journal row lock across PUT and metadata COMMIT. // Cleanup skips that row; a crash rolls back metadata but preserves the reservation. func (s *AttachmentStore) PublishUpload(ctx context.Context, a Attachment, put func(context.Context) error) error { tx, err := s.db.Begin(ctx) if err != nil { return err } defer tx.Rollback(context.Background()) var key string err = tx.QueryRow(ctx, `SELECT object_key FROM upload_attempts WHERE id=$1 AND cleanup_after>clock_timestamp() FOR UPDATE`, a.ID).Scan(&key) if err != nil { return err } if key != a.ObjectKey { return errors.New("upload reservation mismatch") } if err = put(ctx); err != nil { return err } _, err = tx.Exec(ctx, `INSERT INTO attachments(id,chat_id,owner_id,filename,object_key,content_type,size_bytes,sha256,created_at,updated_at) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)`, a.ID, a.ChatID, a.OwnerID, a.Filename, a.ObjectKey, a.ContentType, a.SizeBytes, a.SHA256, a.CreatedAt, a.UpdatedAt) if err != nil { return err } if _, err = tx.Exec(ctx, "DELETE FROM upload_attempts WHERE id=$1", a.ID); err != nil { return err } return tx.Commit(ctx) } type CleanupResult struct { Candidates int `json:"candidates"` Deleted int `json:"deleted"` Eligible int `json:"eligible"` Protected int `json:"protected"` Skipped int `json:"skipped"` Failed int `json:"failed"` DryRun bool `json:"dry_run"` } // CleanupUploads only visits journal entries; it never scans or deletes legacy data. func (s *AttachmentStore) CleanupUploads(ctx context.Context, dryRun bool, remove func(context.Context, string) error) (CleanupResult, error) { result := CleanupResult{DryRun: dryRun} rows, err := s.db.Query(ctx, `SELECT id::text FROM upload_attempts WHERE cleanup_after<=clock_timestamp() ORDER BY cleanup_after,id LIMIT 100`) if err != nil { return result, err } ids := []string{} for rows.Next() { var id string if err = rows.Scan(&id); err != nil { rows.Close() return result, err } ids = append(ids, id) } err = rows.Err() rows.Close() if err != nil { return result, err } result.Candidates = len(ids) for _, id := range ids { outcome, err := s.cleanupUpload(ctx, id, dryRun, remove) if err != nil { result.Failed++ continue } switch outcome { case "eligible": result.Eligible++ case "deleted": result.Deleted++ case "protected": result.Protected++ default: result.Skipped++ } } if result.Failed > 0 { return result, fmt.Errorf("%d upload cleanup operations failed", result.Failed) } return result, nil } func (s *AttachmentStore) cleanupUpload(ctx context.Context, id string, dryRun bool, remove func(context.Context, string) error) (string, error) { ctx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() tx, err := s.db.Begin(ctx) if err != nil { return "", err } defer tx.Rollback(context.Background()) var key string err = tx.QueryRow(ctx, `SELECT object_key FROM upload_attempts WHERE id=$1 AND cleanup_after<=clock_timestamp() FOR UPDATE SKIP LOCKED`, id).Scan(&key) if errors.Is(err, pgx.ErrNoRows) { return "skipped", nil } if err != nil { return "", err } // Restrict destructive actions to server-generated keys even if a journal row is malformed. parsed, err := uuid.Parse(id) if err != nil || key != "originals/"+parsed.String() { return "", errors.New("invalid upload journal key") } var ready bool if err = tx.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM attachments WHERE object_key=$1)", key).Scan(&ready); err != nil { return "", err } if dryRun { if ready { return "protected", nil } return "eligible", nil } if !ready { // On DELETE failure retain the journal entry for the next pass. if err = remove(ctx, key); err != nil { return "", err } } if _, err = tx.Exec(ctx, "DELETE FROM upload_attempts WHERE id=$1", id); err != nil { return "", err } if err = tx.Commit(ctx); err != nil { return "", err } if ready { return "protected", nil } return "deleted", nil }