-- +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, -- ".v", 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();