feat(notification): add durable mail delivery state

This commit is contained in:
shira committed 2026-10-06 10:52:47 +03:00
1 parent 391c8a6cec
commit 2db585fbff
41 files changed
+4903 -108

No files matched your search

@@ -0,0 +1,295 @@
-- +goose Up
-- Mail requests: the caller text of a requested notification, written in the
-- producer's business transaction next to the outbox event that announces
-- it. The event carries only the request ID, so the text never reaches the
-- event bus. The delivery consumer reads the row, stores the rendered
-- Delivery, and deletes the row in the same transaction; a request whose
-- account is deleted first goes with the account.
CREATE TABLE mail_requests (
-- Generated in Go; the aggregate ID of the event and the ID of the
-- delivery it becomes.
id uuid NOT NULL,
recipient_user_id uuid NOT NULL,
kind text NOT NULL,
subject text NOT NULL,
body text NOT NULL,
link_path text NOT NULL,
created_at timestamptz NOT NULL,
CONSTRAINT mail_requests_pkey PRIMARY KEY (id),
CONSTRAINT mail_requests_recipient_user_id_fkey FOREIGN KEY (
recipient_user_id
) REFERENCES users (id) ON DELETE CASCADE,
-- Mail with a one-time token is never requested through an event.
CONSTRAINT mail_requests_kind_known CHECK (kind IN ('notification')),
CONSTRAINT mail_requests_text_length CHECK (
char_length(subject) <= 1000
AND char_length(body) <= 16000
AND octet_length(link_path) <= 256
)
);
-- Serves the cascade from users and the account cleanup.
CREATE INDEX mail_requests_recipient_user_id_idx
ON mail_requests (recipient_user_id);
-- Mail deliveries: the durable state of sending one message to one
-- recipient. A delivery keeps the rendered content it was created with, the
-- provider account it is pinned to, and the idempotency key sent with every
-- attempt, so a retry repeats exactly the same request even after the
-- templates or the configuration changed. Every timestamp comes from the
-- application clock.
--
-- The rows hold personal data: the recipient address and the bodies. Bodies
-- of verification and password reset mail hold a one-time bearer token until
-- it expires or is used. Read them only to send the message; never copy them
-- into logs, metrics, tickets, or events.
CREATE TABLE deliveries (
-- Stable ID of the logical request, generated in Go. A repeated request
-- maps to the same row.
id uuid NOT NULL,
-- The domain event the delivery was created from; NULL for a delivery
-- created directly in a business transaction.
source_event_id uuid,
recipient_user_id uuid NOT NULL,
-- Delivery form of the account address when the delivery was created.
recipient_email text NOT NULL,
kind text NOT NULL,
-- "<kind>.v<N>", the immutable template version that rendered the body.
template_version text NOT NULL,
subject text NOT NULL,
text_body text NOT NULL,
html_body text NOT NULL,
-- SHA-256 over the version, subject, and both parts as netstrings; the
-- domain checks it on every read.
content_sha256 bytea NOT NULL,
-- Transport and provider account label from configuration; never a
-- credential.
provider text NOT NULL,
provider_account text NOT NULL,
-- Sent with every attempt; contains no personal data.
idempotency_key text NOT NULL,
status text NOT NULL,
attempt_count integer NOT NULL,
-- When the delivery is due; NULL when no automatic attempt is scheduled.
next_attempt_at timestamptz,
last_attempt_at timestamptz,
-- Set once the provider accepted the message.
provider_message_id text,
-- Optimistic concurrency version, advanced by every attempt.
version bigint NOT NULL,
created_at timestamptz NOT NULL,
updated_at timestamptz NOT NULL,
CONSTRAINT deliveries_pkey PRIMARY KEY (id),
CONSTRAINT deliveries_idempotency_key_key UNIQUE (idempotency_key),
-- Deleting an account deletes the copies of its address and the bodies
-- addressed to it.
CONSTRAINT deliveries_recipient_user_id_fkey FOREIGN KEY (
recipient_user_id
) REFERENCES users (id) ON DELETE CASCADE,
CONSTRAINT deliveries_recipient_email_ascii CHECK (
char_length(recipient_email) BETWEEN 3 AND 254
AND octet_length(recipient_email) = char_length(recipient_email)
),
CONSTRAINT deliveries_kind_known CHECK (
kind IN ('verification', 'password_reset', 'notification')
),
CONSTRAINT deliveries_template_version_of_kind CHECK (
template_version ~ '^[a-z][a-z_]*\.v[1-9][0-9]{0,8}$'
AND left(template_version, char_length(kind) + 2) = kind || '.v'
),
CONSTRAINT deliveries_subject_length CHECK (
char_length(subject) BETWEEN 1 AND 150
),
CONSTRAINT deliveries_body_present CHECK (
text_body <> '' OR html_body <> ''
),
CONSTRAINT deliveries_content_sha256_size CHECK (
octet_length(content_sha256) = 32
),
CONSTRAINT deliveries_provider_format CHECK (
provider ~ '^[a-z][a-z0-9_]{0,31}$'
),
CONSTRAINT deliveries_provider_account_format CHECK (
provider_account ~ '^[a-z0-9][a-z0-9._-]{0,63}$'
),
-- PostgreSQL regular expressions bound repetition at 255, so the length
-- is checked separately.
CONSTRAINT deliveries_idempotency_key_format CHECK (
char_length(idempotency_key) <= 256
AND idempotency_key ~ '^[!-~]+$'
),
CONSTRAINT deliveries_status_known CHECK (
status IN (
'pending', 'accepted', 'rejected', 'unknown', 'waiting_quota'
)
),
-- pending is picked up again by the worker, so it says when; accepted
-- and rejected are terminal; unknown and waiting_quota may wait without
-- a time for a reconciliation, an unknown quota reset, or an operator.
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')
),
CONSTRAINT deliveries_provider_message_id_when_accepted CHECK (
(status = 'accepted') = (provider_message_id IS NOT NULL)
AND (
provider_message_id IS NULL
OR provider_message_id ~ '^[!-~]{1,128}$'
)
),
CONSTRAINT deliveries_attempts_counted CHECK (
attempt_count >= 0
AND (attempt_count = 0) = (last_attempt_at IS NULL)
),
CONSTRAINT deliveries_version_positive CHECK (version > 0),
CONSTRAINT deliveries_timestamps_after_creation CHECK (
updated_at >= created_at
AND (last_attempt_at IS NULL OR last_attempt_at >= created_at)
)
);
-- Serves the cascade from users and the account cleanup, which locks the
-- deliveries of each account it deletes.
CREATE INDEX deliveries_recipient_user_id_idx
ON deliveries (recipient_user_id);
-- One row per transport attempt, appended in the transaction that advances
-- the delivery. Kept as history next to the counters on deliveries: the
-- worker reads the counters, while operators and the retry and quota rules
-- need every outcome, provider code, and wait hint.
CREATE TABLE delivery_attempts (
delivery_id uuid NOT NULL,
-- 1 for the first attempt of the delivery.
attempt_number integer NOT NULL,
attempted_at timestamptz NOT NULL,
outcome text NOT NULL,
-- Set only for a rejected attempt.
rejection text,
-- Documented provider error name; never provider free text.
provider_code text,
provider_message_id text,
-- Provider or transport wait hint in nanoseconds, the exact Go
-- time.Duration; 0 when there was none.
retry_after_ns bigint NOT NULL,
status_after text NOT NULL,
next_attempt_at timestamptz,
CONSTRAINT delivery_attempts_pkey PRIMARY KEY (
delivery_id, attempt_number
),
CONSTRAINT delivery_attempts_delivery_id_fkey FOREIGN KEY (
delivery_id
) REFERENCES deliveries (id) ON DELETE CASCADE,
CONSTRAINT delivery_attempts_number_positive CHECK (attempt_number > 0),
CONSTRAINT delivery_attempts_outcome_known CHECK (
outcome IN ('accepted', 'rejected', 'unknown')
),
CONSTRAINT delivery_attempts_rejection_when_rejected CHECK (
(outcome = 'rejected') = (rejection IS NOT NULL)
AND (
rejection IS NULL
OR rejection IN (
'permanent',
'invalid_request',
'rate_limited',
'quota_exhausted',
'temporary'
)
)
),
CONSTRAINT delivery_attempts_message_id_when_accepted CHECK (
(outcome = 'accepted') = (provider_message_id IS NOT NULL)
AND (
provider_message_id IS NULL
OR provider_message_id ~ '^[!-~]{1,128}$'
)
),
CONSTRAINT delivery_attempts_provider_code_format CHECK (
provider_code ~ '^[a-z][a-z0-9_]{0,63}$'
),
CONSTRAINT delivery_attempts_retry_after_not_negative CHECK (
retry_after_ns >= 0
),
CONSTRAINT delivery_attempts_status_after_known CHECK (
status_after IN (
'pending', 'accepted', 'rejected', 'unknown', 'waiting_quota'
)
),
CONSTRAINT delivery_attempts_next_after_attempt CHECK (
next_attempt_at IS NULL OR next_attempt_at >= attempted_at
)
);
-- Refuses an UPDATE that changes what a delivery sends or where: the
-- recipient, the content, the idempotency key, the source event, and the
-- creation time. The provider account may change only while the delivery
-- has no attempt, because a provider that saw an attempt may hold the key.
-- The attempt state stays updatable. Errors use SQLSTATE 23000 and the
-- constraint names deliveries_content_immutable and
-- deliveries_provider_pinned, which the adapter maps without reading the
-- message; the messages quote no row values.
-- +goose StatementBegin
CREATE 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
CREATE TRIGGER deliveries_refuse_content_change
BEFORE UPDATE ON deliveries
FOR EACH ROW EXECUTE FUNCTION deliveries_refuse_content_change();
-- Attempts are history: an UPDATE is refused. Deletes stay possible for the
-- cascade from an account and for a later retention rule.
-- +goose StatementBegin
CREATE FUNCTION delivery_attempts_refuse_update() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
RAISE EXCEPTION USING
ERRCODE = 'integrity_constraint_violation',
CONSTRAINT = 'delivery_attempts_immutable',
TABLE = 'delivery_attempts',
MESSAGE = 'delivery attempts are immutable';
END;
$$;
-- +goose StatementEnd
CREATE TRIGGER delivery_attempts_refuse_update
BEFORE UPDATE ON delivery_attempts
FOR EACH ROW EXECUTE FUNCTION delivery_attempts_refuse_update();
-- +goose Down
DROP TABLE delivery_attempts;
DROP TABLE deliveries;
DROP TABLE mail_requests;
DROP FUNCTION delivery_attempts_refuse_update();
DROP FUNCTION deliveries_refuse_content_change();
+203
View File
@@ -0,0 +1,203 @@
-- 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.
-- 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,
version,
created_at,
updated_at
) VALUES (
sqlc.arg(id),
sqlc.narg(source_event_id),
sqlc.arg(recipient_user_id),
sqlc.arg(recipient_email),
sqlc.arg(kind),
sqlc.arg(template_version),
sqlc.arg(subject),
sqlc.arg(text_body),
sqlc.arg(html_body),
sqlc.arg(content_sha256),
sqlc.arg(provider),
sqlc.arg(provider_account),
sqlc.arg(idempotency_key),
sqlc.arg(status),
sqlc.arg(attempt_count),
sqlc.narg(next_attempt_at),
sqlc.narg(last_attempt_at),
sqlc.narg(provider_message_id),
sqlc.arg(version),
sqlc.arg(created_at),
sqlc.arg(updated_at)
)
ON CONFLICT (id) DO NOTHING;
-- 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
FROM deliveries
WHERE id = sqlc.arg(id);
-- 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. Content columns are not touched; a trigger refuses
-- any change to them.
-- name: RecordDeliveryAttempt :execrows
WITH advanced AS (
UPDATE deliveries
SET
status = sqlc.arg(status),
attempt_count = sqlc.arg(attempt_number),
next_attempt_at = sqlc.narg(next_attempt_at),
last_attempt_at = sqlc.arg(attempted_at),
provider_message_id = coalesce(
sqlc.narg(provider_message_id), deliveries.provider_message_id
),
version = deliveries.version + 1,
updated_at = sqlc.arg(updated_at)
WHERE
deliveries.id = sqlc.arg(delivery_id)
AND deliveries.version = sqlc.arg(expected_version)
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,
sqlc.arg(attempt_number),
sqlc.arg(attempted_at),
sqlc.arg(outcome),
sqlc.narg(rejection),
sqlc.narg(provider_code),
sqlc.narg(provider_message_id),
sqlc.arg(retry_after_ns),
sqlc.arg(status),
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.
-- name: UpdateDeliveryState :execrows
UPDATE deliveries
SET
status = sqlc.arg(status),
next_attempt_at = sqlc.narg(next_attempt_at),
provider = sqlc.arg(provider),
provider_account = sqlc.arg(provider_account),
version = deliveries.version + 1,
updated_at = sqlc.arg(updated_at)
WHERE
deliveries.id = sqlc.arg(id)
AND deliveries.version = sqlc.arg(expected_version);
-- 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 = sqlc.arg(delivery_id)
ORDER BY attempt_number;
-- name: InsertMailRequest :exec
INSERT INTO mail_requests (
id,
recipient_user_id,
kind,
subject,
body,
link_path,
created_at
) VALUES (
sqlc.arg(id),
sqlc.arg(recipient_user_id),
sqlc.arg(kind),
sqlc.arg(subject),
sqlc.arg(body),
sqlc.arg(link_path),
sqlc.arg(created_at)
);
-- 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.
-- name: LockMailRequest :one
SELECT
id,
recipient_user_id,
kind,
subject,
body,
link_path,
created_at
FROM mail_requests
WHERE id = sqlc.arg(id)
FOR UPDATE;
-- name: DeleteMailRequest :execrows
DELETE FROM mail_requests
WHERE id = sqlc.arg(id);
+38 -7
View File
@@ -121,11 +121,14 @@ RETURNING
updated_at;
-- Deletes one batch of accounts that stayed unverified since before cutoff,
-- oldest first, with their tokens and sessions. Every lock is taken with SKIP
-- LOCKED, so the statement never waits: an account whose row is locked, for
-- example by a re-registration or a token insert, is skipped, and so is an
-- account with any token or session row locked, for example by a
-- confirmation that consumed a token. Skipped accounts stay for the next run.
-- oldest first, with their tokens, sessions, mail requests, and mail
-- deliveries (and through the deliveries their attempts). Every lock is taken
-- with SKIP LOCKED, so the statement never waits: an account whose row is
-- locked, for example by a re-registration, a token insert, or a delivery
-- insert, is skipped, and so is an account with any token, session, mail
-- request, or delivery row locked, for example by a confirmation that
-- consumed a token, the delivery consumer, or a worker recording an attempt.
-- Skipped accounts stay for the next run.
-- Taking the account lock before the token locks is the reverse of the
-- documented order, which is safe only because no lock here waits.
-- name: DeleteUnverifiedUsersRegisteredBefore :execrows
@@ -154,8 +157,22 @@ locked_session AS (
FOR UPDATE SKIP LOCKED
),
-- An account qualifies only when every token and session row visible to the
-- statement was locked above.
locked_mail_request AS (
SELECT request.recipient_user_id
FROM mail_requests AS request
WHERE request.recipient_user_id IN (SELECT candidate.id FROM candidate)
FOR UPDATE SKIP LOCKED
),
locked_delivery AS (
SELECT delivery.recipient_user_id
FROM deliveries AS delivery
WHERE delivery.recipient_user_id IN (SELECT candidate.id FROM candidate)
FOR UPDATE SKIP LOCKED
),
-- An account qualifies only when every token, session, mail request, and
-- delivery row visible to the statement was locked above.
deletable AS (
SELECT candidate.id
FROM candidate
@@ -174,6 +191,20 @@ deletable AS (
SELECT count(*) FROM locked_session
WHERE locked_session.user_id = candidate.id
)
AND (
SELECT count(*) FROM mail_requests AS request
WHERE request.recipient_user_id = candidate.id
) = (
SELECT count(*) FROM locked_mail_request
WHERE locked_mail_request.recipient_user_id = candidate.id
)
AND (
SELECT count(*) FROM deliveries AS delivery
WHERE delivery.recipient_user_id = candidate.id
) = (
SELECT count(*) FROM locked_delivery
WHERE locked_delivery.recipient_user_id = candidate.id
)
)
DELETE FROM users