// Code generated by sqlc. DO NOT EDIT. // versions: // sqlc v1.31.1 // source: delivery.sql package sqlc import ( "context" "github.com/jackc/pgx/v5/pgtype" ) const authorizeUnknownDeliveryRetry = `-- name: AuthorizeUnknownDeliveryRetry :execrows WITH eligible AS MATERIALIZED ( SELECT due.id, (due.claim_owner IS NOT NULL) AS previous_lease_expired, ( due.manual_retry_started_at IS NOT NULL AND due.send_started_attempt_count = due.attempt_count ) AS unsettled_manual_send, greatest( clock_timestamp(), due.updated_at, coalesce(due.last_attempt_at, due.updated_at) ) AS lost_attempt_at FROM deliveries AS due WHERE due.id = $3 AND due.status = 'unknown' AND due.next_attempt_at IS NULL AND ( due.claim_owner IS NULL OR due.claimed_until <= clock_timestamp() ) AND due.attempt_count > 0 AND due.provider = $4 AND due.provider_account = $5 AND due.first_send_started_at IS NOT NULL AND clock_timestamp() - due.first_send_started_at >= make_interval(secs => $6::float8) AND $2::boolean AND $1::text ~ '^operator:[a-z0-9][a-z0-9._-]*$' FOR UPDATE ), authorized AS ( UPDATE deliveries AS due SET attempt_count = due.attempt_count + CASE WHEN eligible.unsettled_manual_send THEN 1 ELSE 0 END, last_attempt_at = CASE WHEN eligible.unsettled_manual_send THEN eligible.lost_attempt_at ELSE due.last_attempt_at END, next_attempt_at = greatest( $7::timestamptz, due.updated_at, coalesce(eligible.lost_attempt_at, due.updated_at) ), manual_retry_authorized_at = clock_timestamp(), manual_retry_started_at = NULL, claim_owner = NULL, claimed_until = NULL, version = due.version + 1, updated_at = greatest( due.updated_at, $7::timestamptz, coalesce(eligible.lost_attempt_at, due.updated_at) ) FROM eligible WHERE due.id = eligible.id RETURNING due.id, due.attempt_count, eligible.previous_lease_expired, eligible.unsettled_manual_send, eligible.lost_attempt_at ), recorded_lost_attempt AS ( -- A manual send whose lease expired after Mark but before settlement has -- no provider answer. Preserve it as an unknown attempt before this new -- explicit decision schedules another possible send. INSERT INTO delivery_attempts ( delivery_id, attempt_number, attempted_at, outcome, rejection, provider_code, provider_message_id, retry_after_ns, status_after, next_attempt_at ) SELECT authorized.id, authorized.attempt_count, authorized.lost_attempt_at, 'unknown', NULL, NULL, NULL, 0, 'unknown', NULL FROM authorized WHERE authorized.unsettled_manual_send RETURNING delivery_id ) INSERT INTO delivery_retry_decisions ( delivery_id, attempt_count, actor, duplicate_risk_acknowledged, previous_lease_expired, decided_at ) SELECT authorized.id, authorized.attempt_count, $1, $2, authorized.previous_lease_expired, clock_timestamp() FROM authorized ` type AuthorizeUnknownDeliveryRetryParams struct { Actor string DuplicateRiskAcknowledged bool DeliveryID pgtype.UUID Provider string ProviderAccount string MinimumAgeSeconds float64 Now pgtype.Timestamptz } // Authorizes one retry of a terminal unknown delivery. The update and append- // only decision share one statement and lock the current row, so a second or // concurrent operator decision cannot schedule another send for the same // unknown attempt. The provider account must still match the delivery's pin. func (q *Queries) AuthorizeUnknownDeliveryRetry(ctx context.Context, arg AuthorizeUnknownDeliveryRetryParams) (int64, error) { result, err := q.db.Exec(ctx, authorizeUnknownDeliveryRetry, arg.Actor, arg.DuplicateRiskAcknowledged, arg.DeliveryID, arg.Provider, arg.ProviderAccount, arg.MinimumAgeSeconds, arg.Now, ) if err != nil { return 0, err } return result.RowsAffected(), nil } const cancelUnreadableDelivery = `-- name: CancelUnreadableDelivery :execrows UPDATE deliveries SET status = 'cancelled', cancel_reason = 'content_invalid', next_attempt_at = NULL, claim_owner = NULL, claimed_until = NULL, text_body = CASE WHEN deliveries.kind IN ('verification', 'password_reset', 'notification') THEN '' ELSE deliveries.text_body END, html_body = CASE WHEN deliveries.kind IN ('verification', 'password_reset', 'notification') THEN '' ELSE deliveries.html_body END, body_redacted_at = CASE WHEN deliveries.kind IN ('verification', 'password_reset', 'notification') THEN greatest(deliveries.updated_at, $1::timestamptz) ELSE deliveries.body_redacted_at END, version = deliveries.version + 1, updated_at = greatest(deliveries.updated_at, $1::timestamptz) WHERE id = $2 AND status IN ('pending', 'waiting_quota') ` type CancelUnreadableDeliveryParams struct { Now pgtype.Timestamptz ID pgtype.UUID } // Ends a claimed delivery whose stored content no longer matches its hash, so // one broken row never blocks the delivery queue. It matches only a delivery // that the worker could still send, ends the lease, advances the version, and // redacts the bodies of a token mail like any other cancellation. now is the // application clock. func (q *Queries) CancelUnreadableDelivery(ctx context.Context, arg CancelUnreadableDeliveryParams) (int64, error) { result, err := q.db.Exec(ctx, cancelUnreadableDelivery, arg.Now, arg.ID) if err != nil { return 0, err } return result.RowsAffected(), nil } const claimDueDelivery = `-- name: ClaimDueDelivery :one WITH candidate AS ( SELECT due.id, due.claimed_until AS previous_claimed_until, coalesce( extract(EPOCH FROM clock_timestamp() - due.first_send_started_at), -1 )::float8 AS since_first_send_seconds, (due.manual_retry_authorized_at IS NOT NULL AND due.manual_retry_started_at IS NULL) AS manual_retry_pending, (due.manual_retry_started_at IS NOT NULL)::boolean AS manual_retry_cycle_started, ( due.send_started_attempt_count IS NOT NULL AND due.send_started_attempt_count = due.attempt_count )::boolean AS send_start_unsettled, EXISTS ( SELECT 1 FROM delivery_attempts AS prior_attempt WHERE prior_attempt.delivery_id = due.id AND prior_attempt.outcome = 'unknown' )::boolean AS has_uncertain_attempt FROM deliveries AS due WHERE due.kind IN ('verification', 'password_reset') AND due.kind = any($3::text []) AND due.status IN ('pending', 'waiting_quota', 'unknown') AND due.next_attempt_at IS NOT NULL AND due.next_attempt_at <= $4::timestamptz AND ( ( due.provider = $5 AND due.provider_account = $6 ) OR ( due.provider = $7::text AND due.attempt_count = 0 ) ) AND ( due.claim_owner IS NULL OR due.claimed_until <= clock_timestamp() ) ORDER BY due.next_attempt_at, due.id LIMIT 1 FOR UPDATE SKIP LOCKED ) UPDATE deliveries AS claimed SET claim_owner = $1::uuid, claimed_until = clock_timestamp() + make_interval(secs => $2::float8) FROM candidate WHERE claimed.id = candidate.id RETURNING claimed.id, claimed.source_event_id, claimed.recipient_user_id, claimed.recipient_email, claimed.kind, claimed.template_version, claimed.subject, claimed.text_body, claimed.html_body, claimed.content_sha256, claimed.provider, claimed.provider_account, claimed.idempotency_key, claimed.status, claimed.attempt_count, claimed.next_attempt_at, claimed.last_attempt_at, claimed.provider_message_id, claimed.email_token_id, claimed.cancel_reason, claimed.body_redacted_at, claimed.failure_count, claimed.version, claimed.created_at, claimed.updated_at, claimed.subject_kind, claimed.subject_id, claimed.subject_organization_id, candidate.previous_claimed_until, candidate.since_first_send_seconds, candidate.manual_retry_pending, candidate.manual_retry_cycle_started, candidate.send_start_unsettled, candidate.has_uncertain_attempt ` type ClaimDueDeliveryParams struct { LeaseOwner pgtype.UUID LeaseSeconds float64 Kinds []string Now pgtype.Timestamptz Provider string ProviderAccount string RebindProvider string } type ClaimDueDeliveryRow struct { ID pgtype.UUID SourceEventID pgtype.UUID RecipientUserID pgtype.UUID RecipientEmail string Kind string TemplateVersion string Subject string TextBody string HtmlBody string ContentSha256 []byte Provider string ProviderAccount string IdempotencyKey string Status string AttemptCount int32 NextAttemptAt pgtype.Timestamptz LastAttemptAt pgtype.Timestamptz ProviderMessageID pgtype.Text EmailTokenID pgtype.UUID CancelReason pgtype.Text BodyRedactedAt pgtype.Timestamptz FailureCount int32 Version int64 CreatedAt pgtype.Timestamptz UpdatedAt pgtype.Timestamptz SubjectKind pgtype.Text SubjectID pgtype.UUID SubjectOrganizationID pgtype.UUID PreviousClaimedUntil pgtype.Timestamptz SinceFirstSendSeconds float64 ManualRetryPending pgtype.Bool ManualRetryCycleStarted bool SendStartUnsettled bool HasUncertainAttempt bool } // Claims the most overdue delivery that the sending worker may send, in one // statement: a pending, waiting_quota, or scheduled unknown delivery of the service mail kinds // (the literals match the predicate of deliveries_due_idx, so an idle poll // reads only that small index) whose next_attempt_at has passed, pinned to the // configured provider account (or to rebind_provider before its first // attempt, which the worker moves to the configured account), and held by no // live lease. A row that another worker locks is skipped without waiting, so // several processes never take the same delivery, and a delivery whose lease // expired, because its worker stopped, is claimed again. // The lease is measured by the database clock, never by the clock of an // application instance: it lasts lease_seconds from clock_timestamp(), and a // lease is live while claimed_until is later than clock_timestamp(). Due times // stay on the application clock that wrote them. Neither the version nor // updated_at changes: a claim is not a change of the delivery. // previous_claimed_until is the deadline of an abandoned lease, NULL for a // delivery nobody held; since_first_send_seconds always measures from the // original first request by the database clock, and is -1 when none started. // manual_retry_pending is true until the first provider call of the latest // manual authorization starts. send_start_unsettled means a provider call // started at the current attempt_count but no result was recorded afterward. // has_uncertain_attempt keeps an earlier unknown result visible even if a // later confirmed refusal moved the current delivery back to pending. // now is the application clock. Unknown deliveries without a scheduled retry // and quota waits with an unknown reset wait for an operator. func (q *Queries) ClaimDueDelivery(ctx context.Context, arg ClaimDueDeliveryParams) (ClaimDueDeliveryRow, error) { row := q.db.QueryRow(ctx, claimDueDelivery, arg.LeaseOwner, arg.LeaseSeconds, arg.Kinds, arg.Now, arg.Provider, arg.ProviderAccount, arg.RebindProvider, ) var i ClaimDueDeliveryRow err := row.Scan( &i.ID, &i.SourceEventID, &i.RecipientUserID, &i.RecipientEmail, &i.Kind, &i.TemplateVersion, &i.Subject, &i.TextBody, &i.HtmlBody, &i.ContentSha256, &i.Provider, &i.ProviderAccount, &i.IdempotencyKey, &i.Status, &i.AttemptCount, &i.NextAttemptAt, &i.LastAttemptAt, &i.ProviderMessageID, &i.EmailTokenID, &i.CancelReason, &i.BodyRedactedAt, &i.FailureCount, &i.Version, &i.CreatedAt, &i.UpdatedAt, &i.SubjectKind, &i.SubjectID, &i.SubjectOrganizationID, &i.PreviousClaimedUntil, &i.SinceFirstSendSeconds, &i.ManualRetryPending, &i.ManualRetryCycleStarted, &i.SendStartUnsettled, &i.HasUncertainAttempt, ) return i, err } const claimDueProductDelivery = `-- name: ClaimDueProductDelivery :one WITH candidate AS ( SELECT due.id, due.claimed_until AS previous_claimed_until, coalesce( extract(EPOCH FROM clock_timestamp() - due.first_send_started_at), -1 )::float8 AS since_first_send_seconds, (due.manual_retry_authorized_at IS NOT NULL AND due.manual_retry_started_at IS NULL) AS manual_retry_pending, (due.manual_retry_started_at IS NOT NULL)::boolean AS manual_retry_cycle_started, ( due.send_started_attempt_count IS NOT NULL AND due.send_started_attempt_count = due.attempt_count )::boolean AS send_start_unsettled, EXISTS ( SELECT 1 FROM delivery_attempts AS prior_attempt WHERE prior_attempt.delivery_id = due.id AND prior_attempt.outcome = 'unknown' )::boolean AS has_uncertain_attempt FROM deliveries AS due WHERE due.kind = 'notification' AND due.status IN ('pending', 'waiting_quota', 'unknown') AND due.next_attempt_at IS NOT NULL AND due.next_attempt_at <= $3::timestamptz AND ( ( due.provider = $4 AND due.provider_account = $5 ) OR ( due.provider = $6::text AND due.attempt_count = 0 ) ) AND ( due.claim_owner IS NULL OR due.claimed_until <= clock_timestamp() ) ORDER BY due.next_attempt_at, due.id LIMIT 1 FOR UPDATE SKIP LOCKED ) UPDATE deliveries AS claimed SET claim_owner = $1::uuid, claimed_until = clock_timestamp() + make_interval(secs => $2::float8) FROM candidate WHERE claimed.id = candidate.id RETURNING claimed.id, claimed.source_event_id, claimed.recipient_user_id, claimed.recipient_email, claimed.kind, claimed.template_version, claimed.subject, claimed.text_body, claimed.html_body, claimed.content_sha256, claimed.provider, claimed.provider_account, claimed.idempotency_key, claimed.status, claimed.attempt_count, claimed.next_attempt_at, claimed.last_attempt_at, claimed.provider_message_id, claimed.email_token_id, claimed.cancel_reason, claimed.body_redacted_at, claimed.failure_count, claimed.version, claimed.created_at, claimed.updated_at, claimed.subject_kind, claimed.subject_id, claimed.subject_organization_id, candidate.previous_claimed_until, candidate.since_first_send_seconds, candidate.manual_retry_pending, candidate.manual_retry_cycle_started, candidate.send_start_unsettled, candidate.has_uncertain_attempt ` type ClaimDueProductDeliveryParams struct { LeaseOwner pgtype.UUID LeaseSeconds float64 Now pgtype.Timestamptz Provider string ProviderAccount string RebindProvider string } type ClaimDueProductDeliveryRow struct { ID pgtype.UUID SourceEventID pgtype.UUID RecipientUserID pgtype.UUID RecipientEmail string Kind string TemplateVersion string Subject string TextBody string HtmlBody string ContentSha256 []byte Provider string ProviderAccount string IdempotencyKey string Status string AttemptCount int32 NextAttemptAt pgtype.Timestamptz LastAttemptAt pgtype.Timestamptz ProviderMessageID pgtype.Text EmailTokenID pgtype.UUID CancelReason pgtype.Text BodyRedactedAt pgtype.Timestamptz FailureCount int32 Version int64 CreatedAt pgtype.Timestamptz UpdatedAt pgtype.Timestamptz SubjectKind pgtype.Text SubjectID pgtype.UUID SubjectOrganizationID pgtype.UUID PreviousClaimedUntil pgtype.Timestamptz SinceFirstSendSeconds float64 ManualRetryPending pgtype.Bool ManualRetryCycleStarted bool SendStartUnsettled bool HasUncertainAttempt bool } // Claims the most overdue product notification, under the same rules as // ClaimDueDelivery: a lease in the database clock, the configured provider // account or a rebind of a delivery before its first attempt, and no live // lease. It reads deliveries_product_due_idx, whose predicate repeats the // literal kind below, so the backlog of service mail never enters the scan. // A notification is claimed here whatever its subject; the sending worker // checks the subject's rights after the claim and cancels a notice whose // basis no longer holds. func (q *Queries) ClaimDueProductDelivery(ctx context.Context, arg ClaimDueProductDeliveryParams) (ClaimDueProductDeliveryRow, error) { row := q.db.QueryRow(ctx, claimDueProductDelivery, arg.LeaseOwner, arg.LeaseSeconds, arg.Now, arg.Provider, arg.ProviderAccount, arg.RebindProvider, ) var i ClaimDueProductDeliveryRow err := row.Scan( &i.ID, &i.SourceEventID, &i.RecipientUserID, &i.RecipientEmail, &i.Kind, &i.TemplateVersion, &i.Subject, &i.TextBody, &i.HtmlBody, &i.ContentSha256, &i.Provider, &i.ProviderAccount, &i.IdempotencyKey, &i.Status, &i.AttemptCount, &i.NextAttemptAt, &i.LastAttemptAt, &i.ProviderMessageID, &i.EmailTokenID, &i.CancelReason, &i.BodyRedactedAt, &i.FailureCount, &i.Version, &i.CreatedAt, &i.UpdatedAt, &i.SubjectKind, &i.SubjectID, &i.SubjectOrganizationID, &i.PreviousClaimedUntil, &i.SinceFirstSendSeconds, &i.ManualRetryPending, &i.ManualRetryCycleStarted, &i.SendStartUnsettled, &i.HasUncertainAttempt, ) return i, err } const deleteMailRequest = `-- name: DeleteMailRequest :execrows DELETE FROM mail_requests WHERE id = $1 ` func (q *Queries) DeleteMailRequest(ctx context.Context, id pgtype.UUID) (int64, error) { result, err := q.db.Exec(ctx, deleteMailRequest, id) if err != nil { return 0, err } return result.RowsAffected(), nil } const getDeliveryByID = `-- name: GetDeliveryByID :one SELECT id, source_event_id, recipient_user_id, recipient_email, kind, template_version, subject, text_body, html_body, content_sha256, provider, provider_account, idempotency_key, status, attempt_count, next_attempt_at, last_attempt_at, provider_message_id, version, created_at, updated_at, email_token_id, cancel_reason, claim_owner, claimed_until, first_send_started_at, failure_count, body_redacted_at, subject_kind, subject_id, subject_organization_id FROM deliveries WHERE id = $1 ` type GetDeliveryByIDRow struct { ID pgtype.UUID SourceEventID pgtype.UUID RecipientUserID pgtype.UUID RecipientEmail string Kind string TemplateVersion string Subject string TextBody string HtmlBody string ContentSha256 []byte Provider string ProviderAccount string IdempotencyKey string Status string AttemptCount int32 NextAttemptAt pgtype.Timestamptz LastAttemptAt pgtype.Timestamptz ProviderMessageID pgtype.Text Version int64 CreatedAt pgtype.Timestamptz UpdatedAt pgtype.Timestamptz EmailTokenID pgtype.UUID CancelReason pgtype.Text ClaimOwner pgtype.UUID ClaimedUntil pgtype.Timestamptz FirstSendStartedAt pgtype.Timestamptz FailureCount int32 BodyRedactedAt pgtype.Timestamptz SubjectKind pgtype.Text SubjectID pgtype.UUID SubjectOrganizationID pgtype.UUID } func (q *Queries) GetDeliveryByID(ctx context.Context, id pgtype.UUID) (GetDeliveryByIDRow, error) { row := q.db.QueryRow(ctx, getDeliveryByID, id) var i GetDeliveryByIDRow err := row.Scan( &i.ID, &i.SourceEventID, &i.RecipientUserID, &i.RecipientEmail, &i.Kind, &i.TemplateVersion, &i.Subject, &i.TextBody, &i.HtmlBody, &i.ContentSha256, &i.Provider, &i.ProviderAccount, &i.IdempotencyKey, &i.Status, &i.AttemptCount, &i.NextAttemptAt, &i.LastAttemptAt, &i.ProviderMessageID, &i.Version, &i.CreatedAt, &i.UpdatedAt, &i.EmailTokenID, &i.CancelReason, &i.ClaimOwner, &i.ClaimedUntil, &i.FirstSendStartedAt, &i.FailureCount, &i.BodyRedactedAt, &i.SubjectKind, &i.SubjectID, &i.SubjectOrganizationID, ) return i, err } const getDeliveryRetrySnapshot = `-- name: GetDeliveryRetrySnapshot :one SELECT id, provider, provider_account, status, attempt_count, next_attempt_at, first_send_started_at, manual_retry_started_at FROM deliveries WHERE id = $1 ` type GetDeliveryRetrySnapshotRow struct { ID pgtype.UUID Provider string ProviderAccount string Status string AttemptCount int32 NextAttemptAt pgtype.Timestamptz FirstSendStartedAt pgtype.Timestamptz ManualRetryStartedAt pgtype.Timestamptz } // Reads only the metadata needed by the local operator retry interface. It // intentionally does not select the address, token, subject, or message body. func (q *Queries) GetDeliveryRetrySnapshot(ctx context.Context, id pgtype.UUID) (GetDeliveryRetrySnapshotRow, error) { row := q.db.QueryRow(ctx, getDeliveryRetrySnapshot, id) var i GetDeliveryRetrySnapshotRow err := row.Scan( &i.ID, &i.Provider, &i.ProviderAccount, &i.Status, &i.AttemptCount, &i.NextAttemptAt, &i.FirstSendStartedAt, &i.ManualRetryStartedAt, ) return i, err } const getDeliveryStatistics = `-- name: GetDeliveryStatistics :many SELECT kind, status, count(*) AS deliveries, min(next_attempt_at) FILTER ( WHERE status = 'pending' )::timestamptz AS earliest_pending_attempt_at FROM deliveries GROUP BY kind, status ` type GetDeliveryStatisticsRow struct { Kind string Status string Deliveries int64 EarliestPendingAttemptAt pgtype.Timestamptz } // Aggregates the deliveries by kind and status for the metrics, at most once // per metrics interval. It reads only kind, status, and next_attempt_at, // never an address, a body, or an ID. No index covers status, so it scans // the table; add an index on (status) or keep per-status counters before // the table holds millions of rows. func (q *Queries) GetDeliveryStatistics(ctx context.Context) ([]GetDeliveryStatisticsRow, error) { rows, err := q.db.Query(ctx, getDeliveryStatistics) if err != nil { return nil, err } defer rows.Close() var items []GetDeliveryStatisticsRow for rows.Next() { var i GetDeliveryStatisticsRow if err := rows.Scan( &i.Kind, &i.Status, &i.Deliveries, &i.EarliestPendingAttemptAt, ); err != nil { return nil, err } items = append(items, i) } if err := rows.Err(); err != nil { return nil, err } return items, nil } const getLatestDeliveryStatus = `-- name: GetLatestDeliveryStatus :one SELECT id, kind, status, next_attempt_at, created_at, updated_at FROM deliveries WHERE recipient_user_id = $1 AND kind = $2 ORDER BY created_at DESC, id DESC LIMIT 1 ` type GetLatestDeliveryStatusParams struct { RecipientUserID pgtype.UUID Kind string } type GetLatestDeliveryStatusRow struct { ID pgtype.UUID Kind string Status string NextAttemptAt pgtype.Timestamptz CreatedAt pgtype.Timestamptz UpdatedAt pgtype.Timestamptz } // Reads the status of the newest delivery of a kind addressed to an account, // for the account's own view of its mail. It selects no address and no // content. The recipient index narrows the scan to the account's rows. func (q *Queries) GetLatestDeliveryStatus(ctx context.Context, arg GetLatestDeliveryStatusParams) (GetLatestDeliveryStatusRow, error) { row := q.db.QueryRow(ctx, getLatestDeliveryStatus, arg.RecipientUserID, arg.Kind) var i GetLatestDeliveryStatusRow err := row.Scan( &i.ID, &i.Kind, &i.Status, &i.NextAttemptAt, &i.CreatedAt, &i.UpdatedAt, ) return i, err } const getServiceMailState = `-- name: GetServiceMailState :one SELECT (token.id IS NOT NULL)::boolean AS token_found, token.purpose AS token_purpose, token.user_id AS token_user_id, token.registration_version AS token_registration_version, token.consumed_at AS token_consumed_at, token.invalidated_at AS token_invalidated_at, token.expires_at AS token_expires_at, owner.registration_version AS account_registration_version, (owner.email_verified_at IS NOT NULL)::boolean AS account_email_verified, owner.email_normalized AS account_email_key FROM deliveries AS delivery INNER JOIN users AS owner ON delivery.recipient_user_id = owner.id LEFT JOIN email_tokens AS token ON delivery.email_token_id = token.id WHERE delivery.id = $1 ` type GetServiceMailStateRow struct { TokenFound bool TokenPurpose pgtype.Text TokenUserID pgtype.UUID TokenRegistrationVersion pgtype.Int8 TokenConsumedAt pgtype.Timestamptz TokenInvalidatedAt pgtype.Timestamptz TokenExpiresAt pgtype.Timestamptz AccountRegistrationVersion int64 AccountEmailVerified bool AccountEmailKey string } // Reads the token a delivery is bound to and the account it is addressed to // in one statement, for the check right before a service mail is sent. It // takes no lock. It reads the account address only as the comparison key and // selects no token hash. A missing binding or token row gives NULL token // columns. func (q *Queries) GetServiceMailState(ctx context.Context, id pgtype.UUID) (GetServiceMailStateRow, error) { row := q.db.QueryRow(ctx, getServiceMailState, id) var i GetServiceMailStateRow err := row.Scan( &i.TokenFound, &i.TokenPurpose, &i.TokenUserID, &i.TokenRegistrationVersion, &i.TokenConsumedAt, &i.TokenInvalidatedAt, &i.TokenExpiresAt, &i.AccountRegistrationVersion, &i.AccountEmailVerified, &i.AccountEmailKey, ) return i, err } const insertDelivery = `-- name: InsertDelivery :execrows INSERT INTO deliveries ( id, source_event_id, recipient_user_id, recipient_email, kind, template_version, subject, text_body, html_body, content_sha256, provider, provider_account, idempotency_key, status, attempt_count, next_attempt_at, last_attempt_at, provider_message_id, email_token_id, subject_kind, subject_id, subject_organization_id, version, created_at, updated_at ) VALUES ( $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25 ) ON CONFLICT (id) DO NOTHING ` type InsertDeliveryParams struct { ID pgtype.UUID SourceEventID pgtype.UUID RecipientUserID pgtype.UUID RecipientEmail string Kind string TemplateVersion string Subject string TextBody string HtmlBody string ContentSha256 []byte Provider string ProviderAccount string IdempotencyKey string Status string AttemptCount int32 NextAttemptAt pgtype.Timestamptz LastAttemptAt pgtype.Timestamptz ProviderMessageID pgtype.Text EmailTokenID pgtype.UUID SubjectKind pgtype.Text SubjectID pgtype.UUID SubjectOrganizationID pgtype.UUID Version int64 CreatedAt pgtype.Timestamptz UpdatedAt pgtype.Timestamptz } // Stores a new delivery. A delivery with the same ID already exists when the // same request is handled again; the statement then inserts nothing and // returns 0 rows, and the stored content stays as it was. While another // transaction holds an uncommitted row with the same ID, the insert waits // for it. func (q *Queries) InsertDelivery(ctx context.Context, arg InsertDeliveryParams) (int64, error) { result, err := q.db.Exec(ctx, insertDelivery, arg.ID, arg.SourceEventID, arg.RecipientUserID, arg.RecipientEmail, arg.Kind, arg.TemplateVersion, arg.Subject, arg.TextBody, arg.HtmlBody, arg.ContentSha256, arg.Provider, arg.ProviderAccount, arg.IdempotencyKey, arg.Status, arg.AttemptCount, arg.NextAttemptAt, arg.LastAttemptAt, arg.ProviderMessageID, arg.EmailTokenID, arg.SubjectKind, arg.SubjectID, arg.SubjectOrganizationID, arg.Version, arg.CreatedAt, arg.UpdatedAt, ) if err != nil { return 0, err } return result.RowsAffected(), nil } const insertMailRequest = `-- name: InsertMailRequest :exec INSERT INTO mail_requests ( id, recipient_user_id, kind, subject, body, link_path, subject_kind, subject_id, subject_organization_id, created_at ) VALUES ( $1, $2, $3, $4, $5, $6, $7, $8, $9, $10 ) ` type InsertMailRequestParams struct { ID pgtype.UUID RecipientUserID pgtype.UUID Kind string Subject string Body string LinkPath string SubjectKind pgtype.Text SubjectID pgtype.UUID SubjectOrganizationID pgtype.UUID CreatedAt pgtype.Timestamptz } func (q *Queries) InsertMailRequest(ctx context.Context, arg InsertMailRequestParams) error { _, err := q.db.Exec(ctx, insertMailRequest, arg.ID, arg.RecipientUserID, arg.Kind, arg.Subject, arg.Body, arg.LinkPath, arg.SubjectKind, arg.SubjectID, arg.SubjectOrganizationID, arg.CreatedAt, ) return err } const listDeliveryAttempts = `-- name: ListDeliveryAttempts :many SELECT delivery_id, attempt_number, attempted_at, outcome, rejection, provider_code, provider_message_id, retry_after_ns, status_after, next_attempt_at FROM delivery_attempts WHERE delivery_id = $1 ORDER BY attempt_number ` func (q *Queries) ListDeliveryAttempts(ctx context.Context, deliveryID pgtype.UUID) ([]DeliveryAttempt, error) { rows, err := q.db.Query(ctx, listDeliveryAttempts, deliveryID) if err != nil { return nil, err } defer rows.Close() var items []DeliveryAttempt for rows.Next() { var i DeliveryAttempt if err := rows.Scan( &i.DeliveryID, &i.AttemptNumber, &i.AttemptedAt, &i.Outcome, &i.Rejection, &i.ProviderCode, &i.ProviderMessageID, &i.RetryAfterNs, &i.StatusAfter, &i.NextAttemptAt, ); err != nil { return nil, err } items = append(items, i) } if err := rows.Err(); err != nil { return nil, err } return items, nil } const lockClaimedDelivery = `-- name: LockClaimedDelivery :one SELECT id FROM deliveries WHERE id = $1 AND claim_owner = $2 FOR UPDATE ` type LockClaimedDeliveryParams struct { ID pgtype.UUID LeaseOwner pgtype.UUID } // Locks the delivery row of the lease holder until the transaction ends, so // every path that settles a send takes the delivery lock before the quota // rows, the same order as the claim. No row means that owner no longer holds // the lease. func (q *Queries) LockClaimedDelivery(ctx context.Context, arg LockClaimedDeliveryParams) (pgtype.UUID, error) { row := q.db.QueryRow(ctx, lockClaimedDelivery, arg.ID, arg.LeaseOwner) var id pgtype.UUID err := row.Scan(&id) return id, err } const lockMailRequest = `-- name: LockMailRequest :one SELECT id, recipient_user_id, kind, subject, body, link_path, subject_kind, subject_id, subject_organization_id, created_at FROM mail_requests WHERE id = $1 FOR UPDATE ` type LockMailRequestRow struct { ID pgtype.UUID RecipientUserID pgtype.UUID Kind string Subject string Body string LinkPath string SubjectKind pgtype.Text SubjectID pgtype.UUID SubjectOrganizationID pgtype.UUID CreatedAt pgtype.Timestamptz } // Locks a request for the consumer transaction that turns it into a // delivery. A concurrent consumer of the same request waits here and then // finds the row deleted. The account cleanup and the cascade from users take // the same row lock, so a request is never converted for an account whose // deletion is in progress without one of the two transactions waiting. func (q *Queries) LockMailRequest(ctx context.Context, id pgtype.UUID) (LockMailRequestRow, error) { row := q.db.QueryRow(ctx, lockMailRequest, id) var i LockMailRequestRow err := row.Scan( &i.ID, &i.RecipientUserID, &i.Kind, &i.Subject, &i.Body, &i.LinkPath, &i.SubjectKind, &i.SubjectID, &i.SubjectOrganizationID, &i.CreatedAt, ) return i, err } const markDeliverySendStarted = `-- name: MarkDeliverySendStarted :execrows UPDATE deliveries SET first_send_started_at = coalesce(deliveries.first_send_started_at, clock_timestamp()), send_started_attempt_count = deliveries.attempt_count, next_attempt_at = CASE WHEN deliveries.manual_retry_authorized_at IS NOT NULL AND deliveries.manual_retry_started_at IS NULL THEN NULL ELSE deliveries.next_attempt_at END, manual_retry_started_at = CASE WHEN deliveries.manual_retry_authorized_at IS NOT NULL AND deliveries.manual_retry_started_at IS NULL THEN clock_timestamp() ELSE deliveries.manual_retry_started_at END, failure_count = 0 WHERE id = $1 AND claim_owner = $2 AND ( NOT $3::boolean OR (deliveries.manual_retry_authorized_at IS NOT NULL AND deliveries.manual_retry_started_at IS NULL) OR coalesce(deliveries.manual_retry_started_at, deliveries.first_send_started_at) IS NULL OR clock_timestamp() - coalesce(deliveries.manual_retry_started_at, deliveries.first_send_started_at) < make_interval(secs => $4::float8) ) ` type MarkDeliverySendStartedParams struct { ID pgtype.UUID LeaseOwner pgtype.UUID RequireDedupWindow bool RetryWindowSeconds float64 } // Notes that a request is about to start, by the database clock, and clears // the count of worker failures. For an operator-authorized send, this sets // its single-use marker without overwriting the original first-send time. The // marker captures the current attempt_count so a lost result can be recovered // as unknown instead of silently retried. When require_dedup_window is true, // the age check is repeated here after quota work and the row lock, immediately // before the network call; manual starts never reset that original window. func (q *Queries) MarkDeliverySendStarted(ctx context.Context, arg MarkDeliverySendStartedParams) (int64, error) { result, err := q.db.Exec(ctx, markDeliverySendStarted, arg.ID, arg.LeaseOwner, arg.RequireDedupWindow, arg.RetryWindowSeconds, ) if err != nil { return 0, err } return result.RowsAffected(), nil } const recordDeliveryAttempt = `-- name: RecordDeliveryAttempt :execrows WITH advanced AS ( UPDATE deliveries SET status = $8, attempt_count = $1, next_attempt_at = $9, last_attempt_at = $2, provider_message_id = coalesce( $6, deliveries.provider_message_id ), claim_owner = NULL, claimed_until = NULL, failure_count = 0, text_body = CASE WHEN $8::text IN ('accepted', 'rejected') AND deliveries.kind IN ('verification', 'password_reset') THEN '' ELSE deliveries.text_body END, html_body = CASE WHEN $8::text IN ('accepted', 'rejected') AND deliveries.kind IN ('verification', 'password_reset') THEN '' ELSE deliveries.html_body END, body_redacted_at = CASE WHEN $8::text IN ('accepted', 'rejected') AND deliveries.kind IN ('verification', 'password_reset') THEN $10 ELSE deliveries.body_redacted_at END, version = deliveries.version + 1, updated_at = $10 WHERE deliveries.id = $11 AND deliveries.version = $12 AND ( $13::uuid IS NULL OR deliveries.claim_owner = $13::uuid ) RETURNING deliveries.id ) INSERT INTO delivery_attempts ( delivery_id, attempt_number, attempted_at, outcome, rejection, provider_code, provider_message_id, retry_after_ns, status_after, next_attempt_at ) SELECT advanced.id, $1, $2, $3, $4, $5, $6, $7, $8, $9 FROM advanced ` type RecordDeliveryAttemptParams struct { AttemptNumber int32 AttemptedAt pgtype.Timestamptz Outcome string Rejection pgtype.Text ProviderCode pgtype.Text ProviderMessageID pgtype.Text RetryAfterNs int64 Status string NextAttemptAt pgtype.Timestamptz UpdatedAt pgtype.Timestamptz DeliveryID pgtype.UUID ExpectedVersion int64 LeaseOwner pgtype.UUID } // Advances a delivery past one attempt and appends the attempt in one // statement, so both happen or neither does, inside or outside a // transaction. The update applies only while the stored version still // equals expected_version; otherwise nothing is written and the statement // returns 0 rows. Two workers that record the same attempt number therefore // cannot both succeed. The lease of the sending worker ends with the // attempt, and so does the count of worker failures. When lease_owner is // given, the update applies only while that worker still holds the lease. // A token mail that reaches a terminal status loses its bodies in the same // statement, so the one-time token does not stay at rest; the trigger allows // exactly this change of the content columns. func (q *Queries) RecordDeliveryAttempt(ctx context.Context, arg RecordDeliveryAttemptParams) (int64, error) { result, err := q.db.Exec(ctx, recordDeliveryAttempt, arg.AttemptNumber, arg.AttemptedAt, arg.Outcome, arg.Rejection, arg.ProviderCode, arg.ProviderMessageID, arg.RetryAfterNs, arg.Status, arg.NextAttemptAt, arg.UpdatedAt, arg.DeliveryID, arg.ExpectedVersion, arg.LeaseOwner, ) if err != nil { return 0, err } return result.RowsAffected(), nil } const recordDeliveryFailure = `-- name: RecordDeliveryFailure :one UPDATE deliveries SET failure_count = CASE WHEN $1::boolean THEN deliveries.failure_count + 1 ELSE deliveries.failure_count END, status = CASE WHEN $1::boolean AND deliveries.failure_count + 1 >= $2::integer THEN 'cancelled' ELSE deliveries.status END, cancel_reason = CASE WHEN $1::boolean AND deliveries.failure_count + 1 >= $2::integer THEN 'processing_failed' ELSE deliveries.cancel_reason END, next_attempt_at = CASE WHEN $1::boolean AND deliveries.failure_count + 1 >= $2::integer THEN NULL ELSE $3::timestamptz END, text_body = CASE WHEN $1::boolean AND deliveries.failure_count + 1 >= $2::integer AND deliveries.kind IN ('verification', 'password_reset', 'notification') THEN '' ELSE deliveries.text_body END, html_body = CASE WHEN $1::boolean AND deliveries.failure_count + 1 >= $2::integer AND deliveries.kind IN ('verification', 'password_reset', 'notification') THEN '' ELSE deliveries.html_body END, body_redacted_at = CASE WHEN $1::boolean AND deliveries.failure_count + 1 >= $2::integer AND deliveries.kind IN ('verification', 'password_reset', 'notification') THEN greatest(deliveries.updated_at, $4::timestamptz) ELSE deliveries.body_redacted_at END, claim_owner = NULL, claimed_until = NULL, version = deliveries.version + 1, updated_at = greatest(deliveries.updated_at, $4::timestamptz) WHERE id = $5 AND status IN ('pending', 'waiting_quota') AND ( claim_owner IS NULL OR claim_owner = $6::uuid OR claimed_until <= clock_timestamp() ) RETURNING status ` type RecordDeliveryFailureParams struct { CountFailure bool MaxFailures int32 NextAttemptAt pgtype.Timestamptz Now pgtype.Timestamptz ID pgtype.UUID LeaseOwner pgtype.UUID } // Records that the sending worker failed on a delivery, so a broken row does // not stay at the head of the queue: the delivery is due again at // next_attempt_at and its lease ends. With count_failure the failure is // counted; after max_failures consecutive failures the delivery is cancelled // with the reason processing_failed, which an operator sees, and a token mail // loses its bodies. Without it nothing is counted and nothing is cancelled: // the failure says nothing about the row (a transient storage error, or a // stretch of failures across many rows). The row is touched only when no other // worker holds a live lease on it: lease_owner may hold it, or the lease is // free or expired. It returns the status after the change; no row means that // the delivery is no longer pending or waiting, or another worker holds it. // now is the application clock. func (q *Queries) RecordDeliveryFailure(ctx context.Context, arg RecordDeliveryFailureParams) (string, error) { row := q.db.QueryRow(ctx, recordDeliveryFailure, arg.CountFailure, arg.MaxFailures, arg.NextAttemptAt, arg.Now, arg.ID, arg.LeaseOwner, ) var status string err := row.Scan(&status) return status, err } const releaseDeliveryClaim = `-- name: ReleaseDeliveryClaim :execrows UPDATE deliveries SET claim_owner = NULL, claimed_until = NULL WHERE id = $1 AND claim_owner = $2 ` type ReleaseDeliveryClaimParams struct { ID pgtype.UUID LeaseOwner pgtype.UUID } // Gives a claimed delivery back without changing it, so the next pass may // claim it. It matches only the lease of lease_owner: a delivery that another // worker took over after the lease expired is left alone. func (q *Queries) ReleaseDeliveryClaim(ctx context.Context, arg ReleaseDeliveryClaimParams) (int64, error) { result, err := q.db.Exec(ctx, releaseDeliveryClaim, arg.ID, arg.LeaseOwner) if err != nil { return 0, err } return result.RowsAffected(), nil } const stopUnknownDeliveryRetry = `-- name: StopUnknownDeliveryRetry :execrows UPDATE deliveries SET status = 'unknown', next_attempt_at = NULL, claim_owner = NULL, claimed_until = NULL, version = deliveries.version + 1, updated_at = greatest(deliveries.updated_at, $1::timestamptz) WHERE id = $2 AND status IN ('pending', 'waiting_quota', 'unknown') AND next_attempt_at IS NOT NULL AND claim_owner = $3::uuid ` type StopUnknownDeliveryRetryParams struct { Now pgtype.Timestamptz ID pgtype.UUID LeaseOwner pgtype.UUID } // Stops a due automatic retry of an unknown delivery without recording a // fictitious provider attempt, for example when the 23-hour safety cutoff is // reached after the claim but before the provider call. func (q *Queries) StopUnknownDeliveryRetry(ctx context.Context, arg StopUnknownDeliveryRetryParams) (int64, error) { result, err := q.db.Exec(ctx, stopUnknownDeliveryRetry, arg.Now, arg.ID, arg.LeaseOwner) if err != nil { return 0, err } return result.RowsAffected(), nil } const updateDeliveryState = `-- name: UpdateDeliveryState :execrows UPDATE deliveries SET status = $1, next_attempt_at = $2, cancel_reason = $3, failure_count = 0, provider = $4, provider_account = $5, claim_owner = CASE WHEN $6::boolean THEN NULL ELSE deliveries.claim_owner END, claimed_until = CASE WHEN $6::boolean THEN NULL ELSE deliveries.claimed_until END, text_body = CASE WHEN $1::text = 'cancelled' AND deliveries.kind IN ('verification', 'password_reset', 'notification') THEN '' ELSE deliveries.text_body END, html_body = CASE WHEN $1::text = 'cancelled' AND deliveries.kind IN ('verification', 'password_reset', 'notification') THEN '' ELSE deliveries.html_body END, body_redacted_at = CASE WHEN $1::text = 'cancelled' AND deliveries.kind IN ('verification', 'password_reset', 'notification') THEN $7 ELSE deliveries.body_redacted_at END, version = deliveries.version + 1, updated_at = $7 WHERE deliveries.id = $8 AND deliveries.version = $9 ` type UpdateDeliveryStateParams struct { Status string NextAttemptAt pgtype.Timestamptz CancelReason pgtype.Text Provider string ProviderAccount string ReleaseClaim bool UpdatedAt pgtype.Timestamptz ID pgtype.UUID ExpectedVersion int64 } // Stores a change of the delivery state that is not an attempt: a quota wait, // a cancellation, or a new provider account before the first attempt. It // applies only while the stored version still equals expected_version and // returns 0 rows otherwise. The trigger refuses a provider change after an // attempt. release_claim ends the lease of the sending worker with the // change; a new provider account keeps it, because the worker rebinds a // delivery it holds and then sends it. func (q *Queries) UpdateDeliveryState(ctx context.Context, arg UpdateDeliveryStateParams) (int64, error) { result, err := q.db.Exec(ctx, updateDeliveryState, arg.Status, arg.NextAttemptAt, arg.CancelReason, arg.Provider, arg.ProviderAccount, arg.ReleaseClaim, arg.UpdatedAt, arg.ID, arg.ExpectedVersion, ) if err != nil { return 0, err } return result.RowsAffected(), nil }