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

+4 -1
View File
@@ -81,7 +81,10 @@ type Config struct {
// other transports are not loaded.
EmailProvider EmailProvider
// EmailFrom is the sender mailbox for every outgoing message.
EmailFrom string
EmailFrom string
// EmailAccount labels the provider account that new deliveries are
// pinned to. It is configuration identity, never a credential.
EmailAccount string
EmailTimeout time.Duration
// AppPublicURL is the public origin without a trailing slash, for links
// in mail.
+13
View File
@@ -6,6 +6,7 @@ import (
"net"
"net/mail"
"net/url"
"regexp"
"strconv"
"strings"
"time"
@@ -36,6 +37,9 @@ const (
)
const (
// defaultEmailAccount labels the only provider account of a stand that
// never switched accounts.
defaultEmailAccount = "default"
defaultEmailTimeout = 10 * time.Second
// One attempt waits at least long enough for a TLS handshake and an API
// answer, and at most one minute so that a hung provider cannot hold a
@@ -44,6 +48,10 @@ const (
maxEmailTimeout = time.Minute
)
// emailAccountPattern matches domain.NewMailProviderAccount: a lowercase
// label that cannot hold the mixed-case characters of an API key.
var emailAccountPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]{0,63}$`)
// loadMail reads the common mail settings and only the settings of the
// selected transport, so settings of an inactive transport, including its
// secrets, never reach Config.
@@ -55,6 +63,7 @@ func (config *Config) loadMail(lookup LookupEnv) error {
provider := strings.ToLower(strings.TrimSpace(valueOrDefault(lookup, "EMAIL_PROVIDER", "")))
config.EmailProvider = EmailProvider(provider)
config.EmailFrom = strings.TrimSpace(valueOrDefault(lookup, "EMAIL_FROM", ""))
config.EmailAccount = strings.TrimSpace(valueOrDefault(lookup, "EMAIL_ACCOUNT", defaultEmailAccount))
// One trailing slash is accepted and dropped so that the stored value is
// an origin that links can be appended to.
config.AppPublicURL = strings.TrimSuffix(strings.TrimSpace(valueOrDefault(lookup, "APP_PUBLIC_URL", "")), "/")
@@ -109,6 +118,10 @@ func (config Config) ValidateMail() error {
if err := validateEmailFrom(config.EmailFrom); err != nil {
return err
}
// The value is not echoed: an API key pasted here must not reach logs.
if !emailAccountPattern.MatchString(config.EmailAccount) {
return errors.New("Config.ValidateMail - EMAIL_ACCOUNT must be a label of 1 to 64 lowercase letters, digits, '.', '_', or '-' that starts with a letter or digit")
}
if err := validateAppPublicURL(config.AppPublicURL); err != nil {
return err
}
+11 -1
View File
@@ -67,6 +67,9 @@ func TestLoadFromEnvMailDisabledIgnoresTransportSettings(t *testing.T) {
if settings.EmailTimeout != 10*time.Second {
t.Fatalf("EmailTimeout = %s, want the 10s default", settings.EmailTimeout)
}
if settings.EmailAccount != "default" {
t.Fatalf("EmailAccount = %q, want the default label", settings.EmailAccount)
}
if settings.ResendAPIKey != "" || settings.SMTPHost != "" || settings.SMTPPort != 0 || settings.SMTPPassword != "" || settings.SMTPTLSMode != "" {
t.Fatal("settings of an inactive transport were loaded")
}
@@ -118,6 +121,8 @@ func TestLoadFromEnvAcceptsMailBoundaries(t *testing.T) {
{name: "punycode sender domain", values: map[string]string{"EMAIL_FROM": "no-reply@xn--e1afmkfd.xn--p1ai"}},
{name: "minimum timeout", values: map[string]string{"EMAIL_TIMEOUT": "1s"}},
{name: "maximum timeout", values: map[string]string{"EMAIL_TIMEOUT": "60s"}},
{name: "account label with separators", values: map[string]string{"EMAIL_ACCOUNT": " resend-main.2_eu "}},
{name: "account label of 64 characters", values: map[string]string{"EMAIL_ACCOUNT": strings.Repeat("a", 64)}},
{name: "HTTPS origin with port", values: map[string]string{"APP_PUBLIC_URL": "https://lincodex.example:8443"}},
{name: "HTTP loopback IPv4", values: map[string]string{"APP_PUBLIC_URL": "http://127.0.0.1:8080"}},
{name: "HTTP loopback IPv6", values: map[string]string{"APP_PUBLIC_URL": "http://[::1]:8080/"}},
@@ -156,6 +161,11 @@ func TestLoadFromEnvRejectsMailSettings(t *testing.T) {
{name: "sender single-label domain", values: map[string]string{"EMAIL_FROM": "no-reply@localhost"}, want: "config.validateEmailFrom - EMAIL_FROM address must be"},
{name: "sender IP literal", values: map[string]string{"EMAIL_FROM": "no-reply@[127.0.0.1]"}, want: "config.validateEmailFrom - EMAIL_FROM address must be"},
{name: "sender quoted local part", values: map[string]string{"EMAIL_FROM": `"no reply"@example.com`}, want: "config.validateEmailFrom - EMAIL_FROM address must be"},
{name: "account empty", values: map[string]string{"EMAIL_ACCOUNT": " "}, want: "Config.ValidateMail - EMAIL_ACCOUNT must be a label"},
{name: "account with uppercase", values: map[string]string{"EMAIL_ACCOUNT": "Main"}, want: "Config.ValidateMail - EMAIL_ACCOUNT must be a label"},
{name: "API key pasted as account", values: map[string]string{"EMAIL_ACCOUNT": "re_" + strings.ToUpper(secretMarker)}, want: "Config.ValidateMail - EMAIL_ACCOUNT must be a label"},
{name: "account starting with a dash", values: map[string]string{"EMAIL_ACCOUNT": "-main"}, want: "Config.ValidateMail - EMAIL_ACCOUNT must be a label"},
{name: "account too long", values: map[string]string{"EMAIL_ACCOUNT": strings.Repeat("a", 65)}, want: "Config.ValidateMail - EMAIL_ACCOUNT must be a label"},
{name: "timeout unparsable", values: map[string]string{"EMAIL_TIMEOUT": "soon"}, want: "config.durationOrDefault - parse EMAIL_TIMEOUT"},
{name: "timeout empty", values: map[string]string{"EMAIL_TIMEOUT": ""}, want: "config.durationOrDefault - parse EMAIL_TIMEOUT"},
{name: "timeout zero", values: map[string]string{"EMAIL_TIMEOUT": "0s"}, want: "Config.ValidateMail - EMAIL_TIMEOUT must be between 1s and 1m0s"},
@@ -196,7 +206,7 @@ func TestLoadFromEnvRejectsMailSettings(t *testing.T) {
if err == nil || !strings.HasPrefix(err.Error(), test.want) {
t.Fatalf("LoadFromEnv() error = %v, want an error starting with %q", err, test.want)
}
for _, secret := range []string{secretMarker, testResendAPIKey, testSMTPPassword} {
for _, secret := range []string{secretMarker, strings.ToUpper(secretMarker), testResendAPIKey, testSMTPPassword} {
if strings.Contains(err.Error(), secret) {
t.Fatalf("configuration error discloses a configured value: %v", err)
}
@@ -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
+604
View File
@@ -0,0 +1,604 @@
//go:build integration
package integration_test
import (
"bytes"
"context"
"errors"
"fmt"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/notification"
"lincodex/backend/internal/usecase/notification/mailtemplate"
"lincodex/backend/internal/worker/eventconsumer"
)
const (
deliveryTestTimeout = 5 * time.Minute
// The private markers are searched for in logs and events; they must
// appear only in the mail request and delivery rows.
deliveryRecipientAddress = "Delivery.Recipient@Example.com"
deliverySubject = "PRIVATE-SUBJECT about an invitation"
deliveryBody = "PRIVATE-BODY: a company invited you to an interview."
deliveryLinkPath = "/candidate/invitations"
deliveryProvider = "resend"
deliveryAccount = "integration"
deliveryOtherAccount = "integration-eu"
deliveryMessageID = "4ef9a417-02e9-4d39-ad75-9611e0fcc33c"
// deliveryV2Version is a template version that exists only in this test.
deliveryV2Version = "notification.v2"
// renamedDeliveryConsumer replays requests as a renamed consumer would:
// the dedup markers of the real name do not apply to it.
renamedDeliveryConsumer = "notification_delivery_replay"
// deliveryRetryAfter has sub-millisecond parts, so a lossy round trip
// would show.
deliveryRetryAfter = 2*time.Second + 1500*time.Microsecond + 7*time.Nanosecond
)
var (
deliveryTables = []pgx.Identifier{{"delivery_attempts"}, {"deliveries"}, {"mail_requests"}}
deliveryPrivacyMarkers = []string{deliveryRecipientAddress, strings.ToLower(deliveryRecipientAddress), "PRIVATE-SUBJECT", "PRIVATE-BODY"}
)
// deliveryHarness wires the request usecase, the delivery handler, and the
// stores against one database.
type deliveryHarness struct {
env *testEnvironment
pool *pgxpool.Pool
transactor *postgresadapter.Transactor
consumers *postgresadapter.EventConsumerStore
identity *postgresadapter.IdentityStore
requester *notification.MailRequester
handler *notification.DeliveryHandler
account domain.MailProviderAccount
logs *syncBuffer
// now is truncated to microseconds, the precision PostgreSQL stores.
now time.Time
}
// syncBuffer collects the logs of a consumer goroutine and the test.
type syncBuffer struct {
mu sync.Mutex
buffer bytes.Buffer
}
func (buffer *syncBuffer) Write(data []byte) (int, error) {
buffer.mu.Lock()
defer buffer.mu.Unlock()
return buffer.buffer.Write(data)
}
func (buffer *syncBuffer) String() string {
buffer.mu.Lock()
defer buffer.mu.Unlock()
return buffer.buffer.String()
}
// v2Renderer stands for a later template version: it renders other copy
// under notification.v2 without touching the committed templates.
type v2Renderer struct{}
func (v2Renderer) RenderNotification(mailtemplate.NotificationData) (domain.MailContent, error) {
return domain.NewMailContent(domain.MailKindNotification, deliveryV2Version,
"Новая версия письма", "Текст новой версии шаблона.\n", "<p>Текст новой версии шаблона.</p>\n")
}
func TestMailDelivery(t *testing.T) {
env := bootstrap(t, postgresService, kafkaService)
ctx, cancel := context.WithTimeout(t.Context(), deliveryTestTimeout)
defer cancel()
pool := env.newPool(ctx, t)
templates, err := mailtemplate.NewRenderer(env.Config.AppPublicURL)
if err != nil {
t.Fatalf("NewRenderer() error = %v", err)
}
account, err := domain.NewMailProviderAccount(deliveryProvider, deliveryAccount)
if err != nil {
t.Fatalf("NewMailProviderAccount() error = %v", err)
}
renderer := notification.NewTemplateRenderer(templates)
harness := &deliveryHarness{
env: env,
pool: pool,
transactor: postgresadapter.NewTransactor(pool),
consumers: postgresadapter.NewEventConsumerStore(pool, consumerHandlerTime),
identity: postgresadapter.NewIdentityStore(pool),
account: account,
logs: &syncBuffer{},
now: time.Now().UTC().Truncate(time.Microsecond),
}
harness.requester = notification.NewMailRequester(renderer, harness.clock)
harness.handler = harness.newHandler(renderer)
// Subtests share tables and run sequentially; each starts from empty
// tables.
reset := func(t *testing.T) {
t.Helper()
tables := append([]pgx.Identifier{
outboxEventsTable,
{"consumer_processed_events"},
{"consumer_dead_letters"},
}, deliveryTables...)
truncateTables(ctx, t, pool, append(tables, identityTables...)...)
}
t.Run("one event processed twice through the consumer creates one delivery", func(t *testing.T) {
reset(t)
recipient := harness.createRecipient(ctx, t, true)
deliveryID := harness.requestNotification(ctx, t, recipient)
event := harness.outboxEvent(ctx, t, deliveryID)
topic := env.createKafkaTopic(ctx, t, 1)
// The relay publishes the event, then publishes it again as after a
// crash between the broker acknowledgement and the published_at
// commit; both records carry the same event_id.
relay := (&relayHarness{env: env, pool: pool, store: postgresadapter.NewOutboxRelayStore(pool, relayStoreTimeouts)}).
newRelay((&relayHarness{env: env}).newPublisher(t, topic))
for publication := range 2 {
if result, err := relay.PublishPending(ctx); err != nil || result.Published != 1 {
t.Fatalf("publication %d: PublishPending() = %+v, %v; want one event", publication+1, result, err)
}
if _, err := pool.Exec(ctx, "UPDATE outbox_events SET published_at = NULL"); err != nil {
t.Fatalf("mark the event unpublished again: %v", err)
}
}
metrics := prometheus.New()
group := newConsumerGroup()
source, _ := (&consumerHarness{env: env}).newSource(t, topic, group)
consumerLogger := slog.New(slog.NewJSONHandler(harness.logs, nil))
consumer, err := eventconsumer.New(harness.handler, source, harness.consumers, metrics, consumerLogger, consumerTestSettings(consumerGrace))
if err != nil {
t.Fatalf("eventconsumer.New() error = %v", err)
}
runConsumer(ctx, t, consumer)
env.waitForCommittedOffsets(ctx, t, group, topic, map[int32]int64{0: 2})
assertRowCount(ctx, t, pool, pgx.Identifier{"deliveries"}, 1)
assertRowCount(ctx, t, pool, pgx.Identifier{"mail_requests"}, 0)
assertDeliveryRecords(t, metrics, "applied", 1)
assertDeliveryRecords(t, metrics, "duplicate", 1)
delivery := harness.getDelivery(ctx, t, pool, deliveryID)
content := delivery.Content()
switch {
case delivery.SourceEventID() != event.EventID:
t.Fatal("the delivery does not name the event it came from")
case delivery.RecipientUserID() != recipient.ID || delivery.Recipient().Address() != deliveryRecipientAddress:
t.Fatal("the delivery is not addressed to the recipient account")
case delivery.Kind() != domain.MailKindNotification || content.TemplateVersion() != "notification.v1":
t.Fatalf("delivery kind %s, version %s", delivery.Kind(), content.TemplateVersion())
case delivery.ProviderAccount() != harness.account:
t.Fatal("the delivery is not pinned to the configured provider account")
case delivery.IdempotencyKey() != "delivery/"+deliveryID.String():
t.Fatalf("idempotency key %q", delivery.IdempotencyKey())
case delivery.Status() != domain.DeliveryStatusPending || delivery.AttemptCount() != 0 || delivery.Version() != 1:
t.Fatalf("new delivery is %s with %d attempts at version %d", delivery.Status(), delivery.AttemptCount(), delivery.Version())
case !strings.Contains(content.Text(), "PRIVATE-BODY") || !strings.Contains(content.Text(), env.Config.AppPublicURL+deliveryLinkPath):
t.Fatal("the stored body is not the rendering of the request")
}
harness.assertLogsHoldNoPersonalData(t)
})
t.Run("a stored delivery keeps its body after the template changes", func(t *testing.T) {
reset(t)
recipient := harness.createRecipient(ctx, t, true)
first := harness.requestNotification(ctx, t, recipient)
firstEvent := harness.outboxEvent(ctx, t, first)
harness.apply(ctx, t, notification.DeliveryConsumerName, harness.handler, firstEvent)
original := harness.getDelivery(ctx, t, pool, first)
// The template moves to notification.v2. A new request gets the new
// version; a replay of the first request under another consumer name
// finds the request consumed and stores nothing.
v2Handler := harness.newHandler(v2Renderer{})
second := harness.requestNotification(ctx, t, recipient)
harness.apply(ctx, t, notification.DeliveryConsumerName, v2Handler, harness.outboxEvent(ctx, t, second))
harness.apply(ctx, t, renamedDeliveryConsumer, v2Handler, firstEvent)
assertRowCount(ctx, t, pool, pgx.Identifier{"deliveries"}, 2)
if got := harness.getDelivery(ctx, t, pool, second).Content(); got.TemplateVersion() != deliveryV2Version {
t.Fatalf("the new request rendered %s, want %s", got.TemplateVersion(), deliveryV2Version)
}
// Read through a fresh pool and store, as another instance would.
kept := harness.getDelivery(ctx, t, newPoolFor(ctx, t, env.Config.DatabaseURL), first).Content()
want := original.Content()
if kept.TemplateVersion() != "notification.v1" || kept.Subject() != want.Subject() ||
kept.Text() != want.Text() || kept.HTML() != want.HTML() || kept.Hash() != want.Hash() {
t.Fatal("the stored delivery changed after the template version changed")
}
// The database refuses a direct change of the stored body.
_, err := pool.Exec(ctx, "UPDATE deliveries SET text_body = 'rewritten' WHERE id = $1", first)
assertSQLRefusal(t, err, "deliveries_content_immutable")
harness.assertLogsHoldNoPersonalData(t)
})
t.Run("attempts and the provider message ID survive a restart", func(t *testing.T) {
reset(t)
recipient := harness.createRecipient(ctx, t, true)
deliveryID := harness.requestNotification(ctx, t, recipient)
harness.apply(ctx, t, notification.DeliveryConsumerName, harness.handler, harness.outboxEvent(ctx, t, deliveryID))
// The first instance records two attempts through its own pool.
firstPool := newPoolFor(ctx, t, env.Config.DatabaseURL)
firstStore := postgresadapter.NewDeliveryStore(firstPool).Deliveries()
created, err := firstStore.Get(ctx, deliveryID)
if err != nil {
t.Fatalf("Get() error = %v", err)
}
uncertainAt := harness.now.Add(time.Minute)
uncertain, firstAttempt, err := created.RecordAttempt(domain.DeliveryAttemptInput{
At: uncertainAt,
Outcome: domain.DeliveryOutcomeUnknown,
ProviderCode: "concurrent_idempotent_requests",
RetryAfter: deliveryRetryAfter,
NextAttemptAt: uncertainAt.Add(time.Minute),
})
if err != nil {
t.Fatalf("RecordAttempt(unknown) error = %v", err)
}
if err := firstStore.RecordAttempt(ctx, uncertain, firstAttempt); err != nil {
t.Fatalf("store the unknown attempt: %v", err)
}
// A second writer of the same attempt loses on the version.
if err := firstStore.RecordAttempt(ctx, uncertain, firstAttempt); !errors.Is(err, outbound.ErrDeliveryVersionConflict) {
t.Fatalf("store the same attempt again: error = %v, want ErrDeliveryVersionConflict", err)
}
acceptedAt := uncertainAt.Add(2 * time.Minute)
accepted, secondAttempt, err := uncertain.RecordAttempt(domain.DeliveryAttemptInput{
At: acceptedAt,
Outcome: domain.DeliveryOutcomeAccepted,
ProviderMessageID: deliveryMessageID,
})
if err != nil {
t.Fatalf("RecordAttempt(accepted) error = %v", err)
}
if err := firstStore.RecordAttempt(ctx, accepted, secondAttempt); err != nil {
t.Fatalf("store the accepted attempt: %v", err)
}
firstPool.Close()
// A new instance reads the state back.
secondStore := postgresadapter.NewDeliveryStore(newPoolFor(ctx, t, env.Config.DatabaseURL)).Deliveries()
restored, err := secondStore.Get(ctx, deliveryID)
if err != nil {
t.Fatalf("Get() after restart error = %v", err)
}
switch {
case restored.Status() != domain.DeliveryStatusAccepted || restored.ProviderMessageID() != deliveryMessageID:
t.Fatalf("restored delivery is %s with message ID %q", restored.Status(), restored.ProviderMessageID())
case restored.AttemptCount() != 2 || restored.Version() != 3 || !restored.LastAttemptAt().Equal(acceptedAt):
t.Fatalf("restored delivery has %d attempts, version %d, last at %s", restored.AttemptCount(), restored.Version(), restored.LastAttemptAt())
case !restored.NextAttemptAt().IsZero() || restored.IdempotencyKey() != created.IdempotencyKey():
t.Fatal("the restored delivery has a next attempt or another key")
}
attempts, err := secondStore.ListAttempts(ctx, deliveryID)
if err != nil {
t.Fatalf("ListAttempts() error = %v", err)
}
// sameAttempt compares RetryAfter exactly, nanoseconds included.
if len(attempts) != 2 || !sameAttempt(attempts[0], firstAttempt) || !sameAttempt(attempts[1], secondAttempt) {
t.Fatalf("restored attempts = %+v, want %+v and %+v", attempts, firstAttempt, secondAttempt)
}
if _, _, err := restored.RecordAttempt(domain.DeliveryAttemptInput{At: acceptedAt.Add(time.Minute), Outcome: domain.DeliveryOutcomeUnknown}); !errors.Is(err, domain.ErrDeliveryTransition) {
t.Fatalf("an attempt after acceptance: error = %v, want ErrDeliveryTransition", err)
}
_, err = pool.Exec(ctx, "UPDATE delivery_attempts SET outcome = 'unknown' WHERE delivery_id = $1", deliveryID)
assertSQLRefusal(t, err, "delivery_attempts_immutable")
harness.assertLogsHoldNoPersonalData(t)
})
t.Run("a delivery is rebound and parked for the quota only within its rules", func(t *testing.T) {
reset(t)
recipient := harness.createRecipient(ctx, t, true)
deliveryID := harness.requestNotification(ctx, t, recipient)
harness.apply(ctx, t, notification.DeliveryConsumerName, harness.handler, harness.outboxEvent(ctx, t, deliveryID))
store := postgresadapter.NewDeliveryStore(pool).Deliveries()
created := harness.getDelivery(ctx, t, pool, deliveryID)
otherAccount, err := domain.NewMailProviderAccount(deliveryProvider, deliveryOtherAccount)
if err != nil {
t.Fatalf("NewMailProviderAccount() error = %v", err)
}
rebound, err := created.Rebind(harness.now.Add(time.Minute), otherAccount)
if err != nil {
t.Fatalf("Rebind() error = %v", err)
}
if err := store.Rebind(ctx, rebound); err != nil {
t.Fatalf("store Rebind() error = %v", err)
}
// A local quota defers the delivery before any attempt; the reset is
// unknown.
waiting, err := rebound.WaitForQuota(harness.now.Add(2*time.Minute), time.Time{})
if err != nil {
t.Fatalf("WaitForQuota() error = %v", err)
}
if err := store.WaitForQuota(ctx, waiting); err != nil {
t.Fatalf("store WaitForQuota() error = %v", err)
}
if err := store.WaitForQuota(ctx, waiting); !errors.Is(err, outbound.ErrDeliveryVersionConflict) {
t.Fatalf("store WaitForQuota() over a stale version error = %v, want ErrDeliveryVersionConflict", err)
}
stored := harness.getDelivery(ctx, t, pool, deliveryID)
if stored.Status() != domain.DeliveryStatusWaitingQuota || !stored.NextAttemptAt().IsZero() ||
stored.ProviderAccount() != otherAccount || stored.AttemptCount() != 0 || stored.Version() != 3 {
t.Fatalf("stored delivery is %s due %s on %s/%s with %d attempts at version %d", stored.Status(), stored.NextAttemptAt(),
stored.ProviderAccount().Provider(), stored.ProviderAccount().Account(), stored.AttemptCount(), stored.Version())
}
assertRowCount(ctx, t, pool, pgx.Identifier{"delivery_attempts"}, 0)
// After the first attempt the account is fixed, in the domain and in
// the database.
attemptAt := harness.now.Add(3 * time.Minute)
attempted, attempt, err := stored.RecordAttempt(domain.DeliveryAttemptInput{
At: attemptAt, Outcome: domain.DeliveryOutcomeRejected, Rejection: domain.DeliveryRejectionTemporary, NextAttemptAt: attemptAt.Add(time.Minute),
})
if err != nil {
t.Fatalf("RecordAttempt() error = %v", err)
}
if err := store.RecordAttempt(ctx, attempted, attempt); err != nil {
t.Fatalf("store RecordAttempt() error = %v", err)
}
if _, err := attempted.Rebind(attemptAt.Add(time.Minute), harness.account); !errors.Is(err, domain.ErrDeliveryTransition) {
t.Fatalf("Rebind() after an attempt error = %v, want ErrDeliveryTransition", err)
}
_, err = pool.Exec(ctx, "UPDATE deliveries SET provider_account = $2 WHERE id = $1", deliveryID, deliveryAccount)
assertSQLRefusal(t, err, "deliveries_provider_pinned")
harness.assertLogsHoldNoPersonalData(t)
})
t.Run("a notification to an unverified address is skipped", func(t *testing.T) {
reset(t)
recipient := harness.createRecipient(ctx, t, false)
deliveryID := harness.requestNotification(ctx, t, recipient)
harness.apply(ctx, t, notification.DeliveryConsumerName, harness.handler, harness.outboxEvent(ctx, t, deliveryID))
assertRowCount(ctx, t, pool, pgx.Identifier{"deliveries"}, 0)
assertRowCount(ctx, t, pool, pgx.Identifier{"mail_requests"}, 0)
if !strings.Contains(harness.logs.String(), deliveryID.String()) {
t.Fatal("the skip is not logged with the delivery ID")
}
harness.assertLogsHoldNoPersonalData(t)
})
t.Run("a request for an account that no longer exists is skipped", func(t *testing.T) {
reset(t)
recipient := harness.createRecipient(ctx, t, true)
deliveryID := harness.requestNotification(ctx, t, recipient)
event := harness.outboxEvent(ctx, t, deliveryID)
if _, err := pool.Exec(ctx, "DELETE FROM users WHERE id = $1", recipient.ID); err != nil {
t.Fatalf("delete the recipient: %v", err)
}
// The request text goes with the account; the outbox keeps only IDs.
assertRowCount(ctx, t, pool, pgx.Identifier{"mail_requests"}, 0)
harness.apply(ctx, t, notification.DeliveryConsumerName, harness.handler, event)
assertRowCount(ctx, t, pool, pgx.Identifier{"deliveries"}, 0)
if !strings.Contains(harness.logs.String(), deliveryID.String()) {
t.Fatal("the skip is not logged with the delivery ID")
}
harness.assertLogsHoldNoPersonalData(t)
})
t.Run("the unverified account cleanup removes requests and deliveries and skips a locked one", func(t *testing.T) {
reset(t)
recipient := harness.createRecipient(ctx, t, false)
// A pending request and a delivery created directly, as the identity
// flows will create token mail.
harness.requestNotification(ctx, t, recipient)
deliveryID := harness.createDeliveryDirectly(ctx, t, recipient)
cutoff := harness.now.Add(time.Hour)
users := harness.identity.Users()
// A worker holds the delivery row; the cleanup skips the account
// instead of waiting.
held, err := pool.Begin(ctx)
if err != nil {
t.Fatalf("begin the holding transaction: %v", err)
}
if _, err := held.Exec(ctx, "SELECT 1 FROM deliveries WHERE id = $1 FOR UPDATE", deliveryID); err != nil {
t.Fatalf("lock the delivery: %v", err)
}
deleted, err := users.DeleteUnverifiedRegisteredBefore(ctx, cutoff, 10)
if rollbackErr := held.Rollback(ctx); rollbackErr != nil {
t.Fatalf("release the delivery lock: %v", rollbackErr)
}
if err != nil || deleted != 0 {
t.Fatalf("DeleteUnverifiedRegisteredBefore() with a locked delivery = %d, %v, want 0", deleted, err)
}
deleted, err = users.DeleteUnverifiedRegisteredBefore(ctx, cutoff, 10)
if err != nil || deleted != 1 {
t.Fatalf("DeleteUnverifiedRegisteredBefore() = %d, %v, want 1", deleted, err)
}
assertRowCount(ctx, t, pool, pgx.Identifier{"deliveries"}, 0)
assertRowCount(ctx, t, pool, pgx.Identifier{"mail_requests"}, 0)
harness.assertLogsHoldNoPersonalData(t)
})
}
func (harness *deliveryHarness) clock() time.Time { return harness.now }
func (harness *deliveryHarness) newHandler(renderer notification.NotificationRenderer) *notification.DeliveryHandler {
logger := slog.New(slog.NewJSONHandler(harness.logs, nil))
return notification.NewDeliveryHandler(renderer, harness.account, harness.clock, logger)
}
// createRecipient creates an account with deliveryRecipientAddress,
// confirmed when verified is true.
func (harness *deliveryHarness) createRecipient(ctx context.Context, t *testing.T, verified bool) domain.User {
t.Helper()
hash, err := domain.NewPasswordHash(identityTestPasswordHash)
if err != nil {
t.Fatalf("NewPasswordHash() error = %v", err)
}
user, err := domain.NewUser(domain.Registration{
Email: mustEmail(t, deliveryRecipientAddress),
PasswordHash: hash,
Scenario: domain.ScenarioCandidate,
RegisteredAt: harness.now,
})
if err != nil {
t.Fatalf("NewUser() error = %v", err)
}
users := harness.identity.Users()
if err := users.Create(ctx, user); err != nil {
t.Fatalf("create the recipient account: %v", err)
}
if !verified {
return user
}
confirmed, err := users.MarkEmailVerified(ctx, user.ID, user.RegistrationVersion, harness.now)
if err != nil {
t.Fatalf("confirm the recipient address: %v", err)
}
return confirmed
}
// requestNotification records a request in a business transaction, as a
// product usecase would, and returns the delivery ID.
func (harness *deliveryHarness) requestNotification(ctx context.Context, t *testing.T, recipient domain.User) uuid.UUID {
t.Helper()
var deliveryID uuid.UUID
err := harness.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
var err error
deliveryID, err = harness.requester.RequestNotification(ctx, unit, notification.NotificationRequest{
RecipientUserID: recipient.ID,
Notification: mailtemplate.NotificationData{Subject: deliverySubject, Body: deliveryBody, LinkPath: deliveryLinkPath},
})
return err
})
if err != nil {
t.Fatalf("RequestNotification() error = %v", err)
}
return deliveryID
}
// createDeliveryDirectly stores a delivery without a request, as a
// transaction that issues a token will.
func (harness *deliveryHarness) createDeliveryDirectly(ctx context.Context, t *testing.T, recipient domain.User) uuid.UUID {
t.Helper()
content, err := domain.NewMailContent(domain.MailKindVerification, "verification.v1", "Подтвердите почту", "PRIVATE-BODY link\n", "")
if err != nil {
t.Fatalf("NewMailContent() error = %v", err)
}
delivery, err := domain.NewDelivery(domain.NewDeliveryInput{
ID: uuid.Must(uuid.NewV7()),
RecipientUserID: recipient.ID,
Recipient: recipient.Email,
Content: content,
ProviderAccount: harness.account,
CreatedAt: harness.now,
})
if err != nil {
t.Fatalf("NewDelivery() error = %v", err)
}
if created, err := postgresadapter.NewDeliveryStore(harness.pool).Deliveries().Create(ctx, delivery); err != nil || !created {
t.Fatalf("Create() = %t, %v; want the delivery stored", created, err)
}
return delivery.ID()
}
// outboxEvent reads the request event from the outbox as the consumer
// receives it, and checks that it carries no personal data.
func (harness *deliveryHarness) outboxEvent(ctx context.Context, t *testing.T, deliveryID uuid.UUID) outbound.ConsumedEvent {
t.Helper()
for _, stored := range readOutboxEvents(ctx, t, harness.pool) {
if stored.aggregateID != deliveryID {
continue
}
for _, marker := range append([]string{"@"}, deliveryPrivacyMarkers...) {
if strings.Contains(string(stored.payload), marker) {
t.Fatalf("the outbox event carries personal data: %s", stored.payload)
}
}
return outbound.ConsumedEvent{
EventID: stored.eventID,
EventType: stored.eventType,
SchemaVersion: stored.schemaVersion,
AggregateType: stored.aggregateType,
AggregateID: stored.aggregateID,
AggregateVersion: stored.aggregateVersion,
OccurredAt: harness.now,
Payload: stored.payload,
}
}
t.Fatalf("no outbox event for delivery %s", deliveryID)
return outbound.ConsumedEvent{}
}
// apply runs handler in a consumer transaction with its dedup marker, as the
// consumer runtime does, and expects the event to be applied.
func (harness *deliveryHarness) apply(
ctx context.Context,
t *testing.T,
consumer string,
handler *notification.DeliveryHandler,
event outbound.ConsumedEvent,
) {
t.Helper()
applied, err := harness.consumers.ApplyOnce(ctx, consumer, event.EventID, func(ctx context.Context, unit outbound.UnitOfWork) error {
return handler.Handle(ctx, unit, event)
})
if err != nil || !applied {
t.Fatalf("ApplyOnce(%s) = %t, %v; want the event applied", consumer, applied, err)
}
}
func (harness *deliveryHarness) getDelivery(ctx context.Context, t *testing.T, pool *pgxpool.Pool, id uuid.UUID) domain.Delivery {
t.Helper()
delivery, err := postgresadapter.NewDeliveryStore(pool).Deliveries().Get(ctx, id)
if err != nil {
t.Fatalf("Get(%s) error = %v", id, err)
}
return delivery
}
func (harness *deliveryHarness) assertLogsHoldNoPersonalData(t *testing.T) {
t.Helper()
logs := harness.logs.String()
for _, marker := range deliveryPrivacyMarkers {
if strings.Contains(logs, marker) {
t.Fatalf("personal data %q reached the logs:\n%s", marker, logs)
}
}
}
// assertDeliveryRecords checks a record counter of the delivery consumer.
func assertDeliveryRecords(t *testing.T, metrics *prometheus.Metrics, outcome string, want int) {
t.Helper()
response := httptest.NewRecorder()
metrics.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/metrics", nil))
series := fmt.Sprintf(`lincodex_event_consumer_records_total{consumer=%q,outcome=%q} %d`, notification.DeliveryConsumerName, outcome, want)
if !strings.Contains(response.Body.String(), series+"\n") {
t.Fatalf("metrics output lacks %s", series)
}
}
func assertSQLRefusal(t *testing.T, err error, constraint string) {
t.Helper()
var pgError *pgconn.PgError
if !errors.As(err, &pgError) || pgError.Code != "23000" || pgError.ConstraintName != constraint {
t.Fatalf("statement error = %v, want SQLSTATE 23000 on %s", err, constraint)
}
}
func sameAttempt(got, want domain.DeliveryAttempt) bool {
return got.DeliveryID == want.DeliveryID && got.Number == want.Number && got.At.Equal(want.At) &&
got.Outcome == want.Outcome && got.Rejection == want.Rejection && got.ProviderCode == want.ProviderCode &&
got.ProviderMessageID == want.ProviderMessageID && got.RetryAfter == want.RetryAfter &&
got.StatusAfter == want.StatusAfter && got.NextAttemptAt.Equal(want.NextAttemptAt)
}
+3 -1
View File
@@ -7,6 +7,7 @@ import (
"crypto/sha256"
"errors"
"fmt"
"slices"
"strings"
"sync"
"testing"
@@ -69,7 +70,8 @@ func TestIdentityRepositories(t *testing.T) {
// Subtests share tables and run sequentially; each starts from empty tables.
reset := func(t *testing.T) {
t.Helper()
truncateTables(ctx, t, pool, identityTables...)
// The deliveries reference users, so TRUNCATE must name them too.
truncateTables(ctx, t, pool, slices.Concat(identityTables, deliveryTables)...)
}
t.Run("stores an account and finds it by ID and by any case of its email", func(t *testing.T) {
@@ -26,16 +26,21 @@ const (
policyMigrationVersion = 3
// consumerMigrationVersion creates consumerTableNames.
consumerMigrationVersion = 5
// deliveryMigrationVersion creates deliveryTableNames (mail requests,
// deliveries, and their attempts) and deliveryFunctionNames.
deliveryMigrationVersion = 6
)
var (
// Tables created by 00001, 00002, 00003, and 00005.
// Tables created by 00001, 00002, 00003, 00005, and 00006.
outboxTables = []string{"outbox_events"}
identityTableNames = []string{"users", "email_tokens", "sessions"}
policyTableNames = []string{"policy_versions"}
consumerTableNames = []string{"consumer_processed_events", "consumer_dead_letters"}
// Trigger functions created by 00003.
policyFunctionNames = []string{"policy_versions_refuse_change()", "policy_versions_stamp_creation()"}
deliveryTableNames = []string{"mail_requests", "deliveries", "delivery_attempts"}
// Trigger functions created by 00003 and 00006.
policyFunctionNames = []string{"policy_versions_refuse_change()", "policy_versions_stamp_creation()"}
deliveryFunctionNames = []string{"deliveries_refuse_content_change()", "delivery_attempts_refuse_update()"}
)
func TestPostgresMigrations(t *testing.T) {
@@ -65,8 +70,10 @@ func TestPostgresMigrations(t *testing.T) {
assertTablesExist(ctx, t, pool, true, policyTableNames...)
assertFunctionsExist(ctx, t, pool, true, policyFunctionNames...)
assertTablesExist(ctx, t, pool, true, consumerTableNames...)
assertTablesExist(ctx, t, pool, true, deliveryTableNames...)
assertFunctionsExist(ctx, t, pool, true, deliveryFunctionNames...)
identityRolledBack, policyRolledBack, consumerRolledBack := false, false, false
identityRolledBack, policyRolledBack, consumerRolledBack, deliveryRolledBack := false, false, false, false
for rolledBack := 0; ; rolledBack++ {
result, err := migrator.DownOne(ctx)
if errors.Is(err, postgresadapter.ErrNoMigrationToRollBack) {
@@ -78,6 +85,14 @@ func TestPostgresMigrations(t *testing.T) {
if err != nil {
t.Fatalf("DownOne() after %d rollbacks error = %v", rolledBack, err)
}
if result.Version == deliveryMigrationVersion {
// The delivery migration removes its tables and functions
// and leaves the identity tables they referenced.
assertTablesExist(ctx, t, pool, false, deliveryTableNames...)
assertFunctionsExist(ctx, t, pool, false, deliveryFunctionNames...)
assertTablesExist(ctx, t, pool, true, identityTableNames...)
deliveryRolledBack = true
}
if result.Version == consumerMigrationVersion {
// The consumer migration removes only its own tables.
assertTablesExist(ctx, t, pool, false, consumerTableNames...)
@@ -100,8 +115,9 @@ func TestPostgresMigrations(t *testing.T) {
identityRolledBack = true
}
}
if !identityRolledBack || !policyRolledBack || !consumerRolledBack {
t.Fatalf("migrations %d, %d, and %d were not all rolled back", identityMigrationVersion, policyMigrationVersion, consumerMigrationVersion)
if !identityRolledBack || !policyRolledBack || !consumerRolledBack || !deliveryRolledBack {
t.Fatalf("migrations %d, %d, %d, and %d were not all rolled back",
identityMigrationVersion, policyMigrationVersion, consumerMigrationVersion, deliveryMigrationVersion)
}
assertTablesExist(ctx, t, pool, false, outboxTables...)
assertTablesExist(ctx, t, pool, false, identityTableNames...)
@@ -141,6 +157,7 @@ func TestPostgresMigrations(t *testing.T) {
assertTablesExist(ctx, t, pool, true, policyTableNames...)
assertFunctionsExist(ctx, t, pool, true, policyFunctionNames...)
assertTablesExist(ctx, t, pool, true, consumerTableNames...)
assertTablesExist(ctx, t, pool, true, deliveryTableNames...)
assertAllApplied(ctx, t, migrator, total)
})
@@ -0,0 +1,345 @@
package postgres
import (
"context"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// deliveryConstraintErrors maps the delivery constraints and triggers whose
// violation is a caller-visible outcome to port sentinels, by SQLSTATE and
// constraint name, never by text.
var deliveryConstraintErrors = map[constraintViolation]error{
{foreignKeyViolationCode, "deliveries_recipient_user_id_fkey"}: outbound.ErrUserNotFound,
{foreignKeyViolationCode, "delivery_attempts_delivery_id_fkey"}: outbound.ErrDeliveryNotFound,
{integrityConstraintViolationCode, "deliveries_content_immutable"}: outbound.ErrDeliveryContentImmutable,
{integrityConstraintViolationCode, "delivery_attempts_immutable"}: outbound.ErrDeliveryContentImmutable,
{integrityConstraintViolationCode, "deliveries_provider_pinned"}: outbound.ErrDeliveryProviderPinned,
{foreignKeyViolationCode, "mail_requests_recipient_user_id_fkey"}: outbound.ErrUserNotFound,
// A backstop: the version check already stops a second writer of the
// same attempt number.
{uniqueViolationCode, "delivery_attempts_pkey"}: outbound.ErrDeliveryVersionConflict,
}
// mapDeliveryError turns a known delivery or mail request constraint
// violation into its sentinel and replaces any other PostgreSQL error with
// its SQLSTATE and constraint name, because the message and detail can quote
// the recipient address, request text, or a body that holds a token. Deadlocks and serialization failures
// also match ErrTransactionConflict.
func mapDeliveryError(err error) error {
var pgError *pgconn.PgError
if !errors.As(err, &pgError) {
return sanitizeConnectError(err)
}
if sentinel, ok := deliveryConstraintErrors[constraintViolation{code: pgError.Code, constraint: pgError.ConstraintName}]; ok {
return fmt.Errorf("postgres.mapDeliveryError - violate constraint %s: %w", pgError.ConstraintName, sentinel)
}
return markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName})
}
// DeliveryStore provides the delivery repository outside a transaction. Every
// call runs as its own statement on a pool connection; RecordAttempt is one
// statement, so it stays atomic. Called with a context that belongs to a
// Transactor callback, it fails with outbound.ErrNestedTransaction; use
// UnitOfWork.Deliveries there.
type DeliveryStore struct {
queries *sqlc.Queries
}
func NewDeliveryStore(pool *pgxpool.Pool) *DeliveryStore {
return &DeliveryStore{queries: sqlc.New(standaloneDB{pool: pool})}
}
func (store *DeliveryStore) Deliveries() outbound.DeliveryRepository {
return deliveryRepository{queries: store.queries}
}
func (unit *UnitOfWork) Deliveries() outbound.DeliveryRepository {
return deliveryRepository{queries: unit.queries}
}
// MailRequests is available only inside a transaction: a request is written
// with the outbox event that announces it and consumed under a row lock.
func (unit *UnitOfWork) MailRequests() outbound.MailRequestRepository {
return mailRequestRepository{queries: unit.queries}
}
type deliveryRepository struct {
queries *sqlc.Queries
}
var _ outbound.DeliveryRepository = deliveryRepository{}
func (repository deliveryRepository) Create(ctx context.Context, delivery domain.Delivery) (bool, error) {
if delivery.IsZero() || delivery.Content().IsZero() {
return false, fmt.Errorf("deliveryRepository.Create - delivery was not built by domain.NewDelivery: %w", domain.ErrInvalidDelivery)
}
content := delivery.Content()
hash := content.Hash()
inserted, err := repository.queries.InsertDelivery(ctx, sqlc.InsertDeliveryParams{
ID: pgUUID(delivery.ID()),
SourceEventID: pgOptionalUUID(delivery.SourceEventID()),
RecipientUserID: pgUUID(delivery.RecipientUserID()),
RecipientEmail: delivery.Recipient().Address(),
Kind: string(content.Kind()),
TemplateVersion: content.TemplateVersion(),
Subject: content.Subject(),
TextBody: content.Text(),
HtmlBody: content.HTML(),
ContentSha256: hash[:],
Provider: delivery.ProviderAccount().Provider(),
ProviderAccount: delivery.ProviderAccount().Account(),
IdempotencyKey: delivery.IdempotencyKey(),
Status: string(delivery.Status()),
AttemptCount: delivery.AttemptCount(),
NextAttemptAt: pgZeroableTime(delivery.NextAttemptAt()),
LastAttemptAt: pgZeroableTime(delivery.LastAttemptAt()),
ProviderMessageID: pgOptionalText(delivery.ProviderMessageID()),
Version: delivery.Version(),
CreatedAt: pgTime(delivery.CreatedAt()),
UpdatedAt: pgTime(delivery.UpdatedAt()),
})
if err != nil {
return false, fmt.Errorf("deliveryRepository.Create - insert delivery: %w", mapDeliveryError(err))
}
return inserted == 1, nil
}
func (repository deliveryRepository) Get(ctx context.Context, id uuid.UUID) (domain.Delivery, error) {
row, err := repository.queries.GetDeliveryByID(ctx, pgUUID(id))
if errors.Is(err, pgx.ErrNoRows) {
return domain.Delivery{}, fmt.Errorf("deliveryRepository.Get - select delivery: %w", outbound.ErrDeliveryNotFound)
}
if err != nil {
return domain.Delivery{}, fmt.Errorf("deliveryRepository.Get - select delivery: %w", mapDeliveryError(err))
}
return deliveryFromRow(row)
}
func (repository deliveryRepository) ListAttempts(ctx context.Context, id uuid.UUID) ([]domain.DeliveryAttempt, error) {
rows, err := repository.queries.ListDeliveryAttempts(ctx, pgUUID(id))
if err != nil {
return nil, fmt.Errorf("deliveryRepository.ListAttempts - select attempts: %w", mapDeliveryError(err))
}
attempts := make([]domain.DeliveryAttempt, 0, len(rows))
for _, row := range rows {
attempt, err := domain.RestoreDeliveryAttempt(domain.DeliveryAttempt{
DeliveryID: uuid.UUID(row.DeliveryID.Bytes),
Number: row.AttemptNumber,
At: row.AttemptedAt.Time,
Outcome: domain.DeliveryAttemptOutcome(row.Outcome),
Rejection: domain.DeliveryRejection(row.Rejection.String),
ProviderCode: row.ProviderCode.String,
ProviderMessageID: row.ProviderMessageID.String,
RetryAfter: time.Duration(row.RetryAfterNs),
StatusAfter: domain.DeliveryStatus(row.StatusAfter),
NextAttemptAt: zeroableTime(row.NextAttemptAt),
})
if err != nil {
return nil, fmt.Errorf("deliveryRepository.ListAttempts - decode attempt %d: %w", row.AttemptNumber, err)
}
attempts = append(attempts, attempt)
}
return attempts, nil
}
func (repository deliveryRepository) RecordAttempt(ctx context.Context, next domain.Delivery, attempt domain.DeliveryAttempt) error {
const location = "deliveryRepository.RecordAttempt"
if next.IsZero() || attempt.DeliveryID != next.ID() || attempt.Number != next.AttemptCount() || next.Version() <= 1 {
return fmt.Errorf("%s - state and attempt were not built by domain.Delivery.RecordAttempt: %w", location, domain.ErrInvalidDelivery)
}
recorded, err := repository.queries.RecordDeliveryAttempt(ctx, sqlc.RecordDeliveryAttemptParams{
AttemptNumber: attempt.Number,
AttemptedAt: pgTime(attempt.At),
Outcome: string(attempt.Outcome),
Rejection: pgOptionalText(string(attempt.Rejection)),
ProviderCode: pgOptionalText(attempt.ProviderCode),
ProviderMessageID: pgOptionalText(attempt.ProviderMessageID),
RetryAfterNs: int64(attempt.RetryAfter),
Status: string(next.Status()),
NextAttemptAt: pgZeroableTime(next.NextAttemptAt()),
UpdatedAt: pgTime(next.UpdatedAt()),
DeliveryID: pgUUID(next.ID()),
ExpectedVersion: next.Version() - 1,
})
if err != nil {
return fmt.Errorf("%s - update delivery and insert attempt: %w", location, mapDeliveryError(err))
}
if recorded == 0 {
return fmt.Errorf("%s - expected version %d: %w", location, next.Version()-1, outbound.ErrDeliveryVersionConflict)
}
return nil
}
func (repository deliveryRepository) WaitForQuota(ctx context.Context, next domain.Delivery) error {
if next.Status() != domain.DeliveryStatusWaitingQuota {
return fmt.Errorf("deliveryRepository.WaitForQuota - state was not built by domain.Delivery.WaitForQuota: %w", domain.ErrInvalidDelivery)
}
return repository.updateState(ctx, "deliveryRepository.WaitForQuota", next)
}
func (repository deliveryRepository) Rebind(ctx context.Context, next domain.Delivery) error {
if next.AttemptCount() != 0 {
return fmt.Errorf("deliveryRepository.Rebind - state was not built by domain.Delivery.Rebind: %w", domain.ErrInvalidDelivery)
}
return repository.updateState(ctx, "deliveryRepository.Rebind", next)
}
// updateState stores a state change without an attempt over the version
// before it.
func (repository deliveryRepository) updateState(ctx context.Context, location string, next domain.Delivery) error {
if next.IsZero() || next.Version() <= 1 {
return fmt.Errorf("%s - state was not built by a domain.Delivery transition: %w", location, domain.ErrInvalidDelivery)
}
updated, err := repository.queries.UpdateDeliveryState(ctx, sqlc.UpdateDeliveryStateParams{
Status: string(next.Status()),
NextAttemptAt: pgZeroableTime(next.NextAttemptAt()),
Provider: next.ProviderAccount().Provider(),
ProviderAccount: next.ProviderAccount().Account(),
UpdatedAt: pgTime(next.UpdatedAt()),
ID: pgUUID(next.ID()),
ExpectedVersion: next.Version() - 1,
})
if err != nil {
return fmt.Errorf("%s - update delivery: %w", location, mapDeliveryError(err))
}
if updated == 0 {
return fmt.Errorf("%s - expected version %d: %w", location, next.Version()-1, outbound.ErrDeliveryVersionConflict)
}
return nil
}
func deliveryFromRow(row sqlc.Delivery) (domain.Delivery, error) {
kind, err := domain.ParseMailKind(row.Kind)
if err != nil {
return domain.Delivery{}, fmt.Errorf("postgres.deliveryFromRow - decode kind: %w", err)
}
content, err := domain.RestoreMailContent(kind, row.TemplateVersion, row.Subject, row.TextBody, row.HtmlBody, row.ContentSha256)
if err != nil {
return domain.Delivery{}, fmt.Errorf("postgres.deliveryFromRow - decode content: %w", err)
}
providerAccount, err := domain.NewMailProviderAccount(row.Provider, row.ProviderAccount)
if err != nil {
return domain.Delivery{}, fmt.Errorf("postgres.deliveryFromRow - decode provider account: %w", err)
}
delivery, err := domain.RestoreDelivery(domain.DeliverySnapshot{
ID: uuid.UUID(row.ID.Bytes),
SourceEventID: optionalUUID(row.SourceEventID),
RecipientUserID: uuid.UUID(row.RecipientUserID.Bytes),
RecipientAddress: row.RecipientEmail,
Content: content,
ProviderAccount: providerAccount,
IdempotencyKey: row.IdempotencyKey,
Status: domain.DeliveryStatus(row.Status),
AttemptCount: row.AttemptCount,
NextAttemptAt: zeroableTime(row.NextAttemptAt),
LastAttemptAt: zeroableTime(row.LastAttemptAt),
ProviderMessageID: row.ProviderMessageID.String,
Version: row.Version,
CreatedAt: row.CreatedAt.Time,
UpdatedAt: row.UpdatedAt.Time,
})
if err != nil {
return domain.Delivery{}, fmt.Errorf("postgres.deliveryFromRow - decode delivery: %w", err)
}
return delivery, nil
}
// pgZeroableTime stores the zero time, which the domain uses for "not set",
// as NULL.
func pgZeroableTime(value time.Time) pgtype.Timestamptz {
if value.IsZero() {
return pgtype.Timestamptz{}
}
return pgTime(value)
}
func zeroableTime(value pgtype.Timestamptz) time.Time {
if !value.Valid {
return time.Time{}
}
return value.Time
}
func pgOptionalText(value string) pgtype.Text {
return pgtype.Text{String: value, Valid: value != ""}
}
func pgOptionalUUID(id uuid.UUID) pgtype.UUID {
return pgtype.UUID{Bytes: id, Valid: id != uuid.Nil}
}
func optionalUUID(value pgtype.UUID) uuid.UUID {
if !value.Valid {
return uuid.Nil
}
return uuid.UUID(value.Bytes)
}
type mailRequestRepository struct {
queries *sqlc.Queries
}
var _ outbound.MailRequestRepository = mailRequestRepository{}
func (repository mailRequestRepository) Create(ctx context.Context, request domain.MailRequest) error {
if _, err := domain.NewMailRequest(request); err != nil {
return fmt.Errorf("mailRequestRepository.Create - validate request: %w", err)
}
err := repository.queries.InsertMailRequest(ctx, sqlc.InsertMailRequestParams{
ID: pgUUID(request.ID),
RecipientUserID: pgUUID(request.RecipientUserID),
Kind: string(request.Kind),
Subject: request.Notification.Subject,
Body: request.Notification.Body,
LinkPath: request.Notification.LinkPath,
CreatedAt: pgTime(request.CreatedAt),
})
if err != nil {
return fmt.Errorf("mailRequestRepository.Create - insert mail request: %w", mapDeliveryError(err))
}
return nil
}
func (repository mailRequestRepository) Lock(ctx context.Context, id uuid.UUID) (domain.MailRequest, error) {
row, err := repository.queries.LockMailRequest(ctx, pgUUID(id))
if errors.Is(err, pgx.ErrNoRows) {
return domain.MailRequest{}, fmt.Errorf("mailRequestRepository.Lock - select mail request: %w", outbound.ErrMailRequestNotFound)
}
if err != nil {
return domain.MailRequest{}, fmt.Errorf("mailRequestRepository.Lock - select mail request: %w", mapDeliveryError(err))
}
kind, err := domain.ParseMailKind(row.Kind)
if err != nil {
return domain.MailRequest{}, fmt.Errorf("mailRequestRepository.Lock - decode kind: %w", err)
}
request, err := domain.NewMailRequest(domain.MailRequest{
ID: uuid.UUID(row.ID.Bytes),
RecipientUserID: uuid.UUID(row.RecipientUserID.Bytes),
Kind: kind,
Notification: domain.NotificationText{Subject: row.Subject, Body: row.Body, LinkPath: row.LinkPath},
CreatedAt: row.CreatedAt.Time,
})
if err != nil {
return domain.MailRequest{}, fmt.Errorf("mailRequestRepository.Lock - decode mail request: %w", err)
}
return request, nil
}
func (repository mailRequestRepository) Delete(ctx context.Context, id uuid.UUID) error {
if _, err := repository.queries.DeleteMailRequest(ctx, pgUUID(id)); err != nil {
return fmt.Errorf("mailRequestRepository.Delete - delete mail request: %w", mapDeliveryError(err))
}
return nil
}
@@ -0,0 +1,63 @@
package postgres
import (
"errors"
"strings"
"testing"
"github.com/jackc/pgx/v5/pgconn"
"lincodex/backend/internal/port/outbound"
)
const privateRowValue = "Private.Recipient@Example.com"
func TestMapDeliveryErrorRecognizesDeliveryConstraints(t *testing.T) {
tests := []struct {
code, constraint string
want error
}{
{integrityConstraintViolationCode, "deliveries_content_immutable", outbound.ErrDeliveryContentImmutable},
{integrityConstraintViolationCode, "delivery_attempts_immutable", outbound.ErrDeliveryContentImmutable},
{integrityConstraintViolationCode, "deliveries_provider_pinned", outbound.ErrDeliveryProviderPinned},
{foreignKeyViolationCode, "deliveries_recipient_user_id_fkey", outbound.ErrUserNotFound},
{foreignKeyViolationCode, "mail_requests_recipient_user_id_fkey", outbound.ErrUserNotFound},
{foreignKeyViolationCode, "delivery_attempts_delivery_id_fkey", outbound.ErrDeliveryNotFound},
{uniqueViolationCode, "delivery_attempts_pkey", outbound.ErrDeliveryVersionConflict},
}
for _, test := range tests {
t.Run(test.constraint, func(t *testing.T) {
err := mapDeliveryError(&pgconn.PgError{
Code: test.code,
ConstraintName: test.constraint,
Message: "row " + privateRowValue,
Detail: "Key (recipient_email)=(" + privateRowValue + ")",
})
if !errors.Is(err, test.want) {
t.Fatalf("mapDeliveryError() = %v, want %v", err, test.want)
}
if strings.Contains(err.Error(), privateRowValue) {
t.Fatalf("mapped error quotes a row value: %v", err)
}
})
}
}
func TestMapDeliveryErrorDropsTheTextOfOtherPostgreSQLErrors(t *testing.T) {
err := mapDeliveryError(&pgconn.PgError{
Code: checkViolationCode,
ConstraintName: "deliveries_subject_length",
Message: "new row violates check constraint with " + privateRowValue,
Detail: "Failing row contains (" + privateRowValue + ")",
})
var state sqlStateError
if !errors.As(err, &state) || state.SQLState() != checkViolationCode {
t.Fatalf("mapDeliveryError() = %v, want SQLSTATE %s", err, checkViolationCode)
}
if strings.Contains(err.Error(), privateRowValue) || strings.Contains(err.Error(), "violates") {
t.Fatalf("mapped error keeps the PostgreSQL text: %v", err)
}
if !strings.Contains(err.Error(), "deliveries_subject_length") {
t.Fatalf("mapped error lost the constraint name: %v", err)
}
}
@@ -0,0 +1,446 @@
// 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 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
FROM deliveries
WHERE id = $1
`
func (q *Queries) GetDeliveryByID(ctx context.Context, id pgtype.UUID) (Delivery, error) {
row := q.db.QueryRow(ctx, getDeliveryByID, id)
var i Delivery
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,
)
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,
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
)
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
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.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,
created_at
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7
)
`
type InsertMailRequestParams struct {
ID pgtype.UUID
RecipientUserID pgtype.UUID
Kind string
Subject string
Body string
LinkPath string
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.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 lockMailRequest = `-- name: LockMailRequest :one
SELECT
id,
recipient_user_id,
kind,
subject,
body,
link_path,
created_at
FROM mail_requests
WHERE id = $1
FOR UPDATE
`
// 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) (MailRequest, error) {
row := q.db.QueryRow(ctx, lockMailRequest, id)
var i MailRequest
err := row.Scan(
&i.ID,
&i.RecipientUserID,
&i.Kind,
&i.Subject,
&i.Body,
&i.LinkPath,
&i.CreatedAt,
)
return i, err
}
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
),
version = deliveries.version + 1,
updated_at = $10
WHERE
deliveries.id = $11
AND deliveries.version = $12
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
}
// 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.
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,
)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const updateDeliveryState = `-- name: UpdateDeliveryState :execrows
UPDATE deliveries
SET
status = $1,
next_attempt_at = $2,
provider = $3,
provider_account = $4,
version = deliveries.version + 1,
updated_at = $5
WHERE
deliveries.id = $6
AND deliveries.version = $7
`
type UpdateDeliveryStateParams struct {
Status string
NextAttemptAt pgtype.Timestamptz
Provider string
ProviderAccount string
UpdatedAt pgtype.Timestamptz
ID pgtype.UUID
ExpectedVersion int64
}
// 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.
func (q *Queries) UpdateDeliveryState(ctx context.Context, arg UpdateDeliveryStateParams) (int64, error) {
result, err := q.db.Exec(ctx, updateDeliveryState,
arg.Status,
arg.NextAttemptAt,
arg.Provider,
arg.ProviderAccount,
arg.UpdatedAt,
arg.ID,
arg.ExpectedVersion,
)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
@@ -93,6 +93,20 @@ locked_session AS (
FOR UPDATE SKIP LOCKED
),
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
),
deletable AS (
SELECT candidate.id
FROM candidate
@@ -111,6 +125,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
@@ -124,15 +152,18 @@ type DeleteUnverifiedUsersRegisteredBeforeParams struct {
}
// 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.
// An account qualifies only when every token and session row visible to the
// statement was locked above.
// An account qualifies only when every token, session, mail request, and
// delivery row visible to the statement was locked above.
func (q *Queries) DeleteUnverifiedUsersRegisteredBefore(ctx context.Context, arg DeleteUnverifiedUsersRegisteredBeforeParams) (int64, error) {
result, err := q.db.Exec(ctx, deleteUnverifiedUsersRegisteredBefore, arg.Cutoff, arg.BatchLimit)
if err != nil {
@@ -30,6 +30,43 @@ type ConsumerProcessedEvent struct {
ProcessedAt pgtype.Timestamptz
}
type Delivery 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
}
type DeliveryAttempt struct {
DeliveryID pgtype.UUID
AttemptNumber int32
AttemptedAt pgtype.Timestamptz
Outcome string
Rejection pgtype.Text
ProviderCode pgtype.Text
ProviderMessageID pgtype.Text
RetryAfterNs int64
StatusAfter string
NextAttemptAt pgtype.Timestamptz
}
type EmailToken struct {
ID pgtype.UUID
UserID pgtype.UUID
@@ -42,6 +79,16 @@ type EmailToken struct {
InvalidatedAt pgtype.Timestamptz
}
type MailRequest struct {
ID pgtype.UUID
RecipientUserID pgtype.UUID
Kind string
Subject string
Body string
LinkPath string
CreatedAt pgtype.Timestamptz
}
type OutboxEvent struct {
Position pgtype.Int8
EventID pgtype.UUID
@@ -21,18 +21,23 @@ type Querier interface {
// returned registration version in the same transaction, rolled back when it
// matches no row.
ConsumeEmailToken(ctx context.Context, arg ConsumeEmailTokenParams) (EmailToken, error)
DeleteMailRequest(ctx context.Context, id pgtype.UUID) (int64, error)
// 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.
// An account qualifies only when every token and session row visible to the
// statement was locked above.
// An account qualifies only when every token, session, mail request, and
// delivery row visible to the statement was locked above.
DeleteUnverifiedUsersRegisteredBefore(ctx context.Context, arg DeleteUnverifiedUsersRegisteredBeforeParams) (int64, error)
GetActiveSessionByTokenHash(ctx context.Context, arg GetActiveSessionByTokenHashParams) (Session, error)
GetDeliveryByID(ctx context.Context, id pgtype.UUID) (Delivery, error)
// Among the versions of a family already effective at a time, the newest
// publication wins. A version scheduled for later therefore never undoes a
// version published after it. The unique (policy_key, version) index serves
@@ -54,7 +59,14 @@ type Querier interface {
// after a rewind the handler may fail differently. A different value at a
// reused position, after the topic was recreated, gets its own row.
InsertConsumerDeadLetter(ctx context.Context, arg InsertConsumerDeadLetterParams) error
// 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.
InsertDelivery(ctx context.Context, arg InsertDeliveryParams) (int64, error)
InsertEmailToken(ctx context.Context, arg InsertEmailTokenParams) error
InsertMailRequest(ctx context.Context, arg InsertMailRequestParams) error
InsertOutboxEvent(ctx context.Context, arg InsertOutboxEventParams) error
// Stores a version and returns the stored row with the publication time and
// effective time set by the stamp trigger. A taken ID or version number
@@ -71,6 +83,13 @@ type Querier interface {
InsertSession(ctx context.Context, arg InsertSessionParams) error
InsertUser(ctx context.Context, arg InsertUserParams) error
InvalidateActiveEmailTokens(ctx context.Context, arg InvalidateActiveEmailTokensParams) (int64, error)
ListDeliveryAttempts(ctx context.Context, deliveryID pgtype.UUID) ([]DeliveryAttempt, error)
// 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.
LockMailRequest(ctx context.Context, id pgtype.UUID) (MailRequest, error)
// Locks the next relay batch. For each aggregate only its earliest unpublished
// event (lowest aggregate_version, then position) qualifies, so a relay never
// holds a later version while an earlier one is still pending, whether that
@@ -91,6 +110,14 @@ type Querier interface {
// Reports whether a family has any version without reading a document, so a
// caller that only needs presence never depends on decoding.
PolicyVersionExists(ctx context.Context, policyKey string) (bool, error)
// 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.
RecordDeliveryAttempt(ctx context.Context, arg RecordDeliveryAttemptParams) (int64, error)
RevokeSession(ctx context.Context, arg RevokeSessionParams) (int64, error)
RevokeUserSessions(ctx context.Context, arg RevokeUserSessionsParams) (int64, error)
// Bounds a consumer transaction on the server, local to the transaction.
@@ -112,6 +139,11 @@ type Querier interface {
// revoked, expired, or idle session is not revived; the update re-checks
// those conditions against a concurrent change.
TouchSession(ctx context.Context, arg TouchSessionParams) (TouchSessionRow, error)
// 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.
UpdateDeliveryState(ctx context.Context, arg UpdateDeliveryStateParams) (int64, error)
// Replaces the registration of an unverified account and advances the
// registration version in the same statement, so no caller can choose it.
// The version check rejects a writer that read an older row; a verified
+30 -6
View File
@@ -6,12 +6,16 @@ import (
"log/slog"
"math"
"sync"
"time"
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/kafka"
"lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/usecase/notification"
"lincodex/backend/internal/usecase/notification/mailtemplate"
"lincodex/backend/internal/worker/eventconsumer"
"lincodex/backend/internal/worker/retry"
)
@@ -24,11 +28,27 @@ type eventConsumers []*eventconsumer.Consumer
var _ eventconsumer.Metrics = (*prometheus.Metrics)(nil)
// eventHandlers lists the handlers that get a consumer. It is empty because
// no product module consumes domain events yet; a module adds its handler
// here, and its consumer then starts with the next deployment.
func eventHandlers() []inbound.EventHandler {
return nil
// eventHandlers lists the handlers that get a consumer. A product module
// adds its handler here, and its consumer then starts with the next
// deployment.
func eventHandlers(settings config.Config, logger *slog.Logger) ([]inbound.EventHandler, error) {
renderer, err := mailtemplate.NewRenderer(settings.AppPublicURL)
if err != nil {
return nil, fmt.Errorf("bootstrap.eventHandlers - create mail renderer: %w", err)
}
// New deliveries are pinned to the transport and account configured now;
// a later configuration change applies to new deliveries only.
providerAccount, err := domain.NewMailProviderAccount(string(settings.EmailProvider), settings.EmailAccount)
if err != nil {
return nil, fmt.Errorf("bootstrap.eventHandlers - mail provider account: %w", err)
}
deliveries := notification.NewDeliveryHandler(
notification.NewTemplateRenderer(renderer),
providerAccount,
time.Now,
logger.With(slog.String("component", "notification_delivery")),
)
return []inbound.EventHandler{deliveries}, nil
}
func newEventConsumers(
@@ -37,7 +57,11 @@ func newEventConsumers(
logger *slog.Logger,
metrics *prometheus.Metrics,
) (eventConsumers, func(), error) {
return buildEventConsumers(ctx, settings, logger, metrics, eventHandlers())
handlers, err := eventHandlers(settings, logger)
if err != nil {
return nil, nil, err
}
return buildEventConsumers(ctx, settings, logger, metrics, handlers)
}
// buildEventConsumers builds one consumer per handler and the resources they
+19 -3
View File
@@ -16,6 +16,7 @@ import (
"lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/notification"
"lincodex/backend/internal/worker/eventconsumer"
)
@@ -75,9 +76,24 @@ func TestBuildEventConsumersSkipsWithoutWork(t *testing.T) {
}
}
func TestBootstrapRegistersNoEventHandlerYet(t *testing.T) {
if handlers := eventHandlers(); len(handlers) != 0 {
t.Fatalf("eventHandlers() = %d handlers; update the documentation when the first consumer is registered", len(handlers))
func TestBootstrapRegistersTheDeliveryHandler(t *testing.T) {
handlers, err := eventHandlers(consumerTestConfig(t), slog.New(slog.DiscardHandler))
if err != nil {
t.Fatalf("eventHandlers() error = %v", err)
}
if len(handlers) != 1 || handlers[0].ConsumerName() != notification.DeliveryConsumerName {
t.Fatalf("eventHandlers() = %v; update the documentation when the registered consumers change", handlers)
}
if !handlers[0].Handles(notification.MailRequestedEventType) {
t.Fatalf("the delivery handler does not handle %s", notification.MailRequestedEventType)
}
}
func TestBootstrapRefusesAnInvalidMailAccountForDeliveries(t *testing.T) {
settings := consumerTestConfig(t)
settings.EmailAccount = "Not A Label"
if _, err := eventHandlers(settings, slog.New(slog.DiscardHandler)); err == nil {
t.Fatal("eventHandlers() accepted an invalid provider account label")
}
}
+600
View File
@@ -0,0 +1,600 @@
package domain
import (
"errors"
"fmt"
"log/slog"
"math"
"regexp"
"time"
"github.com/google/uuid"
)
// deliveryIdempotencyKeyPrefix and the delivery ID form the key sent to the
// provider: stable for every attempt of one delivery, unique per delivery,
// and free of personal data.
const deliveryIdempotencyKeyPrefix = "delivery/"
var (
// ErrInvalidDelivery reports a delivery, a stored delivery row, or an
// attempt result that breaks a delivery rule. Errors name the rule, never
// the recipient or the content.
ErrInvalidDelivery = errors.New("invalid delivery")
// ErrDeliveryTransition reports a change that the delivery's state does
// not allow: an attempt on an accepted or rejected delivery, a quota wait
// outside pending or waiting_quota, or a new provider account after the
// first attempt.
ErrDeliveryTransition = errors.New("delivery status does not allow the transition")
// Provider names follow config.EmailProvider values; the account is an
// operator label for the provider account, never a credential.
mailProviderPattern = regexp.MustCompile(`^[a-z][a-z0-9_]{0,31}$`)
mailProviderAccountPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]{0,63}$`)
// A provider code is a documented snake_case error name; see
// outbound.MailProviderCode.
mailProviderCodePattern = regexp.MustCompile(`^[a-z][a-z0-9_]{0,63}$`)
// A provider message ID is printable ASCII without spaces, at most 128
// characters, as the Resend transport accepts it.
providerMessageIDPattern = regexp.MustCompile(`^[!-~]{1,128}$`)
idempotencyKeyPattern = regexp.MustCompile(`^[!-~]{1,256}$`)
)
// DeliveryStatus is the state of one delivery. The values follow the
// outcomes of the MailSender port.
//
// Transitions:
//
// pending, waiting_quota, unknown --RecordAttempt--> accepted | rejected | pending | waiting_quota | unknown
// accepted, rejected --RecordAttempt--> refused (ErrDeliveryTransition)
// pending, waiting_quota --WaitForQuota---> waiting_quota (no attempt is recorded)
//
// The attempt outcome decides the target: accepted gives accepted; a
// permanent or invalid_request rejection gives rejected; a temporary or
// rate_limited rejection gives pending again with a scheduled next attempt; a
// quota_exhausted rejection gives waiting_quota until the expected reset, or
// without a time when the reset is unknown; unknown gives unknown.
type DeliveryStatus string
const (
// DeliveryStatusPending waits for its first or next attempt at
// NextAttemptAt.
DeliveryStatusPending DeliveryStatus = "pending"
// DeliveryStatusAccepted means the provider accepted the message and
// returned its ID. It is not delivery to or reading by the recipient.
DeliveryStatusAccepted DeliveryStatus = "accepted"
// DeliveryStatusRejected means the provider refused the message for good;
// the cause must be fixed before mail of this kind can succeed.
DeliveryStatusRejected DeliveryStatus = "rejected"
// DeliveryStatusUnknown means the last attempt may have reached the
// provider without a conclusive answer (delivery_uncertain). A retry must
// reuse the idempotency key and the stored content; it is never treated
// as not sent.
DeliveryStatusUnknown DeliveryStatus = "unknown"
// DeliveryStatusWaitingQuota means the provider or local quota is used
// up. The next attempt waits for the reset at NextAttemptAt; without a
// time the reset is unknown (for example a monthly provider quota) and an
// operator or the quota rule decides.
DeliveryStatusWaitingQuota DeliveryStatus = "waiting_quota"
)
// ParseDeliveryStatus accepts a known status.
func ParseDeliveryStatus(value string) (DeliveryStatus, error) {
switch status := DeliveryStatus(value); status {
case DeliveryStatusPending, DeliveryStatusAccepted, DeliveryStatusRejected, DeliveryStatusUnknown, DeliveryStatusWaitingQuota:
return status, nil
default:
return "", invalidDelivery("domain.ParseDeliveryStatus", "unknown delivery status")
}
}
// IsTerminal reports a status that accepts no further attempt.
func (status DeliveryStatus) IsTerminal() bool {
return status == DeliveryStatusAccepted || status == DeliveryStatusRejected
}
// requiresNextAttempt reports a status that the sending worker picks up again
// by itself, so it must say when.
func (status DeliveryStatus) requiresNextAttempt() bool {
return status == DeliveryStatusPending
}
// DeliveryAttemptOutcome is what one attempt established; the values equal
// outbound.MailOutcome.
type DeliveryAttemptOutcome string
const (
DeliveryOutcomeAccepted DeliveryAttemptOutcome = "accepted"
DeliveryOutcomeRejected DeliveryAttemptOutcome = "rejected"
DeliveryOutcomeUnknown DeliveryAttemptOutcome = "unknown"
)
// DeliveryRejection is the reason of a rejected attempt; the values equal
// outbound.MailRejection.
type DeliveryRejection string
const (
DeliveryRejectionPermanent DeliveryRejection = "permanent"
DeliveryRejectionInvalidRequest DeliveryRejection = "invalid_request"
DeliveryRejectionRateLimited DeliveryRejection = "rate_limited"
DeliveryRejectionQuotaExhausted DeliveryRejection = "quota_exhausted"
DeliveryRejectionTemporary DeliveryRejection = "temporary"
)
// MailProviderAccount names the transport and the provider account that a
// delivery is pinned to, for example resend and "main". It is configuration
// identity, never a credential. A delivery keeps it for its whole life: a
// configuration change applies to new deliveries only, because providers and
// accounts share no idempotency keys.
type MailProviderAccount struct {
provider string
account string
}
// NewMailProviderAccount validates a provider name (lowercase snake_case of
// at most 32 characters) and an account label (lowercase letters, digits,
// ".", "_", or "-", at most 64 characters).
func NewMailProviderAccount(provider, account string) (MailProviderAccount, error) {
if !mailProviderPattern.MatchString(provider) {
return MailProviderAccount{}, invalidDelivery("domain.NewMailProviderAccount", "provider must be a lowercase snake_case name of at most 32 characters")
}
if !mailProviderAccountPattern.MatchString(account) {
return MailProviderAccount{}, invalidDelivery("domain.NewMailProviderAccount", "account must be a lowercase label of at most 64 characters")
}
return MailProviderAccount{provider: provider, account: account}, nil
}
func (identity MailProviderAccount) Provider() string { return identity.provider }
func (identity MailProviderAccount) Account() string { return identity.account }
func (identity MailProviderAccount) IsZero() bool { return identity.provider == "" }
// Delivery is the durable state of sending one message to one recipient: the
// recipient, the immutable rendered content, the provider account it is
// pinned to, the idempotency key, and the attempt state. The content is fixed
// at creation, so a later template version never changes what a retry sends.
//
// Delivery is a value: RecordAttempt returns the next state and leaves the
// receiver unchanged. String, GoString, Format, and LogValue show the ID,
// kind, status, and provider, never the recipient or the content.
type Delivery struct {
id uuid.UUID
sourceEventID uuid.UUID
recipientUserID uuid.UUID
recipient EmailAddress
content MailContent
providerAccount MailProviderAccount
idempotencyKey string
status DeliveryStatus
attemptCount int32
nextAttemptAt time.Time
lastAttemptAt time.Time
providerMessageID string
version int64
createdAt time.Time
updatedAt time.Time
}
// NewDeliveryInput describes a new delivery. ID must be stable for the
// logical request, so a repeated request maps to the same delivery: the
// mail request ID, or another ID the caller derives from its source record.
type NewDeliveryInput struct {
ID uuid.UUID
// SourceEventID is the domain event the delivery was created from;
// uuid.Nil for a delivery created directly in a business transaction.
SourceEventID uuid.UUID
RecipientUserID uuid.UUID
Recipient EmailAddress
Content MailContent
ProviderAccount MailProviderAccount
CreatedAt time.Time
}
// NewDelivery validates input and returns a pending delivery that is due at
// CreatedAt, with version 1 and the idempotency key "delivery/<id>".
func NewDelivery(input NewDeliveryInput) (Delivery, error) {
const location = "domain.NewDelivery"
switch {
case input.ID == uuid.Nil:
return Delivery{}, invalidDelivery(location, "delivery ID must not be nil")
case input.RecipientUserID == uuid.Nil:
return Delivery{}, invalidDelivery(location, "recipient user ID must not be nil")
case input.Recipient.IsZero():
return Delivery{}, invalidDelivery(location, "recipient address must be set")
case input.Content.IsZero():
return Delivery{}, invalidDelivery(location, "content must be built by NewMailContent")
case input.ProviderAccount.IsZero():
return Delivery{}, invalidDelivery(location, "provider account must be set")
case input.CreatedAt.IsZero():
return Delivery{}, invalidDelivery(location, "creation time must be set")
}
return Delivery{
id: input.ID,
sourceEventID: input.SourceEventID,
recipientUserID: input.RecipientUserID,
recipient: input.Recipient,
content: input.Content,
providerAccount: input.ProviderAccount,
idempotencyKey: deliveryIdempotencyKeyPrefix + input.ID.String(),
status: DeliveryStatusPending,
nextAttemptAt: input.CreatedAt,
version: 1,
createdAt: input.CreatedAt,
updatedAt: input.CreatedAt,
}, nil
}
// DeliverySnapshot is a stored delivery row. A zero time means "not set".
type DeliverySnapshot struct {
ID uuid.UUID
SourceEventID uuid.UUID
RecipientUserID uuid.UUID
RecipientAddress string
Content MailContent
ProviderAccount MailProviderAccount
IdempotencyKey string
Status DeliveryStatus
AttemptCount int32
NextAttemptAt time.Time
LastAttemptAt time.Time
ProviderMessageID string
Version int64
CreatedAt time.Time
UpdatedAt time.Time
}
// RestoreDelivery rebuilds a stored delivery and checks the invariants that
// the database also enforces. The recipient is restored without the current
// address syntax rules, so a later, stricter rule does not make stored rows
// unreadable.
func RestoreDelivery(snapshot DeliverySnapshot) (Delivery, error) {
const location = "domain.RestoreDelivery"
recipient, err := RestoreEmailAddress(snapshot.RecipientAddress, normalizeEmailKey(snapshot.RecipientAddress))
if err != nil {
return Delivery{}, fmt.Errorf("%s - restore recipient: %w", location, err)
}
if _, err := ParseDeliveryStatus(string(snapshot.Status)); err != nil {
return Delivery{}, fmt.Errorf("%s - restore status: %w", location, err)
}
switch {
case snapshot.ID == uuid.Nil || snapshot.RecipientUserID == uuid.Nil:
return Delivery{}, invalidDelivery(location, "delivery and recipient user IDs must not be nil")
case snapshot.Content.IsZero() || snapshot.ProviderAccount.IsZero():
return Delivery{}, invalidDelivery(location, "content and provider account must be set")
case !idempotencyKeyPattern.MatchString(snapshot.IdempotencyKey):
return Delivery{}, invalidDelivery(location, "idempotency key must have 1 to 256 printable ASCII characters")
case snapshot.Version <= 0 || snapshot.AttemptCount < 0:
return Delivery{}, invalidDelivery(location, "version must be positive and the attempt count not negative")
case snapshot.CreatedAt.IsZero() || snapshot.UpdatedAt.Before(snapshot.CreatedAt):
return Delivery{}, invalidDelivery(location, "update time must not precede the creation time")
case (snapshot.AttemptCount == 0) != snapshot.LastAttemptAt.IsZero():
return Delivery{}, invalidDelivery(location, "last attempt time must be set exactly when an attempt was made")
case (snapshot.Status == DeliveryStatusAccepted) != (snapshot.ProviderMessageID != ""):
return Delivery{}, invalidDelivery(location, "provider message ID must be set exactly for an accepted delivery")
}
if err := checkNextAttempt(location, snapshot.Status, snapshot.NextAttemptAt); err != nil {
return Delivery{}, err
}
return Delivery{
id: snapshot.ID,
sourceEventID: snapshot.SourceEventID,
recipientUserID: snapshot.RecipientUserID,
recipient: recipient,
content: snapshot.Content,
providerAccount: snapshot.ProviderAccount,
idempotencyKey: snapshot.IdempotencyKey,
status: snapshot.Status,
attemptCount: snapshot.AttemptCount,
nextAttemptAt: snapshot.NextAttemptAt,
lastAttemptAt: snapshot.LastAttemptAt,
providerMessageID: snapshot.ProviderMessageID,
version: snapshot.Version,
createdAt: snapshot.CreatedAt,
updatedAt: snapshot.UpdatedAt,
}, nil
}
func checkNextAttempt(location string, status DeliveryStatus, nextAttemptAt time.Time) error {
switch {
case status.IsTerminal() && !nextAttemptAt.IsZero():
return invalidDelivery(location, "an accepted or rejected delivery has no next attempt")
case status.requiresNextAttempt() && nextAttemptAt.IsZero():
return invalidDelivery(location, "a pending delivery needs a next attempt time")
}
return nil
}
func (delivery Delivery) IsZero() bool { return delivery.id == uuid.Nil }
func (delivery Delivery) ID() uuid.UUID { return delivery.id }
// SourceEventID is the event the delivery was created from, or uuid.Nil.
func (delivery Delivery) SourceEventID() uuid.UUID { return delivery.sourceEventID }
func (delivery Delivery) RecipientUserID() uuid.UUID { return delivery.recipientUserID }
// Recipient is the address captured when the delivery was created. Use it
// only to send the message; never log it.
func (delivery Delivery) Recipient() EmailAddress { return delivery.recipient }
func (delivery Delivery) Kind() MailKind { return delivery.content.Kind() }
func (delivery Delivery) Content() MailContent { return delivery.content }
func (delivery Delivery) ProviderAccount() MailProviderAccount { return delivery.providerAccount }
// IdempotencyKey is sent with every attempt of this delivery.
func (delivery Delivery) IdempotencyKey() string { return delivery.idempotencyKey }
func (delivery Delivery) Status() DeliveryStatus { return delivery.status }
func (delivery Delivery) AttemptCount() int32 { return delivery.attemptCount }
// NextAttemptAt is when the delivery is due; zero when no automatic attempt
// is scheduled (accepted, rejected, unknown without a retry, or waiting_quota
// with an unknown reset).
func (delivery Delivery) NextAttemptAt() time.Time { return delivery.nextAttemptAt }
// LastAttemptAt is zero before the first attempt.
func (delivery Delivery) LastAttemptAt() time.Time { return delivery.lastAttemptAt }
// ProviderMessageID is set once the provider accepted the message.
func (delivery Delivery) ProviderMessageID() string { return delivery.providerMessageID }
// Version is the optimistic concurrency version, advanced by every attempt.
func (delivery Delivery) Version() int64 { return delivery.version }
func (delivery Delivery) CreatedAt() time.Time { return delivery.createdAt }
func (delivery Delivery) UpdatedAt() time.Time { return delivery.updatedAt }
// DeliveryAttemptInput is the result of one transport attempt. The fields
// mirror outbound.SendResult; At is when the attempt ended.
//
// NextAttemptAt is chosen by the caller's retry policy. It is required when
// the outcome leaves the delivery pending (temporary or rate_limited),
// optional for waiting_quota and unknown, where zero means that no automatic
// attempt is scheduled, and must be zero for accepted and for permanent or
// invalid_request rejections. It must not precede At.
type DeliveryAttemptInput struct {
At time.Time
Outcome DeliveryAttemptOutcome
Rejection DeliveryRejection
ProviderCode string
ProviderMessageID string
RetryAfter time.Duration
NextAttemptAt time.Time
}
// DeliveryAttempt is one recorded attempt. Number counts from 1 within its
// delivery. A zero NextAttemptAt means none was scheduled.
type DeliveryAttempt struct {
DeliveryID uuid.UUID
Number int32
At time.Time
Outcome DeliveryAttemptOutcome
Rejection DeliveryRejection
ProviderCode string
ProviderMessageID string
RetryAfter time.Duration
StatusAfter DeliveryStatus
NextAttemptAt time.Time
}
// RecordAttempt applies an attempt result and returns the next state of the
// delivery together with the attempt record. The receiver is not changed. An
// attempt on an accepted or rejected delivery returns ErrDeliveryTransition;
// a result that breaks the rules of DeliveryAttemptInput returns
// ErrInvalidDelivery. The returned delivery has the next version; storage
// applies it only over the receiver's version.
func (delivery Delivery) RecordAttempt(input DeliveryAttemptInput) (Delivery, DeliveryAttempt, error) {
const location = "Delivery.RecordAttempt"
if delivery.IsZero() {
return Delivery{}, DeliveryAttempt{}, invalidDelivery(location, "delivery was not built by NewDelivery or RestoreDelivery")
}
if delivery.status.IsTerminal() {
return Delivery{}, DeliveryAttempt{}, fmt.Errorf("%s - delivery is %s: %w", location, delivery.status, ErrDeliveryTransition)
}
if delivery.attemptCount == math.MaxInt32 {
return Delivery{}, DeliveryAttempt{}, invalidDelivery(location, "attempt numbers are exhausted")
}
switch {
case input.At.IsZero():
return Delivery{}, DeliveryAttempt{}, invalidDelivery(location, "attempt time must be set")
case input.At.Before(delivery.updatedAt):
return Delivery{}, DeliveryAttempt{}, invalidDelivery(location, "attempt time must not precede the last change of the delivery")
}
attempt := DeliveryAttempt{
DeliveryID: delivery.id,
Number: delivery.attemptCount + 1,
At: input.At,
Outcome: input.Outcome,
Rejection: input.Rejection,
ProviderCode: input.ProviderCode,
ProviderMessageID: input.ProviderMessageID,
RetryAfter: input.RetryAfter,
NextAttemptAt: input.NextAttemptAt,
}
statusAfter, err := validateAttempt(location, attempt)
if err != nil {
return Delivery{}, DeliveryAttempt{}, err
}
attempt.StatusAfter = statusAfter
next := delivery
next.status = statusAfter
next.attemptCount = attempt.Number
next.lastAttemptAt = input.At
next.nextAttemptAt = input.NextAttemptAt
if input.Outcome == DeliveryOutcomeAccepted {
next.providerMessageID = input.ProviderMessageID
}
next.version = delivery.version + 1
next.updatedAt = input.At
return next, attempt, nil
}
// WaitForQuota parks a pending or waiting_quota delivery in waiting_quota
// without an attempt, for example when a local quota defers the send before
// the transport is called. until is the expected reset; zero means unknown,
// so no automatic attempt is scheduled. at is the decision time. It returns
// the next state with the next version; no attempt record is written. An
// unknown delivery is refused: parking it would hide that an earlier attempt
// may have been accepted, and its retry is decided by the retry policy.
func (delivery Delivery) WaitForQuota(at, until time.Time) (Delivery, error) {
const location = "Delivery.WaitForQuota"
if err := delivery.checkChangeTime(location, at); err != nil {
return Delivery{}, err
}
if delivery.status != DeliveryStatusPending && delivery.status != DeliveryStatusWaitingQuota {
return Delivery{}, fmt.Errorf("%s - delivery is %s: %w", location, delivery.status, ErrDeliveryTransition)
}
if !until.IsZero() && until.Before(at) {
return Delivery{}, invalidDelivery(location, "quota reset must not precede the decision")
}
next := delivery
next.status = DeliveryStatusWaitingQuota
next.nextAttemptAt = until
next.version = delivery.version + 1
next.updatedAt = at
return next, nil
}
// Rebind pins a delivery that has no attempt yet to another provider
// account, for example after the stand moved from EMAIL_PROVIDER=disabled to
// a real transport. Once an attempt was made, a provider may hold the
// idempotency key, so the account is fixed and Rebind returns
// ErrDeliveryTransition, as it does for an accepted or rejected delivery.
func (delivery Delivery) Rebind(at time.Time, providerAccount MailProviderAccount) (Delivery, error) {
const location = "Delivery.Rebind"
if err := delivery.checkChangeTime(location, at); err != nil {
return Delivery{}, err
}
if providerAccount.IsZero() {
return Delivery{}, invalidDelivery(location, "provider account must be set")
}
if delivery.attemptCount != 0 || delivery.status.IsTerminal() {
return Delivery{}, fmt.Errorf("%s - delivery has attempts or is %s: %w", location, delivery.status, ErrDeliveryTransition)
}
next := delivery
next.providerAccount = providerAccount
next.version = delivery.version + 1
next.updatedAt = at
return next, nil
}
// checkChangeTime rejects a zero delivery and a change time before the last
// recorded change.
func (delivery Delivery) checkChangeTime(location string, at time.Time) error {
if delivery.IsZero() {
return invalidDelivery(location, "delivery was not built by NewDelivery or RestoreDelivery")
}
if at.IsZero() || at.Before(delivery.updatedAt) {
return invalidDelivery(location, "change time must be set and not precede the last change")
}
return nil
}
// RestoreDeliveryAttempt checks a stored attempt with the rules that
// RecordAttempt applied when it was made.
func RestoreDeliveryAttempt(attempt DeliveryAttempt) (DeliveryAttempt, error) {
const location = "domain.RestoreDeliveryAttempt"
if attempt.DeliveryID == uuid.Nil || attempt.Number <= 0 || attempt.At.IsZero() {
return DeliveryAttempt{}, invalidDelivery(location, "attempt needs a delivery ID, a positive number, and a time")
}
statusAfter, err := validateAttempt(location, attempt)
if err != nil {
return DeliveryAttempt{}, err
}
if attempt.StatusAfter != statusAfter {
return DeliveryAttempt{}, invalidDelivery(location, "stored status does not follow from the attempt outcome")
}
return attempt, nil
}
// validateAttempt checks the result fields and returns the status the
// outcome leads to.
func validateAttempt(location string, attempt DeliveryAttempt) (DeliveryStatus, error) {
if attempt.ProviderCode != "" && !mailProviderCodePattern.MatchString(attempt.ProviderCode) {
return "", invalidDelivery(location, "provider code must be a lowercase snake_case name of at most 64 characters")
}
if attempt.RetryAfter < 0 {
return "", invalidDelivery(location, "retry-after must not be negative")
}
statusAfter, err := statusAfterAttempt(location, attempt)
if err != nil {
return "", err
}
if err := checkNextAttempt(location, statusAfter, attempt.NextAttemptAt); err != nil {
return "", err
}
if !attempt.NextAttemptAt.IsZero() && attempt.NextAttemptAt.Before(attempt.At) {
return "", invalidDelivery(location, "next attempt must not precede the attempt")
}
return statusAfter, nil
}
func statusAfterAttempt(location string, attempt DeliveryAttempt) (DeliveryStatus, error) {
if attempt.Outcome != DeliveryOutcomeAccepted && attempt.ProviderMessageID != "" {
return "", invalidDelivery(location, "only an accepted attempt carries a provider message ID")
}
if attempt.Outcome != DeliveryOutcomeRejected && attempt.Rejection != "" {
return "", invalidDelivery(location, "only a rejected attempt carries a rejection reason")
}
switch attempt.Outcome {
case DeliveryOutcomeAccepted:
if !providerMessageIDPattern.MatchString(attempt.ProviderMessageID) {
return "", invalidDelivery(location, "an accepted attempt needs a provider message ID of 1 to 128 printable ASCII characters")
}
if attempt.ProviderCode != "" || attempt.RetryAfter != 0 {
return "", invalidDelivery(location, "an accepted attempt carries no provider code or retry-after")
}
return DeliveryStatusAccepted, nil
case DeliveryOutcomeUnknown:
return DeliveryStatusUnknown, nil
case DeliveryOutcomeRejected:
switch attempt.Rejection {
case DeliveryRejectionPermanent, DeliveryRejectionInvalidRequest:
return DeliveryStatusRejected, nil
case DeliveryRejectionTemporary, DeliveryRejectionRateLimited:
return DeliveryStatusPending, nil
case DeliveryRejectionQuotaExhausted:
return DeliveryStatusWaitingQuota, nil
default:
return "", invalidDelivery(location, "a rejected attempt needs a known rejection reason")
}
default:
return "", invalidDelivery(location, "attempt outcome must be accepted, rejected, or unknown")
}
}
func invalidDelivery(location, reason string) error {
return fmt.Errorf("%s - %s: %w", location, reason, ErrInvalidDelivery)
}
func (delivery Delivery) String() string {
if delivery.IsZero() {
return "[empty delivery]"
}
return fmt.Sprintf("[delivery %s %s %s]", delivery.id, delivery.content.Kind(), delivery.status)
}
func (delivery Delivery) GoString() string { return delivery.String() }
// Format applies String to every verb; without it %+v would print the fields.
func (delivery Delivery) Format(state fmt.State, _ rune) {
_, _ = state.Write([]byte(delivery.String()))
}
// LogValue carries only bounded or opaque fields: the ID, kind, status, and
// provider. The recipient, its account ID, and the content stay out of logs.
func (delivery Delivery) LogValue() slog.Value {
return slog.GroupValue(
slog.String("delivery_id", delivery.id.String()),
slog.String("kind", string(delivery.content.Kind())),
slog.String("status", string(delivery.status)),
slog.String("provider", delivery.providerAccount.provider),
)
}
+526
View File
@@ -0,0 +1,526 @@
package domain
import (
"bytes"
"errors"
"fmt"
"log/slog"
"strings"
"testing"
"time"
"github.com/google/uuid"
)
const (
testDeliveryAddress = "Recipient.Person@Example.com"
testDeliverySubject = "Subject with a private detail"
testDeliveryText = "Text body https://lincodex.example/verify-email#token=SyntheticToken_0123456789-abcdefghij\n"
testDeliveryHTML = "<p>HTML body with a private detail</p>\n"
testMessageID = "4ef9a417-02e9-4d39-ad75-9611e0fcc33c"
)
var testDeliveryCreated = time.Date(2026, 10, 6, 9, 0, 0, 0, time.UTC)
func testMailContent(t *testing.T) MailContent {
t.Helper()
content, err := NewMailContent(MailKindVerification, "verification.v1", testDeliverySubject, testDeliveryText, testDeliveryHTML)
if err != nil {
t.Fatalf("NewMailContent() error = %v", err)
}
return content
}
func testProviderAccount(t *testing.T) MailProviderAccount {
t.Helper()
account, err := NewMailProviderAccount("resend", "main")
if err != nil {
t.Fatalf("NewMailProviderAccount() error = %v", err)
}
return account
}
func testDeliveryInput(t *testing.T) NewDeliveryInput {
t.Helper()
recipient, err := NewEmailAddress(testDeliveryAddress)
if err != nil {
t.Fatalf("NewEmailAddress() error = %v", err)
}
return NewDeliveryInput{
ID: uuid.MustParse("01926f3a-7c00-7000-8000-000000000001"),
RecipientUserID: uuid.MustParse("01926f3a-7c00-7000-8000-000000000002"),
Recipient: recipient,
Content: testMailContent(t),
ProviderAccount: testProviderAccount(t),
CreatedAt: testDeliveryCreated,
}
}
func newTestDelivery(t *testing.T) Delivery {
t.Helper()
delivery, err := NewDelivery(testDeliveryInput(t))
if err != nil {
t.Fatalf("NewDelivery() error = %v", err)
}
return delivery
}
// after returns a time minutes after the creation of the test delivery.
func after(minutes int) time.Time {
return testDeliveryCreated.Add(time.Duration(minutes) * time.Minute)
}
func mustRecord(t *testing.T, delivery Delivery, input DeliveryAttemptInput) Delivery {
t.Helper()
next, _, err := delivery.RecordAttempt(input)
if err != nil {
t.Fatalf("RecordAttempt(%s/%s) error = %v", input.Outcome, input.Rejection, err)
}
return next
}
func TestMailContentHashCoversEveryPart(t *testing.T) {
base := MailContentHash("verification.v1", "subject", "text", "html")
if base != MailContentHash("verification.v1", "subject", "text", "html") {
t.Fatal("the same parts give different hashes")
}
for name, other := range map[string][MailContentHashSize]byte{
"version": MailContentHash("verification.v2", "subject", "text", "html"),
"subject": MailContentHash("verification.v1", "subject!", "text", "html"),
"text": MailContentHash("verification.v1", "subject", "text!", "html"),
"html": MailContentHash("verification.v1", "subject", "text", "html!"),
"shifted border": MailContentHash("verification.v1", "subjec", "ttext", "html"),
} {
if other == base {
t.Fatalf("content hash ignores a change of the %s", name)
}
}
}
func TestNewMailContentRejectsUnsendableContent(t *testing.T) {
tests := []struct {
name string
kind MailKind
version, subject, text, htmlBody string
}{
{name: "unknown kind", kind: "digest", version: "digest.v1", subject: "s", text: "t"},
{name: "version of another kind", kind: MailKindNotification, version: "verification.v1", subject: "s", text: "t"},
{name: "version prefix of another kind", kind: MailKindPasswordReset, version: "password.v1", subject: "s", text: "t"},
{name: "version without number", kind: MailKindNotification, version: "notification.v0", subject: "s", text: "t"},
{name: "blank subject", kind: MailKindNotification, version: "notification.v1", subject: " ", text: "t"},
{name: "subject with a header line", kind: MailKindNotification, version: "notification.v1", subject: "s\r\nBcc: x@example.com", text: "t"},
{name: "subject too long", kind: MailKindNotification, version: "notification.v1", subject: strings.Repeat("я", maxMailSubjectRunes+1), text: "t"},
{name: "blank bodies", kind: MailKindNotification, version: "notification.v1", subject: "s", text: " \n", htmlBody: ""},
{name: "NUL in body", kind: MailKindNotification, version: "notification.v1", subject: "s", text: "t\x00"},
{name: "invalid UTF-8", kind: MailKindNotification, version: "notification.v1", subject: "s", text: "\xff"},
{name: "oversized body", kind: MailKindNotification, version: "notification.v1", subject: "s", text: strings.Repeat("t", maxMailPartBytes+1)},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
_, err := NewMailContent(test.kind, test.version, test.subject, test.text, test.htmlBody)
if !errors.Is(err, ErrInvalidMailContent) {
t.Fatalf("NewMailContent() error = %v, want ErrInvalidMailContent", err)
}
})
}
}
func TestRestoreMailContentDetectsAChangedBody(t *testing.T) {
content := testMailContent(t)
hash := content.Hash()
restored, err := RestoreMailContent(content.Kind(), content.TemplateVersion(), content.Subject(), content.Text(), content.HTML(), hash[:])
if err != nil || restored.Hash() != hash {
t.Fatalf("RestoreMailContent() = %v, %v, want the stored content", restored, err)
}
_, err = RestoreMailContent(content.Kind(), content.TemplateVersion(), content.Subject(), content.Text()+"changed", content.HTML(), hash[:])
if !errors.Is(err, ErrMailContentIntegrity) {
t.Fatalf("RestoreMailContent(changed text) error = %v, want ErrMailContentIntegrity", err)
}
_, err = RestoreMailContent(content.Kind(), content.TemplateVersion(), content.Subject(), content.Text(), content.HTML(), hash[:16])
if !errors.Is(err, ErrMailContentIntegrity) {
t.Fatalf("RestoreMailContent(short hash) error = %v, want ErrMailContentIntegrity", err)
}
}
func TestNewDeliveryStartsPendingWithAStableKey(t *testing.T) {
input := testDeliveryInput(t)
delivery := newTestDelivery(t)
switch {
case delivery.ID() != input.ID || delivery.RecipientUserID() != input.RecipientUserID:
t.Fatal("NewDelivery() changed the IDs")
case delivery.Recipient().Address() != testDeliveryAddress:
t.Fatal("NewDelivery() changed the recipient")
case delivery.Kind() != MailKindVerification || delivery.Content().Hash() != input.Content.Hash():
t.Fatal("NewDelivery() changed the content")
case delivery.IdempotencyKey() != "delivery/"+input.ID.String():
t.Fatalf("IdempotencyKey() = %q", delivery.IdempotencyKey())
case delivery.Status() != DeliveryStatusPending || !delivery.NextAttemptAt().Equal(testDeliveryCreated):
t.Fatalf("new delivery is %s due at %s, want pending and due at creation", delivery.Status(), delivery.NextAttemptAt())
case delivery.AttemptCount() != 0 || !delivery.LastAttemptAt().IsZero() || delivery.ProviderMessageID() != "":
t.Fatal("new delivery has attempt state")
case delivery.Version() != 1 || !delivery.CreatedAt().Equal(testDeliveryCreated) || !delivery.UpdatedAt().Equal(testDeliveryCreated):
t.Fatal("new delivery has the wrong version or times")
}
}
func TestNewDeliveryRejectsIncompleteInput(t *testing.T) {
tests := map[string]func(*NewDeliveryInput){
"nil ID": func(input *NewDeliveryInput) { input.ID = uuid.Nil },
"nil recipient user": func(input *NewDeliveryInput) { input.RecipientUserID = uuid.Nil },
"zero recipient": func(input *NewDeliveryInput) { input.Recipient = EmailAddress{} },
"zero content": func(input *NewDeliveryInput) { input.Content = MailContent{} },
"zero provider": func(input *NewDeliveryInput) { input.ProviderAccount = MailProviderAccount{} },
"zero creation time": func(input *NewDeliveryInput) { input.CreatedAt = time.Time{} },
}
for name, change := range tests {
t.Run(name, func(t *testing.T) {
input := testDeliveryInput(t)
change(&input)
if _, err := NewDelivery(input); !errors.Is(err, ErrInvalidDelivery) {
t.Fatalf("NewDelivery() error = %v, want ErrInvalidDelivery", err)
}
})
}
}
func TestNewMailProviderAccountRejectsCredentialsAndFreeText(t *testing.T) {
for _, test := range []struct{ provider, account string }{
{"", "main"},
{"Resend", "main"},
{"resend", ""},
{"resend", "re_SecretKeyValue"},
{"resend", "main account"},
{"resend", strings.Repeat("a", 65)},
} {
if _, err := NewMailProviderAccount(test.provider, test.account); !errors.Is(err, ErrInvalidDelivery) {
t.Fatalf("NewMailProviderAccount(%q, %q) error = %v, want ErrInvalidDelivery", test.provider, test.account, err)
}
}
}
// TestDeliveryStatusTransitions applies every attempt outcome to every
// status that accepts an attempt, and checks that the terminal statuses
// accept none.
func TestDeliveryStatusTransitions(t *testing.T) {
outcomes := []struct {
name string
input DeliveryAttemptInput
want DeliveryStatus
}{
{"accepted", DeliveryAttemptInput{Outcome: DeliveryOutcomeAccepted, ProviderMessageID: testMessageID}, DeliveryStatusAccepted},
{"permanent", DeliveryAttemptInput{Outcome: DeliveryOutcomeRejected, Rejection: DeliveryRejectionPermanent, ProviderCode: "validation_error"}, DeliveryStatusRejected},
{"invalid request", DeliveryAttemptInput{Outcome: DeliveryOutcomeRejected, Rejection: DeliveryRejectionInvalidRequest, ProviderCode: "invalid_api_key"}, DeliveryStatusRejected},
{"temporary", DeliveryAttemptInput{Outcome: DeliveryOutcomeRejected, Rejection: DeliveryRejectionTemporary, NextAttemptAt: after(90)}, DeliveryStatusPending},
{"rate limited", DeliveryAttemptInput{Outcome: DeliveryOutcomeRejected, Rejection: DeliveryRejectionRateLimited, RetryAfter: time.Second, NextAttemptAt: after(90)}, DeliveryStatusPending},
{"quota", DeliveryAttemptInput{Outcome: DeliveryOutcomeRejected, Rejection: DeliveryRejectionQuotaExhausted, ProviderCode: "daily_quota_exceeded", RetryAfter: time.Hour, NextAttemptAt: after(120)}, DeliveryStatusWaitingQuota},
{"quota with unknown reset", DeliveryAttemptInput{Outcome: DeliveryOutcomeRejected, Rejection: DeliveryRejectionQuotaExhausted, ProviderCode: "monthly_quota_exceeded"}, DeliveryStatusWaitingQuota},
{"unknown with retry", DeliveryAttemptInput{Outcome: DeliveryOutcomeUnknown, ProviderCode: "concurrent_idempotent_requests", NextAttemptAt: after(90)}, DeliveryStatusUnknown},
{"unknown without retry", DeliveryAttemptInput{Outcome: DeliveryOutcomeUnknown, ProviderCode: "invalid_idempotent_request"}, DeliveryStatusUnknown},
}
start := newTestDelivery(t)
starts := map[DeliveryStatus]Delivery{
DeliveryStatusPending: start,
DeliveryStatusWaitingQuota: mustRecord(t, start, DeliveryAttemptInput{
At: after(1), Outcome: DeliveryOutcomeRejected, Rejection: DeliveryRejectionQuotaExhausted, NextAttemptAt: after(60),
}),
DeliveryStatusUnknown: mustRecord(t, start, DeliveryAttemptInput{At: after(1), Outcome: DeliveryOutcomeUnknown}),
}
for from, delivery := range starts {
for _, outcome := range outcomes {
t.Run(string(from)+" then "+outcome.name, func(t *testing.T) {
input := outcome.input
input.At = after(30)
next, attempt, err := delivery.RecordAttempt(input)
if err != nil {
t.Fatalf("RecordAttempt() error = %v", err)
}
if next.Status() != outcome.want || attempt.StatusAfter != outcome.want {
t.Fatalf("status = %s, attempt status = %s, want %s", next.Status(), attempt.StatusAfter, outcome.want)
}
if next.AttemptCount() != delivery.AttemptCount()+1 || attempt.Number != next.AttemptCount() {
t.Fatalf("attempt number = %d, count = %d after %d", attempt.Number, next.AttemptCount(), delivery.AttemptCount())
}
if next.Version() != delivery.Version()+1 || !next.LastAttemptAt().Equal(input.At) || !next.UpdatedAt().Equal(input.At) {
t.Fatal("the attempt did not advance the version and times")
}
if !next.NextAttemptAt().Equal(input.NextAttemptAt) {
t.Fatalf("NextAttemptAt() = %s, want %s", next.NextAttemptAt(), input.NextAttemptAt)
}
if wantID := input.ProviderMessageID; next.ProviderMessageID() != wantID {
t.Fatalf("ProviderMessageID() = %q, want %q", next.ProviderMessageID(), wantID)
}
if next.IdempotencyKey() != delivery.IdempotencyKey() || next.Content().Hash() != delivery.Content().Hash() {
t.Fatal("an attempt changed the key or the content")
}
})
}
}
terminal := map[DeliveryStatus]Delivery{
DeliveryStatusAccepted: mustRecord(t, start, DeliveryAttemptInput{At: after(1), Outcome: DeliveryOutcomeAccepted, ProviderMessageID: testMessageID}),
DeliveryStatusRejected: mustRecord(t, start, DeliveryAttemptInput{At: after(1), Outcome: DeliveryOutcomeRejected, Rejection: DeliveryRejectionPermanent}),
}
for from, delivery := range terminal {
for _, outcome := range outcomes {
t.Run(string(from)+" refuses "+outcome.name, func(t *testing.T) {
input := outcome.input
input.At = after(30)
if _, _, err := delivery.RecordAttempt(input); !errors.Is(err, ErrDeliveryTransition) {
t.Fatalf("RecordAttempt() error = %v, want ErrDeliveryTransition", err)
}
})
}
}
}
func TestRecordAttemptLeavesTheReceiverUnchanged(t *testing.T) {
delivery := newTestDelivery(t)
next := mustRecord(t, delivery, DeliveryAttemptInput{At: after(1), Outcome: DeliveryOutcomeAccepted, ProviderMessageID: testMessageID})
if delivery.Status() != DeliveryStatusPending || delivery.Version() != 1 || delivery.AttemptCount() != 0 {
t.Fatal("RecordAttempt() changed its receiver")
}
if next.Status() != DeliveryStatusAccepted || next.ProviderMessageID() != testMessageID || !next.NextAttemptAt().IsZero() {
t.Fatalf("accepted delivery = %s with ID %q due %s", next.Status(), next.ProviderMessageID(), next.NextAttemptAt())
}
}
func TestRecordAttemptRejectsInconsistentResults(t *testing.T) {
delivery := mustRecord(t, newTestDelivery(t), DeliveryAttemptInput{At: after(10), Outcome: DeliveryOutcomeUnknown})
tests := map[string]DeliveryAttemptInput{
"zero time": {Outcome: DeliveryOutcomeUnknown},
"before the previous attempt": {At: after(5), Outcome: DeliveryOutcomeUnknown},
"unknown outcome": {At: after(20), Outcome: "delivered"},
"accepted without message ID": {At: after(20), Outcome: DeliveryOutcomeAccepted},
"accepted with spaces in ID": {At: after(20), Outcome: DeliveryOutcomeAccepted, ProviderMessageID: "an id"},
"accepted with provider code": {At: after(20), Outcome: DeliveryOutcomeAccepted, ProviderMessageID: testMessageID, ProviderCode: "validation_error"},
"accepted with next attempt": {At: after(20), Outcome: DeliveryOutcomeAccepted, ProviderMessageID: testMessageID, NextAttemptAt: after(30)},
"rejected without reason": {At: after(20), Outcome: DeliveryOutcomeRejected},
"rejected with unknown reason": {At: after(20), Outcome: DeliveryOutcomeRejected, Rejection: "bounced"},
"rejected with message ID": {At: after(20), Outcome: DeliveryOutcomeRejected, Rejection: DeliveryRejectionPermanent, ProviderMessageID: testMessageID},
"permanent with next attempt": {At: after(20), Outcome: DeliveryOutcomeRejected, Rejection: DeliveryRejectionPermanent, NextAttemptAt: after(30)},
"temporary without next": {At: after(20), Outcome: DeliveryOutcomeRejected, Rejection: DeliveryRejectionTemporary},
"next before the attempt": {At: after(20), Outcome: DeliveryOutcomeRejected, Rejection: DeliveryRejectionTemporary, NextAttemptAt: after(15)},
"unknown with a rejection": {At: after(20), Outcome: DeliveryOutcomeUnknown, Rejection: DeliveryRejectionTemporary},
"provider free text": {At: after(20), Outcome: DeliveryOutcomeUnknown, ProviderCode: "Upstream said: no"},
"negative retry-after": {At: after(20), Outcome: DeliveryOutcomeUnknown, RetryAfter: -time.Second},
"oversized provider message ID": {At: after(20), Outcome: DeliveryOutcomeAccepted, ProviderMessageID: strings.Repeat("a", 129)},
}
for name, input := range tests {
t.Run(name, func(t *testing.T) {
if _, _, err := delivery.RecordAttempt(input); !errors.Is(err, ErrInvalidDelivery) {
t.Fatalf("RecordAttempt() error = %v, want ErrInvalidDelivery", err)
}
})
}
if _, _, err := (Delivery{}).RecordAttempt(DeliveryAttemptInput{At: after(20), Outcome: DeliveryOutcomeUnknown}); !errors.Is(err, ErrInvalidDelivery) {
t.Fatalf("RecordAttempt() on a zero delivery error = %v, want ErrInvalidDelivery", err)
}
}
func deliverySnapshot(delivery Delivery) DeliverySnapshot {
return DeliverySnapshot{
ID: delivery.ID(),
SourceEventID: delivery.SourceEventID(),
RecipientUserID: delivery.RecipientUserID(),
RecipientAddress: delivery.Recipient().Address(),
Content: delivery.Content(),
ProviderAccount: delivery.ProviderAccount(),
IdempotencyKey: delivery.IdempotencyKey(),
Status: delivery.Status(),
AttemptCount: delivery.AttemptCount(),
NextAttemptAt: delivery.NextAttemptAt(),
LastAttemptAt: delivery.LastAttemptAt(),
ProviderMessageID: delivery.ProviderMessageID(),
Version: delivery.Version(),
CreatedAt: delivery.CreatedAt(),
UpdatedAt: delivery.UpdatedAt(),
}
}
func TestRestoreDeliveryChecksTheStoredInvariants(t *testing.T) {
accepted := mustRecord(t, newTestDelivery(t), DeliveryAttemptInput{At: after(1), Outcome: DeliveryOutcomeAccepted, ProviderMessageID: testMessageID})
restored, err := RestoreDelivery(deliverySnapshot(accepted))
if err != nil {
t.Fatalf("RestoreDelivery() error = %v", err)
}
if restored.Status() != DeliveryStatusAccepted || restored.ProviderMessageID() != testMessageID ||
restored.Recipient().Normalized() != strings.ToLower(testDeliveryAddress) || restored.Version() != accepted.Version() {
t.Fatal("RestoreDelivery() did not keep the stored state")
}
tests := map[string]func(*DeliverySnapshot){
"unknown status": func(snapshot *DeliverySnapshot) { snapshot.Status = "sent" },
"accepted without message ID": func(snapshot *DeliverySnapshot) { snapshot.ProviderMessageID = "" },
"terminal with next attempt": func(snapshot *DeliverySnapshot) { snapshot.NextAttemptAt = after(5) },
"pending without next": func(snapshot *DeliverySnapshot) {
snapshot.Status, snapshot.ProviderMessageID = DeliveryStatusPending, ""
},
"attempts without last time": func(snapshot *DeliverySnapshot) { snapshot.LastAttemptAt = time.Time{} },
"zero version": func(snapshot *DeliverySnapshot) { snapshot.Version = 0 },
"empty idempotency key": func(snapshot *DeliverySnapshot) { snapshot.IdempotencyKey = "" },
"updated before creation": func(snapshot *DeliverySnapshot) { snapshot.UpdatedAt = testDeliveryCreated.Add(-time.Second) },
"empty recipient": func(snapshot *DeliverySnapshot) { snapshot.RecipientAddress = "" },
}
for name, change := range tests {
t.Run(name, func(t *testing.T) {
snapshot := deliverySnapshot(accepted)
change(&snapshot)
if _, err := RestoreDelivery(snapshot); err == nil {
t.Fatal("RestoreDelivery() accepted a broken row")
}
})
}
}
func TestRestoreDeliveryAttemptChecksTheStatusAfter(t *testing.T) {
_, attempt, err := newTestDelivery(t).RecordAttempt(DeliveryAttemptInput{
At: after(1), Outcome: DeliveryOutcomeRejected, Rejection: DeliveryRejectionRateLimited, RetryAfter: 2 * time.Second, NextAttemptAt: after(2),
})
if err != nil {
t.Fatalf("RecordAttempt() error = %v", err)
}
if _, err := RestoreDeliveryAttempt(attempt); err != nil {
t.Fatalf("RestoreDeliveryAttempt() error = %v", err)
}
attempt.StatusAfter = DeliveryStatusRejected
if _, err := RestoreDeliveryAttempt(attempt); !errors.Is(err, ErrInvalidDelivery) {
t.Fatalf("RestoreDeliveryAttempt(mismatched status) error = %v, want ErrInvalidDelivery", err)
}
}
// deliveryHolder has the delivery in an unexported field, where fmt does not
// call its methods.
type deliveryHolder struct {
delivery Delivery
content MailContent
}
func TestDeliveryNeverPrintsTheRecipientOrContent(t *testing.T) {
delivery := newTestDelivery(t)
holder := deliveryHolder{delivery: delivery, content: delivery.Content()}
var output bytes.Buffer
for _, format := range []string{"%v", "%+v", "%#v", "%s", "%q"} {
fmt.Fprintf(&output, format+"\n", delivery)
fmt.Fprintf(&output, format+"\n", delivery.Content())
}
// For an enclosing struct fmt prints the pointer fields as addresses with
// the value verbs. Other verbs report a bad verb with the pointee, the
// known limit shared with EmailAddress and SecretToken.
for _, format := range []string{"%v", "%+v", "%#v"} {
fmt.Fprintf(&output, format+"\n", holder)
fmt.Fprintf(&output, format+"\n", &holder)
}
for _, logger := range []*slog.Logger{
slog.New(slog.NewTextHandler(&output, nil)),
slog.New(slog.NewJSONHandler(&output, nil)),
} {
logger.Info("delivery", "delivery", delivery, "content", delivery.Content(), "holder", holder)
}
printed := output.String()
for _, secret := range []string{
testDeliveryAddress, strings.ToLower(testDeliveryAddress), testDeliverySubject, "SyntheticToken", "private detail",
delivery.RecipientUserID().String(),
} {
if strings.Contains(printed, secret) {
t.Fatalf("printed delivery contains %q:\n%s", secret, printed)
}
}
for _, expected := range []string{delivery.ID().String(), "verification.v1", "pending", "resend"} {
if !strings.Contains(printed, expected) {
t.Fatalf("printed delivery lacks the bounded field %q:\n%s", expected, printed)
}
}
}
func TestNewDeliveryKeepsTheSourceEvent(t *testing.T) {
input := testDeliveryInput(t)
if delivery := newTestDelivery(t); delivery.SourceEventID() != uuid.Nil {
t.Fatal("a delivery without a source event names one")
}
input.SourceEventID = uuid.MustParse("01926f3a-7c00-7000-8000-0000000000ee")
delivery, err := NewDelivery(input)
if err != nil || delivery.SourceEventID() != input.SourceEventID {
t.Fatalf("NewDelivery() = %v, %v; want the source event kept", delivery, err)
}
restored, err := RestoreDelivery(deliverySnapshot(delivery))
if err != nil || restored.SourceEventID() != input.SourceEventID {
t.Fatalf("RestoreDelivery() = %v, %v; want the source event kept", restored, err)
}
}
func TestWaitForQuotaParksWithoutAnAttempt(t *testing.T) {
pending := newTestDelivery(t)
for name, until := range map[string]time.Time{"known reset": after(60), "unknown reset": {}} {
t.Run(name, func(t *testing.T) {
waiting, err := pending.WaitForQuota(after(1), until)
if err != nil {
t.Fatalf("WaitForQuota() error = %v", err)
}
if waiting.Status() != DeliveryStatusWaitingQuota || !waiting.NextAttemptAt().Equal(until) ||
waiting.AttemptCount() != 0 || waiting.Version() != 2 || !waiting.UpdatedAt().Equal(after(1)) {
t.Fatalf("waiting delivery = %s due %s with %d attempts at version %d", waiting.Status(), waiting.NextAttemptAt(), waiting.AttemptCount(), waiting.Version())
}
if _, err := RestoreDelivery(deliverySnapshot(waiting)); err != nil {
t.Fatalf("RestoreDelivery(waiting) error = %v", err)
}
// A later decision may move the reset again.
if moved, err := waiting.WaitForQuota(after(2), after(90)); err != nil || !moved.NextAttemptAt().Equal(after(90)) {
t.Fatalf("second WaitForQuota() = %s, %v", moved.NextAttemptAt(), err)
}
})
}
unknown := mustRecord(t, pending, DeliveryAttemptInput{At: after(1), Outcome: DeliveryOutcomeUnknown})
accepted := mustRecord(t, pending, DeliveryAttemptInput{At: after(1), Outcome: DeliveryOutcomeAccepted, ProviderMessageID: testMessageID})
for name, delivery := range map[string]Delivery{"unknown": unknown, "accepted": accepted} {
if _, err := delivery.WaitForQuota(after(5), after(60)); !errors.Is(err, ErrDeliveryTransition) {
t.Fatalf("WaitForQuota() on %s error = %v, want ErrDeliveryTransition", name, err)
}
}
for name, times := range map[string][2]time.Time{
"reset before the decision": {after(5), after(4)},
"decision before the change": {testDeliveryCreated.Add(-time.Minute), after(4)},
"zero decision time": {{}, after(4)},
} {
if _, err := pending.WaitForQuota(times[0], times[1]); !errors.Is(err, ErrInvalidDelivery) {
t.Fatalf("WaitForQuota() with %s error = %v, want ErrInvalidDelivery", name, err)
}
}
// An attempt after the wait must not precede the wait.
waiting, err := pending.WaitForQuota(after(10), time.Time{})
if err != nil {
t.Fatalf("WaitForQuota() error = %v", err)
}
if _, _, err := waiting.RecordAttempt(DeliveryAttemptInput{At: after(5), Outcome: DeliveryOutcomeUnknown}); !errors.Is(err, ErrInvalidDelivery) {
t.Fatalf("RecordAttempt() before the wait error = %v, want ErrInvalidDelivery", err)
}
}
func TestRebindIsAllowedOnlyBeforeTheFirstAttempt(t *testing.T) {
pending := newTestDelivery(t)
other, err := NewMailProviderAccount("resend", "eu")
if err != nil {
t.Fatalf("NewMailProviderAccount() error = %v", err)
}
rebound, err := pending.Rebind(after(1), other)
if err != nil {
t.Fatalf("Rebind() error = %v", err)
}
if rebound.ProviderAccount() != other || rebound.Version() != 2 || rebound.IdempotencyKey() != pending.IdempotencyKey() ||
rebound.Status() != DeliveryStatusPending || !rebound.NextAttemptAt().Equal(pending.NextAttemptAt()) {
t.Fatal("Rebind() changed more than the provider account and version")
}
if waiting, err := pending.WaitForQuota(after(1), time.Time{}); err != nil {
t.Fatalf("WaitForQuota() error = %v", err)
} else if _, err := waiting.Rebind(after(2), other); err != nil {
t.Fatalf("Rebind() of a waiting delivery without attempts error = %v", err)
}
if _, err := pending.Rebind(after(1), MailProviderAccount{}); !errors.Is(err, ErrInvalidDelivery) {
t.Fatalf("Rebind(zero account) error = %v, want ErrInvalidDelivery", err)
}
attempted := mustRecord(t, pending, DeliveryAttemptInput{At: after(1), Outcome: DeliveryOutcomeRejected, Rejection: DeliveryRejectionTemporary, NextAttemptAt: after(2)})
if _, err := attempted.Rebind(after(3), other); !errors.Is(err, ErrDeliveryTransition) {
t.Fatalf("Rebind() after an attempt error = %v, want ErrDeliveryTransition", err)
}
}
+214
View File
@@ -0,0 +1,214 @@
package domain
import (
"crypto/sha256"
"crypto/subtle"
"encoding/hex"
"errors"
"fmt"
"io"
"log/slog"
"regexp"
"strings"
"unicode/utf8"
)
const (
// maxMailSubjectRunes matches the rendered subject bound of the mail
// templates; a longer stored subject is not a rendering.
maxMailSubjectRunes = 150
// maxMailPartBytes bounds one stored body part. Rendered service mail is
// a few kilobytes; the bound keeps a broken renderer from filling a row.
maxMailPartBytes = 256 << 10
// MailContentHashSize is the size of the SHA-256 content digest.
MailContentHashSize = sha256.Size
)
var (
// ErrInvalidMailContent reports content that no transport could send or
// that does not belong to its kind. Errors name the rule, never the text.
ErrInvalidMailContent = errors.New("invalid mail content")
// ErrMailContentIntegrity reports stored content whose parts no longer
// match the stored digest: the row was changed outside the application.
ErrMailContentIntegrity = errors.New("mail content does not match its hash")
// "<kind>.v<N>", the template version naming of the mail templates.
mailTemplateVersionPattern = regexp.MustCompile(`^[a-z][a-z_]*\.v[1-9][0-9]{0,8}$`)
)
// MailKind names what a message is for. The values equal the template kinds
// of the mail templates.
type MailKind string
const (
MailKindVerification MailKind = "verification"
MailKindPasswordReset MailKind = "password_reset"
MailKindNotification MailKind = "notification"
)
// ParseMailKind accepts a known kind.
func ParseMailKind(value string) (MailKind, error) {
switch kind := MailKind(value); kind {
case MailKindVerification, MailKindPasswordReset, MailKindNotification:
return kind, nil
default:
return "", fmt.Errorf("domain.ParseMailKind - unknown mail kind: %w", ErrInvalidMailContent)
}
}
// CarriesBearerToken reports kinds whose body holds a one-time bearer token
// in a link. Their stored bodies are secrets until the token expires.
func (kind MailKind) CarriesBearerToken() bool {
return kind == MailKindVerification || kind == MailKindPasswordReset
}
// MailContentHash is SHA-256 over the template version, subject, text part,
// and HTML part, each encoded as a netstring ("<len>:<part>,"), so moving
// bytes from one part to the next changes the digest. The mail templates and
// stored deliveries use this one definition.
func MailContentHash(templateVersion, subject, text, html string) [MailContentHashSize]byte {
digest := sha256.New()
for _, part := range []string{templateVersion, subject, text, html} {
// hash.Hash.Write never returns an error.
_, _ = fmt.Fprintf(digest, "%d:", len(part))
_, _ = io.WriteString(digest, part)
_, _ = io.WriteString(digest, ",")
}
var sum [MailContentHashSize]byte
copy(sum[:], digest.Sum(nil))
return sum
}
// MailContent is one immutable rendered message: its kind, template version,
// subject, plain-text part, HTML part, and content hash. A body of a kind
// that CarriesBearerToken holds a live token.
//
// The parts sit behind a pointer with read-only accessors, so printing an
// enclosing struct shows only an address. String, GoString, Format, and
// LogValue show the kind, version, and hash, never the subject or bodies.
type MailContent struct {
value *mailContentValue
}
type mailContentValue struct {
kind MailKind
templateVersion string
subject string
text string
html string
hash [MailContentHashSize]byte
}
// NewMailContent validates a rendering and computes its hash. The template
// version must name the kind ("<kind>.v<N>"), the subject must be one line
// of 1 to 150 characters, and at least one body part must be non-blank.
func NewMailContent(kind MailKind, templateVersion, subject, text, html string) (MailContent, error) {
if _, err := ParseMailKind(string(kind)); err != nil {
return MailContent{}, fmt.Errorf("domain.NewMailContent - validate kind: %w", err)
}
if err := validateMailContent(kind, templateVersion, subject, text, html); err != nil {
return MailContent{}, err
}
return MailContent{value: &mailContentValue{
kind: kind,
templateVersion: templateVersion,
subject: subject,
text: text,
html: html,
hash: MailContentHash(templateVersion, subject, text, html),
}}, nil
}
// RestoreMailContent rebuilds stored content and checks it against the
// stored hash. A mismatch wraps ErrMailContentIntegrity.
func RestoreMailContent(kind MailKind, templateVersion, subject, text, html string, hash []byte) (MailContent, error) {
content, err := NewMailContent(kind, templateVersion, subject, text, html)
if err != nil {
return MailContent{}, fmt.Errorf("domain.RestoreMailContent - validate stored content: %w", err)
}
stored := content.value.hash
if subtle.ConstantTimeCompare(hash, stored[:]) != 1 {
return MailContent{}, fmt.Errorf("domain.RestoreMailContent - %w", ErrMailContentIntegrity)
}
return content, nil
}
func validateMailContent(kind MailKind, templateVersion, subject, text, html string) error {
switch {
case !mailTemplateVersionPattern.MatchString(templateVersion) || !strings.HasPrefix(templateVersion, string(kind)+".v"):
return invalidMailContent("template version must be <kind>.v<N> of the content kind")
case !utf8.ValidString(subject) || !utf8.ValidString(text) || !utf8.ValidString(html):
return invalidMailContent("subject and body parts must be valid UTF-8")
case strings.TrimSpace(subject) == "" || utf8.RuneCountInString(subject) > maxMailSubjectRunes:
return invalidMailContent(fmt.Sprintf("subject must have 1 to %d characters", maxMailSubjectRunes))
// A control character in the subject could inject header lines.
case strings.ContainsFunc(subject, isMailControlCharacter):
return invalidMailContent("subject must not contain control characters")
case strings.TrimSpace(text) == "" && strings.TrimSpace(html) == "":
return invalidMailContent("text or HTML part must not be blank")
case len(text) > maxMailPartBytes || len(html) > maxMailPartBytes:
return invalidMailContent("body parts must have at most 256 KiB each")
// PostgreSQL text cannot store NUL.
case strings.ContainsRune(text, 0) || strings.ContainsRune(html, 0):
return invalidMailContent("body parts must not contain NUL characters")
}
return nil
}
func isMailControlCharacter(character rune) bool {
return character < ' ' || character == 0x7f
}
func invalidMailContent(reason string) error {
return fmt.Errorf("domain.NewMailContent - %s: %w", reason, ErrInvalidMailContent)
}
// IsZero reports content not built by NewMailContent or RestoreMailContent.
func (content MailContent) IsZero() bool { return content.value == nil }
func (content MailContent) Kind() MailKind { return content.read().kind }
func (content MailContent) TemplateVersion() string { return content.read().templateVersion }
func (content MailContent) Subject() string { return content.read().subject }
// Text returns the plain-text part. It may hold a bearer token; never log it.
func (content MailContent) Text() string { return content.read().text }
// HTML returns the HTML part. It may hold a bearer token; never log it.
func (content MailContent) HTML() string { return content.read().html }
// Hash returns the SHA-256 content digest. It is not secret: a digest over a
// body that holds a 256-bit token cannot be reversed.
func (content MailContent) Hash() [MailContentHashSize]byte { return content.read().hash }
func (content MailContent) read() mailContentValue {
if content.value == nil {
return mailContentValue{}
}
return *content.value
}
func (content MailContent) String() string {
if content.value == nil {
return "[empty mail content]"
}
return fmt.Sprintf("[mail content %s %s, redacted]", content.value.templateVersion, hex.EncodeToString(content.value.hash[:]))
}
func (content MailContent) GoString() string { return content.String() }
// Format applies String to every verb; without it %+v would print the fields.
func (content MailContent) Format(state fmt.State, _ rune) {
_, _ = state.Write([]byte(content.String()))
}
func (content MailContent) LogValue() slog.Value {
value := content.read()
return slog.GroupValue(
slog.String("kind", string(value.kind)),
slog.String("template_version", value.templateVersion),
slog.String("content_hash", hex.EncodeToString(value.hash[:])),
)
}
+102
View File
@@ -0,0 +1,102 @@
package domain
import (
"errors"
"fmt"
"log/slog"
"strings"
"time"
"unicode/utf8"
"github.com/google/uuid"
)
const (
// Raw caller text is bounded before the template normalizes it; the
// rendered subject and body have tighter template limits.
maxMailRequestSubjectRunes = 1000
maxMailRequestBodyRunes = 16000
maxMailRequestLinkPathSize = 256
redactedNotificationText = "[redacted notification text]"
)
// ErrInvalidMailRequest reports a mail request that cannot be stored.
// Errors name the rule, never the text.
var ErrInvalidMailRequest = errors.New("invalid mail request")
// NotificationText is the caller text of a notification mail: the subject,
// the body, and a path inside the application for the link. It is personal
// data addressed to the recipient, so String, GoString, Format, LogValue,
// and MarshalJSON redact it.
type NotificationText struct {
Subject string
Body string
LinkPath string
}
func (text NotificationText) String() string { return redactedNotificationText }
func (text NotificationText) GoString() string { return redactedNotificationText }
// Format redacts every verb; without it %+v would print the fields.
func (text NotificationText) Format(state fmt.State, _ rune) {
_, _ = state.Write([]byte(redactedNotificationText))
}
func (text NotificationText) LogValue() slog.Value { return slog.StringValue(redactedNotificationText) }
// MarshalJSON redacts the text, because slog and other encoders reach a
// nested struct through encoding/json. Nothing serializes the text as JSON.
func (text NotificationText) MarshalJSON() ([]byte, error) {
return []byte(`"` + redactedNotificationText + `"`), nil
}
// MailRequest is a stored request for one mail to one account. It lives in
// the database only until the delivery consumer turned it into a Delivery,
// so the event that announces it carries the request ID and no text.
// Deleting the account deletes a request that is still waiting.
type MailRequest struct {
ID uuid.UUID
RecipientUserID uuid.UUID
Kind MailKind
Notification NotificationText
CreatedAt time.Time
}
// NewMailRequest checks the storage rules of a request. Only notification
// mail is requested this way: mail with a one-time token is created in the
// transaction that issues the token. Whether the text renders is checked by
// the template, not here.
func NewMailRequest(request MailRequest) (MailRequest, error) {
text := request.Notification
switch {
case request.ID == uuid.Nil || request.RecipientUserID == uuid.Nil:
return MailRequest{}, invalidMailRequest("request and recipient user IDs must not be nil")
case request.Kind != MailKindNotification:
return MailRequest{}, invalidMailRequest("only notification mail can be requested")
case request.CreatedAt.IsZero():
return MailRequest{}, invalidMailRequest("creation time must be set")
case !utf8.ValidString(text.Subject) || !utf8.ValidString(text.Body) || !utf8.ValidString(text.LinkPath):
return MailRequest{}, invalidMailRequest("text must be valid UTF-8")
// PostgreSQL text cannot store NUL.
case strings.ContainsRune(text.Subject, 0) || strings.ContainsRune(text.Body, 0) || strings.ContainsRune(text.LinkPath, 0):
return MailRequest{}, invalidMailRequest("text must not contain NUL characters")
case utf8.RuneCountInString(text.Subject) > maxMailRequestSubjectRunes ||
utf8.RuneCountInString(text.Body) > maxMailRequestBodyRunes ||
len(text.LinkPath) > maxMailRequestLinkPathSize:
return MailRequest{}, invalidMailRequest("subject, body, or link path is too long")
}
return request, nil
}
// LogValue carries the IDs and kind only.
func (request MailRequest) LogValue() slog.Value {
return slog.GroupValue(
slog.String("mail_request_id", request.ID.String()),
slog.String("kind", string(request.Kind)),
)
}
func invalidMailRequest(reason string) error {
return fmt.Errorf("domain.NewMailRequest - %s: %w", reason, ErrInvalidMailRequest)
}
@@ -0,0 +1,68 @@
package domain
import (
"bytes"
"errors"
"fmt"
"log/slog"
"strings"
"testing"
"time"
"github.com/google/uuid"
)
func testMailRequest() MailRequest {
return MailRequest{
ID: uuid.MustParse("01926f3a-7c00-7000-8000-000000000101"),
RecipientUserID: uuid.MustParse("01926f3a-7c00-7000-8000-000000000102"),
Kind: MailKindNotification,
Notification: NotificationText{Subject: "PRIVATE-SUBJECT", Body: "PRIVATE-BODY", LinkPath: "/candidate/invitations"},
CreatedAt: time.Date(2026, 10, 6, 9, 0, 0, 0, time.UTC),
}
}
func TestNewMailRequestChecksTheStorageRules(t *testing.T) {
if _, err := NewMailRequest(testMailRequest()); err != nil {
t.Fatalf("NewMailRequest() error = %v", err)
}
tests := map[string]func(*MailRequest){
"nil ID": func(request *MailRequest) { request.ID = uuid.Nil },
"nil recipient": func(request *MailRequest) { request.RecipientUserID = uuid.Nil },
"token mail kind": func(request *MailRequest) { request.Kind = MailKindVerification },
"zero creation time": func(request *MailRequest) { request.CreatedAt = time.Time{} },
"NUL in the body": func(request *MailRequest) { request.Notification.Body += "\x00" },
"invalid UTF-8": func(request *MailRequest) { request.Notification.Subject = "\xff" },
"oversized body": func(request *MailRequest) {
request.Notification.Body = strings.Repeat("я", maxMailRequestBodyRunes+1)
},
"oversized link": func(request *MailRequest) {
request.Notification.LinkPath = "/" + strings.Repeat("a", maxMailRequestLinkPathSize)
},
}
for name, change := range tests {
t.Run(name, func(t *testing.T) {
request := testMailRequest()
change(&request)
if _, err := NewMailRequest(request); !errors.Is(err, ErrInvalidMailRequest) {
t.Fatalf("NewMailRequest() error = %v, want ErrInvalidMailRequest", err)
}
})
}
}
func TestMailRequestNeverPrintsItsText(t *testing.T) {
request := testMailRequest()
var output bytes.Buffer
for _, format := range []string{"%v", "%+v", "%#v", "%s"} {
fmt.Fprintf(&output, format+"\n", request)
fmt.Fprintf(&output, format+"\n", &request)
}
type holder struct{ Request MailRequest }
for _, logger := range []*slog.Logger{slog.New(slog.NewJSONHandler(&output, nil)), slog.New(slog.NewTextHandler(&output, nil))} {
logger.Info("request", "request", request, "holder", holder{Request: request})
}
if printed := output.String(); strings.Contains(printed, "PRIVATE") {
t.Fatalf("printed mail request contains its text:\n%s", printed)
}
}
@@ -0,0 +1,94 @@
package outbound
import (
"context"
"errors"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
var (
// ErrDeliveryNotFound reports that no delivery has the ID.
ErrDeliveryNotFound = errors.New("delivery not found")
// ErrDeliveryVersionConflict reports that RecordAttempt matched no row:
// another worker recorded an attempt first, or the delivery no longer
// exists. Nothing was written; read the delivery again.
ErrDeliveryVersionConflict = errors.New("delivery changed concurrently")
// ErrDeliveryContentImmutable reports a statement that tried to change
// the recipient, content, provider account, or idempotency key of a
// stored delivery, or a recorded attempt. The database refuses it; it
// signals a code defect.
ErrDeliveryContentImmutable = errors.New("delivery content is immutable")
// ErrDeliveryProviderPinned reports a statement that tried to change the
// provider account of a delivery after its first attempt. The database
// refuses it; domain.Delivery.Rebind refuses it first.
ErrDeliveryProviderPinned = errors.New("delivery provider account is pinned")
// ErrMailRequestNotFound reports that no mail request has the ID: it was
// already turned into a delivery, or its account was deleted.
ErrMailRequestNotFound = errors.New("mail request not found")
)
// DeliveryRepository stores mail deliveries and their attempts. UnitOfWork
// binds it to one transaction; an adapter may also provide it outside a
// transaction, where every call is its own statement. Errors never quote the
// recipient or the content.
type DeliveryRepository interface {
// Create stores a delivery built by domain.NewDelivery and reports
// created=true. When a delivery with the same ID exists, it stores
// nothing, keeps the stored content, and reports created=false. It
// returns an error wrapping ErrUserNotFound when the recipient account
// does not exist; the surrounding transaction is then aborted.
Create(ctx context.Context, delivery domain.Delivery) (created bool, err error)
// Get returns ErrDeliveryNotFound when no delivery has the ID, and an
// error wrapping domain.ErrMailContentIntegrity when the stored content
// no longer matches its hash.
Get(ctx context.Context, id uuid.UUID) (domain.Delivery, error)
// ListAttempts returns the recorded attempts in attempt order; an empty
// list for a delivery without attempts or an unknown ID.
ListAttempts(ctx context.Context, id uuid.UUID) ([]domain.DeliveryAttempt, error)
// RecordAttempt stores next and attempt as returned by
// domain.Delivery.RecordAttempt, atomically, when the stored version
// still equals the version before the attempt (next.Version() - 1).
// Otherwise it writes nothing and returns ErrDeliveryVersionConflict.
RecordAttempt(ctx context.Context, next domain.Delivery, attempt domain.DeliveryAttempt) error
// WaitForQuota stores next as returned by domain.Delivery.WaitForQuota,
// without an attempt record, when the stored version still equals
// next.Version() - 1. Otherwise it returns ErrDeliveryVersionConflict.
WaitForQuota(ctx context.Context, next domain.Delivery) error
// Rebind stores the provider account of next as returned by
// domain.Delivery.Rebind under the same version rule as WaitForQuota. A
// delivery that has an attempt meanwhile fails with
// ErrDeliveryVersionConflict; the database refuses a provider change
// after an attempt with ErrDeliveryProviderPinned.
Rebind(ctx context.Context, next domain.Delivery) error
}
// MailRequestRepository stores mail requests between the producer
// transaction and the consumer transaction that turns them into deliveries.
// Errors never quote the request text.
type MailRequestRepository interface {
// Create stores a request built by domain.NewMailRequest. It returns an
// error wrapping ErrUserNotFound when the recipient account does not
// exist; the surrounding transaction is then aborted.
Create(ctx context.Context, request domain.MailRequest) error
// Lock reads the request and locks it until the transaction ends. A
// concurrent caller waits and then gets ErrMailRequestNotFound when the
// first transaction deleted it.
Lock(ctx context.Context, id uuid.UUID) (domain.MailRequest, error)
// Delete removes the request; deleting a missing request is not an
// error.
Delete(ctx context.Context, id uuid.UUID) error
}
+5 -4
View File
@@ -59,7 +59,7 @@ var (
// therefore calls InvalidateActive before UpdateRegistration or Insert; the
// opposite order can deadlock against a concurrent confirmation. The only
// exception is DeleteUnverifiedRegisteredBefore, which locks the account
// before its tokens and sessions; it is safe because every lock it takes uses
// before its tokens, sessions, and deliveries; it is safe because every lock it takes uses
// SKIP LOCKED and never waits. A deadlock that still happens, for example
// between callers that ignore this order, aborts one transaction with
// ErrTransactionConflict, and the caller may retry it.
@@ -99,9 +99,10 @@ type UserRepository interface {
// DeleteUnverifiedRegisteredBefore deletes at most limit accounts that are
// unverified and were last registered before cutoff, oldest first, with
// their tokens and sessions, and returns how many it deleted. It never
// waits for a lock: an account whose row, token, or session is locked by
// another transaction is skipped and stays for the next run. A cleanup job
// their tokens, sessions, and mail deliveries, and returns how many it
// deleted. It never waits for a lock: an account whose row, token,
// session, or delivery is locked by another transaction is skipped and
// stays for the next run. A cleanup job
// repeats it until the result is below limit and runs again later.
DeleteUnverifiedRegisteredBefore(ctx context.Context, cutoff time.Time, limit int32) (int64, error)
}
@@ -50,6 +50,8 @@ type Transactor interface {
type UnitOfWork interface {
IdentityRepositories
Policies() PolicyRepository
Deliveries() DeliveryRepository
MailRequests() MailRequestRepository
Outbox() OutboxWriter
}
@@ -0,0 +1,199 @@
package notification
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/notification/mailtemplate"
)
// DeliveryConsumerName names the consumer group and scopes deduplication.
// Renaming it makes the consumer process every retained request again; the
// delivery IDs then keep the deliveries unique, but do not rename it lightly.
const DeliveryConsumerName = "notification_delivery"
// DeliveryHandler creates one Delivery for each notification.mail_requested
// event, in the consumer transaction that records the event as processed.
//
// The delivery ID is the request ID, so a duplicate event, a replayed dead
// letter, or a renamed consumer maps to the same delivery. The content is
// rendered once, here, and stored; a later template version does not change
// it. The request row is deleted in the same transaction, so its text lives
// only as long as it is needed.
type DeliveryHandler struct {
renderer NotificationRenderer
providerAccount domain.MailProviderAccount
clock func() time.Time
logger *slog.Logger
}
var _ inbound.EventHandler = (*DeliveryHandler)(nil)
// NewDeliveryHandler pins new deliveries to providerAccount, the transport
// and account configured when the event is handled. clock is the
// application clock for the creation time.
func NewDeliveryHandler(
renderer NotificationRenderer,
providerAccount domain.MailProviderAccount,
clock func() time.Time,
logger *slog.Logger,
) *DeliveryHandler {
return &DeliveryHandler{renderer: renderer, providerAccount: providerAccount, clock: clock, logger: logger}
}
func (*DeliveryHandler) ConsumerName() string { return DeliveryConsumerName }
func (*DeliveryHandler) Handles(eventType string) bool { return eventType == MailRequestedEventType }
// Handle turns the request into a delivery:
//
// - A request that breaks the event contract, data the template refuses,
// or an existing delivery under the same ID for another recipient or
// kind is rejected for good (inbound.ErrEventRejected).
// - A request that no longer exists, because it was already turned into a
// delivery or its account was deleted, is skipped.
// - A notification to an account whose address is not verified is skipped
// and its request deleted: notifications go only to confirmed addresses.
// - Storage errors are returned for a retry. That includes an account
// deleted after it was read, which aborts the insert; the retry then
// finds the request gone with the account and skips it.
//
// Errors and logs carry the delivery and event IDs, never the address or
// the notification text.
func (handler *DeliveryHandler) Handle(ctx context.Context, unit outbound.UnitOfWork, event outbound.ConsumedEvent) error {
const location = "DeliveryHandler.Handle"
payload, err := decodeMailRequest(event)
if err != nil {
return err
}
request, err := unit.MailRequests().Lock(ctx, payload.MailRequestID)
if errors.Is(err, outbound.ErrMailRequestNotFound) {
handler.logSkip(ctx, "mail request skipped because it was already handled or its account was deleted", event)
return nil
}
if err != nil {
return fmt.Errorf("%s - lock mail request: %w", location, err)
}
if string(request.Kind) != payload.Kind {
return fmt.Errorf("%s - event kind does not match the stored request: %w", location, inbound.ErrEventRejected)
}
recipient, err := unit.Users().GetByID(ctx, request.RecipientUserID)
if errors.Is(err, outbound.ErrUserNotFound) {
// The foreign key deletes a request with its account, so this is a
// defensive branch.
handler.logSkip(ctx, "mail request skipped because the recipient account does not exist", event)
return handler.finish(ctx, unit, request.ID)
}
if err != nil {
return fmt.Errorf("%s - read recipient account: %w", location, err)
}
if recipient.EmailVerifiedAt == nil {
handler.logSkip(ctx, "notification skipped because the recipient address is not verified", event)
return handler.finish(ctx, unit, request.ID)
}
content, err := handler.renderer.RenderNotification(mailtemplate.NotificationData{
Subject: request.Notification.Subject,
Body: request.Notification.Body,
LinkPath: request.Notification.LinkPath,
})
if errors.Is(err, mailtemplate.ErrInvalidTemplateData) || errors.Is(err, domain.ErrInvalidMailContent) {
return fmt.Errorf("%s - render notification: %w: %w", location, inbound.ErrEventRejected, err)
}
if err != nil {
return fmt.Errorf("%s - render notification: %w", location, err)
}
delivery, err := domain.NewDelivery(domain.NewDeliveryInput{
ID: request.ID,
SourceEventID: event.EventID,
RecipientUserID: recipient.ID,
Recipient: recipient.Email,
Content: content,
ProviderAccount: handler.providerAccount,
CreatedAt: handler.clock(),
})
if err != nil {
return fmt.Errorf("%s - build delivery: %w: %w", location, inbound.ErrEventRejected, err)
}
created, err := unit.Deliveries().Create(ctx, delivery)
if err != nil {
return fmt.Errorf("%s - store delivery: %w", location, err)
}
if !created {
if err := checkExistingDelivery(ctx, unit, request); err != nil {
return err
}
}
return handler.finish(ctx, unit, request.ID)
}
// checkExistingDelivery accepts a delivery stored earlier under the request
// ID only when it is for the same recipient and kind; its content stays as
// stored.
func checkExistingDelivery(ctx context.Context, unit outbound.UnitOfWork, request domain.MailRequest) error {
const location = "notification.checkExistingDelivery"
existing, err := unit.Deliveries().Get(ctx, request.ID)
if err != nil {
return fmt.Errorf("%s - read existing delivery: %w", location, err)
}
if existing.RecipientUserID() != request.RecipientUserID || existing.Kind() != request.Kind {
return fmt.Errorf("%s - a delivery for another recipient or kind has the request ID: %w", location, inbound.ErrEventRejected)
}
return nil
}
// finish deletes the handled request in the consumer transaction.
func (handler *DeliveryHandler) finish(ctx context.Context, unit outbound.UnitOfWork, requestID uuid.UUID) error {
if err := unit.MailRequests().Delete(ctx, requestID); err != nil {
return fmt.Errorf("DeliveryHandler.finish - delete mail request: %w", err)
}
return nil
}
func (handler *DeliveryHandler) logSkip(ctx context.Context, message string, event outbound.ConsumedEvent) {
handler.logger.InfoContext(ctx, message,
slog.String("delivery_id", event.AggregateID.String()),
slog.String("event_id", event.EventID.String()))
}
// decodeMailRequest checks the envelope and payload of a version 1 request.
// Errors name the broken rule and never quote the payload.
func decodeMailRequest(event outbound.ConsumedEvent) (mailRequestedPayload, error) {
const location = "notification.decodeMailRequest"
rejected := func(reason string) error {
return fmt.Errorf("%s - %s: %w", location, reason, inbound.ErrEventRejected)
}
if event.SchemaVersion != mailRequestedSchemaVersion {
return mailRequestedPayload{}, rejected(fmt.Sprintf("schema version %d is not supported", event.SchemaVersion))
}
if event.AggregateType != mailRequestAggregateType || event.AggregateID == uuid.Nil {
return mailRequestedPayload{}, rejected("aggregate must be a mail_request with an ID")
}
var payload mailRequestedPayload
decoder := json.NewDecoder(bytes.NewReader(event.Payload))
// The decoder error can quote a fragment of the payload, so it is not
// wrapped. A second value after the object is refused as well.
if err := decoder.Decode(&payload); err != nil {
return mailRequestedPayload{}, rejected("payload is not a valid mail request")
}
if _, err := decoder.Token(); !errors.Is(err, io.EOF) {
return mailRequestedPayload{}, rejected("payload has data after the mail request")
}
switch {
case payload.MailRequestID != event.AggregateID:
return mailRequestedPayload{}, rejected("mail_request_id must equal the aggregate ID")
case payload.Kind != string(domain.MailKindNotification):
return mailRequestedPayload{}, rejected("kind must be notification in schema version 1")
}
return payload, nil
}
@@ -0,0 +1,148 @@
// Package notification turns mail requests into durable deliveries.
//
// A product usecase requests a notification mail inside its own transaction
// with MailRequester, which stores the request text in mail_requests and
// appends a notification.mail_requested event that names only the request.
// DeliveryHandler consumes the event and, in the transaction of the
// consumer's dedup marker, reads the request, resolves the recipient address
// from the account, renders the current template version once, stores the
// Delivery, and deletes the request. Sending the stored content is the job
// of the delivery worker, which is planned.
package notification
import (
"context"
"encoding/json"
"fmt"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/notification/mailtemplate"
)
const (
// MailRequestedEventType announces a stored mail request.
MailRequestedEventType = "notification.mail_requested"
// mailRequestedSchemaVersion 1 is mailRequestedPayload.
mailRequestedSchemaVersion = 1
// mailRequestAggregateType names the request. Its aggregate ID is the
// request ID and the ID of the delivery it becomes; a request is never
// changed, so its version is 1.
mailRequestAggregateType = "mail_request"
mailRequestAggregateVersion = 1
)
// mailRequestedPayload is version 1 of the event payload. It names the
// request and its kind only. The text and the recipient stay in
// mail_requests, which the account's deletion removes, so neither the
// outbox table nor the event bus keeps personal data after the account is
// gone.
type mailRequestedPayload struct {
MailRequestID uuid.UUID `json:"mail_request_id"`
Kind string `json:"kind"`
}
// NotificationRenderer renders notification mail as the content a delivery
// stores.
type NotificationRenderer interface {
RenderNotification(data mailtemplate.NotificationData) (domain.MailContent, error)
}
// TemplateRenderer renders with the current versions of the embedded mail
// templates.
type TemplateRenderer struct {
renderer *mailtemplate.Renderer
}
func NewTemplateRenderer(renderer *mailtemplate.Renderer) TemplateRenderer {
return TemplateRenderer{renderer: renderer}
}
func (renderer TemplateRenderer) RenderNotification(data mailtemplate.NotificationData) (domain.MailContent, error) {
rendered, err := renderer.renderer.RenderNotification(data)
if err != nil {
return domain.MailContent{}, fmt.Errorf("TemplateRenderer.RenderNotification - render: %w", err)
}
content, err := rendered.Content()
if err != nil {
return domain.MailContent{}, fmt.Errorf("TemplateRenderer.RenderNotification - convert rendering: %w", err)
}
return content, nil
}
// NotificationRequest asks for one notification mail to one account.
type NotificationRequest struct {
RecipientUserID uuid.UUID
Notification mailtemplate.NotificationData
}
// MailRequester records mail requests in the caller's transaction.
type MailRequester struct {
renderer NotificationRenderer
clock func() time.Time
}
// NewMailRequester takes the renderer only to refuse data that the template
// would refuse at handling time, so a bad request fails its own transaction
// instead of becoming a dead letter later. clock is the application clock
// for the request time.
func NewMailRequester(renderer NotificationRenderer, clock func() time.Time) *MailRequester {
return &MailRequester{renderer: renderer, clock: clock}
}
// RequestNotification stores the request and appends a
// notification.mail_requested event through unit, which must be the caller's
// transaction, and returns the ID that the delivery will have. The mail is
// created only if that transaction commits. Invalid input returns an error
// wrapping domain.ErrInvalidMailRequest and writes nothing; an unknown
// recipient account returns an error wrapping outbound.ErrUserNotFound and
// aborts the transaction.
func (requester *MailRequester) RequestNotification(ctx context.Context, unit outbound.UnitOfWork, request NotificationRequest) (uuid.UUID, error) {
const location = "MailRequester.RequestNotification"
if _, err := requester.renderer.RenderNotification(request.Notification); err != nil {
return uuid.Nil, fmt.Errorf("%s - validate notification: %w: %w", location, domain.ErrInvalidMailRequest, err)
}
requestID, err := uuid.NewV7()
if err != nil {
return uuid.Nil, fmt.Errorf("%s - generate request ID: %w", location, err)
}
stored, err := domain.NewMailRequest(domain.MailRequest{
ID: requestID,
RecipientUserID: request.RecipientUserID,
Kind: domain.MailKindNotification,
Notification: domain.NotificationText{
Subject: request.Notification.Subject,
Body: request.Notification.Body,
LinkPath: request.Notification.LinkPath,
},
CreatedAt: requester.clock(),
})
if err != nil {
return uuid.Nil, fmt.Errorf("%s - build request: %w", location, err)
}
payload, err := json.Marshal(mailRequestedPayload{MailRequestID: requestID, Kind: string(domain.MailKindNotification)})
if err != nil {
return uuid.Nil, fmt.Errorf("%s - encode payload: %w", location, err)
}
event, err := domain.NewDomainEvent(domain.DomainEventInput{
EventType: MailRequestedEventType,
SchemaVersion: mailRequestedSchemaVersion,
AggregateType: mailRequestAggregateType,
AggregateID: requestID,
AggregateVersion: mailRequestAggregateVersion,
Payload: payload,
})
if err != nil {
return uuid.Nil, fmt.Errorf("%s - build event: %w", location, err)
}
if err := unit.MailRequests().Create(ctx, stored); err != nil {
return uuid.Nil, fmt.Errorf("%s - store request: %w", location, err)
}
if err := unit.Outbox().Append(ctx, event); err != nil {
return uuid.Nil, fmt.Errorf("%s - append event: %w", location, err)
}
return requestID, nil
}
@@ -1,7 +1,6 @@
package mailtemplate
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"log/slog"
@@ -15,7 +14,7 @@ import (
// the same digest, and any change to any part gives another one. The delivery
// layer can store it with the idempotency key to pin the body of one logical
// delivery and to detect a different body offered under the same key.
type ContentHash [sha256.Size]byte
type ContentHash [domain.MailContentHashSize]byte
// String returns the lowercase hex digest. It is not secret: SHA-256 over a
// body that holds a 256-bit token cannot be reversed.
@@ -50,7 +49,7 @@ func newRenderedMail(kind Kind, version TemplateVersion, subject, text, html str
subject: subject,
text: text,
html: html,
contentHash: contentHash(string(version), subject, text, html),
contentHash: ContentHash(domain.MailContentHash(string(version), subject, text, html)),
}}
}
@@ -78,6 +77,18 @@ func (mail RenderedMail) read() renderedContent {
return *mail.content
}
// Content returns the rendering as domain.MailContent, the form a delivery
// stores. The kinds and the hash are the same: both use
// domain.MailContentHash.
func (mail RenderedMail) Content() (domain.MailContent, error) {
content := mail.read()
stored, err := domain.NewMailContent(domain.MailKind(content.kind), string(content.version), content.subject, content.text, content.html)
if err != nil {
return domain.MailContent{}, fmt.Errorf("RenderedMail.Content - %w", err)
}
return stored, nil
}
// ToOutgoingMail addresses the rendering for the MailSender port. The
// recipient and the idempotency key come from the delivery, never from the
// template data.
@@ -13,7 +13,6 @@ package mailtemplate
import (
"bytes"
"crypto/sha256"
"embed"
"errors"
"fmt"
@@ -172,21 +171,6 @@ func finishPart(part string) string {
return strings.TrimSpace(part) + "\n"
}
// contentHash is SHA-256 over the parts encoded as netstrings ("<len>:<part>,"),
// so moving bytes from one part to the next changes the digest.
func contentHash(parts ...string) ContentHash {
digest := sha256.New()
for _, part := range parts {
// hash.Hash.Write never returns an error.
_, _ = fmt.Fprintf(digest, "%d:", len(part))
_, _ = io.WriteString(digest, part)
_, _ = io.WriteString(digest, ",")
}
var sum ContentHash
copy(sum[:], digest.Sum(nil))
return sum
}
// parseTemplates reads every file in the template directory. Each version
// must provide the subject, text, and HTML parts, and no other file may be
// present, so a misnamed file cannot be silently ignored.
@@ -306,9 +306,20 @@ func TestContentHashPinsTheBody(t *testing.T) {
if mail.ContentHash() != second[kind].ContentHash() {
t.Fatalf("%s content hash differs for the same version and data", kind)
}
if mail.ContentHash() != contentHash(string(mail.TemplateVersion()), mail.Subject(), mail.Text(), mail.HTML()) {
if mail.ContentHash() != ContentHash(domain.MailContentHash(string(mail.TemplateVersion()), mail.Subject(), mail.Text(), mail.HTML())) {
t.Fatalf("%s content hash does not cover the version, subject, and parts", kind)
}
// A delivery stores the rendering as domain.MailContent; both forms
// must name the same kind, version, parts, and hash.
content, err := mail.Content()
if err != nil {
t.Fatalf("%s Content() error = %v", kind, err)
}
if string(content.Kind()) != string(kind) || content.TemplateVersion() != string(mail.TemplateVersion()) ||
content.Subject() != mail.Subject() || content.Text() != mail.Text() || content.HTML() != mail.HTML() ||
ContentHash(content.Hash()) != mail.ContentHash() {
t.Fatalf("%s Content() does not carry the rendering", kind)
}
seen[mail.ContentHash()] = kind
}
if len(seen) != len(first) {
@@ -350,19 +361,6 @@ func TestContentHashPinsTheBody(t *testing.T) {
t.Fatalf("content hash did not change with the %s", change.name)
}
}
base := contentHash("verification.v1", "subject", "text", "html")
for name, other := range map[string]ContentHash{
"version": contentHash("verification.v2", "subject", "text", "html"),
"subject": contentHash("verification.v1", "subject!", "text", "html"),
"text": contentHash("verification.v1", "subject", "text!", "html"),
"html": contentHash("verification.v1", "subject", "text", "html!"),
"shifted border": contentHash("verification.v1", "subjec", "ttext", "html"),
} {
if other == base {
t.Fatalf("content hash ignores a change of the %s", name)
}
}
}
// TestRenderingNeverReachesLogs plays the render harness: it prints every
@@ -0,0 +1,453 @@
package notification
import (
"bytes"
"context"
"encoding/json"
"errors"
"log/slog"
"strings"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/notification/mailtemplate"
)
const (
testOrigin = "https://lincodex.example"
// The private markers must never reach logs, errors, or events.
testRecipientAddress = "Private.Recipient@Example.com"
testSubject = "PRIVATE-SUBJECT invitation"
testBody = "PRIVATE-BODY: a company invited you."
testLinkPath = "/candidate/invitations"
)
var (
testNow = time.Date(2026, 10, 6, 12, 0, 0, 0, time.UTC)
errStorageDown = errors.New("storage unavailable")
privateMarkers = []string{testRecipientAddress, strings.ToLower(testRecipientAddress), "PRIVATE-SUBJECT", "PRIVATE-BODY"}
)
type fakeUsers struct {
outbound.UserRepository
users map[uuid.UUID]domain.User
err error
}
func (users *fakeUsers) GetByID(_ context.Context, id uuid.UUID) (domain.User, error) {
if users.err != nil {
return domain.User{}, users.err
}
user, ok := users.users[id]
if !ok {
return domain.User{}, outbound.ErrUserNotFound
}
return user, nil
}
type fakeDeliveries struct {
outbound.DeliveryRepository
stored map[uuid.UUID]domain.Delivery
createErr error
}
func (deliveries *fakeDeliveries) Create(_ context.Context, delivery domain.Delivery) (bool, error) {
if deliveries.createErr != nil {
return false, deliveries.createErr
}
if _, ok := deliveries.stored[delivery.ID()]; ok {
return false, nil
}
deliveries.stored[delivery.ID()] = delivery
return true, nil
}
func (deliveries *fakeDeliveries) Get(_ context.Context, id uuid.UUID) (domain.Delivery, error) {
delivery, ok := deliveries.stored[id]
if !ok {
return domain.Delivery{}, outbound.ErrDeliveryNotFound
}
return delivery, nil
}
type fakeMailRequests struct {
stored map[uuid.UUID]domain.MailRequest
createErr error
}
func (requests *fakeMailRequests) Create(_ context.Context, request domain.MailRequest) error {
if requests.createErr != nil {
return requests.createErr
}
requests.stored[request.ID] = request
return nil
}
func (requests *fakeMailRequests) Lock(_ context.Context, id uuid.UUID) (domain.MailRequest, error) {
request, ok := requests.stored[id]
if !ok {
return domain.MailRequest{}, outbound.ErrMailRequestNotFound
}
return request, nil
}
func (requests *fakeMailRequests) Delete(_ context.Context, id uuid.UUID) error {
delete(requests.stored, id)
return nil
}
type recordingOutbox struct {
events []domain.DomainEvent
err error
}
func (outbox *recordingOutbox) Append(_ context.Context, events ...domain.DomainEvent) error {
if outbox.err != nil {
return outbox.err
}
outbox.events = append(outbox.events, events...)
return nil
}
// fakeUnit implements the repositories the usecases use; any other call
// panics on the nil embedded interface.
type fakeUnit struct {
outbound.UnitOfWork
users *fakeUsers
deliveries *fakeDeliveries
requests *fakeMailRequests
outbox *recordingOutbox
}
func (unit fakeUnit) Users() outbound.UserRepository { return unit.users }
func (unit fakeUnit) Deliveries() outbound.DeliveryRepository { return unit.deliveries }
func (unit fakeUnit) MailRequests() outbound.MailRequestRepository { return unit.requests }
func (unit fakeUnit) Outbox() outbound.OutboxWriter { return unit.outbox }
type harness struct {
recipient domain.User
unit fakeUnit
handler *DeliveryHandler
requester *MailRequester
logs *bytes.Buffer
}
func newHarness(t *testing.T) *harness {
t.Helper()
renderer, err := mailtemplate.NewRenderer(testOrigin)
if err != nil {
t.Fatalf("NewRenderer() error = %v", err)
}
email, err := domain.NewEmailAddress(testRecipientAddress)
if err != nil {
t.Fatalf("NewEmailAddress() error = %v", err)
}
providerAccount, err := domain.NewMailProviderAccount("resend", "main")
if err != nil {
t.Fatalf("NewMailProviderAccount() error = %v", err)
}
verifiedAt := testNow.Add(-time.Hour)
recipient := domain.User{ID: uuid.MustParse("01926f3a-7c00-7000-8000-0000000000aa"), Email: email, EmailVerifiedAt: &verifiedAt}
logs := &bytes.Buffer{}
templates := NewTemplateRenderer(renderer)
clock := func() time.Time { return testNow }
return &harness{
recipient: recipient,
unit: fakeUnit{
users: &fakeUsers{users: map[uuid.UUID]domain.User{recipient.ID: recipient}},
deliveries: &fakeDeliveries{stored: make(map[uuid.UUID]domain.Delivery)},
requests: &fakeMailRequests{stored: make(map[uuid.UUID]domain.MailRequest)},
outbox: &recordingOutbox{},
},
handler: NewDeliveryHandler(templates, providerAccount, clock, slog.New(slog.NewJSONHandler(logs, nil))),
requester: NewMailRequester(templates, clock),
logs: logs,
}
}
func testNotification() mailtemplate.NotificationData {
return mailtemplate.NotificationData{Subject: testSubject, Body: testBody, LinkPath: testLinkPath}
}
// request records a notification request and returns its event as the
// consumer receives it from the event bus.
func (h *harness) request(t *testing.T) outbound.ConsumedEvent {
t.Helper()
before := len(h.unit.outbox.events)
requestID, err := h.requester.RequestNotification(t.Context(), h.unit, NotificationRequest{
RecipientUserID: h.recipient.ID,
Notification: testNotification(),
})
if err != nil {
t.Fatalf("RequestNotification() error = %v", err)
}
if len(h.unit.outbox.events) != before+1 || h.unit.outbox.events[before].AggregateID() != requestID {
t.Fatalf("RequestNotification() did not append one event for request %s", requestID)
}
return consumedEvent(h.unit.outbox.events[before])
}
func consumedEvent(event domain.DomainEvent) outbound.ConsumedEvent {
return outbound.ConsumedEvent{
EventID: event.EventID(),
EventType: event.EventType(),
SchemaVersion: event.SchemaVersion(),
AggregateType: event.AggregateType(),
AggregateID: event.AggregateID(),
AggregateVersion: event.AggregateVersion(),
OccurredAt: testNow,
Payload: event.Payload(),
}
}
func (h *harness) assertNoPrivateData(t *testing.T, texts ...string) {
t.Helper()
for _, text := range append(texts, h.logs.String()) {
for _, marker := range privateMarkers {
if strings.Contains(text, marker) {
t.Fatalf("personal data %q reached an error, event, or log: %s", marker, text)
}
}
}
}
func TestRequestNotificationStoresTheTextAndAnnouncesOnlyIDs(t *testing.T) {
h := newHarness(t)
event := h.request(t)
if event.EventType != MailRequestedEventType || event.SchemaVersion != 1 ||
event.AggregateType != "mail_request" || event.AggregateVersion != 1 {
t.Fatalf("event = %s v%d %s/%d", event.EventType, event.SchemaVersion, event.AggregateType, event.AggregateVersion)
}
var payload map[string]any
if err := json.Unmarshal(event.Payload, &payload); err != nil {
t.Fatalf("decode payload: %v", err)
}
if len(payload) != 2 || payload["mail_request_id"] != event.AggregateID.String() || payload["kind"] != "notification" {
t.Fatalf("payload = %v, want only the request ID and the kind", payload)
}
h.assertNoPrivateData(t, string(event.Payload))
stored, ok := h.unit.requests.stored[event.AggregateID]
if !ok || stored.RecipientUserID != h.recipient.ID || stored.Kind != domain.MailKindNotification ||
stored.Notification.Subject != testSubject || stored.Notification.Body != testBody ||
stored.Notification.LinkPath != testLinkPath || !stored.CreatedAt.Equal(testNow) {
t.Fatal("the request text was not stored under the event's aggregate ID")
}
}
func TestRequestNotificationRefusesInvalidRequestsBeforeWriting(t *testing.T) {
h := newHarness(t)
hostileLink := testNotification()
hostileLink.LinkPath = "https://evil.example/phish"
nul := testNotification()
nul.Subject += "\x00"
tests := map[string]NotificationRequest{
"nil recipient": {Notification: testNotification()},
"link outside the app": {RecipientUserID: h.recipient.ID, Notification: hostileLink},
"empty notification": {RecipientUserID: h.recipient.ID},
"NUL in the subject": {RecipientUserID: h.recipient.ID, Notification: nul},
}
for name, request := range tests {
t.Run(name, func(t *testing.T) {
_, err := h.requester.RequestNotification(t.Context(), h.unit, request)
if !errors.Is(err, domain.ErrInvalidMailRequest) {
t.Fatalf("RequestNotification() error = %v, want ErrInvalidMailRequest", err)
}
if len(h.unit.outbox.events) != 0 || len(h.unit.requests.stored) != 0 {
t.Fatal("an invalid request was written")
}
h.assertNoPrivateData(t, err.Error())
})
}
h.unit.requests.createErr = outbound.ErrUserNotFound
_, err := h.requester.RequestNotification(t.Context(), h.unit, NotificationRequest{RecipientUserID: h.recipient.ID, Notification: testNotification()})
if !errors.Is(err, outbound.ErrUserNotFound) || len(h.unit.outbox.events) != 0 {
t.Fatalf("RequestNotification() for an unknown account error = %v, events = %d", err, len(h.unit.outbox.events))
}
}
func TestDeliveryHandlerStoresTheRenderedRequest(t *testing.T) {
h := newHarness(t)
event := h.request(t)
if h.handler.ConsumerName() != DeliveryConsumerName || !h.handler.Handles(event.EventType) || h.handler.Handles("identity.user_registered") {
t.Fatal("the handler does not claim exactly the mail request events")
}
if err := h.handler.Handle(t.Context(), h.unit, event); err != nil {
t.Fatalf("Handle() error = %v", err)
}
delivery, ok := h.unit.deliveries.stored[event.AggregateID]
if !ok || len(h.unit.deliveries.stored) != 1 {
t.Fatalf("Handle() stored %d deliveries, want one under the request ID", len(h.unit.deliveries.stored))
}
switch {
case delivery.SourceEventID() != event.EventID:
t.Fatal("the delivery does not name its source event")
case delivery.RecipientUserID() != h.recipient.ID || delivery.Recipient().Address() != testRecipientAddress:
t.Fatal("the delivery is not addressed to the account email")
case delivery.Kind() != domain.MailKindNotification || delivery.Content().TemplateVersion() != "notification.v1":
t.Fatalf("the delivery has kind %s and version %s", delivery.Kind(), delivery.Content().TemplateVersion())
case !strings.Contains(delivery.Content().Text(), "PRIVATE-BODY") || !strings.Contains(delivery.Content().Text(), testOrigin+testLinkPath):
t.Fatal("the stored body is not the rendering of the request")
case delivery.ProviderAccount().Provider() != "resend" || delivery.ProviderAccount().Account() != "main":
t.Fatal("the delivery is not pinned to the configured provider account")
case delivery.Status() != domain.DeliveryStatusPending || !delivery.CreatedAt().Equal(testNow):
t.Fatalf("the delivery is %s, created %s", delivery.Status(), delivery.CreatedAt())
}
if len(h.unit.requests.stored) != 0 {
t.Fatal("the handled request was not deleted")
}
// The same event again finds no request and keeps the first delivery.
if err := h.handler.Handle(t.Context(), h.unit, event); err != nil {
t.Fatalf("second Handle() error = %v", err)
}
if len(h.unit.deliveries.stored) != 1 {
t.Fatal("a repeated request created a second delivery")
}
h.assertNoPrivateData(t)
}
func TestDeliveryHandlerChecksAnExistingDeliveryUnderTheRequestID(t *testing.T) {
h := newHarness(t)
event := h.request(t)
request := h.unit.requests.stored[event.AggregateID]
// A delivery for the same recipient and kind is accepted as the result.
if err := h.handler.Handle(t.Context(), h.unit, event); err != nil {
t.Fatalf("Handle() error = %v", err)
}
h.unit.requests.stored[request.ID] = request
if err := h.handler.Handle(t.Context(), h.unit, event); err != nil {
t.Fatalf("Handle() over a matching delivery error = %v", err)
}
if len(h.unit.requests.stored) != 0 {
t.Fatal("the request was not deleted after the matching delivery")
}
// A delivery for another recipient under the same ID is a contract
// violation.
other := request
other.RecipientUserID = uuid.MustParse("01926f3a-7c00-7000-8000-0000000000bb")
h.unit.users.users[other.RecipientUserID] = domain.User{ID: other.RecipientUserID, Email: h.recipient.Email, EmailVerifiedAt: h.recipient.EmailVerifiedAt}
h.unit.requests.stored[request.ID] = other
err := h.handler.Handle(t.Context(), h.unit, event)
if !errors.Is(err, inbound.ErrEventRejected) {
t.Fatalf("Handle() over a delivery for another recipient error = %v, want ErrEventRejected", err)
}
h.assertNoPrivateData(t, err.Error())
}
func TestDeliveryHandlerRejectsBrokenRequestsWithoutQuotingThem(t *testing.T) {
h := newHarness(t)
valid := h.request(t)
tests := map[string]func(*outbound.ConsumedEvent){
"newer schema version": func(event *outbound.ConsumedEvent) { event.SchemaVersion = 2 },
"other aggregate": func(event *outbound.ConsumedEvent) { event.AggregateType = "user" },
"nil aggregate ID": func(event *outbound.ConsumedEvent) { event.AggregateID = uuid.Nil },
"payload not an object": func(event *outbound.ConsumedEvent) { event.Payload = json.RawMessage(`["PRIVATE-SUBJECT"]`) },
"trailing data": func(event *outbound.ConsumedEvent) {
event.Payload = append(append(json.RawMessage{}, event.Payload...), []byte(` {"PRIVATE-SUBJECT":1}`)...)
},
"request ID not the aggregate": func(event *outbound.ConsumedEvent) {
event.Payload = json.RawMessage(`{"mail_request_id":"01926f3a-7c00-7000-8000-0000000000cc","kind":"notification"}`)
},
"request ID not a UUID": func(event *outbound.ConsumedEvent) {
event.Payload = json.RawMessage(`{"mail_request_id":"PRIVATE-SUBJECT","kind":"notification"}`)
},
"token mail kind": func(event *outbound.ConsumedEvent) {
event.Payload = json.RawMessage(`{"mail_request_id":"` + event.AggregateID.String() + `","kind":"verification"}`)
},
}
for name, change := range tests {
t.Run(name, func(t *testing.T) {
event := valid
change(&event)
err := h.handler.Handle(t.Context(), h.unit, event)
if !errors.Is(err, inbound.ErrEventRejected) {
t.Fatalf("Handle() error = %v, want ErrEventRejected", err)
}
if len(h.unit.deliveries.stored) != 0 {
t.Fatal("a rejected request created a delivery")
}
h.assertNoPrivateData(t, err.Error())
})
}
t.Run("text the template refuses", func(t *testing.T) {
request := h.unit.requests.stored[valid.AggregateID]
request.Notification.LinkPath = "//evil.example/PRIVATE-SUBJECT"
h.unit.requests.stored[valid.AggregateID] = request
err := h.handler.Handle(t.Context(), h.unit, valid)
if !errors.Is(err, inbound.ErrEventRejected) || len(h.unit.deliveries.stored) != 0 {
t.Fatalf("Handle() error = %v, want ErrEventRejected and no delivery", err)
}
h.assertNoPrivateData(t, err.Error())
})
}
func TestDeliveryHandlerSkipsRequestsItMustNotDeliver(t *testing.T) {
tests := map[string]func(*harness, outbound.ConsumedEvent){
"request already gone": func(h *harness, event outbound.ConsumedEvent) {
delete(h.unit.requests.stored, event.AggregateID)
},
"account gone": func(h *harness, _ outbound.ConsumedEvent) {
delete(h.unit.users.users, h.recipient.ID)
},
"address not verified": func(h *harness, _ outbound.ConsumedEvent) {
unverified := h.recipient
unverified.EmailVerifiedAt = nil
h.unit.users.users[h.recipient.ID] = unverified
},
}
for name, change := range tests {
t.Run(name, func(t *testing.T) {
h := newHarness(t)
event := h.request(t)
change(h, event)
if err := h.handler.Handle(t.Context(), h.unit, event); err != nil {
t.Fatalf("Handle() error = %v, want the request skipped", err)
}
if len(h.unit.deliveries.stored) != 0 || len(h.unit.requests.stored) != 0 {
t.Fatal("a skipped request created a delivery or stayed stored")
}
if !strings.Contains(h.logs.String(), event.AggregateID.String()) || !strings.Contains(h.logs.String(), event.EventID.String()) {
t.Fatalf("the skip log does not name the delivery and event IDs: %s", h.logs.String())
}
h.assertNoPrivateData(t)
})
}
}
func TestDeliveryHandlerRetriesStorageFailures(t *testing.T) {
for name, change := range map[string]func(*fakeUnit){
"account read": func(unit *fakeUnit) { unit.users.err = errStorageDown },
"insert": func(unit *fakeUnit) { unit.deliveries.createErr = errStorageDown },
// The account was deleted between its read and the insert. The insert
// aborted the transaction, so the handler cannot skip here; the retry
// finds the request deleted with the account and skips it.
"account deleted before the insert": func(unit *fakeUnit) { unit.deliveries.createErr = outbound.ErrUserNotFound },
} {
t.Run(name, func(t *testing.T) {
h := newHarness(t)
event := h.request(t)
change(&h.unit)
err := h.handler.Handle(t.Context(), h.unit, event)
if err == nil || errors.Is(err, inbound.ErrEventRejected) {
t.Fatalf("Handle() error = %v, want a retryable storage error", err)
}
if len(h.unit.requests.stored) != 1 {
t.Fatal("a failed attempt deleted the request")
}
h.assertNoPrivateData(t, err.Error())
})
}
}