package store import ( "context" "errors" "time" "github.com/jackc/pgx/v5" ) func (s *PostgresStore) BeginUpload(ctx context.Context, id, chatID, ownerID string) error { ctx, cancel := context.WithTimeout(ctx, 3*time.Second) defer cancel() if _, err := s.pool.Exec(ctx, `INSERT INTO upload_intents(id,chat_id,owner_id) VALUES($1,$2,$3)`, id, chatID, ownerID); err != nil { return ErrUnavailable } return nil } // CleanupCandidates is bounded. Each candidate is locked and rechecked later. func (s *PostgresStore) CleanupCandidates(ctx context.Context) ([]string, error) { ctx, cancel := context.WithTimeout(ctx, 3*time.Second) defer cancel() rows, err := s.pool.Query(ctx, `SELECT id::text FROM upload_intents WHERE expires_at<=clock_timestamp() AND next_cleanup_at<=clock_timestamp() ORDER BY next_cleanup_at,id LIMIT 100`) if err != nil { return nil, ErrUnavailable } defer rows.Close() ids := []string{} for rows.Next() { var id string if err := rows.Scan(&id); err != nil { return nil, ErrUnavailable } ids = append(ids, id) } if rows.Err() != nil { return nil, ErrUnavailable } return ids, nil } // CleanupUpload serializes with publication using the same intent row lock. // No deletion is attempted if the DB is unavailable or a row is still fresh. func (s *PostgresStore) CleanupUpload(ctx context.Context, id string, dryRun bool, remove func(context.Context, string) error) (string, error) { ctx, cancel := context.WithTimeout(ctx, 35*time.Second) defer cancel() tx, err := s.pool.Begin(ctx) if err != nil { return "", ErrUnavailable } defer tx.Rollback(context.Background()) var locked string err = tx.QueryRow(ctx, `SELECT id::text FROM upload_intents WHERE id=$1 AND expires_at<=clock_timestamp() AND next_cleanup_at<=clock_timestamp() FOR UPDATE SKIP LOCKED`, id).Scan(&locked) if errors.Is(err, pgx.ErrNoRows) { return "skipped", nil } if err != nil { return "", ErrUnavailable } var published bool if err := tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM attachments WHERE id=$1)`, id).Scan(&published); err != nil { return "", ErrUnavailable } if published { if dryRun { return "protected", nil } if _, err := tx.Exec(ctx, `DELETE FROM upload_intents WHERE id=$1`, id); err != nil { return "", ErrUnavailable } if err := tx.Commit(ctx); err != nil { return "", ErrUnavailable } return "protected", nil } if dryRun { return "would_delete", nil } if err := remove(ctx, id); err != nil { return "", err } // Retain a tombstone: repeat deletion catches a late PUT after a crashed API. if _, err := tx.Exec(ctx, `UPDATE upload_intents SET state='abandoned',next_cleanup_at=clock_timestamp()+INTERVAL '10 minutes' WHERE id=$1`, id); err != nil { return "", ErrUnavailable } if err := tx.Commit(ctx); err != nil { return "", ErrUnavailable } return "deleted", nil }