From 2db585fbff6933cf1c3b871cc96c0206999eb9ac Mon Sep 17 00:00:00 2001 From: shira Date: Tue, 6 Oct 2026 10:52:47 +0300 Subject: [PATCH] feat(notification): add durable mail delivery state --- .env.example | 4 + backend/config/config.go | 5 +- backend/config/mail.go | 13 + backend/config/mail_test.go | 12 +- .../db/migrations/00006_create_deliveries.sql | 295 +++++++++ backend/db/queries/delivery.sql | 203 ++++++ backend/db/queries/identity.sql | 45 +- backend/integration_test/delivery_test.go | 604 ++++++++++++++++++ backend/integration_test/identity_test.go | 4 +- .../postgres_migrations_test.go | 29 +- .../adapter/secondary/postgres/delivery.go | 345 ++++++++++ .../secondary/postgres/delivery_test.go | 63 ++ .../secondary/postgres/sqlc/delivery.sql.go | 446 +++++++++++++ .../secondary/postgres/sqlc/identity.sql.go | 45 +- .../adapter/secondary/postgres/sqlc/models.go | 47 ++ .../secondary/postgres/sqlc/querier.go | 46 +- backend/internal/bootstrap/consumers.go | 36 +- backend/internal/bootstrap/consumers_test.go | 22 +- backend/internal/domain/delivery.go | 600 +++++++++++++++++ backend/internal/domain/delivery_test.go | 526 +++++++++++++++ backend/internal/domain/mail_content.go | 214 +++++++ backend/internal/domain/mail_request.go | 102 +++ backend/internal/domain/mail_request_test.go | 68 ++ backend/internal/port/outbound/delivery.go | 94 +++ backend/internal/port/outbound/identity.go | 9 +- backend/internal/port/outbound/transaction.go | 2 + .../usecase/notification/delivery_handler.go | 199 ++++++ .../usecase/notification/mail_request.go | 148 +++++ .../notification/mailtemplate/rendered.go | 17 +- .../notification/mailtemplate/renderer.go | 16 - .../mailtemplate/renderer_test.go | 26 +- .../usecase/notification/notification_test.go | 453 +++++++++++++ deploy/docker/docker-compose.yml | 1 + docs/en/ARCHITECTURE.md | 77 ++- docs/en/DEPLOY.md | 19 +- docs/en/DEVELOPMENT.md | 12 +- docs/en/TESTING.md | 28 +- docs/ru/ARCHITECTURE.md | 77 ++- docs/ru/DEPLOY.md | 19 +- docs/ru/DEVELOPMENT.md | 12 +- docs/ru/TESTING.md | 28 +- 41 files changed, 4903 insertions(+), 108 deletions(-) create mode 100644 backend/db/migrations/00006_create_deliveries.sql create mode 100644 backend/db/queries/delivery.sql create mode 100644 backend/integration_test/delivery_test.go create mode 100644 backend/internal/adapter/secondary/postgres/delivery.go create mode 100644 backend/internal/adapter/secondary/postgres/delivery_test.go create mode 100644 backend/internal/adapter/secondary/postgres/sqlc/delivery.sql.go create mode 100644 backend/internal/domain/delivery.go create mode 100644 backend/internal/domain/delivery_test.go create mode 100644 backend/internal/domain/mail_content.go create mode 100644 backend/internal/domain/mail_request.go create mode 100644 backend/internal/domain/mail_request_test.go create mode 100644 backend/internal/port/outbound/delivery.go create mode 100644 backend/internal/usecase/notification/delivery_handler.go create mode 100644 backend/internal/usecase/notification/mail_request.go create mode 100644 backend/internal/usecase/notification/notification_test.go diff --git a/.env.example b/.env.example index b8679df..13c2e4d 100644 --- a/.env.example +++ b/.env.example @@ -28,6 +28,10 @@ KAFKA_CLUSTER_ID=SJv4PXUUSJGbK3eSPC57qA # address or skips an account check. EMAIL_PROVIDER=disabled EMAIL_FROM=no-reply@example.com +# Label of the provider account (lowercase letters, digits, ".", "_", "-"), +# never the key. Every new delivery is pinned to EMAIL_PROVIDER and this +# label; change it whenever the key belongs to another provider account. +EMAIL_ACCOUNT=default EMAIL_TIMEOUT=10s # Public origin for links in mail: https, or http only for a loopback host. APP_PUBLIC_URL=http://localhost:8080 diff --git a/backend/config/config.go b/backend/config/config.go index 8a55584..b6c8caa 100644 --- a/backend/config/config.go +++ b/backend/config/config.go @@ -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. diff --git a/backend/config/mail.go b/backend/config/mail.go index cb753e4..144831b 100644 --- a/backend/config/mail.go +++ b/backend/config/mail.go @@ -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 } diff --git a/backend/config/mail_test.go b/backend/config/mail_test.go index ed5fb4f..161e088 100644 --- a/backend/config/mail_test.go +++ b/backend/config/mail_test.go @@ -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) } diff --git a/backend/db/migrations/00006_create_deliveries.sql b/backend/db/migrations/00006_create_deliveries.sql new file mode 100644 index 0000000..e7d7f7b --- /dev/null +++ b/backend/db/migrations/00006_create_deliveries.sql @@ -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, + -- ".v", the immutable template version that rendered the body. + template_version text NOT NULL, + subject text NOT NULL, + text_body text NOT NULL, + html_body text NOT NULL, + -- SHA-256 over the version, subject, and both parts as netstrings; the + -- domain checks it on every read. + content_sha256 bytea NOT NULL, + -- Transport and provider account label from configuration; never a + -- credential. + provider text NOT NULL, + provider_account text NOT NULL, + -- Sent with every attempt; contains no personal data. + idempotency_key text NOT NULL, + status text NOT NULL, + attempt_count integer NOT NULL, + -- When the delivery is due; NULL when no automatic attempt is scheduled. + next_attempt_at timestamptz, + last_attempt_at timestamptz, + -- Set once the provider accepted the message. + provider_message_id text, + -- Optimistic concurrency version, advanced by every attempt. + version bigint NOT NULL, + created_at timestamptz NOT NULL, + updated_at timestamptz NOT NULL, + CONSTRAINT deliveries_pkey PRIMARY KEY (id), + CONSTRAINT deliveries_idempotency_key_key UNIQUE (idempotency_key), + -- Deleting an account deletes the copies of its address and the bodies + -- addressed to it. + CONSTRAINT deliveries_recipient_user_id_fkey FOREIGN KEY ( + recipient_user_id + ) REFERENCES users (id) ON DELETE CASCADE, + CONSTRAINT deliveries_recipient_email_ascii CHECK ( + char_length(recipient_email) BETWEEN 3 AND 254 + AND octet_length(recipient_email) = char_length(recipient_email) + ), + CONSTRAINT deliveries_kind_known CHECK ( + kind IN ('verification', 'password_reset', 'notification') + ), + CONSTRAINT deliveries_template_version_of_kind CHECK ( + template_version ~ '^[a-z][a-z_]*\.v[1-9][0-9]{0,8}$' + AND left(template_version, char_length(kind) + 2) = kind || '.v' + ), + CONSTRAINT deliveries_subject_length CHECK ( + char_length(subject) BETWEEN 1 AND 150 + ), + CONSTRAINT deliveries_body_present CHECK ( + text_body <> '' OR html_body <> '' + ), + CONSTRAINT deliveries_content_sha256_size CHECK ( + octet_length(content_sha256) = 32 + ), + CONSTRAINT deliveries_provider_format CHECK ( + provider ~ '^[a-z][a-z0-9_]{0,31}$' + ), + CONSTRAINT deliveries_provider_account_format CHECK ( + provider_account ~ '^[a-z0-9][a-z0-9._-]{0,63}$' + ), + -- PostgreSQL regular expressions bound repetition at 255, so the length + -- is checked separately. + CONSTRAINT deliveries_idempotency_key_format CHECK ( + char_length(idempotency_key) <= 256 + AND idempotency_key ~ '^[!-~]+$' + ), + CONSTRAINT deliveries_status_known CHECK ( + status IN ( + 'pending', 'accepted', 'rejected', 'unknown', 'waiting_quota' + ) + ), + -- pending is picked up again by the worker, so it says when; accepted + -- and rejected are terminal; unknown and waiting_quota may wait without + -- a time for a reconciliation, an unknown quota reset, or an operator. + CONSTRAINT deliveries_next_attempt_matches_status CHECK ( + (status = 'pending' AND next_attempt_at IS NOT NULL) + OR (status IN ('accepted', 'rejected') AND next_attempt_at IS NULL) + OR status IN ('unknown', 'waiting_quota') + ), + CONSTRAINT deliveries_provider_message_id_when_accepted CHECK ( + (status = 'accepted') = (provider_message_id IS NOT NULL) + AND ( + provider_message_id IS NULL + OR provider_message_id ~ '^[!-~]{1,128}$' + ) + ), + CONSTRAINT deliveries_attempts_counted CHECK ( + attempt_count >= 0 + AND (attempt_count = 0) = (last_attempt_at IS NULL) + ), + CONSTRAINT deliveries_version_positive CHECK (version > 0), + CONSTRAINT deliveries_timestamps_after_creation CHECK ( + updated_at >= created_at + AND (last_attempt_at IS NULL OR last_attempt_at >= created_at) + ) +); + +-- Serves the cascade from users and the account cleanup, which locks the +-- deliveries of each account it deletes. +CREATE INDEX deliveries_recipient_user_id_idx +ON deliveries (recipient_user_id); + +-- One row per transport attempt, appended in the transaction that advances +-- the delivery. Kept as history next to the counters on deliveries: the +-- worker reads the counters, while operators and the retry and quota rules +-- need every outcome, provider code, and wait hint. +CREATE TABLE delivery_attempts ( + delivery_id uuid NOT NULL, + -- 1 for the first attempt of the delivery. + attempt_number integer NOT NULL, + attempted_at timestamptz NOT NULL, + outcome text NOT NULL, + -- Set only for a rejected attempt. + rejection text, + -- Documented provider error name; never provider free text. + provider_code text, + provider_message_id text, + -- Provider or transport wait hint in nanoseconds, the exact Go + -- time.Duration; 0 when there was none. + retry_after_ns bigint NOT NULL, + status_after text NOT NULL, + next_attempt_at timestamptz, + CONSTRAINT delivery_attempts_pkey PRIMARY KEY ( + delivery_id, attempt_number + ), + CONSTRAINT delivery_attempts_delivery_id_fkey FOREIGN KEY ( + delivery_id + ) REFERENCES deliveries (id) ON DELETE CASCADE, + CONSTRAINT delivery_attempts_number_positive CHECK (attempt_number > 0), + CONSTRAINT delivery_attempts_outcome_known CHECK ( + outcome IN ('accepted', 'rejected', 'unknown') + ), + CONSTRAINT delivery_attempts_rejection_when_rejected CHECK ( + (outcome = 'rejected') = (rejection IS NOT NULL) + AND ( + rejection IS NULL + OR rejection IN ( + 'permanent', + 'invalid_request', + 'rate_limited', + 'quota_exhausted', + 'temporary' + ) + ) + ), + CONSTRAINT delivery_attempts_message_id_when_accepted CHECK ( + (outcome = 'accepted') = (provider_message_id IS NOT NULL) + AND ( + provider_message_id IS NULL + OR provider_message_id ~ '^[!-~]{1,128}$' + ) + ), + CONSTRAINT delivery_attempts_provider_code_format CHECK ( + provider_code ~ '^[a-z][a-z0-9_]{0,63}$' + ), + CONSTRAINT delivery_attempts_retry_after_not_negative CHECK ( + retry_after_ns >= 0 + ), + CONSTRAINT delivery_attempts_status_after_known CHECK ( + status_after IN ( + 'pending', 'accepted', 'rejected', 'unknown', 'waiting_quota' + ) + ), + CONSTRAINT delivery_attempts_next_after_attempt CHECK ( + next_attempt_at IS NULL OR next_attempt_at >= attempted_at + ) +); + +-- Refuses an UPDATE that changes what a delivery sends or where: the +-- recipient, the content, the idempotency key, the source event, and the +-- creation time. The provider account may change only while the delivery +-- has no attempt, because a provider that saw an attempt may hold the key. +-- The attempt state stays updatable. Errors use SQLSTATE 23000 and the +-- constraint names deliveries_content_immutable and +-- deliveries_provider_pinned, which the adapter maps without reading the +-- message; the messages quote no row values. +-- +goose StatementBegin +CREATE FUNCTION deliveries_refuse_content_change() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF ( + NEW.id, NEW.source_event_id, NEW.recipient_user_id, + NEW.recipient_email, NEW.kind, NEW.template_version, NEW.subject, + NEW.text_body, NEW.html_body, NEW.content_sha256, + NEW.idempotency_key, NEW.created_at + ) IS DISTINCT FROM ( + OLD.id, OLD.source_event_id, OLD.recipient_user_id, + OLD.recipient_email, OLD.kind, OLD.template_version, OLD.subject, + OLD.text_body, OLD.html_body, OLD.content_sha256, + OLD.idempotency_key, OLD.created_at + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'deliveries_content_immutable', + TABLE = 'deliveries', + MESSAGE = 'delivery content and recipient are immutable'; + END IF; + IF ( + (NEW.provider, NEW.provider_account) + IS DISTINCT FROM (OLD.provider, OLD.provider_account) + ) AND (OLD.attempt_count <> 0 OR NEW.attempt_count <> 0) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'deliveries_provider_pinned', + TABLE = 'deliveries', + MESSAGE = 'the provider account of a delivery is fixed after its first attempt'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER deliveries_refuse_content_change +BEFORE UPDATE ON deliveries +FOR EACH ROW EXECUTE FUNCTION deliveries_refuse_content_change(); + +-- Attempts are history: an UPDATE is refused. Deletes stay possible for the +-- cascade from an account and for a later retention rule. +-- +goose StatementBegin +CREATE FUNCTION delivery_attempts_refuse_update() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'delivery_attempts_immutable', + TABLE = 'delivery_attempts', + MESSAGE = 'delivery attempts are immutable'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER delivery_attempts_refuse_update +BEFORE UPDATE ON delivery_attempts +FOR EACH ROW EXECUTE FUNCTION delivery_attempts_refuse_update(); + +-- +goose Down +DROP TABLE delivery_attempts; +DROP TABLE deliveries; +DROP TABLE mail_requests; +DROP FUNCTION delivery_attempts_refuse_update(); +DROP FUNCTION deliveries_refuse_content_change(); diff --git a/backend/db/queries/delivery.sql b/backend/db/queries/delivery.sql new file mode 100644 index 0000000..756bc42 --- /dev/null +++ b/backend/db/queries/delivery.sql @@ -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); diff --git a/backend/db/queries/identity.sql b/backend/db/queries/identity.sql index d3e86ce..098d4b7 100644 --- a/backend/db/queries/identity.sql +++ b/backend/db/queries/identity.sql @@ -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 diff --git a/backend/integration_test/delivery_test.go b/backend/integration_test/delivery_test.go new file mode 100644 index 0000000..7fe6a4f --- /dev/null +++ b/backend/integration_test/delivery_test.go @@ -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", "

Текст новой версии шаблона.

\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) +} diff --git a/backend/integration_test/identity_test.go b/backend/integration_test/identity_test.go index 5c31764..3afd995 100644 --- a/backend/integration_test/identity_test.go +++ b/backend/integration_test/identity_test.go @@ -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) { diff --git a/backend/integration_test/postgres_migrations_test.go b/backend/integration_test/postgres_migrations_test.go index 782a6d0..ad13b9d 100644 --- a/backend/integration_test/postgres_migrations_test.go +++ b/backend/integration_test/postgres_migrations_test.go @@ -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) }) diff --git a/backend/internal/adapter/secondary/postgres/delivery.go b/backend/internal/adapter/secondary/postgres/delivery.go new file mode 100644 index 0000000..8ee123c --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/delivery.go @@ -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 +} diff --git a/backend/internal/adapter/secondary/postgres/delivery_test.go b/backend/internal/adapter/secondary/postgres/delivery_test.go new file mode 100644 index 0000000..5389d3f --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/delivery_test.go @@ -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) + } +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/delivery.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/delivery.sql.go new file mode 100644 index 0000000..5224a0b --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/sqlc/delivery.sql.go @@ -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 +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/identity.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/identity.sql.go index efe2bd7..cd2e656 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/identity.sql.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/identity.sql.go @@ -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 { diff --git a/backend/internal/adapter/secondary/postgres/sqlc/models.go b/backend/internal/adapter/secondary/postgres/sqlc/models.go index 7ef3966..1e67074 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/models.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/models.go @@ -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 diff --git a/backend/internal/adapter/secondary/postgres/sqlc/querier.go b/backend/internal/adapter/secondary/postgres/sqlc/querier.go index 660bbc7..9488935 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/querier.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/querier.go @@ -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 diff --git a/backend/internal/bootstrap/consumers.go b/backend/internal/bootstrap/consumers.go index 1bce698..5e3959e 100644 --- a/backend/internal/bootstrap/consumers.go +++ b/backend/internal/bootstrap/consumers.go @@ -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 diff --git a/backend/internal/bootstrap/consumers_test.go b/backend/internal/bootstrap/consumers_test.go index a2c64d3..6f80d01 100644 --- a/backend/internal/bootstrap/consumers_test.go +++ b/backend/internal/bootstrap/consumers_test.go @@ -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") } } diff --git a/backend/internal/domain/delivery.go b/backend/internal/domain/delivery.go new file mode 100644 index 0000000..f8f3967 --- /dev/null +++ b/backend/internal/domain/delivery.go @@ -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/". +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), + ) +} diff --git a/backend/internal/domain/delivery_test.go b/backend/internal/domain/delivery_test.go new file mode 100644 index 0000000..7e6e649 --- /dev/null +++ b/backend/internal/domain/delivery_test.go @@ -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 = "

HTML body with a private detail

\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) + } +} diff --git a/backend/internal/domain/mail_content.go b/backend/internal/domain/mail_content.go new file mode 100644 index 0000000..8b85028 --- /dev/null +++ b/backend/internal/domain/mail_content.go @@ -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") + + // ".v", 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 (":,"), 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 (".v"), 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 .v 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[:])), + ) +} diff --git a/backend/internal/domain/mail_request.go b/backend/internal/domain/mail_request.go new file mode 100644 index 0000000..81c7983 --- /dev/null +++ b/backend/internal/domain/mail_request.go @@ -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) +} diff --git a/backend/internal/domain/mail_request_test.go b/backend/internal/domain/mail_request_test.go new file mode 100644 index 0000000..15a7ae2 --- /dev/null +++ b/backend/internal/domain/mail_request_test.go @@ -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) + } +} diff --git a/backend/internal/port/outbound/delivery.go b/backend/internal/port/outbound/delivery.go new file mode 100644 index 0000000..2ab7118 --- /dev/null +++ b/backend/internal/port/outbound/delivery.go @@ -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 +} diff --git a/backend/internal/port/outbound/identity.go b/backend/internal/port/outbound/identity.go index 9bf69ca..cf8b4a7 100644 --- a/backend/internal/port/outbound/identity.go +++ b/backend/internal/port/outbound/identity.go @@ -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) } diff --git a/backend/internal/port/outbound/transaction.go b/backend/internal/port/outbound/transaction.go index 8988e97..aaabced 100644 --- a/backend/internal/port/outbound/transaction.go +++ b/backend/internal/port/outbound/transaction.go @@ -50,6 +50,8 @@ type Transactor interface { type UnitOfWork interface { IdentityRepositories Policies() PolicyRepository + Deliveries() DeliveryRepository + MailRequests() MailRequestRepository Outbox() OutboxWriter } diff --git a/backend/internal/usecase/notification/delivery_handler.go b/backend/internal/usecase/notification/delivery_handler.go new file mode 100644 index 0000000..033536f --- /dev/null +++ b/backend/internal/usecase/notification/delivery_handler.go @@ -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 +} diff --git a/backend/internal/usecase/notification/mail_request.go b/backend/internal/usecase/notification/mail_request.go new file mode 100644 index 0000000..f1d1510 --- /dev/null +++ b/backend/internal/usecase/notification/mail_request.go @@ -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 +} diff --git a/backend/internal/usecase/notification/mailtemplate/rendered.go b/backend/internal/usecase/notification/mailtemplate/rendered.go index 44b88c5..80d9531 100644 --- a/backend/internal/usecase/notification/mailtemplate/rendered.go +++ b/backend/internal/usecase/notification/mailtemplate/rendered.go @@ -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. diff --git a/backend/internal/usecase/notification/mailtemplate/renderer.go b/backend/internal/usecase/notification/mailtemplate/renderer.go index 5cbf2b3..4c1efc4 100644 --- a/backend/internal/usecase/notification/mailtemplate/renderer.go +++ b/backend/internal/usecase/notification/mailtemplate/renderer.go @@ -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 (":,"), -// 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. diff --git a/backend/internal/usecase/notification/mailtemplate/renderer_test.go b/backend/internal/usecase/notification/mailtemplate/renderer_test.go index 81944c6..2c8231e 100644 --- a/backend/internal/usecase/notification/mailtemplate/renderer_test.go +++ b/backend/internal/usecase/notification/mailtemplate/renderer_test.go @@ -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 diff --git a/backend/internal/usecase/notification/notification_test.go b/backend/internal/usecase/notification/notification_test.go new file mode 100644 index 0000000..5395a77 --- /dev/null +++ b/backend/internal/usecase/notification/notification_test.go @@ -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()) + }) + } +} diff --git a/deploy/docker/docker-compose.yml b/deploy/docker/docker-compose.yml index f1a33c0..bbffdcb 100644 --- a/deploy/docker/docker-compose.yml +++ b/deploy/docker/docker-compose.yml @@ -189,6 +189,7 @@ services: KAFKA_BROKERS: kafka:9092 EMAIL_PROVIDER: ${EMAIL_PROVIDER:?Set EMAIL_PROVIDER to resend, smtp, or disabled in the root .env file} EMAIL_FROM: ${EMAIL_FROM:?Set EMAIL_FROM in the root .env file} + EMAIL_ACCOUNT: ${EMAIL_ACCOUNT:-default} EMAIL_TIMEOUT: ${EMAIL_TIMEOUT:-10s} APP_PUBLIC_URL: ${APP_PUBLIC_URL:?Set APP_PUBLIC_URL in the root .env file} RESEND_API_KEY: ${RESEND_API_KEY:-} diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index 54533c1..02019b8 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -114,7 +114,7 @@ The metric `lincodex_outbox_relay_events_total{outcome}` counts published and fa ### Event consumers -Implemented (TASK-010): the consumer runtime in `backend/internal/worker/eventconsumer/`, the handler port `inbound.EventHandler` (`backend/internal/port/inbound/event_handler.go`), the `outbound.EventSource` and `outbound.EventConsumerStore` ports (`backend/internal/port/outbound/event_consumer.go`), the franz-go consumer group member (`adapter/secondary/kafka/consumer.go`), the PostgreSQL store (`adapter/secondary/postgres/event_consumer.go`), and migration `00005_create_event_consumer_tables.sql` with the `consumer_processed_events` and `consumer_dead_letters` tables. No product handler is registered: `eventHandlers()` in `backend/internal/bootstrap/consumers.go` returns an empty list, so the running backend starts no consumer and opens no consumer pool or Kafka group. The integration tests run the runtime with a test-only handler that writes into a table the test creates; there is no invented business effect. A product module adds its handler to that list. Settings are listed in [DEPLOY.md](DEPLOY.md#event-consumers). +Implemented (TASK-010): the consumer runtime in `backend/internal/worker/eventconsumer/`, the handler port `inbound.EventHandler` (`backend/internal/port/inbound/event_handler.go`), the `outbound.EventSource` and `outbound.EventConsumerStore` ports (`backend/internal/port/outbound/event_consumer.go`), the franz-go consumer group member (`adapter/secondary/kafka/consumer.go`), the PostgreSQL store (`adapter/secondary/postgres/event_consumer.go`), and migration `00005_create_event_consumer_tables.sql` with the `consumer_processed_events` and `consumer_dead_letters` tables. One product handler is registered (TASK-015): `eventHandlers()` in `backend/internal/bootstrap/consumers.go` returns the mail delivery handler `notification_delivery` described in [Mail deliveries](#mail-deliveries), so a backend with `CONSUMER_ENABLED` and `DATABASE_URL` runs one consumer in the group `.notification_delivery`. The runtime integration tests use a test-only handler that writes into a table the test creates. A product module adds its handler to that list. Settings are listed in [DEPLOY.md](DEPLOY.md#event-consumers). A handler implements three methods: @@ -154,7 +154,7 @@ The metric `lincodex_event_consumer_records_total{consumer,outcome}` counts fini ### Mail transport -Implemented: the outbound `MailSender` port (`backend/internal/port/outbound/mail.go`), the `disabled` transport (`adapter/secondary/mail/disabled/`), the Resend transport (`adapter/secondary/mail/resend/`, the primary provider for the working stand), and the transport selection in bootstrap. Usecases, templates, and domain events depend only on the port; `EMAIL_PROVIDER` selects exactly one transport (`resend`, `smtp`, or `disabled`), and bootstrap binds the port to it before migrations run. There is no fallback between transports: an unusable selection stops startup. Planned: an SMTP relay transport (`mail/smtp/`, TASK-014, outside the MVP); until it exists, `smtp` fails startup after its settings are validated. No flow calls the port yet; the delivery layer is planned. Settings are described in [DEPLOY.md](DEPLOY.md#mail). +Implemented: the outbound `MailSender` port (`backend/internal/port/outbound/mail.go`), the `disabled` transport (`adapter/secondary/mail/disabled/`), the Resend transport (`adapter/secondary/mail/resend/`, the primary provider for the working stand), and the transport selection in bootstrap. Usecases, templates, and domain events depend only on the port; `EMAIL_PROVIDER` selects exactly one transport (`resend`, `smtp`, or `disabled`), and bootstrap binds the port to it before migrations run. There is no fallback between transports: an unusable selection stops startup. Planned: an SMTP relay transport (`mail/smtp/`, TASK-014, outside the MVP); until it exists, `smtp` fails startup after its settings are validated. No flow calls the port yet: deliveries are stored (see [Mail deliveries](#mail-deliveries)), and the worker that sends them is planned (TASK-016). Settings are described in [DEPLOY.md](DEPLOY.md#mail). `Send(ctx, OutgoingMail)` makes exactly one attempt. `OutgoingMail` carries the recipient, subject, text and HTML bodies, and an idempotency key that stays the same for one logical delivery across retries (1 to 256 printable ASCII characters, the Resend limit, without personal data); the sender comes from `EMAIL_FROM`. With a nil error the result is one of: @@ -190,6 +190,72 @@ The Resend transport uses `net/http` without an SDK. One `Send` is one `POST htt Every `rejected` or `unknown` answer with a known error name sets `ProviderCode` to that name, for example `invalid_idempotent_request`, `invalid_api_key`, or `daily_quota_exceeded`. Known names are those on the Resend errors page plus the older names that the official Node SDK still lists (`invalid_api_key`, `invalid_from_address`, `invalid_access`, `invalid_region`, `security_error`, `internal_server_error`); any other name counts as no name. `RetryAfter` is capped at 24 hours. Rate-limit pacing, waiting for a quota reset or an operator decision, the attempt limit, and the stop at the end of the 24-hour key window belong to the planned delivery layer. +### Mail deliveries + +Implemented (TASK-015): the `domain.Delivery` aggregate, `domain.MailContent`, and `domain.MailRequest` (`backend/internal/domain/delivery.go`, `mail_content.go`, `mail_request.go`), the `outbound.DeliveryRepository` and `outbound.MailRequestRepository` ports (`port/outbound/delivery.go`) through `UnitOfWork.Deliveries()`, `UnitOfWork.MailRequests()`, and `postgres.DeliveryStore`, migration `00006_create_deliveries.sql` with the `mail_requests`, `deliveries`, and `delivery_attempts` tables, the queries in `backend/db/queries/delivery.sql`, and in `backend/internal/usecase/notification/` the request usecase `MailRequester` and the consumer `DeliveryHandler`. Planned: the worker that claims due deliveries and calls `MailSender` (TASK-016), retries and the unknown outcome policy (TASK-017), quotas (TASK-018), delivery metrics (TASK-022), and the permission check before a send (TASK-462). No product flow calls `MailRequester` yet, and nothing sends a stored delivery. + +A delivery is the durable state of sending one message to one recipient. A `deliveries` row holds: + +- `id`: the stable ID of the logical request, so a repeated request maps to the same row. The idempotency key sent to the provider with every attempt is `delivery/` (`idempotency_key`, unique); it contains no personal data. +- `source_event_id`: the domain event the delivery was created from, or NULL for a delivery created directly in a business transaction. +- The recipient: `recipient_user_id`, a foreign key to `users` with `ON DELETE CASCADE`, and `recipient_email`, the delivery form of the account address when the delivery was created. +- The content: `kind` (`verification`, `password_reset`, or `notification`), `template_version` (`.v`), `subject`, `text_body`, `html_body`, and `content_sha256` over the version, subject, and both parts, the same digest as the mail templates (`domain.MailContentHash`). +- The provider account: `provider` and `provider_account`, the values of `EMAIL_PROVIDER` and `EMAIL_ACCOUNT` at creation. They are configuration identity, never a credential. +- The attempt state: `status`, `attempt_count`, `next_attempt_at`, `last_attempt_at`, `provider_message_id`, the optimistic `version`, `created_at`, and `updated_at`, all from the application clock. + +Creation path: + +1. A usecase calls `MailRequester.RequestNotification(ctx, unit, request)` inside its own transaction with the recipient account ID and the notification data. The usecase checks the data with the current template, so a bad request fails its own transaction instead of becoming a dead letter, and assigns a UUIDv7 request ID. In the caller's transaction it inserts a `mail_requests` row with that ID, the recipient, the kind, the raw subject, body, and link path, and the request time, and appends `notification.mail_requested` with schema version 1: aggregate type `mail_request`, aggregate ID equal to the request ID, aggregate version 1, and the payload `{"mail_request_id": , "kind": "notification"}` and nothing else. +2. The relay publishes the event, and the consumer `notification_delivery` applies it in the transaction of its dedup marker. It checks the envelope and that `mail_request_id` equals the aggregate ID, refuses trailing data after the payload object, and locks the request row (`FOR UPDATE`). It reads the account, renders the notification once with the current template version, inserts the delivery under the request ID with `source_event_id` set, and deletes the request row, all in that transaction. +3. A redelivered event is a `duplicate` of the consumer marker. A replay under another consumer name, a replayed dead letter after success, or a concurrent second consumer finds the request row gone (the second consumer waits on its lock) and skips. When an insert finds a delivery under the request ID already, the handler accepts it only for the same recipient and kind, and rejects the event otherwise. +4. Skips: a request that no longer exists, because it was handled or its account was deleted, and a notification to an account whose address is not verified (`email_verified_at` NULL). The unverified case deletes the request; notifications go only to confirmed addresses. Skips are logged at info level with the delivery and event IDs only. An unknown schema version, a payload that breaks the contract, or text that the template refuses is rejected for good and becomes a `handler_rejected` dead letter; storage errors are retried. An account deleted after the handler read it makes the insert fail on the foreign key; the transaction is aborted, so the error is retried, and the retry finds the request deleted with the account and skips. + +Why the event carries only a reference. Events stay in `outbox_events` and in Kafka for the topic retention, and the domain event rule allows only identifiers and minimal facts. FR19 also requires that a queue does not keep revoked data available. The text therefore lives in `mail_requests`, which the account's deletion removes by cascade, and only as long as needed: the handler deletes the row in the transaction that stores the rendered delivery. After that the text exists only in the delivery, under the same retention and access rules. The address is read from the account in the handler transaction, so it is the address current at creation. + +Token mail. Verification and password reset bodies carry a one-time bearer token, which must never enter an event or a request row, and storage keeps only its SHA-256. `mail_requests` and schema version 1 therefore allow only kind `notification`. Token mail deliveries are to be created by the identity flows directly in the transaction that issues the token, through the same `domain.NewDelivery` and `DeliveryRepository.Create`; that wiring is planned with TASK-016 and the registration and reset tasks. + +Immutable content. A delivery stores the rendered body and never renders it again. Rendering at send time would need the raw token, which exists only in memory when it is issued, and a retry under the same idempotency key must repeat exactly the same body: Resend treats a changed body under an old key as a conflict. The domain recomputes the content hash on every read and fails with `domain.ErrMailContentIntegrity` on a mismatch. The trigger `deliveries_refuse_content_change` refuses an UPDATE that changes the recipient, content, idempotency key, source event, or creation time (SQLSTATE 23000, constraint `deliveries_content_immutable`, mapped to `outbound.ErrDeliveryContentImmutable`). A new template version therefore applies to new deliveries only; old template files are not needed to send a stored delivery. + +Personal data at rest. A delivery row holds the recipient address and the bodies, and a pending `mail_requests` row holds the raw notification text. The body of a token mail holds a live bearer token until it is used, replaced, or expires (at most 7 days by policy), so read access to `deliveries` is access to that account's confirmation or reset link, and database dumps and backups carry it. The consequences: + +- Queries for operations select metadata columns (ID, kind, status, attempts, times, provider) and never the bodies, the request text, or the address; see [DEPLOY.md](DEPLOY.md#mail-deliveries). +- Deleting an account deletes its mail requests, deliveries, and their attempts by cascade. The unverified account cleanup locks them with `FOR UPDATE SKIP LOCKED` like tokens and sessions, so it never waits for the delivery consumer or a worker that holds a row. +- A retention rule that deletes or clears terminal deliveries after a bounded period is not implemented yet; until it exists, rows stay. Encryption of the bodies at rest is not implemented either. +- `Delivery`, `MailContent`, `MailRequest`, `NotificationText`, and `EmailAddress` redact themselves in `fmt` and `slog` output: a delivery logs its ID, kind, status, and provider. Handler errors name the broken rule and never quote the payload, and the adapter replaces PostgreSQL error text with its SQLSTATE and constraint. There is no delivery metric yet; TASK-022 adds them with labels limited to kind, status, and provider, never the address, account ID, or subject. + +Statuses. The values follow the `MailSender` outcomes: + +| Status | Meaning | `next_attempt_at` | +| --- | --- | --- | +| `pending` | Waits for its first attempt, or for a retry after a `temporary` or `rate_limited` rejection | Required: when it is due | +| `accepted` | The provider accepted the message and returned `provider_message_id`; not delivery to or reading by a person | None; terminal | +| `rejected` | A `permanent` or `invalid_request` rejection; the cause must be fixed | None; terminal | +| `unknown` | The attempt may have reached the provider (`delivery_uncertain`). Never "not sent": a retry reuses the key and the stored body | Optional; none means no automatic retry | +| `waiting_quota` | A provider quota or the local quota is used up | Optional: the expected reset; none when the reset is unknown, for example Resend's monthly quota, and an operator or the quota rule decides | + +Transitions: + +- `Delivery.RecordAttempt` takes the result of one transport attempt and appends an attempt row. `pending`, `waiting_quota`, and `unknown` accept an attempt: `accepted` gives `accepted`, a `permanent` or `invalid_request` rejection gives `rejected`, `temporary` or `rate_limited` gives `pending`, `quota_exhausted` gives `waiting_quota`, and `unknown` gives `unknown`. `accepted` and `rejected` refuse any further attempt with `domain.ErrDeliveryTransition`. +- `Delivery.WaitForQuota(at, until)` parks a `pending` or `waiting_quota` delivery in `waiting_quota` without an attempt, for the case where TASK-018's local quota defers a send before the transport is called; a zero `until` means the reset is unknown. It refuses `unknown`, whose earlier attempt may have been accepted and whose retry belongs to the retry policy, and the terminal statuses. `DeliveryRepository.WaitForQuota` stores it. +- `Delivery.Rebind(at, account)` moves a delivery that has no attempt yet to another provider account; see below. `DeliveryRepository.Rebind` stores it. + +Every change advances `version`, and the store applies it only over the previous version. The next attempt time comes from the caller's retry policy (TASK-017) and must fit the target status; the CHECK `deliveries_next_attempt_matches_status` repeats the rule, and `deliveries_provider_message_id_when_accepted` requires the provider ID exactly for `accepted`. + +Attempts. The current state sits in counters on `deliveries`, so a worker reads one row, and every attempt is a row in `delivery_attempts`: number, time, outcome, rejection, provider code, provider message ID, wait hint, resulting status, and next attempt time. The history is what an operator needs to judge an unknown outcome, what the end of the 24-hour key window counts from (the first attempt), and what an audit of a manual decision refers to. The wait hint is stored exactly as the Go `time.Duration` in nanoseconds (`retry_after_ns`), so a round trip never changes it. `RecordAttempt` stores the delivery and the attempt in one statement: a data-modifying CTE updates the delivery only while its version is still the one before the attempt and appends the attempt only if that update matched. A second writer of the same attempt gets `outbound.ErrDeliveryVersionConflict` and writes nothing. A trigger refuses an UPDATE of an attempt. + +Quota accounting is not derived from this history: the cascade from an account deletes its deliveries and attempts, so counting sends from `delivery_attempts` would lose sends of deleted accounts and let the provider quota be exceeded. TASK-018 needs its own counter that does not cascade, keyed by provider, provider account, and UTC day or month, and incremented atomically when a send is admitted. + +Provider account. Each delivery is pinned to the transport and account configured when it was created. Providers and accounts share no idempotency keys, so FR19 forbids moving an uncertain delivery to another one; a configuration change applies to new deliveries only, and the sending worker must use the pinned account. `EMAIL_ACCOUNT` names the account (`default` unless set); change it whenever `RESEND_API_KEY` moves to another Resend account. The account may change only while the delivery has no attempt, because before the first attempt no provider has seen the key: `Delivery.Rebind` refuses a delivery with an attempt or in a terminal status, and the trigger refuses a provider change after an attempt (constraint `deliveries_provider_pinned`, mapped to `outbound.ErrDeliveryProviderPinned`). TASK-016 uses it for deliveries created while `EMAIL_PROVIDER=disabled` once the stand enables a transport; whether it rebinds them automatically or on an operator's request is its decision. + +Planned additive changes for later tasks. Each is a new column, index, or CHECK value in a later migration; existing rows stay valid: + +- A terminal cancelled status for a delivery that must not be sent anymore: a token or account invalidated before the send (TASK-016) or a revoked permission (TASK-462). +- A nullable reference from a token mail delivery to `email_tokens.id`, so the worker can check that the token is still the active one for its purpose before it sends (TASK-016). +- For the sending worker (TASK-016): lease columns (for example a claim owner and `claimed_until`) and a partial index on `next_attempt_at` for the statuses that are picked up again, so several processes claim due deliveries with `FOR UPDATE SKIP LOCKED` and an attempt whose process stopped after the request becomes `unknown`. +- The non-cascading quota counter of TASK-018 described above. + +The store already provides `Get`, `ListAttempts`, the version-checked `RecordAttempt`, `WaitForQuota`, and `Rebind`. + ### Product policy versions Implemented as storage, a publisher, and a startup seed (TASK-005): migration `backend/db/migrations/00003_create_policy_versions.sql`, queries in `backend/db/queries/policy.sql`, the typed policy in `backend/internal/domain/` (`policy.go`, `policy_document.go`, `policy_version.go`, `policy_demo.go`), the `outbound.PolicyRepository` port (`port/outbound/policy.go`), the sqlc-backed adapter in `backend/internal/adapter/secondary/postgres/policy.go`, and the publisher in `backend/internal/usecase/policy/`. No product rule reads the policy yet; invitations, quotas, assessment, sessions, and the search status will read it as their tasks are implemented. @@ -276,7 +342,8 @@ backend/ port/inbound/ readiness and event handler input boundaries usecase/identity/ password validation before hashing (Credentials) usecase/policy/ publication of policy versions and the demo policy seed - usecase/notification/mailtemplate/ pure rendering of versioned service emails for identity and delivery usecases (not wired yet) + usecase/notification/ mail requests and the consumer that stores them as deliveries + usecase/notification/mailtemplate/ pure rendering of versioned service emails; the delivery consumer renders notifications with it port/outbound/ readiness, cache, object storage, transaction, outbox, outbox relay, event publishing, event consumption, identity, policy, password hashing, and mail boundaries adapter/primary/http/ api/ generated ogen handler @@ -310,7 +377,7 @@ Product domain types and usecase modules, the SMTP and FSP adapters, and product This is a compact map, not a claim that every planned product package exists. Current Go code includes health usecases and adapters, generated API clients, bootstrap with startup migrations, a PostgreSQL health query, the transactional outbox writer, the outbox relay that publishes committed events to Kafka through the franz-go adapter, the event consumer runtime with no registered product handler, identity repositories without the usecases that will use them, the versioned policy store with its publisher and the demo policy seed at startup, the `PasswordHasher` port with the Argon2id adapter and the password check that registration will call, a Redis cache adapter, a SeaweedFS S3 adapter, the `MailSender` port with the `disabled` and Resend transports, and the mail template renderer that no flow calls yet. Account behavior (registration, verification, login, sessions), resumes, assessments, invitations, worker jobs, file workflows, mail delivery, the SMTP transport, and FSP adapters remain planned. Do not create empty module directories before a real use case exists. -`backend/pkg/` is reserved for small technical packages with a justified shared boundary, not product usecases or domain types. Candidate future packages are `mailer` and test helpers. Mail templates live in `internal/usecase/notification/mailtemplate/` instead: they hold product copy and use domain types such as `SecretToken`. It is a pure rendering package without I/O or logging; the identity usecases (verification and password reset) and the planned delivery usecase are expected to call it, and that wiring is planned. Templates, versions, and link format are described in [DEPLOY.md](DEPLOY.md#mail-templates). Keep the S3 client in the SeaweedFS adapter. Keep service-specific behavior private under `internal/`. +`backend/pkg/` is reserved for small technical packages with a justified shared boundary, not product usecases or domain types. Candidate future packages are `mailer` and test helpers. Mail templates live in `internal/usecase/notification/mailtemplate/` instead: they hold product copy and use domain types such as `SecretToken`. It is a pure rendering package without I/O or logging. The delivery consumer in `internal/usecase/notification/` renders notifications with it; the identity usecases (verification and password reset) are expected to call it when they create their deliveries, and that wiring is planned. Templates, versions, and link format are described in [DEPLOY.md](DEPLOY.md#mail-templates). Keep the S3 client in the SeaweedFS adapter. Keep service-specific behavior private under `internal/`. `api/` contains contract sources and tools; it is not a runtime hop in the request path. `api/core/` and `api/ml/` each own OpenAPI source, route and component fragments, and a committed bundle. Root `scripts/` merges schema fragments. Generated Go output belongs to its consumer: the public handler under `backend/internal/adapter/primary/http/api/`, the internal ML client under `backend/internal/adapter/secondary/ml/api/`, and sqlc output under `backend/internal/adapter/secondary/postgres/sqlc/`. The first is transport code mounted in chi; the latter two are outbound adapters. `backend/cmd/app/main.go` remains a small process entry point; bootstrap owns dependency wiring and graceful shutdown. @@ -424,7 +491,7 @@ What the ports guarantee: - `EmailTokenRepository.Consume` is one `UPDATE ... RETURNING` that requires an unconsumed, uninvalidated, unexpired token. Concurrent callers queue on the token row lock; under READ COMMITTED each waiter re-checks the row after the holder finishes, so exactly one succeeds and, if the holder rolls back, a waiter can still succeed. A miss is reported as `ErrEmailTokenNotFound`, `ErrEmailTokenConsumed`, `ErrEmailTokenInvalidated` (replaced, or issued for an earlier registration version), or `ErrEmailTokenExpired`. `InvalidateActive` marks every earlier token of a user and purpose. - Consume compares the token's registration version with the account only as its statement reads the account, without locking it, so it cannot see a re-registration that commits right after it. The binding of a token to the current registration therefore holds only when a confirmation calls `MarkEmailVerified(token.UserID, token.RegistrationVersion)` in the same transaction and rolls back on `ErrUserVersionConflict`; the rollback also restores the token, which is then superseded. The confirmation usecase (TASK-054) maps that outcome to `verification_token_invalid`. - `SessionRepository.FindActive` and `Touch` take the idle timeout from the caller and accept only an unrevoked session before its absolute deadline and within the idle timeout. `Touch` writes `last_seen_at` only when the stored value is more than one minute older, so frequent requests do not rewrite the row and the idle timeout can end a session up to a minute early; it never moves `last_seen_at` back or revives an ended session. `Revoke` and `RevokeAllForUser` set `revoked_at`. -- `DeleteUnverifiedRegisteredBefore` deletes one batch of unverified accounts, oldest first, and never waits for a lock. It locks the candidate accounts, their tokens, and their sessions with `FOR UPDATE SKIP LOCKED` and skips every account whose row, or any token or session row, is locked by another transaction, such as a re-registration, a resend, or a confirmation; skipped accounts stay for the next run. +- `DeleteUnverifiedRegisteredBefore` deletes one batch of unverified accounts, oldest first, and never waits for a lock. It locks the candidate accounts, their tokens, their sessions, their mail requests, and their mail deliveries with `FOR UPDATE SKIP LOCKED` and skips every account whose row, or any token, session, mail request, or delivery row, is locked by another transaction, such as a re-registration, a resend, a confirmation, the delivery consumer, or a delivery worker; skipped accounts stay for the next run. The mail requests, deliveries, and attempts go with the account by cascade. - `postgres.IdentityStore` runs the same repositories outside a transaction. Called with a context from a `Transactor` callback, it returns `ErrNestedTransaction` instead of committing on a separate connection. - Unique and foreign key violations map to `ErrEmailTaken`, `ErrTokenHashConflict`, and `ErrUserNotFound` by SQLSTATE and constraint name, never by error text. - Lock order: an operation that changes both an account and its tokens locks the tokens first. A confirmation consumes the token and then verifies the account, so a re-registration or resend calls `InvalidateActive` before it updates the account or inserts a token; the opposite order can deadlock. The cleanup is the only exception: it locks the account before the tokens and sessions, which is safe because each of those locks uses SKIP LOCKED and never waits. A deadlock (SQLSTATE 40P01) or serialization failure (40001) that still happens is reported by `Transactor.WithinTransaction` and the identity repositories as `outbound.ErrTransactionConflict`; nothing was committed, and the usecase or job may retry the whole operation with backoff while staying idempotent. diff --git a/docs/en/DEPLOY.md b/docs/en/DEPLOY.md index 5628bb4..81aa5b1 100644 --- a/docs/en/DEPLOY.md +++ b/docs/en/DEPLOY.md @@ -97,7 +97,7 @@ The internal /metrics endpoint shows the backlog: `lincodex_outbox_relay_pending ### Event consumers -The backend runs one event consumer per registered handler in its own process next to the HTTP servers and the relay. A consumer reads `KAFKA_EVENTS_TOPIC` as a member of the group `.`, applies each event once, and commits its offset only after the effect committed in PostgreSQL. The design is in [ARCHITECTURE.md](ARCHITECTURE.md#event-consumers). Current state: no product handler is registered, so the backend logs `no event consumer is registered`, starts no consumer, and opens no consumer group; the settings below take effect once a handler exists. Compose passes none of them, so the stack uses the defaults; to change one, add it to the backend `environment` in `deploy/docker/docker-compose.yml`. An invalid value stops startup, also with consumers disabled. +The backend runs one event consumer per registered handler in its own process next to the HTTP servers and the relay. A consumer reads `KAFKA_EVENTS_TOPIC` as a member of the group `.`, applies each event once, and commits its offset only after the effect committed in PostgreSQL. The design is in [ARCHITECTURE.md](ARCHITECTURE.md#event-consumers). Current state: one product handler is registered, `notification_delivery` (mail deliveries), so the backend runs one consumer in the group `.notification_delivery` (`lincodex.notification_delivery` by default) when `CONSUMER_ENABLED` is true and `DATABASE_URL` is set. Compose passes none of them, so the stack uses the defaults; to change one, add it to the backend `environment` in `deploy/docker/docker-compose.yml`. An invalid value stops startup, also with consumers disabled. | Variable | Default | Meaning | | --- | --- | --- | @@ -166,7 +166,7 @@ To inspect an `invalid_record` while the topic retains it, read exactly that rec The backend sends mail through the `MailSender` port. `EMAIL_PROVIDER` selects exactly one transport: `resend` (the Resend HTTP API, the primary provider for the working stand), `smtp` (a separate SMTP relay), or `disabled`. It has no default, and there is no fallback: when the selected transport cannot start, the backend stops instead of switching to another one. Settings of transports that are not selected are not read. -Current state: this build contains the `disabled` and `resend` transports. With `smtp`, the backend validates the SMTP settings and then exits with `EMAIL_PROVIDER=smtp: mail transport is not available in this build`; under Compose, `restart: unless-stopped` restarts the container repeatedly. SMTP is outside the MVP. `.env.example` and `make -C deploy smoke` use `disabled`, so local runs need no key; the working stand sets `EMAIL_PROVIDER=resend` and `RESEND_API_KEY` explicitly. No flow sends mail yet: the delivery layer that calls the transport is planned. +Current state: this build contains the `disabled` and `resend` transports. With `smtp`, the backend validates the SMTP settings and then exits with `EMAIL_PROVIDER=smtp: mail transport is not available in this build`; under Compose, `restart: unless-stopped` restarts the container repeatedly. SMTP is outside the MVP. `.env.example` and `make -C deploy smoke` use `disabled`, so local runs need no key; the working stand sets `EMAIL_PROVIDER=resend` and `RESEND_API_KEY` explicitly. No flow sends mail yet: mail requests are stored as deliveries (see [Mail deliveries](#mail-deliveries)), and the worker that calls the transport is planned. `resend` sends each message with one request to `https://api.resend.com/emails`. Building the transport makes no network call, so startup checks neither the key nor the sender domain; a wrong key or an unverified domain in `EMAIL_FROM` shows up as a rejected send. One attempt is limited by `EMAIL_TIMEOUT`. The transport follows no redirects, never retries, and logs nothing; retries, backoff, rate-limit pacing, waiting for a daily or monthly quota reset, and outcome records belong to the planned delivery layer. Each request carries the message's idempotency key, and Resend deduplicates the same key and body for 24 hours; after that window a retry may send the mail twice. A success means that Resend accepted the request and returned a message ID, not that the mail was delivered or read. A timeout, a lost answer after the request was sent, or a Resend 500 error is `unknown` (`delivery_uncertain`), not a failure. The backend process follows the standard `HTTPS_PROXY` and `NO_PROXY` variables, but the Compose backend service does not pass them, so under Compose the request goes directly to Resend; a stand that needs an egress proxy must add them to the backend `environment`. The full mapping of answers is in [ARCHITECTURE.md](ARCHITECTURE.md#mail-transport). @@ -176,6 +176,7 @@ Current state: this build contains the `disabled` and `resend` transports. With | --- | --- | --- | | `EMAIL_PROVIDER` | none, required | `resend`, `smtp`, or `disabled`, case-insensitive | | `EMAIL_FROM` | none, required | One mailbox: `no-reply@example.com` or `Lincodex `. Printable ASCII only. The address follows the account address rules: unquoted local part and a DNS domain with at least two labels, no IP literal. | +| `EMAIL_ACCOUNT` | `default` | Label of the provider account that new deliveries are pinned to: 1 to 64 lowercase letters, digits, `.`, `_`, or `-`, starting with a letter or digit. Never the key. | | `EMAIL_TIMEOUT` | `10s` | Go duration from `1s` to `1m`; limits one transport attempt | | `APP_PUBLIC_URL` | none, required | Public origin for links in mail: `https://host[:port]`, or `http` only for `localhost`, `127.0.0.1`, or `[::1]`. No credentials, path, query, or fragment; one trailing `/` is dropped. | | `RESEND_API_KEY` | empty | Read only for `resend`, where it is required. Printable ASCII without whitespace. The `re_` prefix shown in Resend examples is not enforced. | @@ -186,14 +187,24 @@ Current state: this build contains the `disabled` and `resend` transports. With Compose passes these variables from the root `.env`. `EMAIL_PROVIDER`, `EMAIL_FROM`, and `APP_PUBLIC_URL` are required, so Compose refuses to render the project without them; copy the mail block from `.env.example` into an existing `.env`. Keep `RESEND_API_KEY` and `SMTP_PASSWORD` in the server environment or a deployment secret store and never commit them. Configuration errors name the setting but never print its value, and the startup log names only the selected provider. +### Mail deliveries + +A notification request is a row in `mail_requests` until the consumer `notification_delivery` turns it into a row in `deliveries` and deletes it; the model is in [ARCHITECTURE.md](ARCHITECTURE.md#mail-deliveries). Migration 00006 creates `mail_requests`, `deliveries`, and `delivery_attempts` at startup; it needs no setting. The deliveries are only stored for now: the worker that sends them is planned, so no row leaves `pending`. Notifications are created only for accounts with a verified address; a request for an unverified address is dropped with a log line. + +- Each delivery is pinned to `EMAIL_PROVIDER` and `EMAIL_ACCOUNT` at creation, and a later configuration change applies only to new deliveries. Change `EMAIL_ACCOUNT` together with `RESEND_API_KEY` whenever the key belongs to another Resend account, so deliveries that started under the old account are never sent through the new one. Deliveries created while `EMAIL_PROVIDER=disabled` stay pinned to `disabled` until the sending worker (TASK-016) moves them with `Rebind`, which is allowed only before the first attempt. +- The rows hold the recipient address and the rendered bodies, and a waiting `mail_requests` row holds the raw notification text; verification and password reset bodies hold a live one-time token until it is used or expires. Treat read access to `deliveries` like access to those links, and keep database dumps and backups under the same protection. Retention of finished deliveries is not implemented yet. +- To inspect deliveries, select metadata only, for example `SELECT id, kind, template_version, status, attempt_count, next_attempt_at, last_attempt_at, provider, provider_account, created_at FROM deliveries ORDER BY created_at DESC LIMIT 50`, and `SELECT attempt_number, attempted_at, outcome, rejection, provider_code, status_after FROM delivery_attempts WHERE delivery_id = '' ORDER BY attempt_number`. `SELECT count(*), min(created_at) FROM mail_requests` shows requests the consumer has not handled yet; a growing count means the consumer is stopped or its events are dead-lettered. Do not select `recipient_email`, `subject`, `text_body`, `html_body`, or the `mail_requests` text columns, and never paste them into tickets or chats. +- Do not edit a stored delivery by hand: a trigger refuses any change to the recipient, content, or idempotency key and a change of the provider account after the first attempt, and the attempt history refuses updates. A delivery in `waiting_quota` without `next_attempt_at` waits for a quota reset that is not known, such as Resend's monthly quota, and needs an operator decision. +- Logs name a delivery only by `delivery_id` (with the event ID), never by address or subject. Skipped requests are logged at info level: `mail request skipped because it was already handled or its account was deleted` and `notification skipped because the recipient address is not verified`. A request that breaks the event contract is a `handler_rejected` dead letter of the consumer `notification_delivery`; see [Dead letters and replay](#dead-letters-and-replay). Replaying it is safe: the delivery ID keeps one delivery per request. + ### Mail templates -Implemented: the renderer in `backend/internal/usecase/notification/mailtemplate/` with templates for email verification, password reset, and a short notification. Nothing calls it yet: registration, verification, password reset, and mail delivery are planned, so the current build renders and sends no message. +Implemented: the renderer in `backend/internal/usecase/notification/mailtemplate/` with templates for email verification, password reset, and a short notification. The delivery consumer renders notifications with it when it stores a delivery; registration, verification, password reset, and sending are planned, so the current build sends no message. - Templates are embedded in the binary with `go:embed` and parsed once when the renderer is created; a broken template fails its creation. Each version has three files: `.v.subject.tmpl`, `.v.txt.tmpl`, and `.v.html.tmpl`. The HTML part uses `html/template`, the plain-text part and the subject use `text/template`. Every transport sends the same rendering; templates hold no provider settings, keys, or sender address. - Links start with `APP_PUBLIC_URL`, which the renderer checks again with the same rules. Verification: `/verify-email#token=`; password reset: `/reset-password#token=` (the page and the API for the reset are planned). The token is only in the URL fragment, never in the query. A notification link is a path inside the application, such as `/candidate/invitations`; an absolute URL, `//host`, a scheme such as `javascript:`, a query, a fragment, a percent sign, and `.` or `..` segments are rejected. - Messages contain no name, email address, or other contact. Caller text in a notification is escaped in the HTML part; control and bidirectional characters are removed from the plain-text part, and the subject becomes one line, so CR and LF cannot add header lines. The notification subject is limited to 100 characters and the body to 2000. -- Copy is in Russian. A released version is immutable: changing copy adds the next version, for example `verification.v2`, and switches the current version in code. Versions share no files, so one version cannot change the body of another. Each rendering carries its version and a SHA-256 content hash over the version, subject, and both parts; the same version and data always give the same body. The planned delivery layer is expected to store the rendered body with the hash and resend the stored body on retry instead of rendering again; keep the files of an old version while stored deliveries name it. +- Copy is in Russian. A released version is immutable: changing copy adds the next version, for example `verification.v2`, and switches the current version in code. Versions share no files, so one version cannot change the body of another. Each rendering carries its version and a SHA-256 content hash over the version, subject, and both parts; the same version and data always give the same body. A delivery stores the rendered body with the hash, and a retry sends the stored body instead of rendering again, so a new version applies to new deliveries only and an old version's files are not needed to send a stored delivery. - The renderer does not log. A rendering and notification data print only the kind, version, and content hash in `fmt` and `slog` output; tokens, links, and bodies are never printed. - Golden files in `testdata/` make every copy change visible in review. After an intended change, run `go test ./internal/usecase/notification/mailtemplate -update` from `backend/` and review the diff. diff --git a/docs/en/DEVELOPMENT.md b/docs/en/DEVELOPMENT.md index 5333312..9f1da42 100644 --- a/docs/en/DEVELOPMENT.md +++ b/docs/en/DEVELOPMENT.md @@ -50,14 +50,14 @@ What exists now: - Health and readiness routes. Nginx answers `GET /healthz` itself and proxies only `/api/` to Go (deploy/nginx/conf.d/app.conf). Go serves `GET /healthz` (`ok`) and `GET /readyz` (`ready` or 503 `not_ready` after checking PostgreSQL, Redis, and SeaweedFS) on its internal port 8080 outside the OpenAPI contract, plus `GET /api/v1/healthz` from api/core/routes/healthz.yml through the ogen handler (backend/internal/adapter/primary/http). The Go metrics listener uses port 9090 (`METRICS_ADDR`) and Prometheus scrapes `/metrics`. ML serves `GET /healthz`, `GET /readyz` (always 503 `not_ready` because no model is connected), and `/metrics` (ml/src/lincodex_ml, api/ml/routes). deploy/scripts/smoke.sh checks Nginx `/healthz`, `/api/v1/healthz`, Go `/readyz` from inside the Compose network, a 404 for an unknown API route, and that the backend started with `EMAIL_PROVIDER=disabled`; it does not start ML or send mail. - Adapters: PostgreSQL through pgxpool with a generated `SELECT 1` query, a goose migration runner applied at startup, a transactor with the transactional outbox writer, sqlc-backed identity repositories for accounts, email tokens, and sessions, and the versioned policy repository with the demo policy seed at startup; Redis through go-cachekit, and SeaweedFS through the S3 API. The Argon2id password hasher and the `identity.Credentials` password check exist and are tested but are not wired into bootstrap. A generated Go client for the ML contract exists but is not wired into bootstrap. -- Mail: the outbound `MailSender` port, the `disabled` transport, and the `EMAIL_PROVIDER` selection in bootstrap. Only `disabled` works in this build; `resend` and `smtp` fail startup after their settings are validated. Nothing sends mail yet. See [DEPLOY.md](DEPLOY.md#mail) and [ARCHITECTURE.md](ARCHITECTURE.md#mail-transport). +- Mail: the outbound `MailSender` port, the `disabled` and `resend` transports, and the `EMAIL_PROVIDER` selection in bootstrap; `smtp` stops startup after its settings are validated. Notification requests (`mail_requests`) are turned into deliveries (`deliveries`, `delivery_attempts`) by the `notification_delivery` consumer, but nothing sends them yet. See [DEPLOY.md](DEPLOY.md#mail) and [ARCHITECTURE.md](ARCHITECTURE.md#mail-deliveries). - OpenAPI contracts api/core/ and api/ml/ with schema merge, bundles, lint, and generation for Go (ogen), TypeScript (Orval), and Python (datamodel-code-generator). The SPA has an interface scaffold with placeholder screens, a generated API client, and MSW handlers. - Compose projects: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`), and monitoring (`docker-compose.monitoring.yml`). -- Kafka: one KRaft node in the core Compose project with an internal-only listener, a named volume, a health check, and a memory limit. The backend runs the outbox relay, which creates the `lincodex.domain.events` topic and publishes committed outbox events to it through a franz-go producer; see [Outbox relay](#outbox-relay). Readiness does not check Kafka. The event consumer runtime exists, but no product handler is registered, so nothing consumes the events yet; see [Event consumers](#event-consumers). +- Kafka: one KRaft node in the core Compose project with an internal-only listener, a named volume, a health check, and a memory limit. The backend runs the outbox relay, which creates the `lincodex.domain.events` topic and publishes committed outbox events to it through a franz-go producer; see [Outbox relay](#outbox-relay). Readiness does not check Kafka. The event consumer runtime runs one product handler, the mail delivery consumer, and no product flow emits its event yet; see [Event consumers](#event-consumers). - CI jobs in .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix of two shards), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke`, `e2e` (Playwright suite on an isolated stand), and the required `aggregate` result, which fails when any of them fails, is cancelled, or is skipped. See [TESTING.md](TESTING.md) for sharding and the browser suite. - Observability: Prometheus, Loki, Alloy, Grafana with provisioned datasources and dashboards, and PostgreSQL, Redis, and node exporters. The React app does not send telemetry yet. -Not implemented yet: registration and login (their contract is declared; the operations answer 501 or 401), consents, profiles, the questionnaire and assessment, the company cabinet, needs and matching, invitations and contacts, the Resend and SMTP transports and mail delivery, product event consumers, notifications, support, and an end-to-end business suite. backend/db/migrations/ contains the outbox table with its relay index, the identity storage tables (`users`, `email_tokens`, `sessions`), the `policy_versions` table, and the event consumer tables (`consumer_processed_events`, `consumer_dead_letters`) and no other business schema; no product rule reads the policy yet; registration, verification, and session behavior on top of that storage comes in later tasks, product usecase and adapter directories other than the password hashing and policy pieces contain only placeholders, and `make -C deploy test-e2e` runs only a technical Playwright smoke of the SPA, API health, and error routes on a throwaway stack, not a business flow (see [TESTING.md](TESTING.md#browser-e2e-suite)). The target design is in [ARCHITECTURE.md](ARCHITECTURE.md). +Not implemented yet: registration and login (their contract is declared; the operations answer 501 or 401), consents, profiles, the questionnaire and assessment, the company cabinet, needs and matching, invitations and contacts, the SMTP transport and the worker that sends stored deliveries, product event producers, notifications, support, and an end-to-end business suite. backend/db/migrations/ contains the outbox table with its relay index, the identity storage tables (`users`, `email_tokens`, `sessions`), the `policy_versions` table, the event consumer tables (`consumer_processed_events`, `consumer_dead_letters`), and the mail delivery tables (`deliveries`, `delivery_attempts`) and no other business schema; no product rule reads the policy yet; registration, verification, and session behavior on top of that storage comes in later tasks, product usecase and adapter directories other than the password hashing and policy pieces contain only placeholders, and `make -C deploy test-e2e` runs only a technical Playwright smoke of the SPA, API health, and error routes on a throwaway stack, not a business flow (see [TESTING.md](TESTING.md#browser-e2e-suite)). The target design is in [ARCHITECTURE.md](ARCHITECTURE.md). ## Install and work loop @@ -189,10 +189,14 @@ A directly launched backend with `DATABASE_URL` set runs the relay against `KAFK The consumer runtime applies events from Kafka to this service's own state, once per consumer. The loop lives in `backend/internal/worker/eventconsumer/`; it depends on the `inbound.EventHandler` port (`backend/internal/port/inbound/event_handler.go`) and on the `outbound.EventSource` and `outbound.EventConsumerStore` ports (`backend/internal/port/outbound/event_consumer.go`). `kafka.EventSource` is the franz-go group member that decodes the envelope and commits offsets, and `postgres.EventConsumerStore` runs the dedup transaction with the queries in `backend/db/queries/event_consumer.sql`. The backoff is shared with the relay in `backend/internal/worker/retry/`. -No product handler is registered yet. To add one, implement `inbound.EventHandler` in the module's usecase package: return a stable snake_case `ConsumerName()`, accept only the event types it applies in `Handles`, and write the effect in `Handle` only through the `UnitOfWork` it receives. Return an error that wraps `inbound.ErrEventRejected` for an event that can never be applied, such as an unknown `schema_version`; any other error is retried. Then add the handler to `eventHandlers()` in `backend/internal/bootstrap/consumers.go`. Bootstrap gives it a consumer group, a share of the consumer pool, and a lifecycle next to the HTTP servers. Test the effect with a real PostgreSQL through the store, as `TestEventConsumer` does. +One product handler is registered: `notification.DeliveryHandler` stores mail deliveries (see [Mail deliveries](#mail-deliveries)). To add another, implement `inbound.EventHandler` in the module's usecase package: return a stable snake_case `ConsumerName()`, accept only the event types it applies in `Handles`, and write the effect in `Handle` only through the `UnitOfWork` it receives. Return an error that wraps `inbound.ErrEventRejected` for an event that can never be applied, such as an unknown `schema_version`; any other error is retried. Then add the handler to `eventHandlers()` in `backend/internal/bootstrap/consumers.go`. Bootstrap gives it a consumer group, a share of the consumer pool, and a lifecycle next to the HTTP servers. Test the effect with a real PostgreSQL through the store, as `TestEventConsumer` does. A directly launched backend with a registered handler and `DATABASE_URL` set consumes from `KAFKA_BROKERS`; set `CONSUMER_ENABLED=false` when you do not need it. Design and failure semantics are in [ARCHITECTURE.md](ARCHITECTURE.md#event-consumers); settings, metrics, and the dead letter procedure are in [DEPLOY.md](DEPLOY.md#event-consumers); tests are in [TESTING.md](TESTING.md#event-consumer-tests). +### Mail deliveries + +To send a notification from a usecase, call `notification.MailRequester.RequestNotification(ctx, unit, request)` with the usecase's `UnitOfWork`, the recipient account ID, and `mailtemplate.NotificationData`; it returns the delivery ID. It stores the text in `mail_requests` and appends an event that carries only the request ID and kind, both in the usecase's transaction. The consumer `notification_delivery` then stores the delivery with the address read from the account and the rendered content, and deletes the request; it skips accounts whose address is not verified. Never put an email address, a token, notification text, or another person's contact into any event payload, and never put a token or another person's contact into a request. Verification and password reset mail carry a token and cannot use the event: the identity flows create those deliveries with `domain.NewDelivery` and `UnitOfWork.Deliveries().Create` in the transaction that issues the token. A new template version changes new deliveries only; never update a stored delivery's content. The model is in [ARCHITECTURE.md](ARCHITECTURE.md#mail-deliveries), operations in [DEPLOY.md](DEPLOY.md#mail-deliveries), and tests in [TESTING.md](TESTING.md#mail-delivery-tests). + ## Go readability - Extract repeated parsing, setup, and cleanup into small typed helpers near their consumers. Move code to `pkg/` when several packages actually reuse it. Avoid wrappers that only rename a call. diff --git a/docs/en/TESTING.md b/docs/en/TESTING.md index c2623f7..a29cf59 100644 --- a/docs/en/TESTING.md +++ b/docs/en/TESTING.md @@ -38,7 +38,7 @@ Security checks run separately: `make -C security check` scans source/dependenci ## Current scaffold coverage -Existing checks cover health/readiness, backend PostgreSQL, Redis, and SeaweedFS connectivity, migration up, down to zero, and up again on an isolated database, concurrent migration runners that apply each migration once, the transactional outbox (atomic commit, rollback on error, panic, and context cancellation, nested-transaction rejection, an observed row-lock wait between concurrent transactions, edge payloads, and constraints), identity storage (a unique normalized email, hash-only storage of email and session tokens, exactly one successful consumption of a token under parallel confirmations and an observed lock wait between two consumes, rejection of expired, invalidated, and superseded tokens, including a re-registration that commits during a confirmation, session idle, absolute, and revocation limits and touch throttling, batch cleanup of unverified accounts that skips locked accounts without waiting, a deadlock reported as a retryable conflict, cascade deletes, rollback with the surrounding transaction, and constraints), cache operations and TTL, S3 operations and object persistence, the Kafka test harness (keyed records with headers and per-partition order, refusal to create a missing topic on demand, and topic cleanup), the outbox relay (see [Outbox relay tests](#outbox-relay-tests)), the event consumer runtime (see [Event consumer tests](#event-consumer-tests)), metrics, the API client, ML schemas, and current endpoint availability. There are no registration, login, assessment, search, invitation, or file workflows, no product events or product consumers in Kafka, and no real model inference to validate as product behavior. +Existing checks cover health/readiness, backend PostgreSQL, Redis, and SeaweedFS connectivity, migration up, down to zero, and up again on an isolated database, concurrent migration runners that apply each migration once, the transactional outbox (atomic commit, rollback on error, panic, and context cancellation, nested-transaction rejection, an observed row-lock wait between concurrent transactions, edge payloads, and constraints), identity storage (a unique normalized email, hash-only storage of email and session tokens, exactly one successful consumption of a token under parallel confirmations and an observed lock wait between two consumes, rejection of expired, invalidated, and superseded tokens, including a re-registration that commits during a confirmation, session idle, absolute, and revocation limits and touch throttling, batch cleanup of unverified accounts that skips locked accounts without waiting, a deadlock reported as a retryable conflict, cascade deletes, rollback with the surrounding transaction, and constraints), cache operations and TTL, S3 operations and object persistence, the Kafka test harness (keyed records with headers and per-partition order, refusal to create a missing topic on demand, and topic cleanup), the outbox relay (see [Outbox relay tests](#outbox-relay-tests)), the event consumer runtime (see [Event consumer tests](#event-consumer-tests)), mail deliveries (see [Mail delivery tests](#mail-delivery-tests)), metrics, the API client, ML schemas, and current endpoint availability. There are no registration, login, assessment, search, invitation, or file workflows, no product event producer in Kafka (the mail delivery consumer is exercised only by tests), and no real model inference to validate as product behavior. API verification checks the OpenAPI subset exercised by pinned tools, fixtures, and contracts that actually ran. Its result applies only to those inputs. CI YAML in the repository does not mean a workflow has run on GitHub. @@ -92,7 +92,7 @@ The suite runs against one broker and one PostgreSQL. It does not measure throug ## Event consumer tests -Unit tests (`make -C backend test`) cover the consumer runtime with a fake source, store, and handler (`internal/worker/eventconsumer/`): applied, duplicate, and ignored records committed in poll order; store failures retried beyond the attempt limit without a dead letter, with the offset committed only after the store succeeded; a handler that keeps failing, retried exactly `MaxAttempts` times with at least the minimum backoff between attempts, then dead-lettered with its event ID, type, value size, and SHA-256 while the next record is applied; `ErrEventRejected` and a panic dead-lettered after one attempt without quoting the panic value; an invalid record dead-lettered without calling the handler, with the commit waiting until two failed dead letter writes succeed; a shutdown that abandons a stuck handler after the grace without committing it or anything after it; a record that finishes within the grace and is committed while the next one is not started; no retry and no dead letter during shutdown; backoff after failed polls; commits that PostgreSQL refuses after the handler swallowed an error, counted as attempts and ending in `retries_exhausted`; a serialization conflict at commit retried as an attempt; a panic in `Handles` dead-lettered without quoting its value; the prefix commit right after a dead letter, before the next record starts; `poll` and `commit` failure counts; and the reason sanitizer. The PostgreSQL adapter tests classify refused, conflicting, and transport commit failures and check that handler errors keep their identity without the PostgreSQL message. They also cover envelope decoding and its round trip with the producer, every rejected envelope rule without quoting the value, and commit bookkeeping of the group member, including the refusal of finished records that are not a gap-free prefix of the last poll per partition (`internal/adapter/secondary/kafka/`), the consumer settings and the rebalance budget, including the documented 42.5-second default (`config/`), the consumer counters (`internal/adapter/secondary/prometheus/`), and in `internal/bootstrap/` the skip cases, one consumer per handler, rejected duplicate and invalid names, the empty handler list, label values that match the prepared metrics, and an application that runs a consumer while serving and returns only after it stopped polling. +Unit tests (`make -C backend test`) cover the consumer runtime with a fake source, store, and handler (`internal/worker/eventconsumer/`): applied, duplicate, and ignored records committed in poll order; store failures retried beyond the attempt limit without a dead letter, with the offset committed only after the store succeeded; a handler that keeps failing, retried exactly `MaxAttempts` times with at least the minimum backoff between attempts, then dead-lettered with its event ID, type, value size, and SHA-256 while the next record is applied; `ErrEventRejected` and a panic dead-lettered after one attempt without quoting the panic value; an invalid record dead-lettered without calling the handler, with the commit waiting until two failed dead letter writes succeed; a shutdown that abandons a stuck handler after the grace without committing it or anything after it; a record that finishes within the grace and is committed while the next one is not started; no retry and no dead letter during shutdown; backoff after failed polls; commits that PostgreSQL refuses after the handler swallowed an error, counted as attempts and ending in `retries_exhausted`; a serialization conflict at commit retried as an attempt; a panic in `Handles` dead-lettered without quoting its value; the prefix commit right after a dead letter, before the next record starts; `poll` and `commit` failure counts; and the reason sanitizer. The PostgreSQL adapter tests classify refused, conflicting, and transport commit failures and check that handler errors keep their identity without the PostgreSQL message. They also cover envelope decoding and its round trip with the producer, every rejected envelope rule without quoting the value, and commit bookkeeping of the group member, including the refusal of finished records that are not a gap-free prefix of the last poll per partition (`internal/adapter/secondary/kafka/`), the consumer settings and the rebalance budget, including the documented 42.5-second default (`config/`), the consumer counters (`internal/adapter/secondary/prometheus/`), and in `internal/bootstrap/` the skip cases, one consumer per handler, rejected duplicate and invalid names, the registered delivery handler, label values that match the prepared metrics, and an application that runs a consumer while serving and returns only after it stopped polling. `TestEventConsumer` in `backend/integration_test/event_consumer_test.go` uses `bootstrap(t, postgresService, kafkaService)`. Its handler exists only in the test: it writes one row per applied event into `consumer_test.effects`, a table without a unique key that the test creates, so a second effect would stay visible. The sequential cases, each with its own topic and group, are: @@ -109,7 +109,29 @@ Unit tests (`make -C backend test`) cover the consumer runtime with a fake sourc - Rebalance handover with two members of one group: the first member's commits always fail, and it holds a record while a second member joins; the test waits until the group is in `PreparingRebalance`, releases the record, and waits until the group is stable with one partition per member. Each of four events has exactly one effect, the first member handled both first-round events before the rebalance, the joiner received nothing of the moved partition's first round (its position was committed in the revocation, the only commit path left) and counted no duplicate, the first member never tried to commit or handle a record of the moved partition after losing it, and after the first member leaves, the group's offsets are 2 on both partitions, so the moved partition was not rewound. - An event appended to the outbox through the transactor, published by the relay, and consumed: the decoded event matches the outbox row, so the producer and consumer agree on the envelope. -`TestPostgresMigrations` also checks that migration 00005 creates and drops both consumer tables. The suite uses one broker, one PostgreSQL, and test-only handlers. It does not measure throughput, does not cover a rebalance under load or with more than two members, broker failover, a member removed after the rebalance timeout, or a real product handler, and does not check alert delivery. +`TestPostgresMigrations` also checks that migration 00005 creates and drops both consumer tables. The suite uses one broker, one PostgreSQL, and test-only handlers. It does not measure throughput, does not cover a rebalance under load or with more than two members, broker failover, a member removed after the rebalance timeout, and does not check alert delivery; the product handler has its own [Mail delivery tests](#mail-delivery-tests). + +## Mail delivery tests + +Unit tests (`make -C backend test`) cover the delivery model and its creation path: + +- `internal/domain/`: the content hash covers the version, subject, both parts, and part borders; content that no transport could send or that belongs to another kind is refused; a changed stored body fails the integrity check; a new delivery starts `pending`, due at creation, with version 1, the key `delivery/`, and an optional source event; every attempt outcome applied to `pending`, `waiting_quota`, and `unknown` gives the documented status, attempt number, version, times, and provider ID, including `waiting_quota` without a known reset, and `accepted` and `rejected` refuse every further attempt; inconsistent attempt results are refused; `WaitForQuota` parks `pending` and `waiting_quota` with a known or unknown reset without an attempt, refuses `unknown` and terminal deliveries and times before the last change, and a later attempt must not precede it; `Rebind` changes only the provider account and version before the first attempt and is refused after it; stored rows that break an invariant are refused; a mail request accepts only the notification kind and storable text; and `fmt` and `slog` output of a delivery, its content, and a mail request never shows the address, subject, body, request text, or token. +- `internal/usecase/notification/`: a request stores its text under the event's aggregate ID and the event payload carries only `mail_request_id` and `kind`; invalid requests write nothing; the handler stores one delivery under the request ID with the source event, the account address, the rendered content, the configured provider account, and the clock time, and deletes the request; the same event again finds no request; an existing delivery under the request ID is accepted for the same recipient and kind and rejected otherwise; broken events (another schema version or aggregate, a malformed payload, trailing data, a request ID that is not the aggregate ID, a token mail kind) and text the template refuses are rejected without quoting the payload; a request that is gone, an account that is gone, and an unverified address are skipped with a log line that names only the delivery and event IDs; storage failures, including an account deleted between its read and the insert, stay retryable and keep the request; and no error or log line holds the address, subject, or body. +- `internal/adapter/secondary/postgres/`: delivery and mail request constraint errors map to their sentinels (`deliveries_content_immutable` and `delivery_attempts_immutable` to `ErrDeliveryContentImmutable`, `deliveries_provider_pinned` to `ErrDeliveryProviderPinned`, the user foreign keys to `ErrUserNotFound`), and any other PostgreSQL error, such as a check violation, keeps only its SQLSTATE and constraint without the message or detail. +- `internal/usecase/notification/mailtemplate/`: a rendering converts to the stored content with the same kind, version, parts, and hash. +- `config/` and `internal/bootstrap/`: `EMAIL_ACCOUNT` defaults to `default`, accepts labels up to 64 characters, and refuses empty, mixed-case, key-like, and oversized values without echoing them; bootstrap registers exactly the `notification_delivery` handler and refuses an invalid account label. + +`TestMailDelivery` in `backend/integration_test/delivery_test.go` uses `bootstrap(t, postgresService, kafkaService)` and the real request usecase, handler, relay, consumer runtime, and stores. Its sequential cases are: + +- One event processed twice through the consumer: a request for a verified account is recorded in a business transaction, the relay publishes its event, the row is marked unpublished again as after a crash before the `published_at` commit, and the relay publishes it a second time with the same event ID. The consumer commits offset 2 and counts one `applied` and one `duplicate` record; the database holds exactly one delivery, addressed to the account, rendered with `notification.v1`, pinned to the configured provider account, naming the event as its source, and `pending` with no attempt, and no mail request remains. +- A template change after creation: a first request is stored with `notification.v1`. A handler with a test renderer that stands for `notification.v2` stores a second request with the new version, and a replay of the first request under another consumer name finds its request consumed and stores nothing. The first delivery, read through a new pool, still has the `notification.v1` subject, parts, and hash, and a direct `UPDATE` of its body fails with `deliveries_content_immutable`. +- Restart persistence: one pool records an `unknown` attempt with a provider code and a wait hint with sub-millisecond parts, loses a second write of the same attempt with `ErrDeliveryVersionConflict`, records an `accepted` attempt with a provider message ID, and closes. A new pool and store read the delivery as `accepted` with that ID, two attempts, and version 3, and both attempt rows exactly as written, the wait hint to the nanosecond; a further attempt is refused, and an `UPDATE` of an attempt fails with `delivery_attempts_immutable`. +- Rebind and quota wait: a delivery without attempts is moved to another provider account and parked in `waiting_quota` with an unknown reset, a stale second write fails with a version conflict, and no attempt row exists; after an attempt, `Rebind` is refused by the domain and a direct `UPDATE` of the provider account fails with `deliveries_provider_pinned`. +- A notification to an unverified address stores no delivery, deletes its request, and logs the delivery ID. +- A request whose account is deleted loses its request row with the account; the handler then stores no delivery and logs the delivery ID. +- The unverified account cleanup skips an account whose delivery row another transaction holds, deletes it once the lock is gone, and its pending request and its delivery, created directly through the repository as token mail will be, go with it. + +Every case checks that the captured handler and consumer logs hold neither the address nor the subject or body, and the request events are checked to carry no address and no request text. `TestPostgresMigrations` also checks that migration 00006 creates and drops its three tables and both trigger functions, and `TestIdentityRepositories` runs the cleanup query with the mail request and delivery locks. The suite does not send mail: the sending worker, retries, quotas, and the permission check are later tasks, and there is no test of a verification or password reset delivery, which the identity flows will create. ## Integration test sharding diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index 5cb3be4..896fa5c 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -114,7 +114,7 @@ Producer требует подтверждения от всех in-sync реп ### Обработчики событий -Реализовано (TASK-010): runtime обработчиков в `backend/internal/worker/eventconsumer/`, порт обработчика `inbound.EventHandler` (`backend/internal/port/inbound/event_handler.go`), порты `outbound.EventSource` и `outbound.EventConsumerStore` (`backend/internal/port/outbound/event_consumer.go`), участник consumer group на franz-go (`adapter/secondary/kafka/consumer.go`), хранилище PostgreSQL (`adapter/secondary/postgres/event_consumer.go`) и миграция `00005_create_event_consumer_tables.sql` с таблицами `consumer_processed_events` и `consumer_dead_letters`. Продуктовых обработчиков нет: `eventHandlers()` в `backend/internal/bootstrap/consumers.go` возвращает пустой список, поэтому работающий backend не запускает ни одного обработчика и не открывает для них пул PostgreSQL и группу Kafka. Интеграционные тесты запускают runtime с тестовым обработчиком, который пишет в таблицу, созданную самим тестом; выдуманного бизнес-эффекта нет. Продуктовый модуль добавляет свой обработчик в этот список. Настройки перечислены в [DEPLOY.md](DEPLOY.md#обработчики-событий). +Реализовано (TASK-010): runtime обработчиков в `backend/internal/worker/eventconsumer/`, порт обработчика `inbound.EventHandler` (`backend/internal/port/inbound/event_handler.go`), порты `outbound.EventSource` и `outbound.EventConsumerStore` (`backend/internal/port/outbound/event_consumer.go`), участник consumer group на franz-go (`adapter/secondary/kafka/consumer.go`), хранилище PostgreSQL (`adapter/secondary/postgres/event_consumer.go`) и миграция `00005_create_event_consumer_tables.sql` с таблицами `consumer_processed_events` и `consumer_dead_letters`. Зарегистрирован один продуктовый обработчик (TASK-015): `eventHandlers()` в `backend/internal/bootstrap/consumers.go` возвращает обработчик доставки писем `notification_delivery`, описанный в разделе [Доставки писем](#доставки-писем), поэтому backend с `CONSUMER_ENABLED` и `DATABASE_URL` запускает один обработчик в группе `.notification_delivery`. Интеграционные тесты runtime используют тестовый обработчик, который пишет в таблицу, созданную самим тестом. Продуктовый модуль добавляет свой обработчик в этот список. Настройки перечислены в [DEPLOY.md](DEPLOY.md#обработчики-событий). Обработчик реализует три метода: @@ -154,7 +154,7 @@ Offsets и партиции. Каждый обработчик - один уча ### Почтовый транспорт -Реализовано: outbound порт `MailSender` (`backend/internal/port/outbound/mail.go`), транспорт `disabled` (`adapter/secondary/mail/disabled/`), транспорт Resend (`adapter/secondary/mail/resend/`, основной провайдер рабочего стенда) и выбор транспорта в bootstrap. Usecase, шаблоны и доменные события зависят только от порта; `EMAIL_PROVIDER` выбирает ровно один транспорт (`resend`, `smtp` или `disabled`), и bootstrap связывает с ним порт до запуска миграций. Переключения между транспортами нет: непригодный выбор останавливает запуск. Запланировано: транспорт SMTP relay (`mail/smtp/`, TASK-014, вне MVP); пока его нет, `smtp` после проверки своих настроек останавливает запуск. Порт пока не вызывает ни один сценарий; слой доставки запланирован. Настройки описаны в [DEPLOY.md](DEPLOY.md#почта). +Реализовано: outbound порт `MailSender` (`backend/internal/port/outbound/mail.go`), транспорт `disabled` (`adapter/secondary/mail/disabled/`), транспорт Resend (`adapter/secondary/mail/resend/`, основной провайдер рабочего стенда) и выбор транспорта в bootstrap. Usecase, шаблоны и доменные события зависят только от порта; `EMAIL_PROVIDER` выбирает ровно один транспорт (`resend`, `smtp` или `disabled`), и bootstrap связывает с ним порт до запуска миграций. Переключения между транспортами нет: непригодный выбор останавливает запуск. Запланировано: транспорт SMTP relay (`mail/smtp/`, TASK-014, вне MVP); пока его нет, `smtp` после проверки своих настроек останавливает запуск. Порт пока не вызывает ни один сценарий: доставки уже сохраняются (см. [Доставки писем](#доставки-писем)), а worker, который их отправляет, запланирован (TASK-016). Настройки описаны в [DEPLOY.md](DEPLOY.md#почта). `Send(ctx, OutgoingMail)` делает ровно одну попытку. `OutgoingMail` содержит получателя, тему, текстовое и HTML тело и ключ идемпотентности, который не меняется для одной логической доставки между повторами (от 1 до 256 печатных ASCII символов, предел Resend, без персональных данных); отправитель берется из `EMAIL_FROM`. При nil ошибке результат один из: @@ -190,6 +190,72 @@ Offsets и партиции. Каждый обработчик - один уча Каждый ответ `rejected` или `unknown` с известным именем ошибки заполняет `ProviderCode` этим именем, например `invalid_idempotent_request`, `invalid_api_key` или `daily_quota_exceeded`. Известны имена со страницы ошибок Resend и старые имена, которые все еще перечисляет официальный Node SDK (`invalid_api_key`, `invalid_from_address`, `invalid_access`, `invalid_region`, `security_error`, `internal_server_error`); любое другое имя считается отсутствующим. `RetryAfter` ограничен 24 часами. Темп при rate limit, ожидание сброса квоты или решения оператора, предел числа попыток и остановка по окончании 24-часового окна ключа относятся к запланированному слою доставки. +### Доставки писем + +Реализовано (TASK-015): агрегат `domain.Delivery`, `domain.MailContent` и `domain.MailRequest` (`backend/internal/domain/delivery.go`, `mail_content.go`, `mail_request.go`), порты `outbound.DeliveryRepository` и `outbound.MailRequestRepository` (`port/outbound/delivery.go`) через `UnitOfWork.Deliveries()`, `UnitOfWork.MailRequests()` и `postgres.DeliveryStore`, миграция `00006_create_deliveries.sql` с таблицами `mail_requests`, `deliveries` и `delivery_attempts`, запросы в `backend/db/queries/delivery.sql`, а в `backend/internal/usecase/notification/` usecase запроса `MailRequester` и обработчик `DeliveryHandler`. Запланировано: worker, который берет доставки к отправке и вызывает `MailSender` (TASK-016), повторы и политика неизвестного исхода (TASK-017), квоты (TASK-018), метрики доставки (TASK-022) и проверка разрешений перед отправкой (TASK-462). Ни один продуктовый сценарий пока не вызывает `MailRequester`, и сохраненные доставки никто не отправляет. + +Доставка - устойчивое состояние отправки одного письма одному получателю. Строка `deliveries` содержит: + +- `id`: стабильный ID логического запроса, поэтому повторный запрос попадает в ту же строку. Ключ идемпотентности, который уходит провайдеру с каждой попыткой, - `delivery/` (`idempotency_key`, уникальный); в нем нет персональных данных. +- `source_event_id`: доменное событие, из которого создана доставка, или NULL для доставки, созданной прямо в бизнес-транзакции. +- Получателя: `recipient_user_id`, внешний ключ на `users` с `ON DELETE CASCADE`, и `recipient_email`, форма адреса аккаунта для доставки на момент создания. +- Содержимое: `kind` (`verification`, `password_reset` или `notification`), `template_version` (`.v`), `subject`, `text_body`, `html_body` и `content_sha256` по версии, теме и обеим частям - тот же digest, что у шаблонов писем (`domain.MailContentHash`). +- Аккаунт провайдера: `provider` и `provider_account`, значения `EMAIL_PROVIDER` и `EMAIL_ACCOUNT` на момент создания. Это идентичность конфигурации, а не секрет. +- Состояние попыток: `status`, `attempt_count`, `next_attempt_at`, `last_attempt_at`, `provider_message_id`, оптимистичная `version`, `created_at` и `updated_at`; все время берется из часов приложения. + +Путь создания: + +1. Usecase вызывает `MailRequester.RequestNotification(ctx, unit, request)` внутри своей транзакции с ID аккаунта получателя и данными уведомления. Usecase проверяет данные текущим шаблоном, чтобы некорректный запрос провалил свою транзакцию, а не стал dead letter, и назначает UUIDv7 запроса. В транзакции вызывающего кода он вставляет строку `mail_requests` с этим ID, получателем, видом, исходными темой, текстом и путем ссылки и временем запроса и добавляет `notification.mail_requested` с версией схемы 1: тип агрегата `mail_request`, ID агрегата равен ID запроса, версия агрегата 1, payload `{"mail_request_id": , "kind": "notification"}` и больше ничего. +2. Relay публикует событие, а обработчик `notification_delivery` применяет его в транзакции своего dedup-маркера. Он проверяет конверт и равенство `mail_request_id` и ID агрегата, отклоняет данные после объекта payload и блокирует строку запроса (`FOR UPDATE`). Затем в этой же транзакции он читает аккаунт, один раз рендерит уведомление текущей версией шаблона, вставляет доставку под ID запроса с заполненным `source_event_id` и удаляет строку запроса. +3. Повторно доставленное событие становится `duplicate` по маркеру обработчика. Повтор под другим именем обработчика, повтор dead letter после успеха или параллельный второй обработчик находят строку запроса уже удаленной (второй обработчик ждет ее блокировку) и пропускают событие. Если вставка находит доставку под ID запроса, обработчик принимает ее только для того же получателя и вида, а иначе отклоняет событие. +4. Пропуски: запрос, которого уже нет, потому что его обработали или удалили аккаунт, и уведомление аккаунту с неподтвержденным адресом (`email_verified_at` равен NULL). Во втором случае запрос удаляется: уведомления уходят только на подтвержденные адреса. Пропуски пишутся в лог на уровне info только с ID доставки и события. Неизвестная версия схемы, payload, нарушающий контракт, или текст, который отклоняет шаблон, отклоняются окончательно и становятся dead letter класса `handler_rejected`; ошибки хранилища повторяются. Если аккаунт удалили после того, как обработчик его прочитал, вставка падает на внешнем ключе; транзакция прервана, поэтому ошибка повторяется, а повтор находит запрос удаленным вместе с аккаунтом и пропускает его. + +Почему событие несет только ссылку. События хранятся в `outbox_events` и в Kafka в пределах retention топика, а правило доменных событий разрешает только идентификаторы и минимальные факты. FR19 также требует, чтобы очередь не сохраняла доступ к отозванным данным. Поэтому текст лежит в `mail_requests`, которые удаление аккаунта убирает каскадно, и только пока он нужен: обработчик удаляет строку в той же транзакции, где сохраняет сформированную доставку. После этого текст есть только в доставке, с ее правилами хранения и доступа. Адрес обработчик читает из аккаунта в своей транзакции, поэтому это адрес, актуальный на момент создания. + +Письма с токеном. Тела писем подтверждения почты и сброса пароля содержат одноразовый bearer-токен, который никогда не должен попадать в событие или строку запроса, а хранилище держит только его SHA-256. Поэтому `mail_requests` и версия схемы 1 допускают только вид `notification`. Доставки писем с токеном должны создавать сценарии identity прямо в транзакции, которая выпускает токен, через те же `domain.NewDelivery` и `DeliveryRepository.Create`; это подключение запланировано вместе с TASK-016 и задачами регистрации и сброса пароля. + +Неизменяемое содержимое. Доставка хранит отрендеренное тело и никогда не рендерит его заново. Для рендеринга во время отправки нужен исходный токен, который существует только в памяти в момент выпуска, а повтор под тем же ключом идемпотентности должен повторить ровно то же тело: Resend считает измененное тело под старым ключом конфликтом. Domain пересчитывает hash содержимого при каждом чтении и при несовпадении возвращает `domain.ErrMailContentIntegrity`. Trigger `deliveries_refuse_content_change` отклоняет UPDATE, меняющий получателя, содержимое, ключ идемпотентности, исходное событие или время создания (SQLSTATE 23000, ограничение `deliveries_content_immutable`, адаптер переводит его в `outbound.ErrDeliveryContentImmutable`). Поэтому новая версия шаблона применяется только к новым доставкам, а для отправки сохраненной доставки старые файлы шаблона не нужны. + +Персональные данные в хранилище. Строка доставки содержит адрес получателя и тела письма, а ожидающая строка `mail_requests` - исходный текст уведомления. Тело письма с токеном содержит действующий bearer-токен, пока его не использовали, не заменили или пока не истек срок (по политике не более 7 дней), поэтому доступ на чтение к `deliveries` равен доступу к ссылке подтверждения или сброса для этого аккаунта, а дампы и резервные копии базы ее содержат. Следствия: + +- Запросы для эксплуатации выбирают столбцы метаданных (ID, вид, статус, попытки, время, провайдер) и никогда не выбирают тела, текст запроса и адрес; см. [DEPLOY.md](DEPLOY.md#доставки-писем). +- Удаление аккаунта каскадно удаляет его запросы писем, доставки и их попытки. Очистка неподтвержденных аккаунтов блокирует их через `FOR UPDATE SKIP LOCKED`, как токены и сессии, поэтому никогда не ждет обработчик доставки или worker, который держит строку. +- Правило хранения, которое удаляет или очищает завершенные доставки через ограниченный срок, еще не реализовано; пока его нет, строки остаются. Шифрование тел в хранилище тоже не реализовано. +- `Delivery`, `MailContent`, `MailRequest`, `NotificationText` и `EmailAddress` скрывают себя в выводе `fmt` и `slog`: доставка попадает в лог только как ID, вид, статус и провайдер. Ошибки обработчика называют нарушенное правило и никогда не цитируют payload, а адаптер заменяет текст ошибки PostgreSQL на SQLSTATE и имя ограничения. Метрик доставки пока нет; TASK-022 добавит их с labels только по виду, статусу и провайдеру, без адреса, ID аккаунта и темы. + +Статусы. Значения следуют исходам `MailSender`: + +| Статус | Значение | `next_attempt_at` | +| --- | --- | --- | +| `pending` | Ждет первую попытку или повтор после отказа `temporary` или `rate_limited` | Обязательно: когда доставка должна быть отправлена | +| `accepted` | Провайдер принял письмо и вернул `provider_message_id`; это не доставка человеку и не прочтение | Нет; конечный | +| `rejected` | Отказ `permanent` или `invalid_request`; причину нужно устранить | Нет; конечный | +| `unknown` | Попытка могла дойти до провайдера (`delivery_uncertain`). Это никогда не "не отправлено": повтор использует тот же ключ и сохраненное тело | Необязательно; отсутствие значит, что автоматического повтора нет | +| `waiting_quota` | Исчерпана квота провайдера или локальная квота | Необязательно: ожидаемый сброс; отсутствует, когда момент сброса неизвестен, например для месячной квоты Resend, и решение принимает оператор или правило квот | + +Переходы: + +- `Delivery.RecordAttempt` принимает результат одной попытки транспорта и добавляет строку попытки. `pending`, `waiting_quota` и `unknown` принимают попытку: `accepted` дает `accepted`, отказ `permanent` или `invalid_request` дает `rejected`, `temporary` или `rate_limited` - `pending`, `quota_exhausted` - `waiting_quota`, а `unknown` - `unknown`. `accepted` и `rejected` отклоняют любую следующую попытку с `domain.ErrDeliveryTransition`. +- `Delivery.WaitForQuota(at, until)` переводит доставку из `pending` или `waiting_quota` в `waiting_quota` без попытки - для случая, когда локальная квота TASK-018 откладывает отправку до вызова транспорта; нулевой `until` значит, что момент сброса неизвестен. Переход отклоняет `unknown`, чья прошлая попытка могла быть принята и чей повтор решает политика повторов, и конечные статусы. Сохраняет его `DeliveryRepository.WaitForQuota`. +- `Delivery.Rebind(at, account)` переносит доставку без единой попытки на другой аккаунт провайдера; см. ниже. Сохраняет его `DeliveryRepository.Rebind`. + +Каждое изменение увеличивает `version`, и хранилище применяет его только поверх предыдущей версии. Время следующей попытки задает политика повторов вызывающего кода (TASK-017), и оно должно соответствовать целевому статусу; CHECK `deliveries_next_attempt_matches_status` повторяет это правило, а `deliveries_provider_message_id_when_accepted` требует ID провайдера ровно для `accepted`. + +Попытки. Текущее состояние лежит в счетчиках `deliveries`, поэтому worker читает одну строку, а каждая попытка - отдельная строка `delivery_attempts`: номер, время, исход, причина отказа, код провайдера, ID письма у провайдера, подсказка ожидания, итоговый статус и время следующей попытки. История нужна оператору, чтобы оценить неизвестный исход, от нее (от первой попытки) отсчитывается конец 24-часового окна ключа, и на нее ссылается аудит ручного решения. Подсказка ожидания хранится точно как Go `time.Duration` в наносекундах (`retry_after_ns`), поэтому чтение после записи ее не меняет. `RecordAttempt` сохраняет доставку и попытку одним запросом: data-modifying CTE обновляет доставку, только пока ее версия равна версии до попытки, и добавляет попытку, только если обновление прошло. Второй писатель той же попытки получает `outbound.ErrDeliveryVersionConflict` и ничего не записывает. Trigger отклоняет UPDATE попытки. + +Учет квот не строится на этой истории: каскад от удаления аккаунта удаляет его доставки и попытки, поэтому подсчет отправок по `delivery_attempts` потерял бы отправки удаленных аккаунтов и позволил бы превысить квоту провайдера. TASK-018 нужен собственный счетчик без каскада, с ключом из провайдера, аккаунта провайдера и UTC-суток или месяца, который атомарно увеличивается при допуске отправки. + +Аккаунт провайдера. Каждая доставка закреплена за транспортом и аккаунтом, которые были настроены при ее создании. У провайдеров и аккаунтов нет общих ключей идемпотентности, поэтому FR19 запрещает переносить неопределенную доставку на другой; изменение конфигурации применяется только к новым доставкам, а worker отправки обязан использовать закрепленный аккаунт. `EMAIL_ACCOUNT` называет аккаунт (`default`, если не задан); меняйте его каждый раз, когда `RESEND_API_KEY` переходит к другому аккаунту Resend. Аккаунт можно сменить, только пока у доставки нет попыток, потому что до первой попытки ключ не видел ни один провайдер: `Delivery.Rebind` отклоняет доставку с попыткой или в конечном статусе, а trigger отклоняет смену провайдера после попытки (ограничение `deliveries_provider_pinned`, адаптер переводит его в `outbound.ErrDeliveryProviderPinned`). TASK-016 использует это для доставок, созданных при `EMAIL_PROVIDER=disabled`, когда стенд включит транспорт; переносить их автоматически или по запросу оператора, решает эта задача. + +Запланированные аддитивные изменения для следующих задач. Каждое - новый столбец, индекс или значение CHECK в следующей миграции; существующие строки остаются корректными: + +- Конечный статус отмены для доставки, которую больше нельзя отправлять: токен или аккаунт аннулирован до отправки (TASK-016) или отозвано разрешение (TASK-462). +- Необязательная ссылка доставки письма с токеном на `email_tokens.id`, чтобы worker перед отправкой проверил, что токен все еще действующий для своего назначения (TASK-016). +- Для worker отправки (TASK-016): столбцы lease (например, владелец захвата и `claimed_until`) и частичный индекс по `next_attempt_at` для статусов, которые берутся снова, чтобы несколько процессов захватывали доставки через `FOR UPDATE SKIP LOCKED`, а попытка, процесс которой остановился после отправки запроса, становилась `unknown`. +- Описанный выше счетчик квот TASK-018 без каскада. + +Хранилище уже дает `Get`, `ListAttempts`, `RecordAttempt` с проверкой версии, `WaitForQuota` и `Rebind`. + ### Версии продуктовой политики Реализованы хранение, публикация и начальное заполнение при старте (TASK-005): миграция `backend/db/migrations/00003_create_policy_versions.sql`, запросы в `backend/db/queries/policy.sql`, типизированная политика в `backend/internal/domain/` (`policy.go`, `policy_document.go`, `policy_version.go`, `policy_demo.go`), порт `outbound.PolicyRepository` (`port/outbound/policy.go`), адаптер на sqlc в `backend/internal/adapter/secondary/postgres/policy.go` и публикация в `backend/internal/usecase/policy/`. Ни одно продуктовое правило пока не читает политику; приглашения, квоты, оценивание, сессии и статус поиска начнут читать ее по мере реализации своих задач. @@ -276,7 +342,8 @@ backend/ port/inbound/ inbound границы readiness и обработчиков событий usecase/identity/ проверка пароля до хеширования (Credentials) usecase/policy/ публикация версий политики и начальное заполнение демонстрационной политики - usecase/notification/mailtemplate/ чистый рендеринг версионированных служебных писем для usecase identity и доставки (пока не подключен) + usecase/notification/ запросы писем и обработчик, который сохраняет их как доставки + usecase/notification/mailtemplate/ чистый рендеринг версионированных служебных писем; обработчик доставки рендерит им уведомления port/outbound/ границы readiness, кеша, объектного хранилища, транзакции, outbox, relay outbox, публикации и потребления событий, identity, политики, хеширования паролей и почты adapter/primary/http/ api/ generated ogen handler @@ -310,7 +377,7 @@ backend/ Это компактная карта, а не обещание, что все запланированные продуктовые пакеты уже существуют. Сейчас Go-код включает health usecase/adapters, generated API clients, bootstrap с миграциями при старте, PostgreSQL health query, транзакционную запись outbox, relay outbox, который публикует зафиксированные события в Kafka через адаптер franz-go, runtime обработчиков событий без зарегистрированных продуктовых обработчиков, репозитории identity без использующих их usecase, версионированное хранилище политики с публикацией и начальным заполнением демонстрационной политики при старте, порт `PasswordHasher` с адаптером Argon2id и проверку пароля, которую вызовет регистрация, Redis cache adapter, S3-адаптер SeaweedFS, порт `MailSender` с транспортами `disabled` и Resend и renderer шаблонов писем, который пока не вызывает ни один сценарий. Поведение аккаунтов (регистрация, подтверждение, вход, сессии), резюме, оценивание, приглашения, worker jobs, файловые сценарии, отправка почты, транспорт SMTP и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей. -`backend/pkg/` зарезервирован для небольших технических пакетов с оправданной общей границей, а не для продуктовых usecase или domain types. Возможные пакеты на будущее: `mailer` и тестовые helpers. Шаблоны писем вместо этого находятся в `internal/usecase/notification/mailtemplate/`: они содержат продуктовые тексты и используют domain types, например `SecretToken`. Это чистый пакет рендеринга без I/O и логирования; его должны вызывать usecase identity (подтверждение почты и сброс пароля) и запланированный usecase доставки, это подключение запланировано. Шаблоны, версии и формат ссылок описаны в [DEPLOY.md](DEPLOY.md#шаблоны-писем). S3-клиент остается в адаптере SeaweedFS. Поведение, специфичное для этого сервиса, остается внутри `internal/`. +`backend/pkg/` зарезервирован для небольших технических пакетов с оправданной общей границей, а не для продуктовых usecase или domain types. Возможные пакеты на будущее: `mailer` и тестовые helpers. Шаблоны писем вместо этого находятся в `internal/usecase/notification/mailtemplate/`: они содержат продуктовые тексты и используют domain types, например `SecretToken`. Это чистый пакет рендеринга без I/O и логирования. Обработчик доставки в `internal/usecase/notification/` рендерит им уведомления; usecase identity (подтверждение почты и сброс пароля) должны вызывать его при создании своих доставок, это подключение запланировано. Шаблоны, версии и формат ссылок описаны в [DEPLOY.md](DEPLOY.md#шаблоны-писем). S3-клиент остается в адаптере SeaweedFS. Поведение, специфичное для этого сервиса, остается внутри `internal/`. `api/` хранит контракты и инструменты и не является runtime hop в пути запроса. `api/core/` и `api/ml/` владеют исходным OpenAPI, fragments маршрутов и компонентов, а также коммитируемыми bundles. Схемы объединяет корневой `scripts/`. Сгенерированный Go-код лежит у потребителя: публичный handler - в `backend/internal/adapter/primary/http/api/`, внутренний ML client - в `backend/internal/adapter/secondary/ml/api/`, sqlc output - в `backend/internal/adapter/secondary/postgres/sqlc/`. Первый пакет монтируется в chi; два последних реализуют outbound adapters. `backend/cmd/app/main.go` остается точкой входа, а bootstrap отвечает за wiring и graceful shutdown. @@ -424,7 +491,7 @@ contact_grant относится к паре кандидат-компания - `EmailTokenRepository.Consume` - один `UPDATE ... RETURNING`, который требует непогашенный, неаннулированный и неистекший токен. Параллельные вызовы ждут в очереди на блокировку строки токена; при READ COMMITTED каждый ожидающий заново проверяет строку после завершения владельца блокировки, поэтому успешен ровно один, а если владелец откатился, ожидающий еще может погасить токен. Неудача сообщается как `ErrEmailTokenNotFound`, `ErrEmailTokenConsumed`, `ErrEmailTokenInvalidated` (заменен или выдан для более ранней версии регистрации) или `ErrEmailTokenExpired`. `InvalidateActive` помечает все прежние токены пользователя с этим назначением. - Consume сравнивает версию регистрации токена с аккаунтом только в том виде, в каком его прочитал запрос, без блокировки, поэтому не видит повторную регистрацию, зафиксированную сразу после него. Привязка токена к текущей регистрации поэтому соблюдается, только если подтверждение вызывает `MarkEmailVerified(token.UserID, token.RegistrationVersion)` в той же транзакции и откатывает ее при `ErrUserVersionConflict`; откат возвращает и токен, который затем считается замененным. Usecase подтверждения (TASK-054) переводит этот исход в `verification_token_invalid`. - `SessionRepository.FindActive` и `Touch` получают таймаут простоя от вызывающего кода и принимают только неотозванную сессию до ее абсолютного срока и в пределах таймаута простоя. `Touch` записывает `last_seen_at`, только если сохраненное значение старше более чем на минуту, поэтому частые запросы не переписывают строку, а таймаут простоя может завершить сессию на минуту раньше; `Touch` не сдвигает `last_seen_at` назад и не возобновляет завершенную сессию. `Revoke` и `RevokeAllForUser` устанавливают `revoked_at`. -- `DeleteUnverifiedRegisteredBefore` удаляет одну пачку неподтвержденных аккаунтов, начиная со старых, и никогда не ждет блокировку. Он блокирует аккаунты-кандидаты, их токены и сессии через `FOR UPDATE SKIP LOCKED` и пропускает каждый аккаунт, у которого строка аккаунта или любая строка токена или сессии заблокирована другой транзакцией, например повторной регистрацией, повторной отправкой или подтверждением; пропущенные аккаунты остаются до следующего запуска. +- `DeleteUnverifiedRegisteredBefore` удаляет одну пачку неподтвержденных аккаунтов, начиная со старых, и никогда не ждет блокировку. Он блокирует аккаунты-кандидаты, их токены, сессии, запросы писем и доставки писем через `FOR UPDATE SKIP LOCKED` и пропускает каждый аккаунт, у которого строка аккаунта или любая строка токена, сессии, запроса письма или доставки заблокирована другой транзакцией, например повторной регистрацией, повторной отправкой, подтверждением, обработчиком доставки или worker доставки; пропущенные аккаунты остаются до следующего запуска. Запросы писем, доставки и попытки удаляются вместе с аккаунтом каскадно. - `postgres.IdentityStore` выполняет те же репозитории вне транзакции. При вызове с контекстом из callback `Transactor` он возвращает `ErrNestedTransaction`, а не фиксирует изменения через отдельное соединение. - Нарушения уникальности и внешних ключей переводятся в `ErrEmailTaken`, `ErrTokenHashConflict` и `ErrUserNotFound` по SQLSTATE и имени ограничения, а не по тексту ошибки. - Порядок блокировок: операция, которая меняет и аккаунт, и его токены, сначала блокирует токены. Подтверждение гасит токен, а затем подтверждает аккаунт, поэтому повторная регистрация или повторная отправка вызывает `InvalidateActive` до обновления аккаунта или вставки токена; обратный порядок может привести к взаимной блокировке. Единственное исключение - очистка: она блокирует аккаунт раньше токенов и сессий, и это безопасно, потому что каждая из этих блокировок берется с SKIP LOCKED и никогда не ждет. Если взаимная блокировка (SQLSTATE 40P01) или ошибка сериализации (40001) все же случится, `Transactor.WithinTransaction` и репозитории identity сообщают ее как `outbound.ErrTransactionConflict`; ничего не зафиксировано, и usecase или job может повторить всю операцию с паузой, оставаясь идемпотентным. diff --git a/docs/ru/DEPLOY.md b/docs/ru/DEPLOY.md index 71d0b5c..7af1fbc 100644 --- a/docs/ru/DEPLOY.md +++ b/docs/ru/DEPLOY.md @@ -99,7 +99,7 @@ Relay создает отсутствующий топик и никогда н ### Обработчики событий -Backend запускает по одному обработчику событий на каждый зарегистрированный handler в своем процессе рядом с HTTP-серверами и relay. Обработчик читает `KAFKA_EVENTS_TOPIC` как участник группы `.<имя обработчика>`, применяет каждое событие один раз и фиксирует offset только после того, как эффект зафиксирован в PostgreSQL. Устройство описано в [ARCHITECTURE.md](ARCHITECTURE.md#обработчики-событий). Текущее состояние: продуктовых обработчиков нет, поэтому backend пишет в журнал `no event consumer is registered`, не запускает ни одного обработчика и не открывает consumer group; настройки ниже начнут действовать, когда появится обработчик. Compose не передает ни одну из них, поэтому стек использует значения по умолчанию; чтобы изменить настройку, добавьте ее в `environment` сервиса backend в `deploy/docker/docker-compose.yml`. Недопустимое значение останавливает старт, даже если обработчики выключены. +Backend запускает по одному обработчику событий на каждый зарегистрированный handler в своем процессе рядом с HTTP-серверами и relay. Обработчик читает `KAFKA_EVENTS_TOPIC` как участник группы `.<имя обработчика>`, применяет каждое событие один раз и фиксирует offset только после того, как эффект зафиксирован в PostgreSQL. Устройство описано в [ARCHITECTURE.md](ARCHITECTURE.md#обработчики-событий). Текущее состояние: зарегистрирован один продуктовый обработчик, `notification_delivery` (доставки писем), поэтому при `CONSUMER_ENABLED` и заданном `DATABASE_URL` backend запускает один обработчик в группе `.notification_delivery` (по умолчанию `lincodex.notification_delivery`). Compose не передает ни одну из них, поэтому стек использует значения по умолчанию; чтобы изменить настройку, добавьте ее в `environment` сервиса backend в `deploy/docker/docker-compose.yml`. Недопустимое значение останавливает старт, даже если обработчики выключены. | Переменная | По умолчанию | Назначение | | --- | --- | --- | @@ -168,7 +168,7 @@ Dead letter - запись, от которой обработчик отказ Backend отправляет почту через порт `MailSender`. `EMAIL_PROVIDER` выбирает ровно один транспорт: `resend` (HTTP API Resend, основной провайдер рабочего стенда), `smtp` (отдельный SMTP relay) или `disabled`. Значения по умолчанию нет, и запасного варианта тоже нет: если выбранный транспорт не может запуститься, backend останавливается, а не переключается на другой. Настройки невыбранных транспортов не читаются. -Текущее состояние: в этой сборке есть транспорты `disabled` и `resend`. С `smtp` backend проверяет настройки SMTP и затем завершается с ошибкой `EMAIL_PROVIDER=smtp: mail transport is not available in this build`; в Compose `restart: unless-stopped` будет перезапускать контейнер снова и снова. SMTP вне MVP. `.env.example` и `make -C deploy smoke` используют `disabled`, поэтому локальному запуску ключ не нужен; рабочий стенд явно задает `EMAIL_PROVIDER=resend` и `RESEND_API_KEY`. Пока ни один сценарий не отправляет почту: слой доставки, который вызывает транспорт, запланирован. +Текущее состояние: в этой сборке есть транспорты `disabled` и `resend`. С `smtp` backend проверяет настройки SMTP и затем завершается с ошибкой `EMAIL_PROVIDER=smtp: mail transport is not available in this build`; в Compose `restart: unless-stopped` будет перезапускать контейнер снова и снова. SMTP вне MVP. `.env.example` и `make -C deploy smoke` используют `disabled`, поэтому локальному запуску ключ не нужен; рабочий стенд явно задает `EMAIL_PROVIDER=resend` и `RESEND_API_KEY`. Пока ни один сценарий не отправляет почту: запросы писем сохраняются как доставки (см. [Доставки писем](#доставки-писем)), а worker, который вызывает транспорт, запланирован. `resend` отправляет каждое письмо одним запросом к `https://api.resend.com/emails`. Создание транспорта не обращается к сети, поэтому при запуске не проверяются ни ключ, ни домен отправителя; неверный ключ или неподтвержденный домен в `EMAIL_FROM` проявятся как отказ при отправке. Одну попытку ограничивает `EMAIL_TIMEOUT`. Транспорт не следует редиректам, никогда не повторяет запрос и ничего не логирует; повторы, backoff, темп при rate limit, ожидание сброса дневной или месячной квоты и учет результатов относятся к запланированному слою доставки. Каждый запрос несет ключ идемпотентности письма, и Resend 24 часа не отправляет повторно письмо с тем же ключом и телом; после этого окна повтор может отправить письмо дважды. Успех значит, что Resend принял запрос и вернул идентификатор письма, а не что письмо доставлено или прочитано. Таймаут, потерянный ответ после отправки запроса или ошибка 500 от Resend дают `unknown` (`delivery_uncertain`), а не ошибку. Процесс backend учитывает стандартные переменные `HTTPS_PROXY` и `NO_PROXY`, но сервис backend в Compose их не передает, поэтому под Compose запрос идет в Resend напрямую; если стенду нужен прокси для исходящего трафика, добавьте эти переменные в `environment` сервиса backend. Полное соответствие ответов описано в [ARCHITECTURE.md](ARCHITECTURE.md#почтовый-транспорт). @@ -178,6 +178,7 @@ Backend отправляет почту через порт `MailSender`. `EMAIL | --- | --- | --- | | `EMAIL_PROVIDER` | нет, обязательна | `resend`, `smtp` или `disabled`, без учета регистра | | `EMAIL_FROM` | нет, обязательна | Один mailbox: `no-reply@example.com` или `Lincodex `. Только печатные ASCII символы. Адрес подчиняется правилам адресов аккаунтов: local part без кавычек и DNS-домен минимум из двух меток, без IP literal. | +| `EMAIL_ACCOUNT` | `default` | Метка аккаунта провайдера, за которым закрепляются новые доставки: от 1 до 64 строчных букв, цифр, `.`, `_` или `-`, начиная с буквы или цифры. Никогда не ключ. | | `EMAIL_TIMEOUT` | `10s` | Go duration от `1s` до `1m`; ограничивает одну попытку транспорта | | `APP_PUBLIC_URL` | нет, обязательна | Публичный origin для ссылок в письмах: `https://host[:port]`, а `http` только для `localhost`, `127.0.0.1` или `[::1]`. Без учетных данных, пути, query и fragment; один завершающий `/` отбрасывается. | | `RESEND_API_KEY` | пусто | Читается только для `resend` и там обязательна. Печатные ASCII символы без пробелов. Префикс `re_` из примеров Resend не проверяется. | @@ -188,14 +189,24 @@ Backend отправляет почту через порт `MailSender`. `EMAIL Compose передает эти переменные из корневого `.env`. `EMAIL_PROVIDER`, `EMAIL_FROM` и `APP_PUBLIC_URL` обязательны, поэтому без них Compose не соберет конфигурацию проекта; перенесите блок почты из `.env.example` в существующий `.env`. Храните `RESEND_API_KEY` и `SMTP_PASSWORD` в окружении сервера или в хранилище секретов деплоя и никогда не коммитьте их. Ошибки конфигурации называют настройку, но не печатают ее значение, а лог запуска называет только выбранного провайдера. +### Доставки писем + +Запрос уведомления - строка `mail_requests`, пока обработчик `notification_delivery` не превратит его в строку `deliveries` и не удалит; модель описана в [ARCHITECTURE.md](ARCHITECTURE.md#доставки-писем). Миграция 00006 создает `mail_requests`, `deliveries` и `delivery_attempts` при запуске; настройки для этого не нужны. Пока доставки только сохраняются: worker, который их отправляет, запланирован, поэтому ни одна строка не выходит из `pending`. Уведомления создаются только для аккаунтов с подтвержденным адресом; запрос на неподтвержденный адрес отбрасывается со строкой в логе. + +- Каждая доставка закрепляется за `EMAIL_PROVIDER` и `EMAIL_ACCOUNT` в момент создания, а последующее изменение конфигурации применяется только к новым доставкам. Меняйте `EMAIL_ACCOUNT` вместе с `RESEND_API_KEY` каждый раз, когда ключ принадлежит другому аккаунту Resend, чтобы доставки, начатые под старым аккаунтом, никогда не отправлялись через новый. Доставки, созданные при `EMAIL_PROVIDER=disabled`, остаются закрепленными за `disabled`, пока worker отправки (TASK-016) не перенесет их через `Rebind`, что разрешено только до первой попытки. +- Строки содержат адрес получателя и сформированные тела писем, а ожидающая строка `mail_requests` - исходный текст уведомления; тела писем подтверждения почты и сброса пароля содержат действующий одноразовый токен, пока его не использовали или пока не истек срок. Относитесь к доступу на чтение к `deliveries` как к доступу к этим ссылкам и защищайте дампы и резервные копии базы так же. Срок хранения завершенных доставок пока не реализован. +- Для просмотра доставок выбирайте только метаданные, например `SELECT id, kind, template_version, status, attempt_count, next_attempt_at, last_attempt_at, provider, provider_account, created_at FROM deliveries ORDER BY created_at DESC LIMIT 50` и `SELECT attempt_number, attempted_at, outcome, rejection, provider_code, status_after FROM delivery_attempts WHERE delivery_id = '' ORDER BY attempt_number`. `SELECT count(*), min(created_at) FROM mail_requests` показывает запросы, которые обработчик еще не обработал; растущее число значит, что обработчик остановлен или его события уходят в dead letters. Не выбирайте `recipient_email`, `subject`, `text_body`, `html_body` и текстовые столбцы `mail_requests` и никогда не вставляйте их в задачи и чаты. +- Не правьте сохраненную доставку вручную: trigger отклоняет любое изменение получателя, содержимого или ключа идемпотентности и смену аккаунта провайдера после первой попытки, а история попыток отклоняет обновления. Доставка в `waiting_quota` без `next_attempt_at` ждет сброса квоты, момент которого неизвестен, например месячной квоты Resend, и требует решения оператора. +- Логи называют доставку только по `delivery_id` (вместе с ID события), никогда по адресу или теме. Пропущенные запросы пишутся на уровне info: `mail request skipped because it was already handled or its account was deleted` и `notification skipped because the recipient address is not verified`. Запрос, нарушающий контракт события, становится dead letter класса `handler_rejected` обработчика `notification_delivery`; см. [Dead letters и повторный запуск](#dead-letters-и-повторный-запуск). Повторять его безопасно: ID доставки сохраняет одну доставку на запрос. + ### Шаблоны писем -Реализовано: renderer в `backend/internal/usecase/notification/mailtemplate/` с шаблонами подтверждения почты, сброса пароля и короткого уведомления. Пока его никто не вызывает: регистрация, подтверждение, сброс пароля и доставка почты запланированы, поэтому текущая сборка не формирует и не отправляет писем. +Реализовано: renderer в `backend/internal/usecase/notification/mailtemplate/` с шаблонами подтверждения почты, сброса пароля и короткого уведомления. Обработчик доставки рендерит им уведомления, когда сохраняет доставку; регистрация, подтверждение, сброс пароля и отправка запланированы, поэтому текущая сборка не отправляет писем. - Шаблоны встроены в бинарник через `go:embed` и разбираются один раз при создании renderer; сломанный шаблон останавливает создание. У каждой версии три файла: `.v.subject.tmpl`, `.v.txt.tmpl` и `.v.html.tmpl`. HTML часть использует `html/template`, текстовая часть и тема используют `text/template`. Любой транспорт отправляет один и тот же результат; в шаблонах нет настроек провайдера, ключей и адреса отправителя. - Ссылки начинаются с `APP_PUBLIC_URL`, который renderer повторно проверяет по тем же правилам. Подтверждение: `/verify-email#token=`; сброс пароля: `/reset-password#token=` (страница и API сброса запланированы). Токен находится только во fragment URL и никогда в query. Ссылка уведомления указывает на путь внутри приложения, например `/candidate/invitations`; абсолютный URL, `//host`, схема вроде `javascript:`, query, fragment, знак процента и сегменты `.` или `..` отклоняются. - В письмах нет имени, email или других контактов. Текст вызывающего кода в уведомлении экранируется в HTML части; управляющие и bidi символы удаляются из текстовой части, а тема сводится к одной строке, поэтому CR и LF не могут добавить строки заголовка. Тема уведомления ограничена 100 символами, текст 2000. -- Тексты на русском языке. Выпущенная версия неизменяема: изменение текста добавляет следующую версию, например `verification.v2`, и переключает текущую версию в коде. Версии не делят файлы, поэтому одна версия не может изменить тело другой. Каждый результат содержит свою версию и SHA-256 content hash по версии, теме и обеим частям; одна и та же версия с теми же данными всегда дает то же тело. Запланированный слой доставки должен сохранять сформированное тело вместе с hash и при повторе отправлять сохраненное тело, а не формировать его заново; храните файлы старой версии, пока на нее ссылаются сохраненные доставки. +- Тексты на русском языке. Выпущенная версия неизменяема: изменение текста добавляет следующую версию, например `verification.v2`, и переключает текущую версию в коде. Версии не делят файлы, поэтому одна версия не может изменить тело другой. Каждый результат содержит свою версию и SHA-256 content hash по версии, теме и обеим частям; одна и та же версия с теми же данными всегда дает то же тело. Доставка хранит сформированное тело вместе с hash, а повтор отправляет сохраненное тело, а не формирует его заново, поэтому новая версия применяется только к новым доставкам, а файлы старой версии для отправки сохраненной доставки не нужны. - Renderer ничего не пишет в лог. Результат и данные уведомления в выводе `fmt` и `slog` показывают только тип, версию и content hash; токены, ссылки и тела писем не печатаются. - Golden файлы в `testdata/` делают каждое изменение текста видимым на ревью. После намеренного изменения выполните `go test ./internal/usecase/notification/mailtemplate -update` из `backend/` и проверьте diff. diff --git a/docs/ru/DEVELOPMENT.md b/docs/ru/DEVELOPMENT.md index c59f828..3123deb 100644 --- a/docs/ru/DEVELOPMENT.md +++ b/docs/ru/DEVELOPMENT.md @@ -50,14 +50,14 @@ Frontend зависимости выбираются из актуальных s - Маршруты health и readiness. Nginx сам отвечает на `GET /healthz` и проксирует в Go только `/api/` (deploy/nginx/conf.d/app.conf). Go обслуживает `GET /healthz` (`ok`) и `GET /readyz` (`ready` или 503 `not_ready` после проверки PostgreSQL, Redis и SeaweedFS) на внутреннем порту 8080 вне OpenAPI контракта, а также `GET /api/v1/healthz` из api/core/routes/healthz.yml через ogen handler (backend/internal/adapter/primary/http). Метрики Go отдаются на порту 9090 (`METRICS_ADDR`), Prometheus читает `/metrics`. ML обслуживает `GET /healthz`, `GET /readyz` (всегда 503 `not_ready`, потому что модель не подключена) и `/metrics` (ml/src/lincodex_ml, api/ml/routes). deploy/scripts/smoke.sh проверяет `/healthz` Nginx, `/api/v1/healthz`, `/readyz` Go изнутри сети Compose, 404 для неизвестного API маршрута и то, что backend запустился с `EMAIL_PROVIDER=disabled`; ML он не запускает и писем не отправляет. - Адаптеры: PostgreSQL через pgxpool и generated запрос `SELECT 1`, runner миграций goose, применяемый при старте, transactor с записью transactional outbox, репозитории identity на sqlc для аккаунтов, email-токенов и сессий, а также версионированный репозиторий политики, который при старте заполняет демонстрационную политику; Redis через go-cachekit, SeaweedFS через S3 API. Hasher паролей Argon2id и проверка пароля `identity.Credentials` есть и покрыты тестами, но в bootstrap не подключены. Generated Go client для ML контракта есть, но в bootstrap не подключен. -- Почта: outbound порт `MailSender`, транспорт `disabled` и выбор `EMAIL_PROVIDER` в bootstrap. В этой сборке работает только `disabled`; `resend` и `smtp` после проверки своих настроек останавливают запуск. Пока ничто не отправляет письма. См. [DEPLOY.md](DEPLOY.md#почта) и [ARCHITECTURE.md](ARCHITECTURE.md#почтовый-транспорт). +- Почта: outbound порт `MailSender`, транспорты `disabled` и `resend` и выбор `EMAIL_PROVIDER` в bootstrap; `smtp` после проверки своих настроек останавливает запуск. Запросы уведомлений (`mail_requests`) превращаются в доставки (`deliveries`, `delivery_attempts`) обработчиком `notification_delivery`, но пока ничто их не отправляет. См. [DEPLOY.md](DEPLOY.md#почта) и [ARCHITECTURE.md](ARCHITECTURE.md#доставки-писем). - OpenAPI контракты api/core/ и api/ml/ с объединением схем, bundles, lint и генерацией для Go (ogen), TypeScript (Orval) и Python (datamodel-code-generator). В SPA есть каркас интерфейса с экранами-заготовками, generated API client и MSW handlers. - Compose проекты: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`) и monitoring (`docker-compose.monitoring.yml`). -- Kafka: один узел KRaft в core Compose проекте с listener только во внутренней сети, именованным volume, healthcheck и лимитом памяти. Backend запускает relay outbox, который создает топик `lincodex.domain.events` и публикует в него зафиксированные события outbox через producer на franz-go; см. [Relay outbox](#relay-outbox). Readiness не проверяет Kafka. Runtime обработчиков событий есть, но продуктовые обработчики не зарегистрированы, поэтому события пока никто не читает; см. [Обработчики событий](#обработчики-событий). +- Kafka: один узел KRaft в core Compose проекте с listener только во внутренней сети, именованным volume, healthcheck и лимитом памяти. Backend запускает relay outbox, который создает топик `lincodex.domain.events` и публикует в него зафиксированные события outbox через producer на franz-go; см. [Relay outbox](#relay-outbox). Readiness не проверяет Kafka. Runtime обработчиков событий запускает один продуктовый обработчик - обработчик доставки писем, а продуктовые сценарии пока не создают его событие; см. [Обработчики событий](#обработчики-событий). - CI jobs в .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix из двух шардов), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke`, `e2e` (набор Playwright на изолированном стенде) и обязательный итог `aggregate`, который падает, если любой из них упал, отменен или пропущен. Шардирование и браузерный набор описаны в [TESTING.md](TESTING.md). - Observability: Prometheus, Loki, Alloy, Grafana с provisioned datasources и dashboards, exporters для PostgreSQL, Redis и node. React-приложение пока не отправляет телеметрию. -Еще не реализованы: регистрация и вход (их контракт объявлен; операции отвечают 501 или 401), согласия, профили, анкета и тестирование, кабинет компании, потребности и подбор, приглашения и контакты, транспорты Resend и SMTP и отправка почты, продуктовые обработчики событий, уведомления, поддержка и бизнес-E2E suite. В backend/db/migrations/ есть таблица outbox с индексом для relay, таблицы хранения identity (`users`, `email_tokens`, `sessions`), таблица `policy_versions` и таблицы обработчиков событий (`consumer_processed_events`, `consumer_dead_letters`), другой бизнес-схемы нет; ни одно продуктовое правило пока не читает политику; регистрация, подтверждение и сессии поверх этого хранения появятся в следующих задачах, каталоги продуктовых usecase и адаптеров, кроме частей для хеширования паролей и политики, содержат только заглушки, а `make -C deploy test-e2e` запускает только технический smoke на Playwright для SPA, health API и маршрутов ошибок на одноразовом стеке, а не бизнес-сценарий (см. [TESTING.md](TESTING.md#браузерный-e2e-набор)). Целевая архитектура описана в [ARCHITECTURE.md](ARCHITECTURE.md). +Еще не реализованы: регистрация и вход (их контракт объявлен; операции отвечают 501 или 401), согласия, профили, анкета и тестирование, кабинет компании, потребности и подбор, приглашения и контакты, транспорт SMTP и worker, который отправляет сохраненные доставки, продуктовые источники событий, уведомления, поддержка и бизнес-E2E suite. В backend/db/migrations/ есть таблица outbox с индексом для relay, таблицы хранения identity (`users`, `email_tokens`, `sessions`), таблица `policy_versions` таблицы обработчиков событий (`consumer_processed_events`, `consumer_dead_letters`) и таблицы доставок писем (`deliveries`, `delivery_attempts`), другой бизнес-схемы нет; ни одно продуктовое правило пока не читает политику; регистрация, подтверждение и сессии поверх этого хранения появятся в следующих задачах, каталоги продуктовых usecase и адаптеров, кроме частей для хеширования паролей и политики, содержат только заглушки, а `make -C deploy test-e2e` запускает только технический smoke на Playwright для SPA, health API и маршрутов ошибок на одноразовом стеке, а не бизнес-сценарий (см. [TESTING.md](TESTING.md#браузерный-e2e-набор)). Целевая архитектура описана в [ARCHITECTURE.md](ARCHITECTURE.md). ## Установка и цикл работы @@ -189,10 +189,14 @@ Backend, запущенный напрямую с `DATABASE_URL`, запуска Runtime обработчиков применяет события из Kafka к собственному состоянию сервиса, по одному разу на обработчик. Цикл находится в `backend/internal/worker/eventconsumer/`; он зависит от порта `inbound.EventHandler` (`backend/internal/port/inbound/event_handler.go`) и портов `outbound.EventSource` и `outbound.EventConsumerStore` (`backend/internal/port/outbound/event_consumer.go`). `kafka.EventSource` - участник группы на franz-go, который декодирует конверт и фиксирует offsets, а `postgres.EventConsumerStore` выполняет транзакцию дедупликации запросами из `backend/db/queries/event_consumer.sql`. Backoff общий с relay и находится в `backend/internal/worker/retry/`. -Продуктовых обработчиков пока нет. Чтобы добавить обработчик, реализуйте `inbound.EventHandler` в пакете usecase модуля: верните стабильное имя в snake_case из `ConsumerName()`, принимайте в `Handles` только применяемые типы событий и пишите эффект в `Handle` только через полученный `UnitOfWork`. Для события, которое нельзя применить никогда, например с неизвестной `schema_version`, верните ошибку, оборачивающую `inbound.ErrEventRejected`; любая другая ошибка повторяется. Затем добавьте обработчик в `eventHandlers()` в `backend/internal/bootstrap/consumers.go`. Bootstrap выдает ему consumer group, соединение из пула обработчиков и жизненный цикл рядом с HTTP-серверами. Проверяйте эффект на реальном PostgreSQL через хранилище, как это делает `TestEventConsumer`. +Зарегистрирован один продуктовый обработчик: `notification.DeliveryHandler` сохраняет доставки писем (см. [Доставки писем](#доставки-писем)). Чтобы добавить другой обработчик, реализуйте `inbound.EventHandler` в пакете usecase модуля: верните стабильное имя в snake_case из `ConsumerName()`, принимайте в `Handles` только применяемые типы событий и пишите эффект в `Handle` только через полученный `UnitOfWork`. Для события, которое нельзя применить никогда, например с неизвестной `schema_version`, верните ошибку, оборачивающую `inbound.ErrEventRejected`; любая другая ошибка повторяется. Затем добавьте обработчик в `eventHandlers()` в `backend/internal/bootstrap/consumers.go`. Bootstrap выдает ему consumer group, соединение из пула обработчиков и жизненный цикл рядом с HTTP-серверами. Проверяйте эффект на реальном PostgreSQL через хранилище, как это делает `TestEventConsumer`. Backend, запущенный напрямую с зарегистрированным обработчиком и `DATABASE_URL`, читает события из `KAFKA_BROKERS`; задайте `CONSUMER_ENABLED=false`, если это не нужно. Устройство и поведение при сбоях описаны в [ARCHITECTURE.md](ARCHITECTURE.md#обработчики-событий); настройки, метрики и порядок работы с dead letters - в [DEPLOY.md](DEPLOY.md#обработчики-событий); тесты - в [TESTING.md](TESTING.md#тесты-обработчиков-событий). +### Доставки писем + +Чтобы отправить уведомление из usecase, вызовите `notification.MailRequester.RequestNotification(ctx, unit, request)` с `UnitOfWork` usecase, ID аккаунта получателя и `mailtemplate.NotificationData`; вызов возвращает ID доставки. Он сохраняет текст в `mail_requests` и добавляет событие, которое несет только ID запроса и вид, оба действия - в транзакции usecase. Затем обработчик `notification_delivery` сохраняет доставку с адресом, прочитанным из аккаунта, и сформированным содержимым и удаляет запрос; аккаунты с неподтвержденным адресом он пропускает. Никогда не кладите email, токен, текст уведомления или контакт другого человека в payload любого события и никогда не кладите токен или контакт другого человека в запрос. Письма подтверждения почты и сброса пароля содержат токен и не могут идти через событие: сценарии identity создают такие доставки через `domain.NewDelivery` и `UnitOfWork.Deliveries().Create` в транзакции, которая выпускает токен. Новая версия шаблона меняет только новые доставки; никогда не обновляйте содержимое сохраненной доставки. Модель описана в [ARCHITECTURE.md](ARCHITECTURE.md#доставки-писем), эксплуатация - в [DEPLOY.md](DEPLOY.md#доставки-писем), тесты - в [TESTING.md](TESTING.md#тесты-доставки-писем). + ## Читаемость Go-кода - Повторяющиеся parsing, setup и cleanup выносятся в небольшие типизированные helpers рядом с потребителями. В `pkg/` код переносится при реальном использовании несколькими пакетами. Обертка, которая лишь переименовывает вызов, не нужна. diff --git a/docs/ru/TESTING.md b/docs/ru/TESTING.md index ab28e88..cd28646 100644 --- a/docs/ru/TESTING.md +++ b/docs/ru/TESTING.md @@ -38,7 +38,7 @@ make -C ml check-generated использует datamodel-code-generator --check ## Что покрывает текущий каркас -Существующие проверки относятся к health/readiness, проверке соединения backend с PostgreSQL, Redis и SeaweedFS, миграциям up, down до нуля и повторному up на изолированной базе, конкурентным runner миграций, которые применяют каждую миграцию один раз, transactional outbox (атомарная фиксация, откат при ошибке, panic и отмене контекста, отказ во вложенной транзакции, наблюдаемое ожидание блокировки строки между параллельными транзакциями, граничные payload и ограничения), хранению identity (уникальный нормализованный email, хранение только хешей email-токенов и токенов сессий, ровно одно успешное погашение токена при параллельных подтверждениях и наблюдаемое ожидание блокировки между двумя погашениями, отказ для истекших, аннулированных и замененных токенов, в том числе при повторной регистрации во время подтверждения, пределы простоя, абсолютного срока и отзыва сессии и ограничение частоты записи активности, пакетная очистка неподтвержденных аккаунтов, которая пропускает заблокированные аккаунты без ожидания, взаимная блокировка как повторяемый конфликт, каскадное удаление, откат вместе с внешней транзакцией и ограничения), операциям кеша и TTL, S3-операциям и сохранению объектов, тестовой обвязке Kafka (записи с ключом и заголовками и порядок внутри партиции, отказ создавать отсутствующий топик по запросу и очистка топиков), relay outbox (см. [Тесты relay outbox](#тесты-relay-outbox)), runtime обработчиков событий (см. [Тесты обработчиков событий](#тесты-обработчиков-событий)), метрикам, API client, ML schema и доступности текущих endpoint. В каркасе нет сценариев регистрации, входа, тестирования, поиска, приглашений или работы с файлами, нет продуктовых событий и продуктовых обработчиков в Kafka и нет реального model inference, которые можно было бы проверить как бизнес-результат. +Существующие проверки относятся к health/readiness, проверке соединения backend с PostgreSQL, Redis и SeaweedFS, миграциям up, down до нуля и повторному up на изолированной базе, конкурентным runner миграций, которые применяют каждую миграцию один раз, transactional outbox (атомарная фиксация, откат при ошибке, panic и отмене контекста, отказ во вложенной транзакции, наблюдаемое ожидание блокировки строки между параллельными транзакциями, граничные payload и ограничения), хранению identity (уникальный нормализованный email, хранение только хешей email-токенов и токенов сессий, ровно одно успешное погашение токена при параллельных подтверждениях и наблюдаемое ожидание блокировки между двумя погашениями, отказ для истекших, аннулированных и замененных токенов, в том числе при повторной регистрации во время подтверждения, пределы простоя, абсолютного срока и отзыва сессии и ограничение частоты записи активности, пакетная очистка неподтвержденных аккаунтов, которая пропускает заблокированные аккаунты без ожидания, взаимная блокировка как повторяемый конфликт, каскадное удаление, откат вместе с внешней транзакцией и ограничения), операциям кеша и TTL, S3-операциям и сохранению объектов, тестовой обвязке Kafka (записи с ключом и заголовками и порядок внутри партиции, отказ создавать отсутствующий топик по запросу и очистка топиков), relay outbox (см. [Тесты relay outbox](#тесты-relay-outbox)), runtime обработчиков событий (см. [Тесты обработчиков событий](#тесты-обработчиков-событий)), доставкам писем (см. [Тесты доставки писем](#тесты-доставки-писем)), метрикам, API client, ML schema и доступности текущих endpoint. В каркасе нет сценариев регистрации, входа, тестирования, поиска, приглашений или работы с файлами, нет продуктовых источников событий в Kafka (обработчик доставки писем проверяется только тестами) и нет реального model inference, которые можно было бы проверить как бизнес-результат. API verify проверяет выбранный OpenAPI subset через pinned toolchain; его результат относится только к реально запущенным fixture и контрактам. CI YAML в репозитории не означает, что workflow уже выполнился на GitHub. @@ -92,7 +92,7 @@ Unit-тесты (`make -C backend test`) покрывают конверт за ## Тесты обработчиков событий -Unit-тесты (`make -C backend test`) покрывают runtime обработчиков с поддельными источником, хранилищем и обработчиком (`internal/worker/eventconsumer/`): записи `applied`, `duplicate` и `ignored`, зафиксированные в порядке получения; сбои хранилища, которые повторяются сверх лимита попыток без dead letter, а offset фиксируется только после успеха хранилища; обработчик, который все время падает, повторяется ровно `MaxAttempts` раз не чаще минимального backoff, а затем уходит в dead letters с ID и типом события, размером значения и SHA-256, пока следующая запись применяется; `ErrEventRejected` и panic, которые уходят в dead letters после одной попытки без цитирования значения panic; невалидную запись, которая уходит в dead letters без вызова обработчика, причем commit ждет, пока две неудачные записи dead letter не пройдут; остановку, которая бросает зависший обработчик после grace без фиксации его и всего после него; запись, которая завершается в пределах grace и фиксируется, тогда как следующая не начинается; отсутствие повторов и dead letters во время остановки; backoff после неудачных чтений; commit, который PostgreSQL отвергает после того, как обработчик проглотил ошибку, считается попыткой и заканчивается `retries_exhausted`; конфликт сериализации при commit повторяется как попытка; panic в `Handles` уходит в dead letters без цитирования значения; начало пачки фиксируется сразу после dead letter, до начала следующей записи; счетчики сбоев `poll` и `commit`; очистку причины. Тесты адаптера PostgreSQL проверяют классификацию отвергнутого, конфликтного и сетевого сбоя commit и то, что ошибки обработчика сохраняют идентичность без сообщения PostgreSQL. Они же покрывают декодирование конверта и его согласованность с producer, каждое отвергнутое правило конверта без цитирования значения и учет commit участника группы, включая отказ для завершенных записей, которые не являются для каждой партиции началом последнего чтения без пропусков (`internal/adapter/secondary/kafka/`), настройки обработчиков и бюджет ребалансировки, включая описанное в документации значение по умолчанию 42,5 секунды (`config/`), счетчики обработчиков (`internal/adapter/secondary/prometheus/`), а в `internal/bootstrap/` - случаи пропуска, один обработчик на handler, отказ для повторяющихся и недопустимых имен, пустой список обработчиков, значения меток, совпадающие с подготовленными метриками, и приложение, которое запускает обработчик вместе с серверами и возвращается только после того, как он перестал читать. +Unit-тесты (`make -C backend test`) покрывают runtime обработчиков с поддельными источником, хранилищем и обработчиком (`internal/worker/eventconsumer/`): записи `applied`, `duplicate` и `ignored`, зафиксированные в порядке получения; сбои хранилища, которые повторяются сверх лимита попыток без dead letter, а offset фиксируется только после успеха хранилища; обработчик, который все время падает, повторяется ровно `MaxAttempts` раз не чаще минимального backoff, а затем уходит в dead letters с ID и типом события, размером значения и SHA-256, пока следующая запись применяется; `ErrEventRejected` и panic, которые уходят в dead letters после одной попытки без цитирования значения panic; невалидную запись, которая уходит в dead letters без вызова обработчика, причем commit ждет, пока две неудачные записи dead letter не пройдут; остановку, которая бросает зависший обработчик после grace без фиксации его и всего после него; запись, которая завершается в пределах grace и фиксируется, тогда как следующая не начинается; отсутствие повторов и dead letters во время остановки; backoff после неудачных чтений; commit, который PostgreSQL отвергает после того, как обработчик проглотил ошибку, считается попыткой и заканчивается `retries_exhausted`; конфликт сериализации при commit повторяется как попытка; panic в `Handles` уходит в dead letters без цитирования значения; начало пачки фиксируется сразу после dead letter, до начала следующей записи; счетчики сбоев `poll` и `commit`; очистку причины. Тесты адаптера PostgreSQL проверяют классификацию отвергнутого, конфликтного и сетевого сбоя commit и то, что ошибки обработчика сохраняют идентичность без сообщения PostgreSQL. Они же покрывают декодирование конверта и его согласованность с producer, каждое отвергнутое правило конверта без цитирования значения и учет commit участника группы, включая отказ для завершенных записей, которые не являются для каждой партиции началом последнего чтения без пропусков (`internal/adapter/secondary/kafka/`), настройки обработчиков и бюджет ребалансировки, включая описанное в документации значение по умолчанию 42,5 секунды (`config/`), счетчики обработчиков (`internal/adapter/secondary/prometheus/`), а в `internal/bootstrap/` - случаи пропуска, один обработчик на handler, отказ для повторяющихся и недопустимых имен, зарегистрированный обработчик доставки, значения меток, совпадающие с подготовленными метриками, и приложение, которое запускает обработчик вместе с серверами и возвращается только после того, как он перестал читать. `TestEventConsumer` в `backend/integration_test/event_consumer_test.go` использует `bootstrap(t, postgresService, kafkaService)`. Его обработчик существует только в тесте: он пишет одну строку на примененное событие в `consumer_test.effects`, таблицу без уникального ключа, которую создает тест, поэтому второй эффект остался бы виден. Последовательные случаи, каждый со своими топиком и группой: @@ -109,7 +109,29 @@ Unit-тесты (`make -C backend test`) покрывают runtime обрабо - Передача партиции между двумя участниками одной группы: commit первого участника всегда падает, и он держит запись, пока присоединяется второй; тест ждет состояния группы `PreparingRebalance`, отпускает запись и ждет, пока группа не станет стабильной с одной партицией у каждого участника. У каждого из четырех событий ровно один эффект, первый участник обработал оба события первого раунда до ребалансировки, второй не получил ничего из первого раунда переданной партиции (ее позиция зафиксирована при отзыве, единственным оставшимся путем commit) и не насчитал дубликатов, первый участник после потери партиции не пытался ни фиксировать, ни обрабатывать ее записи, а после выхода первого участника offsets группы равны 2 в обеих партициях, то есть переданная партиция не перемотана назад. - Событие, добавленное в outbox через transactor, опубликованное relay и прочитанное обработчиком: декодированное событие совпадает со строкой outbox, значит producer и consumer одинаково понимают конверт. -`TestPostgresMigrations` дополнительно проверяет, что миграция 00005 создает и удаляет обе таблицы обработчиков. Набор использует один брокер, один PostgreSQL и тестовые обработчики. Он не измеряет пропускную способность, не покрывает ребалансировку под нагрузкой или с более чем двумя участниками, переключение брокеров, исключение участника после rebalance timeout и реальный продуктовый обработчик и не проверяет доставку alerts. +`TestPostgresMigrations` дополнительно проверяет, что миграция 00005 создает и удаляет обе таблицы обработчиков. Набор использует один брокер, один PostgreSQL и тестовые обработчики. Он не измеряет пропускную способность, не покрывает ребалансировку под нагрузкой или с более чем двумя участниками, переключение брокеров, исключение участника после rebalance timeout и не проверяет доставку alerts; у продуктового обработчика свои [тесты доставки писем](#тесты-доставки-писем). + +## Тесты доставки писем + +Unit-тесты (`make -C backend test`) покрывают модель доставки и путь ее создания: + +- `internal/domain/`: content hash учитывает версию, тему, обе части и границы между частями; содержимое, которое не отправит ни один транспорт или которое относится к другому виду, отклоняется; измененное сохраненное тело не проходит проверку целостности; новая доставка начинается в `pending` со сроком в момент создания, версией 1, ключом `delivery/` и необязательным исходным событием; каждый исход попытки, примененный к `pending`, `waiting_quota` и `unknown`, дает описанный статус, номер попытки, версию, время и ID провайдера, в том числе `waiting_quota` без известного сброса, а `accepted` и `rejected` отклоняют любую следующую попытку; несогласованные результаты попытки отклоняются; `WaitForQuota` переводит `pending` и `waiting_quota` в ожидание с известным или неизвестным сбросом без попытки, отклоняет `unknown`, конечные доставки и время раньше последнего изменения, а следующая попытка не может быть раньше него; `Rebind` до первой попытки меняет только аккаунт провайдера и версию, а после нее отклоняется; сохраненные строки, нарушающие инвариант, отклоняются; запрос письма принимает только вид уведомления и текст, который можно сохранить; вывод `fmt` и `slog` доставки, ее содержимого и запроса письма никогда не показывает адрес, тему, тело, текст запроса или токен. +- `internal/usecase/notification/`: запрос сохраняет текст под ID агрегата события, а payload события содержит только `mail_request_id` и `kind`; некорректные запросы ничего не записывают; обработчик сохраняет одну доставку под ID запроса с исходным событием, адресом аккаунта, сформированным содержимым, настроенным аккаунтом провайдера и временем часов и удаляет запрос; то же событие повторно не находит запрос; существующая доставка под ID запроса принимается для того же получателя и вида и отклоняется в остальных случаях; сломанные события (другая версия схемы или агрегат, некорректный payload, данные после объекта, ID запроса, не равный ID агрегата, вид письма с токеном) и текст, который отклоняет шаблон, отклоняются без цитирования payload; исчезнувший запрос, исчезнувший аккаунт и неподтвержденный адрес пропускаются со строкой лога, которая называет только ID доставки и события; ошибки хранилища, включая аккаунт, удаленный между чтением и вставкой, остаются повторяемыми и сохраняют запрос; ни одна ошибка и строка лога не содержит адрес, тему или тело. +- `internal/adapter/secondary/postgres/`: ошибки ограничений доставок и запросов писем переводятся в свои sentinel (`deliveries_content_immutable` и `delivery_attempts_immutable` - в `ErrDeliveryContentImmutable`, `deliveries_provider_pinned` - в `ErrDeliveryProviderPinned`, внешние ключи на пользователей - в `ErrUserNotFound`), а любая другая ошибка PostgreSQL, например нарушение CHECK, сохраняет только SQLSTATE и имя ограничения без message и detail. +- `internal/usecase/notification/mailtemplate/`: результат рендеринга переводится в сохраняемое содержимое с тем же видом, версией, частями и hash. +- `config/` и `internal/bootstrap/`: `EMAIL_ACCOUNT` по умолчанию равен `default`, принимает метки до 64 символов и отклоняет пустые, со смешанным регистром, похожие на ключ и слишком длинные значения, не повторяя их; bootstrap регистрирует ровно обработчик `notification_delivery` и отклоняет некорректную метку аккаунта. + +`TestMailDelivery` в `backend/integration_test/delivery_test.go` использует `bootstrap(t, postgresService, kafkaService)` и настоящие usecase запроса, обработчик, relay, runtime обработчиков и хранилища. Последовательные случаи: + +- Одно событие обрабатывается дважды: запрос для подтвержденного аккаунта записывается в бизнес-транзакции, relay публикует его событие, строка снова помечается неопубликованной, как после сбоя до фиксации `published_at`, и relay публикует ее второй раз с тем же ID события. Обработчик фиксирует offset 2 и считает одну запись `applied` и одну `duplicate`; в базе ровно одна доставка: адресована аккаунту, сформирована версией `notification.v1`, закреплена за настроенным аккаунтом провайдера, называет событие своим источником и находится в `pending` без попыток, а запросов писем не остается. +- Изменение шаблона после создания: первый запрос сохраняется с `notification.v1`. Обработчик с тестовым renderer, изображающим `notification.v2`, сохраняет второй запрос с новой версией, а повтор первого запроса под другим именем обработчика находит запрос уже обработанным и ничего не сохраняет. Первая доставка, прочитанная через новый пул, сохраняет тему, части и hash `notification.v1`, а прямой `UPDATE` ее тела завершается ошибкой `deliveries_content_immutable`. +- Сохранение после перезапуска: один пул записывает попытку `unknown` с кодом провайдера и подсказкой ожидания с долями миллисекунды, проигрывает повторную запись той же попытки с `ErrDeliveryVersionConflict`, записывает попытку `accepted` с ID письма у провайдера и закрывается. Новый пул и хранилище читают доставку как `accepted` с этим ID, двумя попытками и версией 3, а обе строки попыток - ровно в записанном виде, подсказку ожидания до наносекунды; следующая попытка отклоняется, а `UPDATE` попытки завершается ошибкой `delivery_attempts_immutable`. +- Перенос и ожидание квоты: доставка без попыток переносится на другой аккаунт провайдера и переводится в `waiting_quota` с неизвестным сбросом, повторная запись по устаревшей версии получает конфликт версии, строк попыток нет; после попытки `Rebind` отклоняется domain, а прямой `UPDATE` аккаунта провайдера завершается ошибкой `deliveries_provider_pinned`. +- Уведомление на неподтвержденный адрес не сохраняет доставку, удаляет свой запрос и записывает в лог ID доставки. +- Запрос, аккаунт которого удален, теряет строку запроса вместе с аккаунтом; затем обработчик не сохраняет доставку и записывает в лог ID доставки. +- Очистка неподтвержденных аккаунтов пропускает аккаунт, строку доставки которого держит другая транзакция, удаляет его после снятия блокировки, и вместе с ним удаляются его ожидающий запрос и доставка, созданная прямо через репозиторий, как будут создаваться письма с токеном. + +Каждый случай проверяет, что собранные логи обработчика и runtime не содержат ни адреса, ни темы, ни тела, а события запросов проверяются на отсутствие адреса и текста запроса. `TestPostgresMigrations` дополнительно проверяет, что миграция 00006 создает и удаляет три свои таблицы и обе trigger-функции, а `TestIdentityRepositories` выполняет запрос очистки с блокировкой запросов писем и доставок. Набор не отправляет писем: worker отправки, повторы, квоты и проверка разрешений относятся к следующим задачам, и нет теста доставки подтверждения почты или сброса пароля, которые создадут сценарии identity. ## Шардирование интеграционных тестов