// Code generated by sqlc. DO NOT EDIT. // versions: // sqlc v1.31.1 // source: attachments_jobs.sql package sqlc import ( "context" "github.com/jackc/pgx/v5/pgtype" ) const claimJob = `-- name: ClaimJob :one WITH claimed AS ( UPDATE attachment_jobs AS j SET lease_generation = j.lease_generation + 1, lease_until = $1::timestamptz, attempts_started = j.attempts_started + 1, next_attempt_at = NULL, updated_at = clock_timestamp() FROM attachments AS a WHERE j.id = $2 AND a.id = j.attachment_id AND a.pipeline_version = j.pipeline_version AND j.attempts_started < j.max_attempts AND $1::timestamptz > clock_timestamp() AND ( (a.status = 'queued' AND j.lease_until IS NULL AND j.next_attempt_at <= clock_timestamp()) OR (a.status = 'processing' AND j.lease_until <= clock_timestamp()) ) RETURNING j.id, j.attachment_id, j.pipeline_version, j.attempts_started, j.max_attempts, j.next_attempt_at, j.lease_generation, j.lease_until, j.created_at, j.updated_at, j.published_original_key ), expired AS ( UPDATE attachment_attempts AS attempt SET outcome = 'lease_expired', error_code = 'lease_expired', finished_at = claimed.updated_at FROM claimed WHERE attempt.job_id = claimed.id AND attempt.lease_generation = claimed.lease_generation - 1 AND attempt.finished_at IS NULL ), recorded AS ( INSERT INTO attachment_attempts (job_id, lease_generation, attempt, started_at) SELECT id, lease_generation, attempts_started, updated_at FROM claimed RETURNING job_id ), processing AS ( UPDATE attachments AS a SET status = 'processing', updated_at = claimed.updated_at FROM claimed WHERE a.id = claimed.attachment_id RETURNING a.id ) SELECT claimed.id, claimed.attachment_id, claimed.pipeline_version, claimed.attempts_started, claimed.max_attempts, claimed.next_attempt_at, claimed.lease_generation, claimed.lease_until, claimed.created_at, claimed.updated_at, claimed.published_original_key FROM claimed JOIN recorded ON recorded.job_id = claimed.id JOIN processing ON processing.id = claimed.attachment_id ` type ClaimJobParams struct { NewLeaseUntil pgtype.Timestamptz JobID pgtype.UUID } type ClaimJobRow struct { ID pgtype.UUID AttachmentID pgtype.UUID PipelineVersion int32 AttemptsStarted int32 MaxAttempts int32 NextAttemptAt pgtype.Timestamptz LeaseGeneration int32 LeaseUntil pgtype.Timestamptz CreatedAt pgtype.Timestamptz UpdatedAt pgtype.Timestamptz PublishedOriginalKey pgtype.Text } func (q *Queries) ClaimJob(ctx context.Context, arg ClaimJobParams) (ClaimJobRow, error) { row := q.db.QueryRow(ctx, claimJob, arg.NewLeaseUntil, arg.JobID) var i ClaimJobRow err := row.Scan( &i.ID, &i.AttachmentID, &i.PipelineVersion, &i.AttemptsStarted, &i.MaxAttempts, &i.NextAttemptAt, &i.LeaseGeneration, &i.LeaseUntil, &i.CreatedAt, &i.UpdatedAt, &i.PublishedOriginalKey, ) return i, err } const clearStagingReference = `-- name: ClearStagingReference :execrows UPDATE attachments SET object_key = CASE WHEN status = 'failed' AND object_key = staging_key THEN NULL ELSE object_key END, staging_key = NULL WHERE id = $1 AND staging_key = $2 ` type ClearStagingReferenceParams struct { ID pgtype.UUID StagingKey pgtype.Text } func (q *Queries) ClearStagingReference(ctx context.Context, arg ClearStagingReferenceParams) (int64, error) { result, err := q.db.Exec(ctx, clearStagingReference, arg.ID, arg.StagingKey) if err != nil { return 0, err } return result.RowsAffected(), nil } const completeJob = `-- name: CompleteJob :execrows WITH completed AS ( UPDATE attachment_jobs AS j SET lease_until = NULL, next_attempt_at = NULL, updated_at = clock_timestamp(), published_original_key = $1::text FROM attachments AS a WHERE j.id = $2 AND j.lease_generation = $3 AND j.lease_until > clock_timestamp() AND a.id = j.attachment_id AND a.pipeline_version = j.pipeline_version AND a.status = 'processing' AND (SELECT count(*) FROM attachment_variants AS v WHERE v.attachment_id = a.id AND v.pipeline_version = j.pipeline_version) = 3 RETURNING j.id, j.attachment_id, j.pipeline_version, j.attempts_started, j.max_attempts, j.next_attempt_at, j.lease_generation, j.lease_until, j.created_at, j.updated_at, j.published_original_key ), recorded AS ( UPDATE attachment_attempts AS attempt SET outcome = 'ready', finished_at = completed.updated_at FROM completed WHERE attempt.job_id = completed.id AND attempt.lease_generation = completed.lease_generation ) UPDATE attachments AS a SET status = 'ready', object_key = $1::text, updated_at = completed.updated_at FROM completed WHERE a.id = completed.attachment_id ` type CompleteJobParams struct { ObjectKey string JobID pgtype.UUID LeaseGeneration int32 } func (q *Queries) CompleteJob(ctx context.Context, arg CompleteJobParams) (int64, error) { result, err := q.db.Exec(ctx, completeJob, arg.ObjectKey, arg.JobID, arg.LeaseGeneration) if err != nil { return 0, err } return result.RowsAffected(), nil } const createAttachmentJob = `-- name: CreateAttachmentJob :one INSERT INTO attachment_jobs (attachment_id, pipeline_version, next_attempt_at, max_attempts, created_at) VALUES ($1, $2, $3::timestamptz, $4, clock_timestamp()) RETURNING id, attachment_id, pipeline_version, attempts_started, max_attempts, next_attempt_at, lease_generation, lease_until, created_at, updated_at, published_original_key ` type CreateAttachmentJobParams struct { AttachmentID pgtype.UUID PipelineVersion int32 AvailableAt pgtype.Timestamptz MaxAttempts int32 } func (q *Queries) CreateAttachmentJob(ctx context.Context, arg CreateAttachmentJobParams) (AttachmentJob, error) { row := q.db.QueryRow(ctx, createAttachmentJob, arg.AttachmentID, arg.PipelineVersion, arg.AvailableAt, arg.MaxAttempts, ) var i AttachmentJob err := row.Scan( &i.ID, &i.AttachmentID, &i.PipelineVersion, &i.AttemptsStarted, &i.MaxAttempts, &i.NextAttemptAt, &i.LeaseGeneration, &i.LeaseUntil, &i.CreatedAt, &i.UpdatedAt, &i.PublishedOriginalKey, ) return i, err } const failJob = `-- name: FailJob :execrows WITH failed AS ( UPDATE attachment_jobs AS j SET lease_until = NULL, next_attempt_at = NULL, updated_at = clock_timestamp() FROM attachments AS a WHERE j.id = $2 AND j.lease_generation = $3 AND ( j.lease_until > clock_timestamp() OR (j.lease_until <= clock_timestamp() AND j.attempts_started = j.max_attempts AND $1::text = 'retry_exhausted') ) AND a.id = j.attachment_id AND a.pipeline_version = j.pipeline_version AND a.status = 'processing' RETURNING j.id, j.attachment_id, j.pipeline_version, j.attempts_started, j.max_attempts, j.next_attempt_at, j.lease_generation, j.lease_until, j.created_at, j.updated_at, j.published_original_key ), recorded AS ( UPDATE attachment_attempts AS attempt SET outcome = 'failed', error_code = $1::text, finished_at = failed.updated_at FROM failed WHERE attempt.job_id = failed.id AND attempt.lease_generation = failed.lease_generation ) UPDATE attachments AS a SET status = 'failed', error_code = $1::text, updated_at = failed.updated_at FROM failed WHERE a.id = failed.attachment_id ` type FailJobParams struct { ErrorCode string JobID pgtype.UUID LeaseGeneration int32 } func (q *Queries) FailJob(ctx context.Context, arg FailJobParams) (int64, error) { result, err := q.db.Exec(ctx, failJob, arg.ErrorCode, arg.JobID, arg.LeaseGeneration) if err != nil { return 0, err } return result.RowsAffected(), nil } const getAttachmentByStagingKey = `-- name: GetAttachmentByStagingKey :one SELECT id, chat_id, owner_id, filename, object_key, content_type, size_bytes, sha256, created_at, updated_at, status, error_code, staging_key, pipeline_version FROM attachments WHERE staging_key = $1::text ` func (q *Queries) GetAttachmentByStagingKey(ctx context.Context, stagingKey string) (Attachment, error) { row := q.db.QueryRow(ctx, getAttachmentByStagingKey, stagingKey) var i Attachment err := row.Scan( &i.ID, &i.ChatID, &i.OwnerID, &i.Filename, &i.ObjectKey, &i.ContentType, &i.SizeBytes, &i.Sha256, &i.CreatedAt, &i.UpdatedAt, &i.Status, &i.ErrorCode, &i.StagingKey, &i.PipelineVersion, ) return i, err } const getAttachmentJobState = `-- name: GetAttachmentJobState :one SELECT j.id, j.attachment_id, j.pipeline_version, CASE WHEN a.pipeline_version = j.pipeline_version THEN a.status ELSE 'superseded' END::text AS status, j.lease_generation, j.lease_until, coalesce(j.lease_until <= clock_timestamp(), false)::boolean AS lease_expired, j.attempts_started, j.max_attempts, j.next_attempt_at FROM attachment_jobs AS j JOIN attachments AS a ON a.id = j.attachment_id WHERE j.id = $1::uuid ` type GetAttachmentJobStateRow struct { ID pgtype.UUID AttachmentID pgtype.UUID PipelineVersion int32 Status string LeaseGeneration int32 LeaseUntil pgtype.Timestamptz LeaseExpired bool AttemptsStarted int32 MaxAttempts int32 NextAttemptAt pgtype.Timestamptz } func (q *Queries) GetAttachmentJobState(ctx context.Context, jobID pgtype.UUID) (GetAttachmentJobStateRow, error) { row := q.db.QueryRow(ctx, getAttachmentJobState, jobID) var i GetAttachmentJobStateRow err := row.Scan( &i.ID, &i.AttachmentID, &i.PipelineVersion, &i.Status, &i.LeaseGeneration, &i.LeaseUntil, &i.LeaseExpired, &i.AttemptsStarted, &i.MaxAttempts, &i.NextAttemptAt, ) return i, err } const getQueueStats = `-- name: GetQueueStats :one SELECT count(*)::bigint AS depth, COALESCE(EXTRACT(EPOCH FROM (statement_timestamp() - min(j.created_at))), 0)::double precision AS oldest_seconds FROM attachment_jobs AS j JOIN attachments AS a ON a.id = j.attachment_id WHERE a.status = 'queued' AND a.pipeline_version = j.pipeline_version ` type GetQueueStatsRow struct { Depth int64 OldestSeconds float64 } func (q *Queries) GetQueueStats(ctx context.Context) (GetQueueStatsRow, error) { row := q.db.QueryRow(ctx, getQueueStats) var i GetQueueStatsRow err := row.Scan(&i.Depth, &i.OldestSeconds) return i, err } const listFailedAttachmentJobs = `-- name: ListFailedAttachmentJobs :many SELECT j.id, j.attachment_id, j.attempts_started, a.error_code, a.updated_at FROM attachment_jobs j JOIN attachments a ON a.id = j.attachment_id AND a.pipeline_version = j.pipeline_version WHERE a.status = 'failed' ORDER BY a.updated_at DESC, j.id LIMIT $1 ` type ListFailedAttachmentJobsRow struct { ID pgtype.UUID AttachmentID pgtype.UUID AttemptsStarted int32 ErrorCode pgtype.Text UpdatedAt pgtype.Timestamptz } func (q *Queries) ListFailedAttachmentJobs(ctx context.Context, batchSize int32) ([]ListFailedAttachmentJobsRow, error) { rows, err := q.db.Query(ctx, listFailedAttachmentJobs, batchSize) if err != nil { return nil, err } defer rows.Close() var items []ListFailedAttachmentJobsRow for rows.Next() { var i ListFailedAttachmentJobsRow if err := rows.Scan( &i.ID, &i.AttachmentID, &i.AttemptsStarted, &i.ErrorCode, &i.UpdatedAt, ); err != nil { return nil, err } items = append(items, i) } if err := rows.Err(); err != nil { return nil, err } return items, nil } const lockActiveAttachmentJob = `-- name: LockActiveAttachmentJob :one SELECT j.id, j.attachment_id, j.pipeline_version, j.attempts_started, j.max_attempts, j.next_attempt_at, j.lease_generation, j.lease_until, j.created_at, j.updated_at, j.published_original_key FROM attachment_jobs AS j JOIN attachments AS a ON a.id = j.attachment_id WHERE j.id = $1 AND j.lease_generation = $2 AND j.lease_until > clock_timestamp() AND a.status = 'processing' AND a.pipeline_version = j.pipeline_version FOR UPDATE OF j ` type LockActiveAttachmentJobParams struct { JobID pgtype.UUID LeaseGeneration int32 } // Hold this lock through variant insertion and CompleteJob. Roll back on a zero-row completion. func (q *Queries) LockActiveAttachmentJob(ctx context.Context, arg LockActiveAttachmentJobParams) (AttachmentJob, error) { row := q.db.QueryRow(ctx, lockActiveAttachmentJob, arg.JobID, arg.LeaseGeneration) var i AttachmentJob err := row.Scan( &i.ID, &i.AttachmentID, &i.PipelineVersion, &i.AttemptsStarted, &i.MaxAttempts, &i.NextAttemptAt, &i.LeaseGeneration, &i.LeaseUntil, &i.CreatedAt, &i.UpdatedAt, &i.PublishedOriginalKey, ) return i, err } const lockAttachmentJobForPipeline = `-- name: LockAttachmentJobForPipeline :one SELECT j.id, j.attachment_id, j.pipeline_version, j.attempts_started, j.max_attempts, j.next_attempt_at, j.lease_generation, j.lease_until, j.created_at, j.updated_at, j.published_original_key FROM attachment_jobs j WHERE j.attachment_id = $1 AND j.pipeline_version = $2 FOR UPDATE ` type LockAttachmentJobForPipelineParams struct { AttachmentID pgtype.UUID PipelineVersion int32 } func (q *Queries) LockAttachmentJobForPipeline(ctx context.Context, arg LockAttachmentJobForPipelineParams) (AttachmentJob, error) { row := q.db.QueryRow(ctx, lockAttachmentJobForPipeline, arg.AttachmentID, arg.PipelineVersion) var i AttachmentJob err := row.Scan( &i.ID, &i.AttachmentID, &i.PipelineVersion, &i.AttemptsStarted, &i.MaxAttempts, &i.NextAttemptAt, &i.LeaseGeneration, &i.LeaseUntil, &i.CreatedAt, &i.UpdatedAt, &i.PublishedOriginalKey, ) return i, err } const lockAttachmentJobForReplay = `-- name: LockAttachmentJobForReplay :one SELECT j.id, j.attachment_id, j.pipeline_version, j.attempts_started, j.max_attempts, j.next_attempt_at, j.lease_generation, j.lease_until, j.created_at, j.updated_at, j.published_original_key FROM attachment_jobs j WHERE j.id = $1 FOR UPDATE ` func (q *Queries) LockAttachmentJobForReplay(ctx context.Context, id pgtype.UUID) (AttachmentJob, error) { row := q.db.QueryRow(ctx, lockAttachmentJobForReplay, id) var i AttachmentJob err := row.Scan( &i.ID, &i.AttachmentID, &i.PipelineVersion, &i.AttemptsStarted, &i.MaxAttempts, &i.NextAttemptAt, &i.LeaseGeneration, &i.LeaseUntil, &i.CreatedAt, &i.UpdatedAt, &i.PublishedOriginalKey, ) return i, err } const replayFailed = `-- name: ReplayFailed :execrows WITH replayed AS ( UPDATE attachment_jobs AS j SET max_attempts = j.attempts_started + $1::int, next_attempt_at = clock_timestamp(), updated_at = clock_timestamp() FROM attachments AS a WHERE j.id = $2 AND a.id = j.attachment_id AND a.pipeline_version = j.pipeline_version AND a.status = 'failed' AND a.staging_key IS NOT NULL AND j.lease_until IS NULL AND j.next_attempt_at IS NULL AND NOT EXISTS ( SELECT 1 FROM attachment_replays AS r WHERE r.request_id = $3::uuid ) RETURNING j.id, j.attachment_id, j.pipeline_version, j.attempts_started, j.max_attempts, j.next_attempt_at, j.lease_generation, j.lease_until, j.created_at, j.updated_at, j.published_original_key ), recorded AS ( INSERT INTO attachment_replays (request_id, job_id, operator_id, reason, extra_attempts) SELECT $3::uuid, id, $4, $5, $1 FROM replayed ), event AS ( INSERT INTO outbox (job_id, payload, available_at, dedup_key) SELECT id, attachment_job_payload(id, attachment_id, pipeline_version, attempts_started + 1, updated_at), next_attempt_at, 'replay/' || id || '/' || $3::uuid FROM replayed ) UPDATE attachments AS a SET status = 'queued', error_code = NULL, updated_at = replayed.updated_at FROM replayed WHERE a.id = replayed.attachment_id ` type ReplayFailedParams struct { ExtraAttempts int32 JobID pgtype.UUID RequestID pgtype.UUID OperatorID string Reason string } func (q *Queries) ReplayFailed(ctx context.Context, arg ReplayFailedParams) (int64, error) { result, err := q.db.Exec(ctx, replayFailed, arg.ExtraAttempts, arg.JobID, arg.RequestID, arg.OperatorID, arg.Reason, ) if err != nil { return 0, err } return result.RowsAffected(), nil } const scheduleRetry = `-- name: ScheduleRetry :execrows WITH scheduled AS ( UPDATE attachment_jobs AS j SET lease_until = NULL, next_attempt_at = $1::timestamptz, updated_at = clock_timestamp() FROM attachments AS a WHERE j.id = $2 AND j.lease_generation = $3 AND j.lease_until > clock_timestamp() AND a.id = j.attachment_id AND a.pipeline_version = j.pipeline_version AND a.status = 'processing' AND j.attempts_started < j.max_attempts AND $1::timestamptz > clock_timestamp() RETURNING j.id, j.attachment_id, j.pipeline_version, j.attempts_started, j.max_attempts, j.next_attempt_at, j.lease_generation, j.lease_until, j.created_at, j.updated_at, j.published_original_key ), recorded AS ( UPDATE attachment_attempts AS attempt SET outcome = 'retry', error_code = $4::text, finished_at = scheduled.updated_at FROM scheduled WHERE attempt.job_id = scheduled.id AND attempt.lease_generation = scheduled.lease_generation ), event AS ( INSERT INTO outbox (job_id, payload, available_at, dedup_key) SELECT id, attachment_job_payload(id, attachment_id, pipeline_version, attempts_started + 1, updated_at) || jsonb_strip_nulls(jsonb_build_object( 'traceparent', NULLIF($5::text, ''), 'tracestate', NULLIF($6::text, '') )), next_attempt_at, 'retry/' || id || '/' || (attempts_started + 1) FROM scheduled ) UPDATE attachments AS a SET status = 'queued', updated_at = scheduled.updated_at FROM scheduled WHERE a.id = scheduled.attachment_id ` type ScheduleRetryParams struct { AvailableAt pgtype.Timestamptz JobID pgtype.UUID LeaseGeneration int32 ErrorCode string Traceparent string Tracestate string } func (q *Queries) ScheduleRetry(ctx context.Context, arg ScheduleRetryParams) (int64, error) { result, err := q.db.Exec(ctx, scheduleRetry, arg.AvailableAt, arg.JobID, arg.LeaseGeneration, arg.ErrorCode, arg.Traceparent, arg.Tracestate, ) if err != nil { return 0, err } return result.RowsAffected(), nil }