feat(mail): send service identity mail through a leased worker
This commit is contained in:
1 parent
204c6bae62
commit
d21fd49a42
58 files changed
+7577
-164
No files matched your search
@@ -0,0 +1,283 @@
|
||||
-- +goose Up
|
||||
-- Sending of service identity mail (TASK-016). The sending worker claims a
|
||||
-- due delivery under a lease, checks that the token and the account behind
|
||||
-- it are still current, and ends a delivery that must not be sent in a
|
||||
-- terminal non-sent status with a reason.
|
||||
--
|
||||
-- Everything is additive: existing rows stay valid. Every new column is
|
||||
-- nullable except failure_count, which is NOT NULL DEFAULT 0. No column holds
|
||||
-- personal data or a secret.
|
||||
|
||||
-- A reset token is a second purpose of the same table. The purpose names
|
||||
-- what the token authorizes, and the worker compares it with the kind of the
|
||||
-- delivery that carries it.
|
||||
ALTER TABLE email_tokens DROP CONSTRAINT email_tokens_purpose_known;
|
||||
ALTER TABLE email_tokens ADD CONSTRAINT email_tokens_purpose_known CHECK (
|
||||
purpose IN ('email_verification', 'password_reset')
|
||||
);
|
||||
|
||||
ALTER TABLE deliveries
|
||||
ADD COLUMN email_token_id uuid,
|
||||
ADD COLUMN cancel_reason text,
|
||||
ADD COLUMN claim_owner uuid,
|
||||
ADD COLUMN claimed_until timestamptz,
|
||||
ADD COLUMN first_send_started_at timestamptz,
|
||||
ADD COLUMN failure_count integer NOT NULL DEFAULT 0,
|
||||
ADD COLUMN body_redacted_at timestamptz;
|
||||
|
||||
COMMENT ON COLUMN deliveries.email_token_id IS
|
||||
'The token whose link the body carries; set for verification and password reset mail, NULL for notifications. The worker checks the token before it sends.';
|
||||
COMMENT ON COLUMN deliveries.cancel_reason IS
|
||||
'Why a cancelled delivery was not sent; set exactly when the status is cancelled.';
|
||||
COMMENT ON COLUMN deliveries.claim_owner IS
|
||||
'Lease owner of the sending worker that claimed the delivery; NULL when no worker holds it.';
|
||||
COMMENT ON COLUMN deliveries.first_send_started_at IS
|
||||
'When the first request of this delivery was started, by the database clock; the provider keeps the idempotency key for a window counted from here.';
|
||||
COMMENT ON COLUMN deliveries.failure_count IS
|
||||
'Consecutive failures of the sending worker on this row (not provider answers); reset by a recorded attempt.';
|
||||
COMMENT ON COLUMN deliveries.body_redacted_at IS
|
||||
'Set when the bodies of a token mail were cleared after the delivery reached a terminal status, so a database dump holds no live or dead token.';
|
||||
COMMENT ON COLUMN deliveries.claimed_until IS
|
||||
'When the lease of claim_owner expires; another worker may claim the delivery after it.';
|
||||
|
||||
-- The binding is by ID only. Deleting an account deletes its tokens and its
|
||||
-- deliveries in one statement, so the reference needs no cascade of its own.
|
||||
ALTER TABLE deliveries ADD CONSTRAINT deliveries_email_token_id_fkey
|
||||
FOREIGN KEY (email_token_id) REFERENCES email_tokens (id);
|
||||
|
||||
ALTER TABLE deliveries DROP CONSTRAINT deliveries_status_known;
|
||||
ALTER TABLE deliveries ADD CONSTRAINT deliveries_status_known CHECK (
|
||||
status IN (
|
||||
'pending', 'accepted', 'rejected', 'unknown', 'waiting_quota',
|
||||
'cancelled'
|
||||
)
|
||||
);
|
||||
|
||||
-- cancelled is terminal like accepted and rejected: no next attempt.
|
||||
ALTER TABLE deliveries DROP CONSTRAINT deliveries_next_attempt_matches_status;
|
||||
ALTER TABLE deliveries ADD CONSTRAINT deliveries_next_attempt_matches_status CHECK (
|
||||
(status = 'pending' AND next_attempt_at IS NOT NULL)
|
||||
OR (status IN ('accepted', 'rejected', 'cancelled') AND next_attempt_at IS NULL)
|
||||
OR status IN ('unknown', 'waiting_quota')
|
||||
);
|
||||
|
||||
ALTER TABLE deliveries ADD CONSTRAINT deliveries_cancel_reason_matches_status CHECK (
|
||||
(status = 'cancelled') = (cancel_reason IS NOT NULL)
|
||||
AND (
|
||||
cancel_reason IS NULL
|
||||
OR cancel_reason IN (
|
||||
'token_missing',
|
||||
'token_purpose_mismatch',
|
||||
'token_owner_mismatch',
|
||||
'token_consumed',
|
||||
'token_revoked',
|
||||
'token_expired',
|
||||
'account_not_current',
|
||||
'recipient_mismatch',
|
||||
'content_invalid',
|
||||
'processing_failed'
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
-- A lease has an owner and a deadline together, and only a delivery that a
|
||||
-- worker may still send holds one.
|
||||
ALTER TABLE deliveries ADD CONSTRAINT deliveries_claim_complete CHECK (
|
||||
(claim_owner IS NULL) = (claimed_until IS NULL)
|
||||
AND (
|
||||
claim_owner IS NULL
|
||||
OR status IN ('pending', 'waiting_quota', 'unknown')
|
||||
)
|
||||
);
|
||||
|
||||
ALTER TABLE deliveries ADD CONSTRAINT deliveries_token_only_for_token_kinds CHECK (
|
||||
email_token_id IS NULL OR kind IN ('verification', 'password_reset')
|
||||
);
|
||||
|
||||
ALTER TABLE deliveries ADD CONSTRAINT deliveries_failure_count_not_negative CHECK (
|
||||
failure_count >= 0
|
||||
);
|
||||
|
||||
-- A redacted token mail has no bodies; any other delivery has at least one.
|
||||
-- Only a terminal token mail may be redacted.
|
||||
ALTER TABLE deliveries DROP CONSTRAINT deliveries_body_present;
|
||||
ALTER TABLE deliveries ADD CONSTRAINT deliveries_body_present CHECK (
|
||||
(body_redacted_at IS NULL AND (text_body <> '' OR html_body <> ''))
|
||||
OR (
|
||||
body_redacted_at IS NOT NULL
|
||||
AND text_body = '' AND html_body = ''
|
||||
AND kind IN ('verification', 'password_reset')
|
||||
AND status IN ('accepted', 'rejected', 'cancelled')
|
||||
)
|
||||
);
|
||||
|
||||
-- Serves the claim of due service mail. The predicate names the kinds the
|
||||
-- sending worker handles, so rows of other kinds (notifications, which wait
|
||||
-- for TASK-462) never enter the index and an idle poll does not scan them.
|
||||
-- The claim query repeats the kind literals so the planner can use it.
|
||||
CREATE INDEX deliveries_due_idx
|
||||
ON deliveries (next_attempt_at, id)
|
||||
WHERE
|
||||
status IN ('pending', 'waiting_quota')
|
||||
AND next_attempt_at IS NOT NULL
|
||||
AND kind IN ('verification', 'password_reset');
|
||||
|
||||
-- Serves the foreign key check when a token is deleted.
|
||||
CREATE INDEX deliveries_email_token_id_idx
|
||||
ON deliveries (email_token_id)
|
||||
WHERE email_token_id IS NOT NULL;
|
||||
|
||||
-- The token a delivery is bound to never changes, like the rest of what the
|
||||
-- delivery sends. The attempt state, the cancel reason, and the lease stay
|
||||
-- updatable. The bodies of a token mail change in exactly one way: once, to
|
||||
-- empty, together with body_redacted_at, when the delivery is terminal, so
|
||||
-- no token outlives its mail. Errors are the same as in migration 00006.
|
||||
-- +goose StatementBegin
|
||||
CREATE OR REPLACE FUNCTION deliveries_refuse_content_change() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF (
|
||||
NEW.id, NEW.source_event_id, NEW.recipient_user_id,
|
||||
NEW.recipient_email, NEW.kind, NEW.template_version, NEW.subject,
|
||||
NEW.content_sha256,
|
||||
NEW.idempotency_key, NEW.created_at, NEW.email_token_id
|
||||
) IS DISTINCT FROM (
|
||||
OLD.id, OLD.source_event_id, OLD.recipient_user_id,
|
||||
OLD.recipient_email, OLD.kind, OLD.template_version, OLD.subject,
|
||||
OLD.content_sha256,
|
||||
OLD.idempotency_key, OLD.created_at, OLD.email_token_id
|
||||
) THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = 'integrity_constraint_violation',
|
||||
CONSTRAINT = 'deliveries_content_immutable',
|
||||
TABLE = 'deliveries',
|
||||
MESSAGE = 'delivery content and recipient are immutable';
|
||||
END IF;
|
||||
IF (NEW.text_body, NEW.html_body) IS DISTINCT FROM (OLD.text_body, OLD.html_body) THEN
|
||||
IF NOT (
|
||||
OLD.body_redacted_at IS NULL AND NEW.body_redacted_at IS NOT NULL
|
||||
AND NEW.text_body = '' AND NEW.html_body = ''
|
||||
AND NEW.status IN ('accepted', 'rejected', 'cancelled')
|
||||
) THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = 'integrity_constraint_violation',
|
||||
CONSTRAINT = 'deliveries_content_immutable',
|
||||
TABLE = 'deliveries',
|
||||
MESSAGE = 'delivery content and recipient are immutable';
|
||||
END IF;
|
||||
ELSIF OLD.body_redacted_at IS DISTINCT FROM NEW.body_redacted_at THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = 'integrity_constraint_violation',
|
||||
CONSTRAINT = 'deliveries_content_immutable',
|
||||
TABLE = 'deliveries',
|
||||
MESSAGE = 'delivery content and recipient are immutable';
|
||||
END IF;
|
||||
IF (
|
||||
(NEW.provider, NEW.provider_account)
|
||||
IS DISTINCT FROM (OLD.provider, OLD.provider_account)
|
||||
) AND (OLD.attempt_count <> 0 OR NEW.attempt_count <> 0) THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = 'integrity_constraint_violation',
|
||||
CONSTRAINT = 'deliveries_provider_pinned',
|
||||
TABLE = 'deliveries',
|
||||
MESSAGE = 'the provider account of a delivery is fixed after its first attempt';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
-- +goose Down
|
||||
-- A cancelled delivery becomes rejected, the closest status of the earlier
|
||||
-- schema, and reset tokens are removed with the purpose that no longer
|
||||
-- exists. The checks that tie a reason to the cancelled status go first, so
|
||||
-- the status can change.
|
||||
ALTER TABLE deliveries DROP CONSTRAINT deliveries_token_only_for_token_kinds;
|
||||
ALTER TABLE deliveries DROP CONSTRAINT deliveries_claim_complete;
|
||||
ALTER TABLE deliveries DROP CONSTRAINT deliveries_cancel_reason_matches_status;
|
||||
|
||||
UPDATE deliveries SET status = 'rejected' WHERE status = 'cancelled';
|
||||
|
||||
-- Redacted bodies cannot come back; a placeholder keeps the earlier schema's
|
||||
-- body check satisfied. The placeholder no longer matches content_sha256, so
|
||||
-- code of the earlier schema cannot restore such a row as content: it reads
|
||||
-- terminal rows only through the status reader, which selects no body, and
|
||||
-- never sends them. The content trigger is lifted for this one statement.
|
||||
ALTER TABLE deliveries DROP CONSTRAINT deliveries_body_present;
|
||||
ALTER TABLE deliveries DISABLE TRIGGER deliveries_refuse_content_change;
|
||||
UPDATE deliveries SET text_body = 'redacted' WHERE body_redacted_at IS NOT NULL;
|
||||
ALTER TABLE deliveries ENABLE TRIGGER deliveries_refuse_content_change;
|
||||
|
||||
-- +goose StatementBegin
|
||||
CREATE OR REPLACE FUNCTION deliveries_refuse_content_change() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF (
|
||||
NEW.id, NEW.source_event_id, NEW.recipient_user_id,
|
||||
NEW.recipient_email, NEW.kind, NEW.template_version, NEW.subject,
|
||||
NEW.text_body, NEW.html_body, NEW.content_sha256,
|
||||
NEW.idempotency_key, NEW.created_at
|
||||
) IS DISTINCT FROM (
|
||||
OLD.id, OLD.source_event_id, OLD.recipient_user_id,
|
||||
OLD.recipient_email, OLD.kind, OLD.template_version, OLD.subject,
|
||||
OLD.text_body, OLD.html_body, OLD.content_sha256,
|
||||
OLD.idempotency_key, OLD.created_at
|
||||
) THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = 'integrity_constraint_violation',
|
||||
CONSTRAINT = 'deliveries_content_immutable',
|
||||
TABLE = 'deliveries',
|
||||
MESSAGE = 'delivery content and recipient are immutable';
|
||||
END IF;
|
||||
IF (
|
||||
(NEW.provider, NEW.provider_account)
|
||||
IS DISTINCT FROM (OLD.provider, OLD.provider_account)
|
||||
) AND (OLD.attempt_count <> 0 OR NEW.attempt_count <> 0) THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = 'integrity_constraint_violation',
|
||||
CONSTRAINT = 'deliveries_provider_pinned',
|
||||
TABLE = 'deliveries',
|
||||
MESSAGE = 'the provider account of a delivery is fixed after its first attempt';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
DROP INDEX deliveries_email_token_id_idx;
|
||||
DROP INDEX deliveries_due_idx;
|
||||
|
||||
ALTER TABLE deliveries DROP CONSTRAINT deliveries_failure_count_not_negative;
|
||||
ALTER TABLE deliveries ADD CONSTRAINT deliveries_body_present CHECK (
|
||||
text_body <> '' OR html_body <> ''
|
||||
);
|
||||
|
||||
ALTER TABLE deliveries DROP CONSTRAINT deliveries_next_attempt_matches_status;
|
||||
ALTER TABLE deliveries ADD CONSTRAINT deliveries_next_attempt_matches_status CHECK (
|
||||
(status = 'pending' AND next_attempt_at IS NOT NULL)
|
||||
OR (status IN ('accepted', 'rejected') AND next_attempt_at IS NULL)
|
||||
OR status IN ('unknown', 'waiting_quota')
|
||||
);
|
||||
|
||||
ALTER TABLE deliveries DROP CONSTRAINT deliveries_status_known;
|
||||
ALTER TABLE deliveries ADD CONSTRAINT deliveries_status_known CHECK (
|
||||
status IN (
|
||||
'pending', 'accepted', 'rejected', 'unknown', 'waiting_quota'
|
||||
)
|
||||
);
|
||||
|
||||
ALTER TABLE deliveries DROP CONSTRAINT deliveries_email_token_id_fkey;
|
||||
ALTER TABLE deliveries
|
||||
DROP COLUMN body_redacted_at,
|
||||
DROP COLUMN failure_count,
|
||||
DROP COLUMN first_send_started_at,
|
||||
DROP COLUMN claimed_until,
|
||||
DROP COLUMN claim_owner,
|
||||
DROP COLUMN cancel_reason,
|
||||
DROP COLUMN email_token_id;
|
||||
|
||||
DELETE FROM email_tokens WHERE purpose = 'password_reset';
|
||||
ALTER TABLE email_tokens DROP CONSTRAINT email_tokens_purpose_known;
|
||||
ALTER TABLE email_tokens ADD CONSTRAINT email_tokens_purpose_known CHECK (
|
||||
purpose IN ('email_verification')
|
||||
);
|
||||
@@ -23,6 +23,7 @@ INSERT INTO deliveries (
|
||||
next_attempt_at,
|
||||
last_attempt_at,
|
||||
provider_message_id,
|
||||
email_token_id,
|
||||
version,
|
||||
created_at,
|
||||
updated_at
|
||||
@@ -45,6 +46,7 @@ INSERT INTO deliveries (
|
||||
sqlc.narg(next_attempt_at),
|
||||
sqlc.narg(last_attempt_at),
|
||||
sqlc.narg(provider_message_id),
|
||||
sqlc.narg(email_token_id),
|
||||
sqlc.arg(version),
|
||||
sqlc.arg(created_at),
|
||||
sqlc.arg(updated_at)
|
||||
@@ -73,7 +75,14 @@ SELECT
|
||||
provider_message_id,
|
||||
version,
|
||||
created_at,
|
||||
updated_at
|
||||
updated_at,
|
||||
email_token_id,
|
||||
cancel_reason,
|
||||
claim_owner,
|
||||
claimed_until,
|
||||
first_send_started_at,
|
||||
failure_count,
|
||||
body_redacted_at
|
||||
FROM deliveries
|
||||
WHERE id = sqlc.arg(id);
|
||||
|
||||
@@ -82,8 +91,12 @@ WHERE id = sqlc.arg(id);
|
||||
-- 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. Content columns are not touched; a trigger refuses
|
||||
-- any change to them.
|
||||
-- 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.
|
||||
-- name: RecordDeliveryAttempt :execrows
|
||||
WITH advanced AS (
|
||||
UPDATE deliveries
|
||||
@@ -95,11 +108,39 @@ WITH advanced AS (
|
||||
provider_message_id = coalesce(
|
||||
sqlc.narg(provider_message_id), deliveries.provider_message_id
|
||||
),
|
||||
claim_owner = NULL,
|
||||
claimed_until = NULL,
|
||||
failure_count = 0,
|
||||
text_body = CASE
|
||||
WHEN
|
||||
sqlc.arg(status)::text IN ('accepted', 'rejected')
|
||||
AND deliveries.kind IN ('verification', 'password_reset')
|
||||
THEN ''
|
||||
ELSE deliveries.text_body
|
||||
END,
|
||||
html_body = CASE
|
||||
WHEN
|
||||
sqlc.arg(status)::text IN ('accepted', 'rejected')
|
||||
AND deliveries.kind IN ('verification', 'password_reset')
|
||||
THEN ''
|
||||
ELSE deliveries.html_body
|
||||
END,
|
||||
body_redacted_at = CASE
|
||||
WHEN
|
||||
sqlc.arg(status)::text IN ('accepted', 'rejected')
|
||||
AND deliveries.kind IN ('verification', 'password_reset')
|
||||
THEN sqlc.arg(updated_at)
|
||||
ELSE deliveries.body_redacted_at
|
||||
END,
|
||||
version = deliveries.version + 1,
|
||||
updated_at = sqlc.arg(updated_at)
|
||||
WHERE
|
||||
deliveries.id = sqlc.arg(delivery_id)
|
||||
AND deliveries.version = sqlc.arg(expected_version)
|
||||
AND (
|
||||
sqlc.narg(lease_owner)::uuid IS NULL
|
||||
OR deliveries.claim_owner = sqlc.narg(lease_owner)::uuid
|
||||
)
|
||||
RETURNING deliveries.id
|
||||
)
|
||||
|
||||
@@ -128,23 +169,313 @@ SELECT
|
||||
sqlc.narg(next_attempt_at)
|
||||
FROM advanced;
|
||||
|
||||
-- Stores a change of the delivery state that is not an attempt: a quota wait
|
||||
-- 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.
|
||||
-- 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.
|
||||
-- name: UpdateDeliveryState :execrows
|
||||
UPDATE deliveries
|
||||
SET
|
||||
status = sqlc.arg(status),
|
||||
next_attempt_at = sqlc.narg(next_attempt_at),
|
||||
cancel_reason = sqlc.narg(cancel_reason),
|
||||
failure_count = 0,
|
||||
provider = sqlc.arg(provider),
|
||||
provider_account = sqlc.arg(provider_account),
|
||||
claim_owner = CASE
|
||||
WHEN sqlc.arg(release_claim)::boolean THEN NULL ELSE deliveries.claim_owner
|
||||
END,
|
||||
claimed_until = CASE
|
||||
WHEN sqlc.arg(release_claim)::boolean THEN NULL ELSE deliveries.claimed_until
|
||||
END,
|
||||
text_body = CASE
|
||||
WHEN
|
||||
sqlc.arg(status)::text = 'cancelled'
|
||||
AND deliveries.kind IN ('verification', 'password_reset')
|
||||
THEN ''
|
||||
ELSE deliveries.text_body
|
||||
END,
|
||||
html_body = CASE
|
||||
WHEN
|
||||
sqlc.arg(status)::text = 'cancelled'
|
||||
AND deliveries.kind IN ('verification', 'password_reset')
|
||||
THEN ''
|
||||
ELSE deliveries.html_body
|
||||
END,
|
||||
body_redacted_at = CASE
|
||||
WHEN
|
||||
sqlc.arg(status)::text = 'cancelled'
|
||||
AND deliveries.kind IN ('verification', 'password_reset')
|
||||
THEN sqlc.arg(updated_at)
|
||||
ELSE deliveries.body_redacted_at
|
||||
END,
|
||||
version = deliveries.version + 1,
|
||||
updated_at = sqlc.arg(updated_at)
|
||||
WHERE
|
||||
deliveries.id = sqlc.arg(id)
|
||||
AND deliveries.version = sqlc.arg(expected_version);
|
||||
|
||||
-- Claims the most overdue delivery that the sending worker may send, in one
|
||||
-- statement: a pending or waiting_quota 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 is how long ago, by the
|
||||
-- database clock, its first request started, -1 when none did. now is the
|
||||
-- application clock. Deliveries that are unknown or wait for an unknown quota
|
||||
-- reset have no due time here and wait for an operator.
|
||||
-- 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
|
||||
FROM deliveries AS due
|
||||
WHERE
|
||||
due.kind IN ('verification', 'password_reset')
|
||||
AND due.kind = any(sqlc.arg(kinds)::text [])
|
||||
AND due.status IN ('pending', 'waiting_quota')
|
||||
AND due.next_attempt_at IS NOT NULL
|
||||
AND due.next_attempt_at <= sqlc.arg(now)::timestamptz
|
||||
AND (
|
||||
(
|
||||
due.provider = sqlc.arg(provider)
|
||||
AND due.provider_account = sqlc.arg(provider_account)
|
||||
)
|
||||
OR (
|
||||
due.provider = sqlc.arg(rebind_provider)::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 = sqlc.arg(lease_owner)::uuid,
|
||||
claimed_until = clock_timestamp()
|
||||
+ make_interval(secs => sqlc.arg(lease_seconds)::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,
|
||||
candidate.previous_claimed_until,
|
||||
candidate.since_first_send_seconds;
|
||||
|
||||
-- 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.
|
||||
-- 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') THEN '' ELSE deliveries.text_body
|
||||
END,
|
||||
html_body = CASE
|
||||
WHEN deliveries.kind IN ('verification', 'password_reset') THEN '' ELSE deliveries.html_body
|
||||
END,
|
||||
body_redacted_at = CASE
|
||||
WHEN
|
||||
deliveries.kind IN ('verification', 'password_reset')
|
||||
THEN greatest(deliveries.updated_at, sqlc.arg(now)::timestamptz)
|
||||
ELSE deliveries.body_redacted_at
|
||||
END,
|
||||
version = deliveries.version + 1,
|
||||
updated_at = greatest(deliveries.updated_at, sqlc.arg(now)::timestamptz)
|
||||
WHERE
|
||||
id = sqlc.arg(id)
|
||||
AND status IN ('pending', 'waiting_quota');
|
||||
|
||||
-- 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.
|
||||
-- name: RecordDeliveryFailure :one
|
||||
UPDATE deliveries
|
||||
SET
|
||||
failure_count = CASE
|
||||
WHEN sqlc.arg(count_failure)::boolean THEN deliveries.failure_count + 1 ELSE deliveries.failure_count
|
||||
END,
|
||||
status = CASE
|
||||
WHEN
|
||||
sqlc.arg(count_failure)::boolean
|
||||
AND deliveries.failure_count + 1 >= sqlc.arg(max_failures)::integer
|
||||
THEN 'cancelled'
|
||||
ELSE deliveries.status
|
||||
END,
|
||||
cancel_reason = CASE
|
||||
WHEN
|
||||
sqlc.arg(count_failure)::boolean
|
||||
AND deliveries.failure_count + 1 >= sqlc.arg(max_failures)::integer
|
||||
THEN 'processing_failed'
|
||||
ELSE deliveries.cancel_reason
|
||||
END,
|
||||
next_attempt_at = CASE
|
||||
WHEN
|
||||
sqlc.arg(count_failure)::boolean
|
||||
AND deliveries.failure_count + 1 >= sqlc.arg(max_failures)::integer
|
||||
THEN NULL
|
||||
ELSE sqlc.arg(next_attempt_at)::timestamptz
|
||||
END,
|
||||
text_body = CASE
|
||||
WHEN
|
||||
sqlc.arg(count_failure)::boolean
|
||||
AND deliveries.failure_count + 1 >= sqlc.arg(max_failures)::integer
|
||||
AND deliveries.kind IN ('verification', 'password_reset')
|
||||
THEN ''
|
||||
ELSE deliveries.text_body
|
||||
END,
|
||||
html_body = CASE
|
||||
WHEN
|
||||
sqlc.arg(count_failure)::boolean
|
||||
AND deliveries.failure_count + 1 >= sqlc.arg(max_failures)::integer
|
||||
AND deliveries.kind IN ('verification', 'password_reset')
|
||||
THEN ''
|
||||
ELSE deliveries.html_body
|
||||
END,
|
||||
body_redacted_at = CASE
|
||||
WHEN
|
||||
sqlc.arg(count_failure)::boolean
|
||||
AND deliveries.failure_count + 1 >= sqlc.arg(max_failures)::integer
|
||||
AND deliveries.kind IN ('verification', 'password_reset')
|
||||
THEN greatest(deliveries.updated_at, sqlc.arg(now)::timestamptz)
|
||||
ELSE deliveries.body_redacted_at
|
||||
END,
|
||||
claim_owner = NULL,
|
||||
claimed_until = NULL,
|
||||
version = deliveries.version + 1,
|
||||
updated_at = greatest(deliveries.updated_at, sqlc.arg(now)::timestamptz)
|
||||
WHERE
|
||||
id = sqlc.arg(id)
|
||||
AND status IN ('pending', 'waiting_quota')
|
||||
AND (
|
||||
claim_owner IS NULL
|
||||
OR claim_owner = sqlc.arg(lease_owner)::uuid
|
||||
OR claimed_until <= clock_timestamp()
|
||||
)
|
||||
RETURNING status;
|
||||
|
||||
-- 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.
|
||||
-- name: LockClaimedDelivery :one
|
||||
SELECT id
|
||||
FROM deliveries
|
||||
WHERE
|
||||
id = sqlc.arg(id)
|
||||
AND claim_owner = sqlc.arg(lease_owner)
|
||||
FOR UPDATE;
|
||||
|
||||
-- Notes that the first request of a claimed delivery is about to start, by the
|
||||
-- database clock, and clears the count of worker failures: the claim and the
|
||||
-- preparation succeeded, so the failures are no longer consecutive. The provider keeps the idempotency key for a window counted
|
||||
-- from this moment, so a later claim can tell whether repeating the request is
|
||||
-- still safe. It never moves.
|
||||
-- name: MarkDeliverySendStarted :execrows
|
||||
UPDATE deliveries
|
||||
SET
|
||||
first_send_started_at = coalesce(deliveries.first_send_started_at, clock_timestamp()),
|
||||
failure_count = 0
|
||||
WHERE
|
||||
id = sqlc.arg(id)
|
||||
AND claim_owner = sqlc.arg(lease_owner);
|
||||
|
||||
-- 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.
|
||||
-- name: ReleaseDeliveryClaim :execrows
|
||||
UPDATE deliveries
|
||||
SET
|
||||
claim_owner = NULL,
|
||||
claimed_until = NULL
|
||||
WHERE
|
||||
id = sqlc.arg(id)
|
||||
AND claim_owner = sqlc.arg(lease_owner);
|
||||
|
||||
-- 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.
|
||||
-- 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 = sqlc.arg(id);
|
||||
|
||||
-- name: ListDeliveryAttempts :many
|
||||
SELECT
|
||||
delivery_id,
|
||||
|
||||
Reference in new issue
Block a user