// Code generated by sqlc. DO NOT EDIT. // versions: // sqlc v1.31.1 // source: scheduled_job.sql package sqlc import ( "context" "github.com/jackc/pgx/v5/pgtype" ) const cancelScheduledJob = `-- name: CancelScheduledJob :execrows UPDATE scheduled_jobs SET status = 'cancelled', lease_owner = NULL, lease_expires_at = NULL, started_at = NULL, updated_at = clock_timestamp() WHERE kind = $1 AND dedup_key = $2 AND status IN ('pending', 'failed', 'running') ` type CancelScheduledJobParams struct { Kind string DedupKey string } // Cancels a job that has not finished. A job whose handler transaction is // in progress holds its row lock, so the statement waits for it: after the // handler committed the job is done and nothing is canceled; otherwise the // worker finds its lease gone and does not run or complete the job. func (q *Queries) CancelScheduledJob(ctx context.Context, arg CancelScheduledJobParams) (int64, error) { result, err := q.db.Exec(ctx, cancelScheduledJob, arg.Kind, arg.DedupKey) if err != nil { return 0, err } return result.RowsAffected(), nil } const claimScheduledJobs = `-- name: ClaimScheduledJobs :many WITH candidates AS ( SELECT candidate.id, ( candidate.status = 'running' AND candidate.started_at IS NULL ) AS unstarted, ( candidate.status = 'running' AND candidate.started_at IS NOT NULL AND candidate.attempts >= coalesce( candidate.max_attempts, $3::integer ) ) AS exhausted FROM scheduled_jobs AS candidate WHERE candidate.kind = any($4::text []) AND ( ( candidate.status IN ('pending', 'failed') AND candidate.available_at <= $5::timestamptz ) OR ( candidate.status = 'running' AND candidate.lease_expires_at <= $5::timestamptz ) ) ORDER BY candidate.available_at, candidate.id LIMIT $6 FOR UPDATE SKIP LOCKED ) UPDATE scheduled_jobs AS job SET status = CASE WHEN candidates.exhausted THEN 'dead' ELSE 'running' END, attempts = CASE WHEN candidates.exhausted OR candidates.unstarted THEN job.attempts ELSE job.attempts + 1 END, lease_owner = CASE WHEN candidates.exhausted THEN NULL ELSE $1::uuid END, lease_expires_at = CASE WHEN candidates.exhausted THEN NULL ELSE $2::timestamptz END, started_at = NULL, last_error_class = CASE WHEN job.status = 'running' AND NOT candidates.unstarted THEN 'lease_expired' ELSE job.last_error_class END, updated_at = clock_timestamp() FROM candidates WHERE job.id = candidates.id RETURNING job.id, job.kind, job.dedup_key, job.payload, job.due_at, job.attempts, coalesce( job.max_attempts, $3::integer )::integer AS max_attempts, candidates.exhausted ` type ClaimScheduledJobsParams struct { LeaseOwner pgtype.UUID LeaseExpiresAt pgtype.Timestamptz DefaultMaxAttempts int32 Kinds []string Now pgtype.Timestamptz BatchLimit int32 } type ClaimScheduledJobsRow struct { ID int64 Kind string DedupKey string Payload []byte DueAt pgtype.Timestamptz Attempts int32 MaxAttempts int32 Exhausted pgtype.Bool } // Claims up to batch_limit jobs of the listed kinds in one statement: jobs // whose available_at has passed, and running jobs whose lease expired // because their worker stopped without finishing them. Rows that another // worker locks are skipped without waiting. Each claimed job gets the lease // of lease_owner and one more attempt, except a job whose expired attempt // never started its handler: that attempt is reused, so a worker that was // busy with other jobs of its batch costs the job nothing. A job whose // started attempt was abandoned on its last allowed attempt becomes dead // with lease_expired instead, so a job that keeps crashing its worker // stops. now is the application clock. // // The kind filter applies after the index on available_at; when many waiting // jobs belong to kinds without a handler in the claiming process, an index // on (kind, available_at, id) is the next step. func (q *Queries) ClaimScheduledJobs(ctx context.Context, arg ClaimScheduledJobsParams) ([]ClaimScheduledJobsRow, error) { rows, err := q.db.Query(ctx, claimScheduledJobs, arg.LeaseOwner, arg.LeaseExpiresAt, arg.DefaultMaxAttempts, arg.Kinds, arg.Now, arg.BatchLimit, ) if err != nil { return nil, err } defer rows.Close() var items []ClaimScheduledJobsRow for rows.Next() { var i ClaimScheduledJobsRow if err := rows.Scan( &i.ID, &i.Kind, &i.DedupKey, &i.Payload, &i.DueAt, &i.Attempts, &i.MaxAttempts, &i.Exhausted, ); err != nil { return nil, err } items = append(items, i) } if err := rows.Err(); err != nil { return nil, err } return items, nil } const completeScheduledJob = `-- name: CompleteScheduledJob :execrows UPDATE scheduled_jobs SET status = 'done', lease_owner = NULL, lease_expires_at = NULL, started_at = NULL, updated_at = clock_timestamp() WHERE id = $1 AND status = 'running' AND lease_owner = $2 AND attempts = $3 ` type CompleteScheduledJobParams struct { ID int64 LeaseOwner pgtype.UUID Attempt int32 } // Completes a job in the transaction of its handler effect. The guard is // the lease owner and the attempt, so a worker that lost its lease cannot // complete the job. func (q *Queries) CompleteScheduledJob(ctx context.Context, arg CompleteScheduledJobParams) (int64, error) { result, err := q.db.Exec(ctx, completeScheduledJob, arg.ID, arg.LeaseOwner, arg.Attempt) if err != nil { return 0, err } return result.RowsAffected(), nil } const failScheduledJob = `-- name: FailScheduledJob :execrows UPDATE scheduled_jobs SET status = $1, available_at = coalesce($2, available_at), last_error_class = $3, lease_owner = NULL, lease_expires_at = NULL, started_at = NULL, updated_at = clock_timestamp() WHERE id = $4 AND status = 'running' AND lease_owner = $5 AND attempts = $6 ` type FailScheduledJobParams struct { Status string RetryAt pgtype.Timestamptz ErrorClass pgtype.Text ID int64 LeaseOwner pgtype.UUID Attempt int32 } // Records a failed attempt after its handler transaction rolled back: the // job waits for its retry at retry_at (status failed) or is dead, with a // NULL retry_at. due_at keeps the deadline. The same guard as the // completion applies. func (q *Queries) FailScheduledJob(ctx context.Context, arg FailScheduledJobParams) (int64, error) { result, err := q.db.Exec(ctx, failScheduledJob, arg.Status, arg.RetryAt, arg.ErrorClass, arg.ID, arg.LeaseOwner, arg.Attempt, ) if err != nil { return 0, err } return result.RowsAffected(), nil } const getScheduledJobBacklog = `-- name: GetScheduledJobBacklog :one SELECT ( SELECT count(*) FROM scheduled_jobs AS due WHERE due.status IN ('pending', 'failed') AND due.available_at <= $1::timestamptz )::bigint AS due_jobs, coalesce(( SELECT extract(EPOCH FROM $1::timestamptz - oldest.available_at) FROM scheduled_jobs AS oldest WHERE oldest.status IN ('pending', 'failed') AND oldest.available_at <= $1::timestamptz ORDER BY oldest.available_at LIMIT 1 ), 0)::float8 AS oldest_due_age_seconds, ( SELECT count(*) FROM scheduled_jobs AS dead WHERE dead.status = 'dead' )::bigint AS dead_jobs ` type GetScheduledJobBacklogRow struct { DueJobs int64 OldestDueAgeSeconds float64 DeadJobs int64 } // Reads the backlog for metrics without locking: jobs that a worker may // claim at now, how long the earliest of them has waited, and the dead // jobs. The // partial indexes keep the cost proportional to those rows. now is the // application clock. func (q *Queries) GetScheduledJobBacklog(ctx context.Context, now pgtype.Timestamptz) (GetScheduledJobBacklogRow, error) { row := q.db.QueryRow(ctx, getScheduledJobBacklog, now) var i GetScheduledJobBacklogRow err := row.Scan(&i.DueJobs, &i.OldestDueAgeSeconds, &i.DeadJobs) return i, err } const getScheduledJobStatus = `-- name: GetScheduledJobStatus :one SELECT job.status FROM scheduled_jobs AS job WHERE job.id = $1 ` // Reads the status of a job whose completion found it changed, inside // the handler transaction that holds its row lock: only that transaction // can have changed it, for example by canceling its own job. func (q *Queries) GetScheduledJobStatus(ctx context.Context, id int64) (string, error) { row := q.db.QueryRow(ctx, getScheduledJobStatus, id) var status string err := row.Scan(&status) return status, err } const insertScheduledJob = `-- name: InsertScheduledJob :execrows INSERT INTO scheduled_jobs ( kind, dedup_key, payload, due_at, available_at, status, attempts, max_attempts ) VALUES ( $1, $2, $3, $4, $4, 'pending', 0, $5 ) ON CONFLICT (kind, dedup_key) DO NOTHING ` type InsertScheduledJobParams struct { Kind string DedupKey string Payload []byte DueAt pgtype.Timestamptz MaxAttempts pgtype.Int4 } // Lock order. A job handler runs while its transaction holds the row lock // of the job, and may then lock product rows. A business transaction that // cancels a job should cancel it before it locks the product rows the // handler touches, so both take the locks in the same order. // Schedules a job in the caller's transaction. The first schedule of a // (kind, dedup_key) wins: a repeat, also after the job finished or was // canceled, inserts nothing and reports 0 rows, so a repeated command never // moves a deadline. A concurrent insert of the same key waits for the first // transaction and then inserts nothing, or inserts after its rollback. func (q *Queries) InsertScheduledJob(ctx context.Context, arg InsertScheduledJobParams) (int64, error) { result, err := q.db.Exec(ctx, insertScheduledJob, arg.Kind, arg.DedupKey, arg.Payload, arg.DueAt, arg.MaxAttempts, ) if err != nil { return 0, err } return result.RowsAffected(), nil } const lockClaimedScheduledJob = `-- name: LockClaimedScheduledJob :one SELECT job.id FROM scheduled_jobs AS job WHERE job.id = $1 AND job.status = 'running' AND job.lease_owner = $2 AND job.attempts = $3 FOR UPDATE ` type LockClaimedScheduledJobParams struct { ID int64 LeaseOwner pgtype.UUID Attempt int32 } // Locks a claimed job for its handler transaction and checks that the lease // still belongs to this attempt. It returns no row when the job was // canceled, or reclaimed after the lease expired. While the lock is held, // other workers skip the row, so the handler never runs twice at once. func (q *Queries) LockClaimedScheduledJob(ctx context.Context, arg LockClaimedScheduledJobParams) (int64, error) { row := q.db.QueryRow(ctx, lockClaimedScheduledJob, arg.ID, arg.LeaseOwner, arg.Attempt) var id int64 err := row.Scan(&id) return id, err } const releaseScheduledJobs = `-- name: ReleaseScheduledJobs :many UPDATE scheduled_jobs AS job SET status = CASE WHEN job.last_error_class IS NULL THEN 'pending' ELSE 'failed' END, attempts = job.attempts - 1, lease_owner = NULL, lease_expires_at = NULL, started_at = NULL, updated_at = clock_timestamp() FROM ( -- Set-returning functions in one select list advance together, so the -- arrays pair up by position. The two-argument unnest(ids, attempts) -- would say the same, but the sqlc analyzer cannot type it, and -- sqlfluff cannot parse ROWS FROM. SELECT unnest($2::bigint []) AS id, unnest($3::integer []) AS attempt ) AS released WHERE job.id = released.id AND job.attempts = released.attempt AND job.status = 'running' AND job.lease_owner = $1 RETURNING job.id ` type ReleaseScheduledJobsParams struct { LeaseOwner pgtype.UUID Ids []int64 Attempts []int32 } // Returns claimed jobs that did not finish, at shutdown or after a database // failure outside the handler, so another worker can run them at once // instead of after the lease expires. The attempt is not counted, because // the job did not cause the failure. The same guard as the completion // applies, one (id, attempt) pair per job. It returns the IDs it released. func (q *Queries) ReleaseScheduledJobs(ctx context.Context, arg ReleaseScheduledJobsParams) ([]int64, error) { rows, err := q.db.Query(ctx, releaseScheduledJobs, arg.LeaseOwner, arg.Ids, arg.Attempts) if err != nil { return nil, err } defer rows.Close() var items []int64 for rows.Next() { var id int64 if err := rows.Scan(&id); err != nil { return nil, err } items = append(items, id) } if err := rows.Err(); err != nil { return nil, err } return items, nil } const setScheduledJobTransactionTimeouts = `-- name: SetScheduledJobTransactionTimeouts :exec SELECT set_config('statement_timeout', $1::text, true), set_config( 'idle_in_transaction_session_timeout', $2::text, true ) ` type SetScheduledJobTransactionTimeoutsParams struct { StatementTimeoutMs string IdleTimeoutMs string } // Bounds a handler transaction on the server, local to the transaction. // statement_timeout stops a slow statement; idle_in_transaction_session_timeout // ends the session of a worker that froze or lost the network inside the // handler, which releases the job row lock so the job can be reclaimed once // its lease expires. func (q *Queries) SetScheduledJobTransactionTimeouts(ctx context.Context, arg SetScheduledJobTransactionTimeoutsParams) error { _, err := q.db.Exec(ctx, setScheduledJobTransactionTimeouts, arg.StatementTimeoutMs, arg.IdleTimeoutMs) return err } const startScheduledJob = `-- name: StartScheduledJob :execrows UPDATE scheduled_jobs SET lease_expires_at = $1, started_at = $2, updated_at = clock_timestamp() WHERE id = $3 AND status = 'running' AND lease_owner = $4 AND attempts = $5 AND lease_expires_at > $2 ` type StartScheduledJobParams struct { LeaseExpiresAt pgtype.Timestamptz Now pgtype.Timestamptz ID int64 LeaseOwner pgtype.UUID Attempt int32 } // Starts a claimed attempt right before its handler transaction: it renews // the lease from now and records the start, committed on its own. It // changes nothing when the lease already expired by now or no longer // belongs to this attempt, so a job whose turn in the batch came too late is // never started on a lease that another worker may take over. now is the // application clock. func (q *Queries) StartScheduledJob(ctx context.Context, arg StartScheduledJobParams) (int64, error) { result, err := q.db.Exec(ctx, startScheduledJob, arg.LeaseExpiresAt, arg.Now, arg.ID, arg.LeaseOwner, arg.Attempt, ) if err != nil { return 0, err } return result.RowsAffected(), nil }