From d21fd49a42b27a582302f8456667e70222b01a4f Mon Sep 17 00:00:00 2001 From: shira Date: Tue, 6 Oct 2026 21:08:11 +0300 Subject: [PATCH] feat(mail): send service identity mail through a leased worker --- backend/.golangci.yml | 22 + .../migrations/00012_add_delivery_sending.sql | 283 ++++ backend/db/queries/delivery.sql | 345 ++++- .../delivery_sending_migration_test.go | 96 ++ backend/integration_test/mail_sender_test.go | 1365 +++++++++++++++++ .../adapter/secondary/mail/resend/fixture.go | 29 + .../mail/resend/resendfixture/fixture.go | 189 +++ .../mail/resend/resendfixture/fixture_test.go | 67 + .../adapter/secondary/postgres/delivery.go | 215 ++- .../secondary/postgres/delivery_statistics.go | 5 + .../secondary/postgres/delivery_test.go | 23 + .../secondary/postgres/sqlc/delivery.sql.go | 567 ++++++- .../adapter/secondary/postgres/sqlc/models.go | 14 + .../secondary/postgres/sqlc/querier.go | 79 +- .../adapter/secondary/prometheus/mail.go | 50 +- .../adapter/secondary/prometheus/mail_test.go | 41 + .../prometheus/product_metrics_test.go | 1 + backend/internal/bootstrap/app.go | 26 +- backend/internal/bootstrap/consumers_test.go | 2 +- .../bootstrap/delivery_metrics_test.go | 2 +- backend/internal/bootstrap/jobs_test.go | 2 +- backend/internal/bootstrap/mail_sender.go | 154 ++ .../internal/bootstrap/mail_sender_test.go | 146 ++ backend/internal/bootstrap/relay_test.go | 2 +- backend/internal/bootstrap/wire.go | 1 + backend/internal/bootstrap/wire_gen.go | 16 +- backend/internal/domain/delivery.go | 209 ++- backend/internal/domain/delivery_guard.go | 80 + .../internal/domain/delivery_guard_test.go | 337 ++++ backend/internal/domain/delivery_test.go | 2 + backend/internal/domain/email_token.go | 21 +- backend/internal/domain/email_token_test.go | 2 +- backend/internal/domain/mail_content.go | 54 + backend/internal/port/inbound/mail_sender.go | 77 + backend/internal/port/outbound/delivery.go | 133 +- .../port/outbound/delivery_statistics.go | 6 +- .../usecase/notification/delivery_status.go | 10 +- .../usecase/notification/mail_request.go | 40 +- .../internal/usecase/notification/quota.go | 7 +- .../usecase/notification/send_retry.go | 58 + .../usecase/notification/service_mail.go | 141 ++ .../usecase/notification/service_mail_test.go | 138 ++ .../usecase/notification/service_sender.go | 725 +++++++++ .../notification/service_sender_test.go | 969 ++++++++++++ backend/internal/worker/mailsender/worker.go | 187 +++ .../internal/worker/mailsender/worker_test.go | 306 ++++ docs/en/ARCHITECTURE.md | 111 +- docs/en/DEPLOY.md | 30 +- docs/en/DEVELOPMENT.md | 2 +- docs/en/TESTING.md | 42 +- docs/ru/ARCHITECTURE.md | 111 +- docs/ru/DEPLOY.md | 30 +- docs/ru/DEVELOPMENT.md | 2 +- docs/ru/TESTING.md | 42 +- .../grafana/dashboards/lincodex-product.json | 4 +- observability/prometheus/rules/lincodex.yml | 23 +- .../prometheus/tests/lincodex_rules_test.yml | 94 +- .../scripts/verify-product-metrics.sh | 6 +- 58 files changed, 7577 insertions(+), 164 deletions(-) create mode 100644 backend/db/migrations/00012_add_delivery_sending.sql create mode 100644 backend/integration_test/delivery_sending_migration_test.go create mode 100644 backend/integration_test/mail_sender_test.go create mode 100644 backend/internal/adapter/secondary/mail/resend/fixture.go create mode 100644 backend/internal/adapter/secondary/mail/resend/resendfixture/fixture.go create mode 100644 backend/internal/adapter/secondary/mail/resend/resendfixture/fixture_test.go create mode 100644 backend/internal/adapter/secondary/prometheus/mail_test.go create mode 100644 backend/internal/bootstrap/mail_sender.go create mode 100644 backend/internal/bootstrap/mail_sender_test.go create mode 100644 backend/internal/domain/delivery_guard.go create mode 100644 backend/internal/domain/delivery_guard_test.go create mode 100644 backend/internal/port/inbound/mail_sender.go create mode 100644 backend/internal/usecase/notification/send_retry.go create mode 100644 backend/internal/usecase/notification/service_mail.go create mode 100644 backend/internal/usecase/notification/service_mail_test.go create mode 100644 backend/internal/usecase/notification/service_sender.go create mode 100644 backend/internal/usecase/notification/service_sender_test.go create mode 100644 backend/internal/worker/mailsender/worker.go create mode 100644 backend/internal/worker/mailsender/worker_test.go diff --git a/backend/.golangci.yml b/backend/.golangci.yml index fe2e022..653e596 100644 --- a/backend/.golangci.yml +++ b/backend/.golangci.yml @@ -13,6 +13,7 @@ linters: - bodyclose - contextcheck - copyloopvar + - depguard - durationcheck - embeddedstructfieldcheck - errname @@ -20,6 +21,7 @@ linters: - exhaustive - exptostd - fatcontext + - forbidigo - gocheckcompilerdirectives - gochecknoinits - gochecksumtype @@ -58,6 +60,23 @@ linters: - zerologlint settings: + depguard: + rules: + # The local Resend stand-in exists for tests of the delivery layer + # only; no production package may import it. + resend-fixture-tests-only: + list-mode: lax + files: + - "!$test" + deny: + - pkg: lincodex/backend/internal/adapter/secondary/mail/resend/resendfixture + desc: the Resend fixture is for tests only + forbidigo: + forbid: + # It accepts a loopback endpoint instead of the fixed Resend one, so + # only tests may call it (see the exclusion for test files below). + - pattern: ^resend\.NewLoopbackSender$ + msg: resend.NewLoopbackSender is for tests only; production uses resend.NewSender gocyclo: min-complexity: 15 govet: @@ -122,6 +141,9 @@ linters: - gosec - errcheck - dupl + - path: _test\.go + linters: + - forbidigo - path: _test\.go text: net/http/httptest\.NewRequest must not be called linters: diff --git a/backend/db/migrations/00012_add_delivery_sending.sql b/backend/db/migrations/00012_add_delivery_sending.sql new file mode 100644 index 0000000..a80ecad --- /dev/null +++ b/backend/db/migrations/00012_add_delivery_sending.sql @@ -0,0 +1,283 @@ +-- +goose Up +-- Sending of service identity mail (TASK-016). The sending worker claims a +-- due delivery under a lease, checks that the token and the account behind +-- it are still current, and ends a delivery that must not be sent in a +-- terminal non-sent status with a reason. +-- +-- Everything is additive: existing rows stay valid. Every new column is +-- nullable except failure_count, which is NOT NULL DEFAULT 0. No column holds +-- personal data or a secret. + +-- A reset token is a second purpose of the same table. The purpose names +-- what the token authorizes, and the worker compares it with the kind of the +-- delivery that carries it. +ALTER TABLE email_tokens DROP CONSTRAINT email_tokens_purpose_known; +ALTER TABLE email_tokens ADD CONSTRAINT email_tokens_purpose_known CHECK ( + purpose IN ('email_verification', 'password_reset') +); + +ALTER TABLE deliveries +ADD COLUMN email_token_id uuid, +ADD COLUMN cancel_reason text, +ADD COLUMN claim_owner uuid, +ADD COLUMN claimed_until timestamptz, +ADD COLUMN first_send_started_at timestamptz, +ADD COLUMN failure_count integer NOT NULL DEFAULT 0, +ADD COLUMN body_redacted_at timestamptz; + +COMMENT ON COLUMN deliveries.email_token_id IS +'The token whose link the body carries; set for verification and password reset mail, NULL for notifications. The worker checks the token before it sends.'; +COMMENT ON COLUMN deliveries.cancel_reason IS +'Why a cancelled delivery was not sent; set exactly when the status is cancelled.'; +COMMENT ON COLUMN deliveries.claim_owner IS +'Lease owner of the sending worker that claimed the delivery; NULL when no worker holds it.'; +COMMENT ON COLUMN deliveries.first_send_started_at IS +'When the first request of this delivery was started, by the database clock; the provider keeps the idempotency key for a window counted from here.'; +COMMENT ON COLUMN deliveries.failure_count IS +'Consecutive failures of the sending worker on this row (not provider answers); reset by a recorded attempt.'; +COMMENT ON COLUMN deliveries.body_redacted_at IS +'Set when the bodies of a token mail were cleared after the delivery reached a terminal status, so a database dump holds no live or dead token.'; +COMMENT ON COLUMN deliveries.claimed_until IS +'When the lease of claim_owner expires; another worker may claim the delivery after it.'; + +-- The binding is by ID only. Deleting an account deletes its tokens and its +-- deliveries in one statement, so the reference needs no cascade of its own. +ALTER TABLE deliveries ADD CONSTRAINT deliveries_email_token_id_fkey +FOREIGN KEY (email_token_id) REFERENCES email_tokens (id); + +ALTER TABLE deliveries DROP CONSTRAINT deliveries_status_known; +ALTER TABLE deliveries ADD CONSTRAINT deliveries_status_known CHECK ( + status IN ( + 'pending', 'accepted', 'rejected', 'unknown', 'waiting_quota', + 'cancelled' + ) +); + +-- cancelled is terminal like accepted and rejected: no next attempt. +ALTER TABLE deliveries DROP CONSTRAINT deliveries_next_attempt_matches_status; +ALTER TABLE deliveries ADD CONSTRAINT deliveries_next_attempt_matches_status CHECK ( + (status = 'pending' AND next_attempt_at IS NOT NULL) + OR (status IN ('accepted', 'rejected', 'cancelled') AND next_attempt_at IS NULL) + OR status IN ('unknown', 'waiting_quota') +); + +ALTER TABLE deliveries ADD CONSTRAINT deliveries_cancel_reason_matches_status CHECK ( + (status = 'cancelled') = (cancel_reason IS NOT NULL) + AND ( + cancel_reason IS NULL + OR cancel_reason IN ( + 'token_missing', + 'token_purpose_mismatch', + 'token_owner_mismatch', + 'token_consumed', + 'token_revoked', + 'token_expired', + 'account_not_current', + 'recipient_mismatch', + 'content_invalid', + 'processing_failed' + ) + ) +); + +-- A lease has an owner and a deadline together, and only a delivery that a +-- worker may still send holds one. +ALTER TABLE deliveries ADD CONSTRAINT deliveries_claim_complete CHECK ( + (claim_owner IS NULL) = (claimed_until IS NULL) + AND ( + claim_owner IS NULL + OR status IN ('pending', 'waiting_quota', 'unknown') + ) +); + +ALTER TABLE deliveries ADD CONSTRAINT deliveries_token_only_for_token_kinds CHECK ( + email_token_id IS NULL OR kind IN ('verification', 'password_reset') +); + +ALTER TABLE deliveries ADD CONSTRAINT deliveries_failure_count_not_negative CHECK ( + failure_count >= 0 +); + +-- A redacted token mail has no bodies; any other delivery has at least one. +-- Only a terminal token mail may be redacted. +ALTER TABLE deliveries DROP CONSTRAINT deliveries_body_present; +ALTER TABLE deliveries ADD CONSTRAINT deliveries_body_present CHECK ( + (body_redacted_at IS NULL AND (text_body <> '' OR html_body <> '')) + OR ( + body_redacted_at IS NOT NULL + AND text_body = '' AND html_body = '' + AND kind IN ('verification', 'password_reset') + AND status IN ('accepted', 'rejected', 'cancelled') + ) +); + +-- Serves the claim of due service mail. The predicate names the kinds the +-- sending worker handles, so rows of other kinds (notifications, which wait +-- for TASK-462) never enter the index and an idle poll does not scan them. +-- The claim query repeats the kind literals so the planner can use it. +CREATE INDEX deliveries_due_idx +ON deliveries (next_attempt_at, id) +WHERE + status IN ('pending', 'waiting_quota') + AND next_attempt_at IS NOT NULL + AND kind IN ('verification', 'password_reset'); + +-- Serves the foreign key check when a token is deleted. +CREATE INDEX deliveries_email_token_id_idx +ON deliveries (email_token_id) +WHERE email_token_id IS NOT NULL; + +-- The token a delivery is bound to never changes, like the rest of what the +-- delivery sends. The attempt state, the cancel reason, and the lease stay +-- updatable. The bodies of a token mail change in exactly one way: once, to +-- empty, together with body_redacted_at, when the delivery is terminal, so +-- no token outlives its mail. Errors are the same as in migration 00006. +-- +goose StatementBegin +CREATE OR REPLACE FUNCTION deliveries_refuse_content_change() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF ( + NEW.id, NEW.source_event_id, NEW.recipient_user_id, + NEW.recipient_email, NEW.kind, NEW.template_version, NEW.subject, + NEW.content_sha256, + NEW.idempotency_key, NEW.created_at, NEW.email_token_id + ) IS DISTINCT FROM ( + OLD.id, OLD.source_event_id, OLD.recipient_user_id, + OLD.recipient_email, OLD.kind, OLD.template_version, OLD.subject, + OLD.content_sha256, + OLD.idempotency_key, OLD.created_at, OLD.email_token_id + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'deliveries_content_immutable', + TABLE = 'deliveries', + MESSAGE = 'delivery content and recipient are immutable'; + END IF; + IF (NEW.text_body, NEW.html_body) IS DISTINCT FROM (OLD.text_body, OLD.html_body) THEN + IF NOT ( + OLD.body_redacted_at IS NULL AND NEW.body_redacted_at IS NOT NULL + AND NEW.text_body = '' AND NEW.html_body = '' + AND NEW.status IN ('accepted', 'rejected', 'cancelled') + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'deliveries_content_immutable', + TABLE = 'deliveries', + MESSAGE = 'delivery content and recipient are immutable'; + END IF; + ELSIF OLD.body_redacted_at IS DISTINCT FROM NEW.body_redacted_at THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'deliveries_content_immutable', + TABLE = 'deliveries', + MESSAGE = 'delivery content and recipient are immutable'; + END IF; + IF ( + (NEW.provider, NEW.provider_account) + IS DISTINCT FROM (OLD.provider, OLD.provider_account) + ) AND (OLD.attempt_count <> 0 OR NEW.attempt_count <> 0) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'deliveries_provider_pinned', + TABLE = 'deliveries', + MESSAGE = 'the provider account of a delivery is fixed after its first attempt'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +-- +goose Down +-- A cancelled delivery becomes rejected, the closest status of the earlier +-- schema, and reset tokens are removed with the purpose that no longer +-- exists. The checks that tie a reason to the cancelled status go first, so +-- the status can change. +ALTER TABLE deliveries DROP CONSTRAINT deliveries_token_only_for_token_kinds; +ALTER TABLE deliveries DROP CONSTRAINT deliveries_claim_complete; +ALTER TABLE deliveries DROP CONSTRAINT deliveries_cancel_reason_matches_status; + +UPDATE deliveries SET status = 'rejected' WHERE status = 'cancelled'; + +-- Redacted bodies cannot come back; a placeholder keeps the earlier schema's +-- body check satisfied. The placeholder no longer matches content_sha256, so +-- code of the earlier schema cannot restore such a row as content: it reads +-- terminal rows only through the status reader, which selects no body, and +-- never sends them. The content trigger is lifted for this one statement. +ALTER TABLE deliveries DROP CONSTRAINT deliveries_body_present; +ALTER TABLE deliveries DISABLE TRIGGER deliveries_refuse_content_change; +UPDATE deliveries SET text_body = 'redacted' WHERE body_redacted_at IS NOT NULL; +ALTER TABLE deliveries ENABLE TRIGGER deliveries_refuse_content_change; + +-- +goose StatementBegin +CREATE OR REPLACE FUNCTION deliveries_refuse_content_change() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF ( + NEW.id, NEW.source_event_id, NEW.recipient_user_id, + NEW.recipient_email, NEW.kind, NEW.template_version, NEW.subject, + NEW.text_body, NEW.html_body, NEW.content_sha256, + NEW.idempotency_key, NEW.created_at + ) IS DISTINCT FROM ( + OLD.id, OLD.source_event_id, OLD.recipient_user_id, + OLD.recipient_email, OLD.kind, OLD.template_version, OLD.subject, + OLD.text_body, OLD.html_body, OLD.content_sha256, + OLD.idempotency_key, OLD.created_at + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'deliveries_content_immutable', + TABLE = 'deliveries', + MESSAGE = 'delivery content and recipient are immutable'; + END IF; + IF ( + (NEW.provider, NEW.provider_account) + IS DISTINCT FROM (OLD.provider, OLD.provider_account) + ) AND (OLD.attempt_count <> 0 OR NEW.attempt_count <> 0) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'deliveries_provider_pinned', + TABLE = 'deliveries', + MESSAGE = 'the provider account of a delivery is fixed after its first attempt'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +DROP INDEX deliveries_email_token_id_idx; +DROP INDEX deliveries_due_idx; + +ALTER TABLE deliveries DROP CONSTRAINT deliveries_failure_count_not_negative; +ALTER TABLE deliveries ADD CONSTRAINT deliveries_body_present CHECK ( + text_body <> '' OR html_body <> '' +); + +ALTER TABLE deliveries DROP CONSTRAINT deliveries_next_attempt_matches_status; +ALTER TABLE deliveries ADD CONSTRAINT deliveries_next_attempt_matches_status CHECK ( + (status = 'pending' AND next_attempt_at IS NOT NULL) + OR (status IN ('accepted', 'rejected') AND next_attempt_at IS NULL) + OR status IN ('unknown', 'waiting_quota') +); + +ALTER TABLE deliveries DROP CONSTRAINT deliveries_status_known; +ALTER TABLE deliveries ADD CONSTRAINT deliveries_status_known CHECK ( + status IN ( + 'pending', 'accepted', 'rejected', 'unknown', 'waiting_quota' + ) +); + +ALTER TABLE deliveries DROP CONSTRAINT deliveries_email_token_id_fkey; +ALTER TABLE deliveries +DROP COLUMN body_redacted_at, +DROP COLUMN failure_count, +DROP COLUMN first_send_started_at, +DROP COLUMN claimed_until, +DROP COLUMN claim_owner, +DROP COLUMN cancel_reason, +DROP COLUMN email_token_id; + +DELETE FROM email_tokens WHERE purpose = 'password_reset'; +ALTER TABLE email_tokens DROP CONSTRAINT email_tokens_purpose_known; +ALTER TABLE email_tokens ADD CONSTRAINT email_tokens_purpose_known CHECK ( + purpose IN ('email_verification') +); diff --git a/backend/db/queries/delivery.sql b/backend/db/queries/delivery.sql index 7e09059..febe45a 100644 --- a/backend/db/queries/delivery.sql +++ b/backend/db/queries/delivery.sql @@ -23,6 +23,7 @@ INSERT INTO deliveries ( next_attempt_at, last_attempt_at, provider_message_id, + email_token_id, version, created_at, updated_at @@ -45,6 +46,7 @@ INSERT INTO deliveries ( sqlc.narg(next_attempt_at), sqlc.narg(last_attempt_at), sqlc.narg(provider_message_id), + sqlc.narg(email_token_id), sqlc.arg(version), sqlc.arg(created_at), sqlc.arg(updated_at) @@ -73,7 +75,14 @@ SELECT provider_message_id, version, created_at, - updated_at + updated_at, + email_token_id, + cancel_reason, + claim_owner, + claimed_until, + first_send_started_at, + failure_count, + body_redacted_at FROM deliveries WHERE id = sqlc.arg(id); @@ -82,8 +91,12 @@ WHERE id = sqlc.arg(id); -- transaction. The update applies only while the stored version still -- equals expected_version; otherwise nothing is written and the statement -- returns 0 rows. Two workers that record the same attempt number therefore --- cannot both succeed. Content columns are not touched; a trigger refuses --- any change to them. +-- cannot both succeed. The lease of the sending worker ends with the +-- attempt, and so does the count of worker failures. When lease_owner is +-- given, the update applies only while that worker still holds the lease. +-- A token mail that reaches a terminal status loses its bodies in the same +-- statement, so the one-time token does not stay at rest; the trigger allows +-- exactly this change of the content columns. -- name: RecordDeliveryAttempt :execrows WITH advanced AS ( UPDATE deliveries @@ -95,11 +108,39 @@ WITH advanced AS ( provider_message_id = coalesce( sqlc.narg(provider_message_id), deliveries.provider_message_id ), + claim_owner = NULL, + claimed_until = NULL, + failure_count = 0, + text_body = CASE + WHEN + sqlc.arg(status)::text IN ('accepted', 'rejected') + AND deliveries.kind IN ('verification', 'password_reset') + THEN '' + ELSE deliveries.text_body + END, + html_body = CASE + WHEN + sqlc.arg(status)::text IN ('accepted', 'rejected') + AND deliveries.kind IN ('verification', 'password_reset') + THEN '' + ELSE deliveries.html_body + END, + body_redacted_at = CASE + WHEN + sqlc.arg(status)::text IN ('accepted', 'rejected') + AND deliveries.kind IN ('verification', 'password_reset') + THEN sqlc.arg(updated_at) + ELSE deliveries.body_redacted_at + END, version = deliveries.version + 1, updated_at = sqlc.arg(updated_at) WHERE deliveries.id = sqlc.arg(delivery_id) AND deliveries.version = sqlc.arg(expected_version) + AND ( + sqlc.narg(lease_owner)::uuid IS NULL + OR deliveries.claim_owner = sqlc.narg(lease_owner)::uuid + ) RETURNING deliveries.id ) @@ -128,23 +169,313 @@ SELECT sqlc.narg(next_attempt_at) FROM advanced; --- Stores a change of the delivery state that is not an attempt: a quota wait --- or a new provider account before the first attempt. It applies only while --- the stored version still equals expected_version and returns 0 rows --- otherwise. The trigger refuses a provider change after an attempt. +-- Stores a change of the delivery state that is not an attempt: a quota wait, +-- a cancellation, or a new provider account before the first attempt. It +-- applies only while the stored version still equals expected_version and +-- returns 0 rows otherwise. The trigger refuses a provider change after an +-- attempt. release_claim ends the lease of the sending worker with the +-- change; a new provider account keeps it, because the worker rebinds a +-- delivery it holds and then sends it. -- name: UpdateDeliveryState :execrows UPDATE deliveries SET status = sqlc.arg(status), next_attempt_at = sqlc.narg(next_attempt_at), + cancel_reason = sqlc.narg(cancel_reason), + failure_count = 0, provider = sqlc.arg(provider), provider_account = sqlc.arg(provider_account), + claim_owner = CASE + WHEN sqlc.arg(release_claim)::boolean THEN NULL ELSE deliveries.claim_owner + END, + claimed_until = CASE + WHEN sqlc.arg(release_claim)::boolean THEN NULL ELSE deliveries.claimed_until + END, + text_body = CASE + WHEN + sqlc.arg(status)::text = 'cancelled' + AND deliveries.kind IN ('verification', 'password_reset') + THEN '' + ELSE deliveries.text_body + END, + html_body = CASE + WHEN + sqlc.arg(status)::text = 'cancelled' + AND deliveries.kind IN ('verification', 'password_reset') + THEN '' + ELSE deliveries.html_body + END, + body_redacted_at = CASE + WHEN + sqlc.arg(status)::text = 'cancelled' + AND deliveries.kind IN ('verification', 'password_reset') + THEN sqlc.arg(updated_at) + ELSE deliveries.body_redacted_at + END, version = deliveries.version + 1, updated_at = sqlc.arg(updated_at) WHERE deliveries.id = sqlc.arg(id) AND deliveries.version = sqlc.arg(expected_version); +-- Claims the most overdue delivery that the sending worker may send, in one +-- statement: a pending or waiting_quota delivery of the service mail kinds +-- (the literals match the predicate of deliveries_due_idx, so an idle poll +-- reads only that small index) whose next_attempt_at has passed, pinned to the +-- configured provider account (or to rebind_provider before its first +-- attempt, which the worker moves to the configured account), and held by no +-- live lease. A row that another worker locks is skipped without waiting, so +-- several processes never take the same delivery, and a delivery whose lease +-- expired, because its worker stopped, is claimed again. +-- The lease is measured by the database clock, never by the clock of an +-- application instance: it lasts lease_seconds from clock_timestamp(), and a +-- lease is live while claimed_until is later than clock_timestamp(). Due times +-- stay on the application clock that wrote them. Neither the version nor +-- updated_at changes: a claim is not a change of the delivery. +-- previous_claimed_until is the deadline of an abandoned lease, NULL for a +-- delivery nobody held; since_first_send_seconds is how long ago, by the +-- database clock, its first request started, -1 when none did. now is the +-- application clock. Deliveries that are unknown or wait for an unknown quota +-- reset have no due time here and wait for an operator. +-- name: ClaimDueDelivery :one +WITH candidate AS ( + SELECT + due.id, + due.claimed_until AS previous_claimed_until, + coalesce( + extract(EPOCH FROM clock_timestamp() - due.first_send_started_at), + -1 + )::float8 AS since_first_send_seconds + FROM deliveries AS due + WHERE + due.kind IN ('verification', 'password_reset') + AND due.kind = any(sqlc.arg(kinds)::text []) + AND due.status IN ('pending', 'waiting_quota') + AND due.next_attempt_at IS NOT NULL + AND due.next_attempt_at <= sqlc.arg(now)::timestamptz + AND ( + ( + due.provider = sqlc.arg(provider) + AND due.provider_account = sqlc.arg(provider_account) + ) + OR ( + due.provider = sqlc.arg(rebind_provider)::text + AND due.attempt_count = 0 + ) + ) + AND ( + due.claim_owner IS NULL + OR due.claimed_until <= clock_timestamp() + ) + ORDER BY due.next_attempt_at, due.id + LIMIT 1 + FOR UPDATE SKIP LOCKED +) + +UPDATE deliveries AS claimed +SET + claim_owner = sqlc.arg(lease_owner)::uuid, + claimed_until = clock_timestamp() + + make_interval(secs => sqlc.arg(lease_seconds)::float8) +FROM candidate +WHERE claimed.id = candidate.id +RETURNING + claimed.id, + claimed.source_event_id, + claimed.recipient_user_id, + claimed.recipient_email, + claimed.kind, + claimed.template_version, + claimed.subject, + claimed.text_body, + claimed.html_body, + claimed.content_sha256, + claimed.provider, + claimed.provider_account, + claimed.idempotency_key, + claimed.status, + claimed.attempt_count, + claimed.next_attempt_at, + claimed.last_attempt_at, + claimed.provider_message_id, + claimed.email_token_id, + claimed.cancel_reason, + claimed.body_redacted_at, + claimed.failure_count, + claimed.version, + claimed.created_at, + claimed.updated_at, + candidate.previous_claimed_until, + candidate.since_first_send_seconds; + +-- Ends a claimed delivery whose stored content no longer matches its hash, so +-- one broken row never blocks the delivery queue. It matches only a delivery +-- that the worker could still send, ends the lease, advances the version, and +-- redacts the bodies of a token mail like any other cancellation. now is the +-- application clock. +-- name: CancelUnreadableDelivery :execrows +UPDATE deliveries +SET + status = 'cancelled', + cancel_reason = 'content_invalid', + next_attempt_at = NULL, + claim_owner = NULL, + claimed_until = NULL, + text_body = CASE + WHEN deliveries.kind IN ('verification', 'password_reset') THEN '' ELSE deliveries.text_body + END, + html_body = CASE + WHEN deliveries.kind IN ('verification', 'password_reset') THEN '' ELSE deliveries.html_body + END, + body_redacted_at = CASE + WHEN + deliveries.kind IN ('verification', 'password_reset') + THEN greatest(deliveries.updated_at, sqlc.arg(now)::timestamptz) + ELSE deliveries.body_redacted_at + END, + version = deliveries.version + 1, + updated_at = greatest(deliveries.updated_at, sqlc.arg(now)::timestamptz) +WHERE + id = sqlc.arg(id) + AND status IN ('pending', 'waiting_quota'); + +-- Records that the sending worker failed on a delivery, so a broken row does +-- not stay at the head of the queue: the delivery is due again at +-- next_attempt_at and its lease ends. With count_failure the failure is +-- counted; after max_failures consecutive failures the delivery is cancelled +-- with the reason processing_failed, which an operator sees, and a token mail +-- loses its bodies. Without it nothing is counted and nothing is cancelled: +-- the failure says nothing about the row (a transient storage error, or a +-- stretch of failures across many rows). The row is touched only when no other +-- worker holds a live lease on it: lease_owner may hold it, or the lease is +-- free or expired. It returns the status after the change; no row means that +-- the delivery is no longer pending or waiting, or another worker holds it. +-- now is the application clock. +-- name: RecordDeliveryFailure :one +UPDATE deliveries +SET + failure_count = CASE + WHEN sqlc.arg(count_failure)::boolean THEN deliveries.failure_count + 1 ELSE deliveries.failure_count + END, + status = CASE + WHEN + sqlc.arg(count_failure)::boolean + AND deliveries.failure_count + 1 >= sqlc.arg(max_failures)::integer + THEN 'cancelled' + ELSE deliveries.status + END, + cancel_reason = CASE + WHEN + sqlc.arg(count_failure)::boolean + AND deliveries.failure_count + 1 >= sqlc.arg(max_failures)::integer + THEN 'processing_failed' + ELSE deliveries.cancel_reason + END, + next_attempt_at = CASE + WHEN + sqlc.arg(count_failure)::boolean + AND deliveries.failure_count + 1 >= sqlc.arg(max_failures)::integer + THEN NULL + ELSE sqlc.arg(next_attempt_at)::timestamptz + END, + text_body = CASE + WHEN + sqlc.arg(count_failure)::boolean + AND deliveries.failure_count + 1 >= sqlc.arg(max_failures)::integer + AND deliveries.kind IN ('verification', 'password_reset') + THEN '' + ELSE deliveries.text_body + END, + html_body = CASE + WHEN + sqlc.arg(count_failure)::boolean + AND deliveries.failure_count + 1 >= sqlc.arg(max_failures)::integer + AND deliveries.kind IN ('verification', 'password_reset') + THEN '' + ELSE deliveries.html_body + END, + body_redacted_at = CASE + WHEN + sqlc.arg(count_failure)::boolean + AND deliveries.failure_count + 1 >= sqlc.arg(max_failures)::integer + AND deliveries.kind IN ('verification', 'password_reset') + THEN greatest(deliveries.updated_at, sqlc.arg(now)::timestamptz) + ELSE deliveries.body_redacted_at + END, + claim_owner = NULL, + claimed_until = NULL, + version = deliveries.version + 1, + updated_at = greatest(deliveries.updated_at, sqlc.arg(now)::timestamptz) +WHERE + id = sqlc.arg(id) + AND status IN ('pending', 'waiting_quota') + AND ( + claim_owner IS NULL + OR claim_owner = sqlc.arg(lease_owner)::uuid + OR claimed_until <= clock_timestamp() + ) +RETURNING status; + +-- Locks the delivery row of the lease holder until the transaction ends, so +-- every path that settles a send takes the delivery lock before the quota +-- rows, the same order as the claim. No row means that owner no longer holds +-- the lease. +-- name: LockClaimedDelivery :one +SELECT id +FROM deliveries +WHERE + id = sqlc.arg(id) + AND claim_owner = sqlc.arg(lease_owner) +FOR UPDATE; + +-- Notes that the first request of a claimed delivery is about to start, by the +-- database clock, and clears the count of worker failures: the claim and the +-- preparation succeeded, so the failures are no longer consecutive. The provider keeps the idempotency key for a window counted +-- from this moment, so a later claim can tell whether repeating the request is +-- still safe. It never moves. +-- name: MarkDeliverySendStarted :execrows +UPDATE deliveries +SET + first_send_started_at = coalesce(deliveries.first_send_started_at, clock_timestamp()), + failure_count = 0 +WHERE + id = sqlc.arg(id) + AND claim_owner = sqlc.arg(lease_owner); + +-- Gives a claimed delivery back without changing it, so the next pass may +-- claim it. It matches only the lease of lease_owner: a delivery that another +-- worker took over after the lease expired is left alone. +-- name: ReleaseDeliveryClaim :execrows +UPDATE deliveries +SET + claim_owner = NULL, + claimed_until = NULL +WHERE + id = sqlc.arg(id) + AND claim_owner = sqlc.arg(lease_owner); + +-- Reads the token a delivery is bound to and the account it is addressed to +-- in one statement, for the check right before a service mail is sent. It +-- takes no lock. It reads the account address only as the comparison key and +-- selects no token hash. A missing binding or token row gives NULL token +-- columns. +-- name: GetServiceMailState :one +SELECT + (token.id IS NOT NULL)::boolean AS token_found, + token.purpose AS token_purpose, + token.user_id AS token_user_id, + token.registration_version AS token_registration_version, + token.consumed_at AS token_consumed_at, + token.invalidated_at AS token_invalidated_at, + token.expires_at AS token_expires_at, + owner.registration_version AS account_registration_version, + (owner.email_verified_at IS NOT NULL)::boolean AS account_email_verified, + owner.email_normalized AS account_email_key +FROM deliveries AS delivery +INNER JOIN users AS owner ON delivery.recipient_user_id = owner.id +LEFT JOIN email_tokens AS token ON delivery.email_token_id = token.id +WHERE delivery.id = sqlc.arg(id); + -- name: ListDeliveryAttempts :many SELECT delivery_id, diff --git a/backend/integration_test/delivery_sending_migration_test.go b/backend/integration_test/delivery_sending_migration_test.go new file mode 100644 index 0000000..bad9ddf --- /dev/null +++ b/backend/integration_test/delivery_sending_migration_test.go @@ -0,0 +1,96 @@ +//go:build integration + +package integration_test + +import ( + "context" + "crypto/sha256" + "testing" + "time" + + "github.com/google/uuid" +) + +// deliverySendingMigrationVersion adds the lease, cancellation, and token +// binding columns of the sending worker to deliveries. +const deliverySendingMigrationVersion = 12 + +// TestDeliverySendingMigration rolls back and applies migration 00012 over +// rows that use what it adds: the earlier schema must keep a cancelled +// delivery as a rejected one and drop reset tokens, and the migration must +// apply again. +func TestDeliverySendingMigration(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + migrator := newMigrator(t, databaseURL) + pool := newPoolFor(ctx, t, databaseURL) + if _, err := migrator.Up(ctx); err != nil { + t.Fatalf("Up() error = %v", err) + } + + now := time.Date(2026, 10, 6, 12, 0, 0, 0, time.UTC) + userID, tokenID, deliveryID := uuid.New(), uuid.New(), uuid.New() + exec := func(statement string, args ...any) { + t.Helper() + if _, err := pool.Exec(ctx, statement, args...); err != nil { + t.Fatalf("exec %q: %v", statement, err) + } + } + exec(`INSERT INTO users (id, email, email_normalized, password_hash, scenario, onboarding_step, registration_version, + last_registered_at, version, created_at, updated_at) + VALUES ($1, 'migration@example.com', 'migration@example.com', $2, 'candidate', 'candidate_consents', 1, $3, 1, $3, $3)`, + userID, identityTestPasswordHash, now) + exec(`INSERT INTO email_tokens (id, user_id, purpose, token_hash, registration_version, created_at, expires_at) + VALUES ($1, $2, 'password_reset', $3, 1, $4, $5)`, + tokenID, userID, make([]byte, sha256.Size), now, now.Add(time.Hour)) + exec(`INSERT INTO deliveries (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, version, + created_at, updated_at, email_token_id, cancel_reason, body_redacted_at) + VALUES ($1, $2, 'migration@example.com', 'password_reset', 'password_reset.v1', 's', '', '', $3, 'resend', 'main', + 'delivery/migration', 'cancelled', 0, NULL, 1, $4, $4, $5, 'processing_failed', $4)`, + deliveryID, userID, make([]byte, sha256.Size), now, tokenID) + + for { + result, err := migrator.DownOne(ctx) + if err != nil { + t.Fatalf("DownOne() error = %v", err) + } + if result.Version == deliverySendingMigrationVersion { + break + } + } + var status string + if err := pool.QueryRow(ctx, "SELECT status FROM deliveries WHERE id = $1", deliveryID).Scan(&status); err != nil || status != "rejected" { + t.Fatalf("delivery after the rollback = %q, %v; want rejected", status, err) + } + var body string + if err := pool.QueryRow(ctx, "SELECT text_body FROM deliveries WHERE id = $1", deliveryID).Scan(&body); err != nil || body == "" { + t.Fatalf("redacted body after the rollback = %q, %v; want a placeholder that satisfies the earlier body check", body, err) + } + var resetTokens, newColumns int + if err := pool.QueryRow(ctx, "SELECT count(*) FROM email_tokens WHERE purpose = 'password_reset'").Scan(&resetTokens); err != nil || resetTokens != 0 { + t.Fatalf("reset tokens after the rollback = %d, %v; want 0", resetTokens, err) + } + err := pool.QueryRow(ctx, `SELECT count(*) FROM information_schema.columns WHERE table_name = 'deliveries' + AND column_name IN ('email_token_id', 'cancel_reason', 'claim_owner', 'claimed_until', 'first_send_started_at', 'failure_count', 'body_redacted_at')`).Scan(&newColumns) + if err != nil || newColumns != 0 { + t.Fatalf("columns of 00012 after the rollback = %d, %v; want 0", newColumns, err) + } + if _, err := pool.Exec(ctx, "UPDATE deliveries SET status = 'cancelled' WHERE id = $1", deliveryID); err == nil { + t.Fatal("the earlier schema accepts the cancelled status") + } + + if _, err := migrator.Up(ctx); err != nil { + t.Fatalf("Up() after the rollback error = %v", err) + } + if err := pool.QueryRow(ctx, `SELECT count(*) FROM information_schema.columns WHERE table_name = 'deliveries' + AND column_name IN ('email_token_id', 'cancel_reason', 'claim_owner', 'claimed_until', 'first_send_started_at', 'failure_count', 'body_redacted_at')`).Scan(&newColumns); err != nil || newColumns != 7 { + t.Fatalf("columns of 00012 after applying it again = %d, %v; want 7", newColumns, err) + } + var due bool + if err := pool.QueryRow(ctx, "SELECT to_regclass('public.deliveries_due_idx') IS NOT NULL").Scan(&due); err != nil || !due { + t.Fatalf("deliveries_due_idx exists = %t, %v; want true", due, err) + } +} diff --git a/backend/integration_test/mail_sender_test.go b/backend/integration_test/mail_sender_test.go new file mode 100644 index 0000000..c8a4123 --- /dev/null +++ b/backend/integration_test/mail_sender_test.go @@ -0,0 +1,1365 @@ +//go:build integration + +package integration_test + +import ( + "context" + "errors" + "fmt" + "log/slog" + "net/http" + "net/http/httptest" + "slices" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + + "lincodex/backend/internal/adapter/secondary/mail/disabled" + "lincodex/backend/internal/adapter/secondary/mail/resend" + "lincodex/backend/internal/adapter/secondary/mail/resend/resendfixture" + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/prometheus" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/inbound" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/notification" + "lincodex/backend/internal/usecase/notification/mailtemplate" + "lincodex/backend/internal/worker/mailsender" + "lincodex/backend/internal/worker/retry" +) + +const ( + mailSenderTestTimeout = 5 * time.Minute + mailSenderAccount = "integration" + // The lease runs by the database clock, so the tests that let it expire + // wait in real time; it is short for that. + mailSenderLease = 3 * time.Second + mailSenderSettleBudget = 1500 * time.Millisecond + // mailSenderTokenLifetime is long enough to outlast the idempotency + // window, so a test can move past it without the token expiring first. + mailSenderTokenLifetime = 72 * time.Hour + mailSenderFrom = "Lincodex " + // mailSenderConcurrentWorkers drain the queue at once; each pass holds + // its own connection. + mailSenderConcurrentWorkers = 4 + mailSenderQueued = 8 +) + +var ( + mailSenderStart = time.Date(2026, 10, 6, 12, 0, 0, 0, time.UTC) + mailSenderTables = []pgx.Identifier{{"mail_quota_reservations"}, {"mail_quota_usage"}} +) + +// testClock is the application clock of the sending tests. Several workers +// read it at once, so it is guarded. +type testClock struct { + mu sync.Mutex + now time.Time +} + +func (clock *testClock) Now() time.Time { + clock.mu.Lock() + defer clock.mu.Unlock() + return clock.now +} + +func (clock *testClock) Advance(by time.Duration) { + clock.mu.Lock() + defer clock.mu.Unlock() + clock.now = clock.now.Add(by) +} + +func (clock *testClock) Set(at time.Time) { + clock.mu.Lock() + defer clock.mu.Unlock() + clock.now = at +} + +// settlementOutage lets the first two transactions through, the claim and the +// check before the send, +// and fails every later one, as a worker does that loses the database right +// after it called the provider. +type settlementOutage struct { + inner outbound.Transactor + calls atomic.Int32 +} + +func (outage *settlementOutage) WithinTransaction(ctx context.Context, fn func(ctx context.Context, unit outbound.UnitOfWork) error) error { + if outage.calls.Add(1) > 2 { + return errors.New("settlement unavailable") + } + return outage.inner.WithinTransaction(ctx, fn) +} + +// failingTransport fails every call without an answer, as a misconfigured +// transport can. +type failingTransport struct{ err error } + +func (transport failingTransport) Send(context.Context, outbound.OutgoingMail) (outbound.SendResult, error) { + return outbound.SendResult{}, transport.err +} + +// countingPass counts the passes of a worker loop. +type countingPass struct { + inner inbound.MailPass + passes atomic.Int32 +} + +func (pass *countingPass) PauseFailureCounting(paused bool) { pass.inner.PauseFailureCounting(paused) } + +func (pass *countingPass) ProcessNext(ctx, workCtx context.Context) (inbound.MailPassResult, error) { + pass.passes.Add(1) + return pass.inner.ProcessNext(ctx, workCtx) +} + +type senderHarness struct { + pool *pgxpool.Pool + transactor *postgresadapter.Transactor + identity *postgresadapter.IdentityStore + deliveries outbound.DeliveryRepository + mailer *notification.ServiceMailer + fixture *resendfixture.Server + transport outbound.MailSender + account domain.MailProviderAccount + clock *testClock + logs *syncBuffer + publicURL string + users int +} + +func TestServiceMailSending(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), mailSenderTestTimeout) + defer cancel() + pool := env.newPoolWithMaxConns(ctx, t, mailSenderConcurrentWorkers*2+4) + templates, err := mailtemplate.NewRenderer(env.Config.AppPublicURL) + if err != nil { + t.Fatalf("NewRenderer() error = %v", err) + } + fixture := resendfixture.New() + t.Cleanup(fixture.Close) + clock := &testClock{now: mailSenderStart} + transport, err := resend.NewLoopbackSender(resendfixture.APIKey, mailSenderFrom, 10*time.Second, fixture.URL(), clock.Now) + if err != nil { + t.Fatalf("NewLoopbackSender() error = %v", err) + } + account, err := domain.NewMailProviderAccount("resend", mailSenderAccount) + if err != nil { + t.Fatalf("NewMailProviderAccount() error = %v", err) + } + harness := &senderHarness{ + pool: pool, + transactor: postgresadapter.NewTransactor(pool), + identity: postgresadapter.NewIdentityStore(pool), + deliveries: postgresadapter.NewDeliveryStore(pool).Deliveries(), + mailer: notification.NewServiceMailer(notification.NewTemplateRenderer(templates), account, clock.Now), + fixture: fixture, + transport: transport, + account: account, + clock: clock, + logs: &syncBuffer{}, + publicURL: env.Config.AppPublicURL, + } + reset := func(t *testing.T) { + t.Helper() + // The fixture keeps what it received; a new one per subtest would + // need a new transport, so the tests compare against the counts at + // their start instead. + truncateTables(ctx, t, pool, slices.Concat(mailSenderTables, usersDependentTables)...) + clock.Set(mailSenderStart) + fixture.SetDelay(0) + } + + t.Run("a service email for an account without C2 is accepted by the local Resend fixture", func(t *testing.T) { + reset(t) + calls := len(fixture.Requests()) + user := harness.createUser(ctx, t, false) + raw, token, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime) + // The account has no consent record of any purpose: C2 is the + // publication of the candidate card, and a service mail needs none. + assertRowCount(ctx, t, pool, pgx.Identifier{"consent_records"}, 0) + + stored := harness.delivery(ctx, t, deliveryID) + switch { + case stored.Status() != domain.DeliveryStatusPending || stored.Kind() != domain.MailKindVerification: + t.Fatalf("enqueued delivery is %s of kind %s", stored.Status(), stored.Kind()) + case stored.EmailTokenID() != token.ID || deliveryID != token.ID: + t.Fatal("the delivery is not bound to the token it was enqueued for") + case stored.IdempotencyKey() != "delivery/"+deliveryID.String(): + t.Fatalf("idempotency key = %q", stored.IdempotencyKey()) + } + + sender := harness.newSender(t, harness.transactor, 100, 3000) + result := harness.pass(ctx, t, sender) + if result.Outcome != inbound.MailPassAccepted || result.DeliveryID != deliveryID { + t.Fatalf("pass = %+v, want accepted for the enqueued delivery", result) + } + + requests := fixture.Requests()[calls:] + if len(requests) != 1 { + t.Fatalf("the fixture received %d calls, want 1", len(requests)) + } + request := requests[0] + link := harness.publicURL + "/verify-email#token=" + raw.Reveal() + switch { + case request.IdempotencyKey != "delivery/"+deliveryID.String(): + t.Fatalf("idempotency key sent = %q", request.IdempotencyKey) + case len(request.To) != 1 || request.To[0] != user.Email.Address(): + t.Fatal("the message was not addressed to the account") + case !strings.Contains(request.Text, link) || !strings.Contains(request.HTML, link): + t.Fatal("the message does not carry the verification link with its token in the fragment") + case strings.Contains(request.Text, "?token=") || strings.Contains(request.HTML, "?token="): + t.Fatal("the token travels in a query") + } + + accepted := harness.delivery(ctx, t, deliveryID) + if accepted.Status() != domain.DeliveryStatusAccepted || accepted.ProviderMessageID() == "" || + accepted.AttemptCount() != 1 || !accepted.NextAttemptAt().IsZero() { + t.Fatalf("delivery is %s with %d attempts and message ID %q, want accepted by the provider after one attempt", + accepted.Status(), accepted.AttemptCount(), accepted.ProviderMessageID()) + } + attempts := harness.attempts(ctx, t, deliveryID) + if len(attempts) != 1 || attempts[0].Outcome != domain.DeliveryOutcomeAccepted || attempts[0].StatusAfter != domain.DeliveryStatusAccepted { + t.Fatalf("attempts = %+v, want one accepted attempt", attempts) + } + harness.assertQuotaUsage(ctx, t, 1) + harness.assertClaimReleased(ctx, t, deliveryID) + + // The account sees the provider's acceptance, and a second pass has + // nothing to do. + status, found, err := notification.NewDeliveryStatusReader(harness.deliveries).LatestForUser(ctx, user.ID, domain.MailKindVerification) + if err != nil || !found || status.Status != domain.DeliveryStatusAccepted { + t.Fatalf("LatestForUser() = %+v, %t, %v; want accepted", status, found, err) + } + if again := harness.pass(ctx, t, sender); again.Outcome != inbound.MailPassIdle { + t.Fatalf("second pass = %+v, want idle", again) + } + if len(fixture.Requests()[calls:]) != 1 { + t.Fatal("the second pass called the provider again") + } + harness.assertLogsHoldNoSecrets(t, user.Email.Address(), raw.Reveal(), "verify-email") + }) + + t.Run("a worker that holds a delivery keeps every other worker off it", func(t *testing.T) { + reset(t) + calls := len(fixture.Requests()) + arrivals := fixture.Arrivals() + user := harness.createUser(ctx, t, false) + _, _, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime) + first := harness.newSender(t, harness.transactor, 100, 3000) + second := harness.newSender(t, harness.transactor, 100, 3000) + + // The provider answers slowly, so the first worker is in the middle + // of its send, holding the lease, when the second one looks. + fixture.SetDelay(500 * time.Millisecond) + firstResult := make(chan inbound.MailPassResult, 1) + go func() { + result, err := first.ProcessNext(ctx, ctx) + if err != nil { + t.Errorf("first ProcessNext() error = %v", err) + } + firstResult <- result + }() + waitFor(ctx, t, "the first worker's request to reach the provider", func() bool { return fixture.Arrivals() == arrivals+1 }) + + if result := harness.pass(ctx, t, second); result.Outcome != inbound.MailPassIdle { + t.Fatalf("the second worker's pass = %+v, want idle while the first one holds the delivery", result) + } + if result := <-firstResult; result.Outcome != inbound.MailPassAccepted || result.DeliveryID != deliveryID { + t.Fatalf("the first worker's pass = %+v, want accepted", result) + } + fixture.SetDelay(0) + + requests := fixture.Requests()[calls:] + if len(requests) != 1 || requests[0].IdempotencyKey != "delivery/"+deliveryID.String() || requests[0].Replayed { + t.Fatalf("provider calls = %+v, want exactly one under the delivery key", requests) + } + assertRowCount(ctx, t, pool, pgx.Identifier{"delivery_attempts"}, 1) + if got := harness.delivery(ctx, t, deliveryID); got.Status() != domain.DeliveryStatusAccepted || got.AttemptCount() != 1 { + t.Fatalf("delivery is %s with %d attempts, want accepted after one", got.Status(), got.AttemptCount()) + } + }) + + t.Run("workers racing for a queue send each delivery exactly once", func(t *testing.T) { + reset(t) + calls := len(fixture.Requests()) + messages := fixture.Messages() + ids := make(map[uuid.UUID]bool, mailSenderQueued) + for range mailSenderQueued { + user := harness.createUser(ctx, t, false) + _, _, id := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime) + ids[id] = true + } + var accepted atomic.Int32 + var workers sync.WaitGroup + for range mailSenderConcurrentWorkers { + sender := harness.newSender(t, harness.transactor, 100, 3000) + workers.Go(func() { + for { + result, err := sender.ProcessNext(ctx, ctx) + if err != nil { + t.Errorf("ProcessNext() error = %v", err) + return + } + if result.Outcome == inbound.MailPassIdle { + return + } + if result.Outcome == inbound.MailPassAccepted { + accepted.Add(1) + } + } + }) + } + workers.Wait() + + if accepted.Load() != mailSenderQueued { + t.Fatalf("%d deliveries were accepted, want %d", accepted.Load(), mailSenderQueued) + } + requests := fixture.Requests()[calls:] + keys := make(map[string]int, len(requests)) + for _, request := range requests { + keys[request.IdempotencyKey]++ + if request.Replayed { + t.Fatalf("a delivery was sent twice: %s", request.IdempotencyKey) + } + } + if len(requests) != mailSenderQueued || len(keys) != mailSenderQueued || fixture.Messages()-messages != mailSenderQueued { + t.Fatalf("provider calls = %d with %d keys and %d messages, want %d of each", len(requests), len(keys), fixture.Messages()-messages, mailSenderQueued) + } + for id := range ids { + if got := harness.delivery(ctx, t, id); got.Status() != domain.DeliveryStatusAccepted || got.AttemptCount() != 1 { + t.Fatalf("a delivery is %s with %d attempts, want accepted after one", got.Status(), got.AttemptCount()) + } + } + harness.assertQuotaUsage(ctx, t, mailSenderQueued) + }) + + t.Run("a worker that stopped after sending is replaced and the provider sees the same key", func(t *testing.T) { + reset(t) + calls := len(fixture.Requests()) + messages := fixture.Messages() + user := harness.createUser(ctx, t, false) + _, _, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime) + + // The first worker's request is accepted, but the database fails + // before it can store the answer: it dies holding the lease. + failing := harness.newSender(t, &settlementOutage{inner: harness.transactor}, 100, 3000) + if _, err := failing.ProcessNext(ctx, ctx); err == nil { + t.Fatal("ProcessNext() with a failing settlement returned no error") + } + if got := harness.delivery(ctx, t, deliveryID); got.Status() != domain.DeliveryStatusPending || got.AttemptCount() != 0 { + t.Fatalf("the delivery is %s with %d attempts, want pending with none: nothing was stored", got.Status(), got.AttemptCount()) + } + if owner, _ := harness.claimOf(ctx, t, deliveryID); owner == nil { + t.Fatal("the stopped worker's lease is gone") + } + + // While the lease lives, no other worker takes the delivery. + replacement := harness.newSender(t, harness.transactor, 100, 3000) + if result := harness.pass(ctx, t, replacement); result.Outcome != inbound.MailPassIdle { + t.Fatalf("pass under a live lease = %+v, want idle", result) + } + // After the lease expires the replacement repeats the request under + // the same key; the provider answers with the original message. + time.Sleep(mailSenderLease + 300*time.Millisecond) + if result := harness.pass(ctx, t, replacement); result.Outcome != inbound.MailPassAccepted { + t.Fatalf("pass after the lease expired = %+v, want accepted", result) + } + requests := fixture.Requests()[calls:] + if len(requests) != 2 || requests[0].IdempotencyKey != requests[1].IdempotencyKey || + requests[0].IdempotencyKey != "delivery/"+deliveryID.String() || !requests[1].Replayed { + t.Fatalf("provider calls = %+v, want two calls under one key, the second a replay", requests) + } + if fixture.Messages()-messages != 1 { + t.Fatalf("the provider holds %d new messages, want 1", fixture.Messages()-messages) + } + assertRowCount(ctx, t, pool, pgx.Identifier{"delivery_attempts"}, 1) + // The open reservation was reused: the message counts once. + harness.assertQuotaUsage(ctx, t, 1) + assertRowCount(ctx, t, pool, pgx.Identifier{"mail_quota_reservations"}, 1) + }) + + t.Run("an attempt lost beyond the idempotency window is unknown and is not sent again", func(t *testing.T) { + reset(t) + calls := len(fixture.Requests()) + user := harness.createUser(ctx, t, false) + _, _, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime) + failing := harness.newSender(t, &settlementOutage{inner: harness.transactor}, 100, 3000) + if _, err := failing.ProcessNext(ctx, ctx); err == nil { + t.Fatal("ProcessNext() with a failing settlement returned no error") + } + + // Every worker was gone for longer than the provider remembers keys, + // counted from the first request, whatever the latest lease says. + harness.exec(ctx, t, "UPDATE deliveries SET first_send_started_at = first_send_started_at - interval '25 hours' WHERE id = $1", deliveryID) + time.Sleep(mailSenderLease + 300*time.Millisecond) + replacement := harness.newSender(t, harness.transactor, 100, 3000) + if result := harness.pass(ctx, t, replacement); result.Outcome != inbound.MailPassUnknown { + t.Fatalf("pass = %+v, want unknown", result) + } + if len(fixture.Requests()[calls:]) != 1 { + t.Fatal("the delivery was sent again although the provider may have forgotten its key") + } + got := harness.delivery(ctx, t, deliveryID) + if got.Status() != domain.DeliveryStatusUnknown || got.AttemptCount() != 1 || !got.NextAttemptAt().IsZero() { + t.Fatalf("delivery is %s with %d attempts and a next attempt %s, want unknown after one, for an operator", got.Status(), got.AttemptCount(), got.NextAttemptAt()) + } + if again := harness.pass(ctx, t, replacement); again.Outcome != inbound.MailPassIdle { + t.Fatalf("pass after the unknown record = %+v, want idle", again) + } + }) + + t.Run("a revoked token or an account that moved on sends nothing and ends with a reason", func(t *testing.T) { + tests := []struct { + name string + change func(ctx context.Context, t *testing.T, user domain.User, token domain.EmailToken, raw domain.SecretToken) + want domain.DeliveryCancelReason + }{ + { + name: "token revoked by a resend", + change: func(ctx context.Context, t *testing.T, user domain.User, _ domain.EmailToken, _ domain.SecretToken) { + t.Helper() + invalidated, err := harness.identity.EmailTokens().InvalidateActive(ctx, user.ID, domain.EmailTokenPurposeEmailVerification, harness.clock.Now()) + if err != nil || invalidated != 1 { + t.Fatalf("InvalidateActive() = %d, %v; want 1", invalidated, err) + } + }, + want: domain.DeliveryCancelTokenRevoked, + }, + { + name: "token already used", + change: func(ctx context.Context, t *testing.T, _ domain.User, _ domain.EmailToken, raw domain.SecretToken) { + t.Helper() + if _, err := harness.identity.EmailTokens().Consume(ctx, raw.Hash(), domain.EmailTokenPurposeEmailVerification, harness.clock.Now()); err != nil { + t.Fatalf("Consume() error = %v", err) + } + }, + want: domain.DeliveryCancelTokenConsumed, + }, + { + name: "token expired", + change: func(_ context.Context, _ *testing.T, _ domain.User, token domain.EmailToken, _ domain.SecretToken) { + harness.clock.Set(token.ExpiresAt) + }, + want: domain.DeliveryCancelTokenExpired, + }, + { + name: "account registered again", + change: func(ctx context.Context, t *testing.T, user domain.User, _ domain.EmailToken, _ domain.SecretToken) { + t.Helper() + harness.exec(ctx, t, "UPDATE users SET registration_version = registration_version + 1 WHERE id = $1", user.ID) + }, + want: domain.DeliveryCancelAccountNotCurrent, + }, + { + name: "address already verified", + change: func(ctx context.Context, t *testing.T, user domain.User, token domain.EmailToken, _ domain.SecretToken) { + t.Helper() + if _, err := harness.identity.Users().MarkEmailVerified(ctx, user.ID, token.RegistrationVersion, harness.clock.Now()); err != nil { + t.Fatalf("MarkEmailVerified() error = %v", err) + } + }, + want: domain.DeliveryCancelAccountNotCurrent, + }, + { + name: "address of the account changed", + change: func(ctx context.Context, t *testing.T, user domain.User, _ domain.EmailToken, _ domain.SecretToken) { + t.Helper() + harness.exec(ctx, t, "UPDATE users SET email = 'moved.on@example.com', email_normalized = 'moved.on@example.com' WHERE id = $1", user.ID) + }, + want: domain.DeliveryCancelRecipientMismatch, + }, + { + name: "token of another purpose", + change: func(ctx context.Context, t *testing.T, _ domain.User, token domain.EmailToken, _ domain.SecretToken) { + t.Helper() + harness.exec(ctx, t, "UPDATE email_tokens SET purpose = 'password_reset' WHERE id = $1", token.ID) + }, + want: domain.DeliveryCancelTokenPurposeMismatch, + }, + } + reset(t) + calls := len(fixture.Requests()) + sender := harness.newSender(t, harness.transactor, 100, 3000) + for _, test := range tests { + user := harness.createUser(ctx, t, false) + raw, token, deliveryID := harness.enqueueVerification(ctx, t, user, time.Hour) + test.change(ctx, t, user, token, raw) + + result := harness.pass(ctx, t, sender) + if result.Outcome != inbound.MailPassCancelled || result.CancelReason != test.want || result.DeliveryID != deliveryID { + t.Fatalf("%s: pass = %+v, want cancelled with reason %s", test.name, result, test.want) + } + got := harness.delivery(ctx, t, deliveryID) + if got.Status() != domain.DeliveryStatusCancelled || got.CancelReason() != test.want || + got.AttemptCount() != 0 || !got.NextAttemptAt().IsZero() || got.ProviderMessageID() != "" { + t.Fatalf("%s: delivery is %s (%s) with %d attempts, want cancelled with reason %s and no attempt", + test.name, got.Status(), got.CancelReason(), got.AttemptCount(), test.want) + } + harness.assertClaimReleased(ctx, t, deliveryID) + if again := harness.pass(ctx, t, sender); again.Outcome != inbound.MailPassIdle { + t.Fatalf("%s: pass after the cancellation = %+v, want idle", test.name, again) + } + if _, _, err := got.RecordAttempt(domain.DeliveryAttemptInput{At: harness.clock.Now(), Outcome: domain.DeliveryOutcomeUnknown}); !errors.Is(err, domain.ErrDeliveryTransition) { + t.Fatalf("%s: an attempt on a cancelled delivery error = %v, want ErrDeliveryTransition", test.name, err) + } + status, found, err := notification.NewDeliveryStatusReader(harness.deliveries).LatestForUser(ctx, user.ID, domain.MailKindVerification) + if err != nil || !found || status.Status != domain.DeliveryStatusCancelled { + t.Fatalf("%s: LatestForUser() = %+v, %t, %v; want cancelled", test.name, status, found, err) + } + harness.clock.Set(mailSenderStart) + } + if got := len(fixture.Requests()[calls:]); got != 0 { + t.Fatalf("the provider received %d calls, want none: an invalid mail was sent", got) + } + // Nothing was reserved or counted for mail that never went out. + assertRowCount(ctx, t, pool, pgx.Identifier{"mail_quota_reservations"}, 0) + harness.assertQuotaUsage(ctx, t, 0) + }) + + t.Run("a delivery that cannot be restored is cancelled and does not block the queue", func(t *testing.T) { + reset(t) + calls := len(fixture.Requests()) + poisoned := harness.createUser(ctx, t, false) + _, _, poisonedID := harness.enqueueVerification(ctx, t, poisoned, mailSenderTokenLifetime) + healthy := harness.createUser(ctx, t, false) + _, _, healthyID := harness.enqueueVerification(ctx, t, healthy, mailSenderTokenLifetime) + + // The content trigger refuses any change of a stored body, so the + // test lifts it for one statement to break the content hash, as a + // manual edit of the table would. + harness.exec(ctx, t, "ALTER TABLE deliveries DISABLE TRIGGER deliveries_refuse_content_change") + _, err := pool.Exec(ctx, "UPDATE deliveries SET content_sha256 = $2 WHERE id = $1", poisonedID, make([]byte, 32)) + harness.exec(ctx, t, "ALTER TABLE deliveries ENABLE TRIGGER deliveries_refuse_content_change") + if err != nil { + t.Fatalf("break the content hash: %v", err) + } + if _, err := harness.deliveries.Get(ctx, poisonedID); !errors.Is(err, domain.ErrMailContentIntegrity) { + t.Fatalf("Get() of the broken delivery error = %v, want ErrMailContentIntegrity", err) + } + + sender := harness.newSender(t, harness.transactor, 100, 3000) + result := harness.pass(ctx, t, sender) + if result.Outcome != inbound.MailPassCancelled || result.DeliveryID != poisonedID || result.CancelReason != domain.DeliveryCancelContentInvalid { + t.Fatalf("pass = %+v, want the broken delivery cancelled as content_invalid", result) + } + var status, reason string + var version int64 + if err := pool.QueryRow(ctx, "SELECT status, cancel_reason, version FROM deliveries WHERE id = $1", poisonedID).Scan(&status, &reason, &version); err != nil || + status != "cancelled" || reason != "content_invalid" || version != 2 { + t.Fatalf("broken delivery is %q (%q) at version %d, %v; want cancelled content_invalid at version 2", status, reason, version, err) + } + harness.assertClaimReleased(ctx, t, poisonedID) + if len(fixture.Requests()[calls:]) != 0 { + t.Fatal("a broken delivery reached the provider") + } + + // The delivery behind it is sent in the next pass. + if next := harness.pass(ctx, t, sender); next.Outcome != inbound.MailPassAccepted || next.DeliveryID != healthyID { + t.Fatalf("next pass = %+v, want the healthy delivery accepted", next) + } + harness.assertLogsHoldNoSecrets(t, poisoned.Email.Address(), healthy.Email.Address()) + }) + + t.Run("a row that fails for a reason of its own moves back in the queue and is cancelled after repeated failures", func(t *testing.T) { + reset(t) + calls := len(fixture.Requests()) + broken := harness.createUser(ctx, t, false) + _, _, brokenID := harness.enqueueVerification(ctx, t, broken, mailSenderTokenLifetime) + healthy := harness.createUser(ctx, t, false) + _, _, healthyID := harness.enqueueVerification(ctx, t, healthy, mailSenderTokenLifetime) + + // A subject with a line break passes the table and fails the domain's + // rules, so the row cannot be restored although its hash is intact: + // a deterministic fault that is not a hash mismatch. + harness.exec(ctx, t, "ALTER TABLE deliveries DISABLE TRIGGER deliveries_refuse_content_change") + _, err := pool.Exec(ctx, "UPDATE deliveries SET subject = E'broken\nsubject' WHERE id = $1", brokenID) + harness.exec(ctx, t, "ALTER TABLE deliveries ENABLE TRIGGER deliveries_refuse_content_change") + if err != nil { + t.Fatalf("break the subject: %v", err) + } + sender := harness.newSender(t, harness.transactor, 100, 3000) + + result := harness.pass(ctx, t, sender) + if result.Outcome != inbound.MailPassRowFailed || result.DeliveryID != brokenID { + t.Fatalf("first pass = %+v, want row_failed for the broken delivery", result) + } + var failures int + var due time.Time + if err := pool.QueryRow(ctx, "SELECT failure_count, next_attempt_at FROM deliveries WHERE id = $1", brokenID).Scan(&failures, &due); err != nil || + failures != 1 || !due.Equal(mailSenderStart.Add(time.Minute)) { + t.Fatalf("broken row: %d failures due %s, %v; want 1 failure due a minute later", failures, due, err) + } + harness.assertClaimReleased(ctx, t, brokenID) + // It is not claimed again at once, and the delivery behind it is sent. + if next := harness.pass(ctx, t, sender); next.Outcome != inbound.MailPassAccepted || next.DeliveryID != healthyID { + t.Fatalf("second pass = %+v, want the healthy delivery accepted", next) + } + // Each failure pushes the row further; the third cancels it. + harness.clock.Advance(time.Hour) + if again := harness.pass(ctx, t, sender); again.Outcome != inbound.MailPassRowFailed { + t.Fatalf("pass at the second due time = %+v, want row_failed", again) + } + harness.clock.Advance(2 * time.Hour) + final := harness.pass(ctx, t, sender) + if final.Outcome != inbound.MailPassCancelled || final.CancelReason != domain.DeliveryCancelProcessingFailed { + t.Fatalf("third failure = %+v, want cancelled as processing_failed", final) + } + var status, reason string + var redacted *time.Time + if err := pool.QueryRow(ctx, "SELECT status, cancel_reason, body_redacted_at FROM deliveries WHERE id = $1", brokenID).Scan(&status, &reason, &redacted); err != nil || + status != "cancelled" || reason != "processing_failed" || redacted == nil { + t.Fatalf("broken row is %q (%q) redacted %v, %v; want cancelled processing_failed with its bodies cleared", status, reason, redacted, err) + } + if len(fixture.Requests()[calls:]) != 1 { + t.Fatal("the broken delivery reached the provider") + } + harness.assertLogsHoldNoSecrets(t, broken.Email.Address(), healthy.Email.Address()) + }) + + t.Run("a transport error without an answer moves the row back without counting it, not a loop at the head of the queue", func(t *testing.T) { + reset(t) + user := harness.createUser(ctx, t, false) + _, _, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime) + faulty := *harness + faulty.transport = failingTransport{err: errors.New("transport is misconfigured")} + sender := faulty.newSender(t, harness.transactor, 100, 3000) + + result := faulty.pass(ctx, t, sender) + if result.Outcome != inbound.MailPassInterrupted || result.DeliveryID != deliveryID { + t.Fatalf("pass = %+v, want interrupted: the fault is not counted against the row", result) + } + var failures int + if err := pool.QueryRow(ctx, "SELECT failure_count FROM deliveries WHERE id = $1", deliveryID).Scan(&failures); err != nil || failures != 0 { + t.Fatalf("failure_count = %d, %v; want 0", failures, err) + } + got := harness.delivery(ctx, t, deliveryID) + if got.Status() != domain.DeliveryStatusPending || got.AttemptCount() != 0 || !got.NextAttemptAt().Equal(mailSenderStart.Add(time.Minute)) { + t.Fatalf("delivery is %s due %s after %d attempts, want pending due a minute later with none", got.Status(), got.NextAttemptAt(), got.AttemptCount()) + } + harness.assertClaimReleased(ctx, t, deliveryID) + harness.assertQuotaUsage(ctx, t, 0) + if again := faulty.pass(ctx, t, sender); again.Outcome != inbound.MailPassIdle { + t.Fatalf("pass before the due time = %+v, want idle", again) + } + }) + + t.Run("a failure is recorded only for a row that no other worker holds", func(t *testing.T) { + reset(t) + user := harness.createUser(ctx, t, false) + _, _, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime) + holder, stranger := uuid.New(), uuid.New() + if _, err := harness.deliveries.ClaimDue(ctx, outbound.DeliveryClaim{ + Owner: holder, Account: harness.account, Kinds: domain.ServiceMailKinds(), Now: harness.clock.Now(), Lease: mailSenderLease, + }); err != nil { + t.Fatalf("ClaimDue() error = %v", err) + } + at := harness.clock.Now() + // A stranger whose claim rolled back must not touch a row that the + // holder has just claimed. + moved, err := harness.deliveries.RecordFailure(ctx, deliveryID, stranger, at, at.Add(time.Hour), 3, true) + if err != nil || moved { + t.Fatalf("RecordFailure() by a stranger = %t, %v; want it to leave the row alone", moved, err) + } + var failures int + var due time.Time + if err := pool.QueryRow(ctx, "SELECT failure_count, next_attempt_at FROM deliveries WHERE id = $1", deliveryID).Scan(&failures, &due); err != nil || + failures != 0 || !due.Equal(at) { + t.Fatalf("row after a stranger's failure: %d failures due %s, %v; want it untouched", failures, due, err) + } + if owner, _ := harness.claimOf(ctx, t, deliveryID); owner == nil || *owner != holder { + t.Fatal("a stranger's failure cleared the holder's lease") + } + // The holder itself may record it; counting can be switched off. + if _, err := harness.deliveries.RecordFailure(ctx, deliveryID, holder, at, at.Add(time.Hour), 3, false); err != nil { + t.Fatalf("RecordFailure() by the holder error = %v", err) + } + if err := pool.QueryRow(ctx, "SELECT failure_count FROM deliveries WHERE id = $1", deliveryID).Scan(&failures); err != nil || failures != 0 { + t.Fatalf("failure_count after an uncounted failure = %d, %v; want 0", failures, err) + } + harness.assertClaimReleased(ctx, t, deliveryID) + }) + + t.Run("the first request, not the latest lease, starts the idempotency window", func(t *testing.T) { + reset(t) + calls := len(fixture.Requests()) + user := harness.createUser(ctx, t, false) + _, _, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime) + // Three workers in a row stop after the call. Each takeover is only + // seconds after the lease before it, so counting from the latest lease + // would never see the age of the first request. + for cycle := range 3 { + failing := harness.newSender(t, &settlementOutage{inner: harness.transactor}, 100, 3000) + if _, err := failing.ProcessNext(ctx, ctx); err == nil { + t.Fatalf("cycle %d: ProcessNext() with a failing settlement returned no error", cycle) + } + time.Sleep(mailSenderLease + 300*time.Millisecond) + harness.exec(ctx, t, "UPDATE deliveries SET first_send_started_at = first_send_started_at - interval '8 hours' WHERE id = $1", deliveryID) + } + replacement := harness.newSender(t, harness.transactor, 100, 3000) + // 24 hours after the first request, 23 with the safety margin. + if result := harness.pass(ctx, t, replacement); result.Outcome != inbound.MailPassUnknown { + t.Fatalf("pass = %+v, want unknown: the first request is 24 hours old", result) + } + if got := len(fixture.Requests()[calls:]); got != 3 { + t.Fatalf("provider calls = %d, want the three of the lost workers and no fourth", got) + } + }) + + t.Run("the lease follows the database clock and a result is recorded only by the lease holder", func(t *testing.T) { + reset(t) + user := harness.createUser(ctx, t, false) + _, _, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime) + owner, other := uuid.New(), uuid.New() + claimed, err := harness.deliveries.ClaimDue(ctx, outbound.DeliveryClaim{ + Owner: owner, Account: harness.account, Kinds: domain.ServiceMailKinds(), Now: harness.clock.Now(), Lease: mailSenderLease, + }) + if err != nil || claimed.Delivery.ID() != deliveryID { + t.Fatalf("ClaimDue() = %v, %v; want the enqueued delivery", claimed.Delivery.ID(), err) + } + // The fake application clock is a day apart from the database clock + // at most; the lease must be measured by the database one. + var live, bounded bool + if err := pool.QueryRow(ctx, `SELECT claimed_until > clock_timestamp(), claimed_until <= clock_timestamp() + interval '3 seconds' + FROM deliveries WHERE id = $1`, deliveryID).Scan(&live, &bounded); err != nil || !live || !bounded { + t.Fatalf("lease live = %t, within its length = %t, %v; want a lease of 3 seconds by the database clock", live, bounded, err) + } + next, attempt, err := claimed.Delivery.RecordAttempt(domain.DeliveryAttemptInput{ + At: harness.clock.Now(), Outcome: domain.DeliveryOutcomeAccepted, ProviderMessageID: deliveryMessageID, + }) + if err != nil { + t.Fatalf("RecordAttempt() error = %v", err) + } + if err := harness.deliveries.RecordClaimedAttempt(ctx, other, next, attempt); !errors.Is(err, outbound.ErrDeliveryVersionConflict) { + t.Fatalf("RecordClaimedAttempt() by a stranger error = %v, want ErrDeliveryVersionConflict", err) + } + if held, err := harness.deliveries.LockClaimed(ctx, deliveryID, other); err != nil || held { + t.Fatalf("LockClaimed() by a stranger = %t, %v; want false", held, err) + } + if err := harness.deliveries.RecordClaimedAttempt(ctx, owner, next, attempt); err != nil { + t.Fatalf("RecordClaimedAttempt() by the holder error = %v", err) + } + }) + + t.Run("the claim query reads the small due index, not the notification backlog", func(t *testing.T) { + reset(t) + user := harness.createUser(ctx, t, true) + harness.exec(ctx, t, `INSERT INTO deliveries ( + 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, version, created_at, updated_at + ) + SELECT gen_random_uuid(), $1, 'backlog@example.com', 'notification', 'notification.v1', 's', 't', '', decode(repeat('00', 32), 'hex'), + 'resend', $2, 'delivery/backlog-' || n, 'pending', 0, $3::timestamptz - interval '1 day', 1, $3, $3 + FROM generate_series(1, 5000) AS n`, user.ID, mailSenderAccount, mailSenderStart) + harness.exec(ctx, t, "ANALYZE deliveries") + rows, err := pool.Query(ctx, `EXPLAIN (COSTS OFF) SELECT due.id FROM deliveries AS due + WHERE due.kind IN ('verification', 'password_reset') AND due.kind = any($1::text[]) + AND due.status IN ('pending', 'waiting_quota') AND due.next_attempt_at IS NOT NULL + AND due.next_attempt_at <= $2::timestamptz AND due.provider = 'resend' AND due.provider_account = $3 + AND (due.claim_owner IS NULL OR due.claimed_until <= clock_timestamp()) + ORDER BY due.next_attempt_at, due.id LIMIT 1 FOR UPDATE SKIP LOCKED`, + []string{"verification", "password_reset"}, mailSenderStart, mailSenderAccount) + if err != nil { + t.Fatalf("explain the claim: %v", err) + } + defer rows.Close() + var plan strings.Builder + for rows.Next() { + var line string + if err := rows.Scan(&line); err != nil { + t.Fatalf("scan the plan: %v", err) + } + plan.WriteString(line + "\n") + } + if !strings.Contains(plan.String(), "deliveries_due_idx") || strings.Contains(plan.String(), "Seq Scan") { + t.Fatalf("the claim does not use deliveries_due_idx over 5000 notification rows:\n%s", plan.String()) + } + }) + + t.Run("overdue service mail ignores a notification backlog", func(t *testing.T) { + reset(t) + user := harness.createUser(ctx, t, true) + content, err := domain.NewMailContent(domain.MailKindNotification, "notification.v1", "s", "t\n", "") + if err != nil { + t.Fatalf("NewMailContent() error = %v", err) + } + notificationDelivery, err := domain.NewDelivery(domain.NewDeliveryInput{ + ID: uuid.Must(uuid.NewV7()), RecipientUserID: user.ID, Recipient: user.Email, Content: content, + ProviderAccount: harness.account, CreatedAt: mailSenderStart.Add(-48 * time.Hour), + }) + if err != nil { + t.Fatalf("NewDelivery() error = %v", err) + } + if created, err := harness.deliveries.Create(ctx, notificationDelivery); err != nil || !created { + t.Fatalf("Create() = %t, %v", created, err) + } + reader := postgresadapter.NewDeliveryStatisticsStore(pool) + statistics, err := reader.DeliveryStatistics(ctx) + if err != nil || !statistics.EarliestPendingAttemptAt.IsZero() { + t.Fatalf("DeliveryStatistics() earliest = %s, %v; want none for a notification-only backlog", statistics.EarliestPendingAttemptAt, err) + } + other := harness.createUser(ctx, t, false) + _, _, serviceID := harness.enqueueVerification(ctx, t, other, mailSenderTokenLifetime) + statistics, err = reader.DeliveryStatistics(ctx) + due := harness.delivery(ctx, t, serviceID).NextAttemptAt() + if err != nil || !statistics.EarliestPendingAttemptAt.Equal(due) { + t.Fatalf("DeliveryStatistics() earliest = %s, %v; want the service mail's due time %s", statistics.EarliestPendingAttemptAt, err, due) + } + }) + + t.Run("a token mail loses its bodies when it ends, and only then", func(t *testing.T) { + reset(t) + accepted := harness.createUser(ctx, t, false) + raw, _, acceptedID := harness.enqueueVerification(ctx, t, accepted, mailSenderTokenLifetime) + revoked := harness.createUser(ctx, t, false) + revokedRaw, _, revokedID := harness.enqueueVerification(ctx, t, revoked, mailSenderTokenLifetime) + if invalidated, err := harness.identity.EmailTokens().InvalidateActive(ctx, revoked.ID, domain.EmailTokenPurposeEmailVerification, harness.clock.Now()); err != nil || invalidated != 1 { + t.Fatalf("InvalidateActive() = %d, %v", invalidated, err) + } + // While the mail waits, its body is the token's only home. + var text string + if err := pool.QueryRow(ctx, "SELECT text_body FROM deliveries WHERE id = $1", acceptedID).Scan(&text); err != nil || !strings.Contains(text, raw.Reveal()) { + t.Fatalf("a waiting mail has no body: %v", err) + } + _, err := pool.Exec(ctx, "UPDATE deliveries SET text_body = '', html_body = '', body_redacted_at = now() WHERE id = $1", acceptedID) + assertSQLRefusal(t, err, "deliveries_content_immutable") + + sender := harness.newSender(t, harness.transactor, 100, 3000) + for range 2 { + harness.pass(ctx, t, sender) + } + for name, id := range map[string]uuid.UUID{"accepted": acceptedID, "cancelled": revokedID} { + var text, html string + var redactedAt *time.Time + if err := pool.QueryRow(ctx, "SELECT text_body, html_body, body_redacted_at FROM deliveries WHERE id = $1", id).Scan(&text, &html, &redactedAt); err != nil || + text != "" || html != "" || redactedAt == nil { + t.Fatalf("%s delivery keeps a body (%d, %d bytes) or no redaction time: %v", name, len(text), len(html), err) + } + got := harness.delivery(ctx, t, id) + if !got.Content().Redacted() || got.Content().Text() != "" || got.Content().Subject() == "" { + t.Fatalf("%s delivery restores as %v, want redacted content with its subject", name, got.Content()) + } + } + // Neither the token nor its mail is in the table any more. + var leaked int + if err := pool.QueryRow(ctx, "SELECT count(*) FROM deliveries WHERE text_body LIKE $1 OR html_body LIKE $1 OR text_body LIKE $2 OR html_body LIKE $2", + "%"+raw.Reveal()+"%", "%"+revokedRaw.Reveal()+"%").Scan(&leaked); err != nil || leaked != 0 { + t.Fatalf("%d rows still hold a token, %v", leaked, err) + } + // A redacted row cannot get a body back, or lose its mark. + for _, statement := range []string{ + "UPDATE deliveries SET text_body = 'again' WHERE id = $1", + "UPDATE deliveries SET body_redacted_at = NULL WHERE id = $1", + } { + _, err := pool.Exec(ctx, statement, acceptedID) + assertSQLRefusal(t, err, "deliveries_content_immutable") + } + // The account still sees its status. + status, found, err := notification.NewDeliveryStatusReader(harness.deliveries).LatestForUser(ctx, accepted.ID, domain.MailKindVerification) + if err != nil || !found || status.Status != domain.DeliveryStatusAccepted { + t.Fatalf("LatestForUser() = %+v, %t, %v; want accepted", status, found, err) + } + }) + + t.Run("a deleted account leaves nothing to send", func(t *testing.T) { + reset(t) + calls := len(fixture.Requests()) + user := harness.createUser(ctx, t, false) + _, _, deliveryID := harness.enqueueVerification(ctx, t, user, time.Hour) + harness.exec(ctx, t, "DELETE FROM users WHERE id = $1", user.ID) + if _, err := harness.deliveries.Get(ctx, deliveryID); !errors.Is(err, outbound.ErrDeliveryNotFound) { + t.Fatalf("Get() after the account was deleted error = %v, want ErrDeliveryNotFound", err) + } + sender := harness.newSender(t, harness.transactor, 100, 3000) + if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassIdle || len(fixture.Requests()[calls:]) != 0 { + t.Fatalf("pass = %+v with %d provider calls, want idle and none", result, len(fixture.Requests()[calls:])) + } + }) + + t.Run("provider answers become delivery states and due times without an internal retry", func(t *testing.T) { + reset(t) + calls := len(fixture.Requests()) + user := harness.createUser(ctx, t, false) + _, _, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime) + sender := harness.newSender(t, harness.transactor, 100, 3000) + + // A refusal for now: the delivery is pending again, due later, and + // nothing repeats the request before that. + fixture.Script(resendfixture.Reply{Status: http.StatusServiceUnavailable, Name: "service_unavailable"}) + if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassRetry { + t.Fatalf("pass after a 503 = %+v, want retry", result) + } + pending := harness.delivery(ctx, t, deliveryID) + wantDue := mailSenderStart.Add(time.Minute) + if pending.Status() != domain.DeliveryStatusPending || !pending.NextAttemptAt().Equal(wantDue) || pending.AttemptCount() != 1 { + t.Fatalf("delivery is %s due %s after %d attempts, want pending due %s after one", pending.Status(), pending.NextAttemptAt(), pending.AttemptCount(), wantDue) + } + harness.assertQuotaUsage(ctx, t, 0) // the refused request did not count + if again := harness.pass(ctx, t, sender); again.Outcome != inbound.MailPassIdle || len(fixture.Requests()[calls:]) != 1 { + t.Fatalf("pass before the due time = %+v with %d provider calls, want idle and 1", again, len(fixture.Requests()[calls:])) + } + harness.clock.Set(wantDue) + if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassAccepted { + t.Fatalf("pass at the due time = %+v, want accepted", result) + } + requests := fixture.Requests()[calls:] + if len(requests) != 2 || requests[0].IdempotencyKey != requests[1].IdempotencyKey { + t.Fatalf("provider calls = %+v, want two calls under one key", requests) + } + attempts := harness.attempts(ctx, t, deliveryID) + if len(attempts) != 2 || attempts[0].Rejection != domain.DeliveryRejectionTemporary || attempts[1].Outcome != domain.DeliveryOutcomeAccepted { + t.Fatalf("attempts = %+v, want a temporary refusal and then acceptance", attempts) + } + + // An uncertain answer is never retried by the worker and never read + // as not sent. + other := harness.createUser(ctx, t, false) + _, _, uncertainID := harness.enqueueVerification(ctx, t, other, mailSenderTokenLifetime) + fixture.Script(resendfixture.Reply{Status: http.StatusInternalServerError, Name: "application_error"}) + if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassUnknown { + t.Fatalf("pass after a 500 = %+v, want unknown", result) + } + if got := harness.delivery(ctx, t, uncertainID); got.Status() != domain.DeliveryStatusUnknown || !got.NextAttemptAt().IsZero() { + t.Fatalf("delivery is %s with next attempt %s, want unknown without one", got.Status(), got.NextAttemptAt()) + } + harness.clock.Advance(24 * time.Hour) + callsBefore := len(fixture.Requests()) + if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassIdle || len(fixture.Requests()) != callsBefore { + t.Fatalf("pass after an unknown outcome = %+v, want idle without a call", result) + } + + // A permanent refusal ends the delivery. + harness.clock.Set(mailSenderStart) + third := harness.createUser(ctx, t, false) + _, _, refusedID := harness.enqueueVerification(ctx, t, third, mailSenderTokenLifetime) + fixture.Script(resendfixture.Reply{Status: http.StatusForbidden, Name: "validation_error"}) + if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassRejected { + t.Fatalf("pass after a 403 = %+v, want rejected", result) + } + if got := harness.delivery(ctx, t, refusedID); got.Status() != domain.DeliveryStatusRejected { + t.Fatalf("delivery is %s, want rejected", got.Status()) + } + }) + + t.Run("a used-up quota parks the delivery in a user-visible waiting status", func(t *testing.T) { + reset(t) + calls := len(fixture.Requests()) + // The local gate: one message per day. + sender := harness.newSender(t, harness.transactor, 1, 5) + first := harness.createUser(ctx, t, false) + harness.enqueueVerification(ctx, t, first, mailSenderTokenLifetime) + second := harness.createUser(ctx, t, false) + _, _, waitingID := harness.enqueueVerification(ctx, t, second, mailSenderTokenLifetime) + + if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassAccepted { + t.Fatalf("first pass = %+v, want accepted", result) + } + result := harness.pass(ctx, t, sender) + if result.Outcome != inbound.MailPassWaitingQuota || result.DeliveryID != waitingID { + t.Fatalf("second pass = %+v, want waiting_quota for the second delivery", result) + } + midnight := time.Date(2026, 10, 7, 0, 0, 0, 0, time.UTC) + status, found, err := notification.NewDeliveryStatusReader(harness.deliveries).LatestForUser(ctx, second.ID, domain.MailKindVerification) + if err != nil || !found || !status.WaitingForQuota() || !status.WaitingUntil.Equal(midnight) { + t.Fatalf("LatestForUser() = %+v, %t, %v; want waiting until %s", status, found, err, midnight) + } + if len(fixture.Requests()[calls:]) != 1 { + t.Fatal("the provider was called for a delivery that the local quota deferred") + } + // Not due yet one second before the reset; sent right after it. + harness.clock.Set(midnight.Add(-time.Second)) + if again := harness.pass(ctx, t, sender); again.Outcome != inbound.MailPassIdle { + t.Fatalf("pass before the reset = %+v, want idle", again) + } + harness.clock.Set(midnight) + if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassAccepted || result.DeliveryID != waitingID { + t.Fatalf("pass at the reset = %+v, want the waiting delivery accepted", result) + } + + // The provider's own refusal for its quota also waits for the reset. + third := harness.createUser(ctx, t, false) + _, _, refusedID := harness.enqueueVerification(ctx, t, third, mailSenderTokenLifetime) + fixture.Script(resendfixture.Reply{Status: http.StatusTooManyRequests, Name: "daily_quota_exceeded"}) + wide := harness.newSender(t, harness.transactor, 100, 3000) + nextMidnight := midnight.AddDate(0, 0, 1) + if result := harness.pass(ctx, t, wide); result.Outcome != inbound.MailPassWaitingQuota || result.DeliveryID != refusedID { + t.Fatalf("pass after the provider quota answer = %+v, want waiting_quota", result) + } + if got := harness.delivery(ctx, t, refusedID); got.Status() != domain.DeliveryStatusWaitingQuota || !got.NextAttemptAt().Equal(nextMidnight) { + t.Fatalf("delivery is %s until %s, want waiting_quota until %s", got.Status(), got.NextAttemptAt(), nextMidnight) + } + }) + + t.Run("product notifications are not sent by this worker", func(t *testing.T) { + reset(t) + calls := len(fixture.Requests()) + user := harness.createUser(ctx, t, true) + content, err := domain.NewMailContent(domain.MailKindNotification, "notification.v1", "Синтетическое уведомление", "PRIVATE-BODY notification\n", "") + if err != nil { + t.Fatalf("NewMailContent() error = %v", err) + } + delivery, err := domain.NewDelivery(domain.NewDeliveryInput{ + ID: uuid.Must(uuid.NewV7()), RecipientUserID: user.ID, Recipient: user.Email, + Content: content, ProviderAccount: harness.account, CreatedAt: harness.clock.Now(), + }) + if err != nil { + t.Fatalf("NewDelivery() error = %v", err) + } + if created, err := harness.deliveries.Create(ctx, delivery); err != nil || !created { + t.Fatalf("Create() = %t, %v; want the notification stored", created, err) + } + sender := harness.newSender(t, harness.transactor, 100, 3000) + if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassIdle || len(fixture.Requests()[calls:]) != 0 { + t.Fatalf("pass = %+v with %d provider calls, want idle and none: notifications belong to TASK-462", result, len(fixture.Requests()[calls:])) + } + if got := harness.delivery(ctx, t, delivery.ID()); got.Status() != domain.DeliveryStatusPending || got.AttemptCount() != 0 { + t.Fatalf("the notification is %s with %d attempts, want it untouched", got.Status(), got.AttemptCount()) + } + }) + + t.Run("EMAIL_PROVIDER=disabled sends nothing, keeps the mail, and does not spin", func(t *testing.T) { + reset(t) + disabledAccount, err := domain.NewMailProviderAccount("disabled", mailSenderAccount) + if err != nil { + t.Fatalf("NewMailProviderAccount() error = %v", err) + } + stored := *harness + stored.account = disabledAccount + stored.mailer = notification.NewServiceMailer(notification.NewTemplateRenderer(templates), disabledAccount, clock.Now) + stored.transport = disabled.NewSender() + calls := len(fixture.Requests()) + user := harness.createUser(ctx, t, false) + _, _, deliveryID := stored.enqueueVerification(ctx, t, user, mailSenderTokenLifetime) + if got := harness.delivery(ctx, t, deliveryID); got.ProviderAccount() != disabledAccount { + t.Fatal("the mail stored while no transport runs is not pinned to disabled") + } + + sender := stored.newSender(t, harness.transactor, 100, 3000) + if result := stored.pass(ctx, t, sender); result.Outcome != inbound.MailPassChannelUnavailable { + t.Fatalf("pass = %+v, want channel_unavailable", result) + } + got := harness.delivery(ctx, t, deliveryID) + if got.Status() != domain.DeliveryStatusPending || got.AttemptCount() != 0 || got.Version() != 1 { + t.Fatalf("delivery is %s with %d attempts at version %d, want it untouched", got.Status(), got.AttemptCount(), got.Version()) + } + harness.assertClaimReleased(ctx, t, deliveryID) + harness.assertQuotaUsageFor(ctx, t, disabledAccount, 0) + + // The worker loop backs off instead of claiming again at once. + metrics := prometheus.New() + counted := &countingPass{inner: sender} + worker, err := mailsender.New(counted, metrics, slog.New(slog.NewJSONHandler(harness.logs, nil)), mailsender.Settings{ + PollInterval: 50 * time.Millisecond, + Backoff: retry.Backoff{Initial: 400 * time.Millisecond, Max: time.Second}, + ShutdownGrace: time.Second, + }) + if err != nil { + t.Fatalf("mailsender.New() error = %v", err) + } + runCtx, stop := context.WithCancel(ctx) + stopped := make(chan struct{}) + go func() { + defer close(stopped) + worker.Run(runCtx) + }() + waitFor(ctx, t, "the sender gauge to show the loop", func() bool { return strings.Contains(scrapeMetrics(metrics), "lincodex_mail_sender_running 1\n") }) + time.Sleep(900 * time.Millisecond) + stop() + <-stopped + if passes := counted.passes.Load(); passes > 4 { + t.Fatalf("the loop made %d passes in under a second, want it to back off", passes) + } + if !strings.Contains(scrapeMetrics(metrics), "lincodex_mail_sender_running 0\n") { + t.Fatal("the sender gauge did not return to 0 after the loop stopped") + } + if len(fixture.Requests()[calls:]) != 0 { + t.Fatal("the disabled transport reached the provider") + } + harness.assertQuotaUsageFor(ctx, t, disabledAccount, 0) + + // The stand now enables a transport: the mail is moved to its + // account, before any attempt, and sent. + live := harness.newSenderWithRebind(t, harness.transactor, 100, 3000, "disabled") + if result := harness.pass(ctx, t, live); result.Outcome != inbound.MailPassAccepted || result.DeliveryID != deliveryID { + t.Fatalf("pass with a transport = %+v, want accepted", result) + } + rebound := harness.delivery(ctx, t, deliveryID) + if rebound.ProviderAccount() != harness.account || rebound.Status() != domain.DeliveryStatusAccepted { + t.Fatalf("delivery is %s on %s, want accepted on the configured account", rebound.Status(), rebound.ProviderAccount().Provider()) + } + }) + + t.Run("the schema keeps cancellation, leases, and the token binding consistent", func(t *testing.T) { + reset(t) + user := harness.createUser(ctx, t, false) + _, token, deliveryID := harness.enqueueVerification(ctx, t, user, time.Hour) + other := harness.createUser(ctx, t, false) + _, otherToken, _ := harness.enqueueVerification(ctx, t, other, time.Hour) + + checks := []struct { + name string + statement string + args []any + constraint string + trigger bool + }{ + { + name: "a cancelled delivery has a reason", + statement: "UPDATE deliveries SET status = 'cancelled', next_attempt_at = NULL WHERE id = $1", + args: []any{deliveryID}, + constraint: "deliveries_cancel_reason_matches_status", + }, + { + name: "a reason belongs only to a cancelled delivery", + statement: "UPDATE deliveries SET cancel_reason = 'token_revoked' WHERE id = $1", + args: []any{deliveryID}, + constraint: "deliveries_cancel_reason_matches_status", + }, + { + name: "a lease has an owner and a deadline together", + statement: "UPDATE deliveries SET claim_owner = $2 WHERE id = $1", + args: []any{deliveryID, uuid.New()}, + constraint: "deliveries_claim_complete", + }, + { + name: "a terminal delivery holds no lease", + statement: "UPDATE deliveries SET status = 'rejected', next_attempt_at = NULL, claim_owner = $2, claimed_until = now() WHERE id = $1", + args: []any{deliveryID, uuid.New()}, + constraint: "deliveries_claim_complete", + }, + { + name: "the kind of a stored delivery never changes", + statement: "UPDATE deliveries SET kind = 'notification', template_version = 'notification.v1' WHERE id = $1", + args: []any{deliveryID}, + constraint: "deliveries_content_immutable", + trigger: true, + }, + { + name: "a notification carries no token", + statement: `INSERT INTO deliveries ( + 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, version, created_at, updated_at, email_token_id + ) + SELECT gen_random_uuid(), recipient_user_id, recipient_email, 'notification', 'notification.v1', subject, + text_body, html_body, content_sha256, provider, provider_account, + 'delivery/' || gen_random_uuid()::text, status, attempt_count, next_attempt_at, version, + created_at, updated_at, email_token_id + FROM deliveries WHERE id = $1`, + args: []any{deliveryID}, + constraint: "deliveries_token_only_for_token_kinds", + }, + { + name: "the token binding never changes", + statement: "UPDATE deliveries SET email_token_id = $2 WHERE id = $1", + args: []any{deliveryID, otherToken.ID}, + constraint: "deliveries_content_immutable", + trigger: true, + }, + } + for _, check := range checks { + _, err := pool.Exec(ctx, check.statement, check.args...) + if check.trigger { + assertSQLRefusal(t, err, check.constraint) + continue + } + var pgError interface{ SQLState() string } + if !errors.As(err, &pgError) || pgError.SQLState() != checkViolationCode { + t.Fatalf("%s: error = %v, want a check violation", check.name, err) + } + if !strings.Contains(err.Error(), check.constraint) { + t.Fatalf("%s: error = %v, want constraint %s", check.name, err, check.constraint) + } + } + // A token that a delivery references cannot disappear on its own. + if _, err := pool.Exec(ctx, "DELETE FROM email_tokens WHERE id = $1", token.ID); err == nil { + t.Fatal("a token that a delivery is bound to was deleted") + } + // Deleting the account removes both. + harness.exec(ctx, t, "DELETE FROM users WHERE id = $1", user.ID) + assertRowCount(ctx, t, pool, pgx.Identifier{"email_tokens"}, 1) + assertRowCount(ctx, t, pool, pgx.Identifier{"deliveries"}, 1) + }) +} + +func (harness *senderHarness) createUser(ctx context.Context, t *testing.T, verified bool) domain.User { + t.Helper() + harness.users++ + hash, err := domain.NewPasswordHash(identityTestPasswordHash) + if err != nil { + t.Fatalf("NewPasswordHash() error = %v", err) + } + user, err := domain.NewUser(domain.Registration{ + Email: mustEmail(t, fmt.Sprintf("Synthetic.User%d@Example.com", harness.users)), + PasswordHash: hash, + Scenario: domain.ScenarioCandidate, + RegisteredAt: harness.clock.Now(), + }) + if err != nil { + t.Fatalf("NewUser() error = %v", err) + } + if err := harness.identity.Users().Create(ctx, user); err != nil { + t.Fatalf("create the account: %v", err) + } + if !verified { + return user + } + confirmed, err := harness.identity.Users().MarkEmailVerified(ctx, user.ID, user.RegistrationVersion, harness.clock.Now()) + if err != nil { + t.Fatalf("verify the account: %v", err) + } + return confirmed +} + +// enqueueVerification issues a token and stores its mail in one transaction, +// as the registration flow will. +func (harness *senderHarness) enqueueVerification(ctx context.Context, t *testing.T, user domain.User, lifetime time.Duration) (domain.SecretToken, domain.EmailToken, uuid.UUID) { + t.Helper() + raw, err := domain.NewSecretToken() + if err != nil { + t.Fatalf("NewSecretToken() error = %v", err) + } + token, err := domain.NewEmailToken(domain.NewEmailTokenInput{ + UserID: user.ID, Purpose: domain.EmailTokenPurposeEmailVerification, TokenHash: raw.Hash(), + RegistrationVersion: user.RegistrationVersion, IssuedAt: harness.clock.Now(), Lifetime: lifetime, + }) + if err != nil { + t.Fatalf("NewEmailToken() error = %v", err) + } + var deliveryID uuid.UUID + err = harness.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := unit.EmailTokens().Insert(ctx, token); err != nil { + return err + } + deliveryID, err = harness.mailer.EnqueueVerification(ctx, unit, notification.TokenMailRequest{ + Recipient: user.Email, Token: token, RawToken: raw, Lifetime: domain.Hours(lifetime / time.Hour), + }) + return err + }) + if err != nil { + t.Fatalf("enqueue the verification mail: %v", err) + } + return raw, token, deliveryID +} + +func (harness *senderHarness) newSender(t *testing.T, transactor outbound.Transactor, daily, monthly int64) *notification.ServiceMailSender { + t.Helper() + return harness.newSenderWithRebind(t, transactor, daily, monthly, "") +} + +func (harness *senderHarness) newSenderWithRebind(t *testing.T, transactor outbound.Transactor, daily, monthly int64, rebindProvider string) *notification.ServiceMailSender { + t.Helper() + limits, err := domain.NewMailQuotaLimits(daily, monthly) + if err != nil { + t.Fatalf("NewMailQuotaLimits() error = %v", err) + } + logger := slog.New(slog.NewJSONHandler(harness.logs, nil)) + // The idempotency window is the one of Resend; the disabled transport + // has none, which only matters after a lost attempt. + gate := notification.NewQuotaGate(harness.account, limits, resend.IdempotencyWindow, harness.clock.Now, logger) + sender, err := notification.NewServiceMailSender(transactor, harness.transport, gate, notification.ServiceMailSenderSettings{ + Account: harness.account, + RebindProvider: rebindProvider, + Lease: mailSenderLease, + StoreTimeout: 30 * time.Second, + SettleBudget: mailSenderSettleBudget, + ShutdownSettleBudget: time.Second, + MaxFailures: 3, + Retry: notification.RetryPolicy{Initial: time.Minute, Max: 30 * time.Minute}, + }, harness.clock.Now, logger) + if err != nil { + t.Fatalf("NewServiceMailSender() error = %v", err) + } + return sender +} + +func (harness *senderHarness) pass(ctx context.Context, t *testing.T, sender *notification.ServiceMailSender) inbound.MailPassResult { + t.Helper() + result, err := sender.ProcessNext(ctx, ctx) + if err != nil { + t.Fatalf("ProcessNext() error = %v", err) + } + return result +} + +func (harness *senderHarness) delivery(ctx context.Context, t *testing.T, id uuid.UUID) domain.Delivery { + t.Helper() + delivery, err := harness.deliveries.Get(ctx, id) + if err != nil { + t.Fatalf("Get(%s) error = %v", id, err) + } + return delivery +} + +func (harness *senderHarness) attempts(ctx context.Context, t *testing.T, id uuid.UUID) []domain.DeliveryAttempt { + t.Helper() + attempts, err := harness.deliveries.ListAttempts(ctx, id) + if err != nil { + t.Fatalf("ListAttempts(%s) error = %v", id, err) + } + return attempts +} + +func (harness *senderHarness) exec(ctx context.Context, t *testing.T, statement string, args ...any) { + t.Helper() + if _, err := harness.pool.Exec(ctx, statement, args...); err != nil { + t.Fatalf("exec %q: %v", statement, err) + } +} + +func (harness *senderHarness) claimOf(ctx context.Context, t *testing.T, id uuid.UUID) (*uuid.UUID, *time.Time) { + t.Helper() + var owner *uuid.UUID + var until *time.Time + if err := harness.pool.QueryRow(ctx, "SELECT claim_owner, claimed_until FROM deliveries WHERE id = $1", id).Scan(&owner, &until); err != nil { + t.Fatalf("read the lease of %s: %v", id, err) + } + return owner, until +} + +func (harness *senderHarness) assertClaimReleased(ctx context.Context, t *testing.T, id uuid.UUID) { + t.Helper() + if owner, until := harness.claimOf(ctx, t, id); owner != nil || until != nil { + t.Fatalf("delivery %s still holds a lease", id) + } +} + +func (harness *senderHarness) assertQuotaUsage(ctx context.Context, t *testing.T, want int64) { + t.Helper() + harness.assertQuotaUsageFor(ctx, t, harness.account, want) +} + +// assertQuotaUsageFor checks the recipients counted today and this month +// under account, by the fake clock. +func (harness *senderHarness) assertQuotaUsageFor(ctx context.Context, t *testing.T, account domain.MailProviderAccount, want int64) { + t.Helper() + usage, err := postgresadapter.NewMailQuotaStore(harness.pool).MailQuotas().Usage(ctx, account, domain.MailQuotaWindowsAt(harness.clock.Now())) + if err != nil { + t.Fatalf("Usage() error = %v", err) + } + if usage.DayUsed != want || usage.MonthUsed != want { + t.Fatalf("quota usage under %s = %d today and %d this month, want %d", account.Provider(), usage.DayUsed, usage.MonthUsed, want) + } +} + +func (harness *senderHarness) assertLogsHoldNoSecrets(t *testing.T, forbidden ...string) { + t.Helper() + logs := harness.logs.String() + for _, marker := range forbidden { + if marker != "" && strings.Contains(logs, marker) { + t.Fatalf("a secret or an address reached the logs:\n%s", logs) + } + } +} + +func scrapeMetrics(metrics *prometheus.Metrics) string { + recorder := httptest.NewRecorder() + metrics.Handler().ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/metrics", nil)) + return recorder.Body.String() +} diff --git a/backend/internal/adapter/secondary/mail/resend/fixture.go b/backend/internal/adapter/secondary/mail/resend/fixture.go new file mode 100644 index 0000000..8e95fcd --- /dev/null +++ b/backend/internal/adapter/secondary/mail/resend/fixture.go @@ -0,0 +1,29 @@ +package resend + +import ( + "errors" + "net" + "net/url" + "time" +) + +// NewLoopbackSender builds the transport against a Resend API fixture that +// runs on this machine, for tests of the delivery layer. It accepts only an +// http URL whose host is a loopback address, so the API key and the messages +// of a deployment can never be pointed at another host through it; the +// bootstrap code uses NewSender and its fixed endpoint. +func NewLoopbackSender(apiKey, from string, timeout time.Duration, endpoint string, now func() time.Time) (*Sender, error) { + target, err := url.Parse(endpoint) + if err != nil || target.Scheme != "http" || !isLoopbackHost(target.Hostname()) { + return nil, errors.New("resend.NewLoopbackSender - endpoint must be an http URL on a loopback address") + } + return newSender(apiKey, from, timeout, endpoint, now) +} + +func isLoopbackHost(host string) bool { + if host == "localhost" { + return true + } + address := net.ParseIP(host) + return address != nil && address.IsLoopback() +} diff --git a/backend/internal/adapter/secondary/mail/resend/resendfixture/fixture.go b/backend/internal/adapter/secondary/mail/resend/resendfixture/fixture.go new file mode 100644 index 0000000..0762ffc --- /dev/null +++ b/backend/internal/adapter/secondary/mail/resend/resendfixture/fixture.go @@ -0,0 +1,189 @@ +// Package resendfixture is a local stand-in for the Resend HTTP API, for +// tests of the delivery layer. It speaks the part of the API that the +// resend transport uses: POST /emails with a bearer key and an +// Idempotency-Key, answered with {"id": ...} or a Resend error object. It +// keeps what it receives so a test can check the recipient, the key, and the +// number of provider calls, and it deduplicates a repeated key the way +// Resend does, so a test can tell a second call from a second message. +// +// It is a test fixture only; production keeps the real Resend transport and +// never imports this package. +package resendfixture + +import ( + "crypto/subtle" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strconv" + "sync" + "sync/atomic" + "time" + + "github.com/google/uuid" +) + +// APIKey is the key the fixture accepts. +const APIKey = "re_fixture_key" //nolint:gosec // A key of the local fixture, not a credential. + +const maxRequestBytes = 1 << 20 + +// Request is one call that reached the fixture. +type Request struct { + IdempotencyKey string + To []string + Subject string + Text string + HTML string + // Replayed is set when the key was already used with the same body: the + // fixture answered with the original message and created no new one. + Replayed bool +} + +// Reply is a scripted answer. +type Reply struct { + Status int + // Name is the Resend error name for a non-2xx answer, for example + // "daily_quota_exceeded". + Name string +} + +// Server is the fixture. Create it with New. +type Server struct { + http *httptest.Server + + // arrivals counts calls from the moment they are received, before the + // delay, so a test can tell that a call is in flight. + arrivals atomic.Int64 + delay atomic.Int64 // nanoseconds + + mu sync.Mutex + requests []Request + messages map[string]message // by idempotency key + scripted []Reply +} + +type message struct { + id string + body string +} + +// New starts the fixture on a loopback address. +func New() *Server { + server := &Server{messages: make(map[string]message)} + server.http = httptest.NewServer(http.HandlerFunc(server.serve)) + return server +} + +// URL is the endpoint to give the loopback transport. +func (server *Server) URL() string { return server.http.URL + "/emails" } + +// Close stops the fixture. +func (server *Server) Close() { server.http.Close() } + +// Script queues answers for the next calls, in order; calls after them are +// accepted as usual. +func (server *Server) Script(replies ...Reply) { + server.mu.Lock() + defer server.mu.Unlock() + server.scripted = append(server.scripted, replies...) +} + +// SetDelay makes the fixture wait before it answers every later call, so a +// test can act while a send is in flight. +func (server *Server) SetDelay(delay time.Duration) { server.delay.Store(int64(delay)) } + +// Arrivals returns how many calls the fixture has received, answered or +// not yet. +func (server *Server) Arrivals() int { return int(server.arrivals.Load()) } + +// Requests returns every call received, in order. +func (server *Server) Requests() []Request { + server.mu.Lock() + defer server.mu.Unlock() + return append([]Request(nil), server.requests...) +} + +// Messages returns the number of distinct messages the fixture accepted: a +// replayed key does not add one. +func (server *Server) Messages() int { + server.mu.Lock() + defer server.mu.Unlock() + return len(server.messages) +} + +func (server *Server) serve(response http.ResponseWriter, request *http.Request) { + server.arrivals.Add(1) + if delay := time.Duration(server.delay.Load()); delay > 0 { + time.Sleep(delay) + } + if request.Method != http.MethodPost || request.URL.Path != "/emails" { + writeError(response, http.StatusNotFound, "not_found") + return + } + if subtle.ConstantTimeCompare([]byte(request.Header.Get("Authorization")), []byte("Bearer "+APIKey)) != 1 { + writeError(response, http.StatusUnauthorized, "invalid_api_key") + return + } + payload, err := io.ReadAll(io.LimitReader(request.Body, maxRequestBytes)) + if err != nil { + writeError(response, http.StatusBadRequest, "invalid_parameter") + return + } + var body struct { + To []string `json:"to"` + Subject string `json:"subject"` + Text string `json:"text"` + HTML string `json:"html"` + } + if err := json.Unmarshal(payload, &body); err != nil { + writeError(response, http.StatusBadRequest, "invalid_parameter") + return + } + key := request.Header.Get("Idempotency-Key") + record := Request{IdempotencyKey: key, To: body.To, Subject: body.Subject, Text: body.Text, HTML: body.HTML} + + server.mu.Lock() + defer server.mu.Unlock() + if len(server.scripted) > 0 { + reply := server.scripted[0] + server.scripted = server.scripted[1:] + server.requests = append(server.requests, record) + writeError(response, reply.Status, reply.Name) + return + } + known, seen := server.messages[key] + switch { + case seen && known.body != string(payload): + // The key was used with another body: Resend refuses it. + server.requests = append(server.requests, record) + writeError(response, http.StatusConflict, "invalid_idempotent_request") + return + case seen: + record.Replayed = true + server.requests = append(server.requests, record) + writeAccepted(response, known.id) + return + } + accepted := message{id: uuid.NewString(), body: string(payload)} + if key != "" { + server.messages[key] = accepted + } else { + server.messages[accepted.id] = accepted + } + server.requests = append(server.requests, record) + writeAccepted(response, accepted.id) +} + +func writeAccepted(response http.ResponseWriter, id string) { + response.Header().Set("Content-Type", "application/json") + response.WriteHeader(http.StatusOK) + _ = json.NewEncoder(response).Encode(map[string]string{"id": id}) +} + +func writeError(response http.ResponseWriter, status int, name string) { + response.Header().Set("Content-Type", "application/json") + response.WriteHeader(status) + _ = json.NewEncoder(response).Encode(map[string]any{"statusCode": status, "name": name, "message": "fixture " + strconv.Itoa(status)}) +} diff --git a/backend/internal/adapter/secondary/mail/resend/resendfixture/fixture_test.go b/backend/internal/adapter/secondary/mail/resend/resendfixture/fixture_test.go new file mode 100644 index 0000000..dd9f195 --- /dev/null +++ b/backend/internal/adapter/secondary/mail/resend/resendfixture/fixture_test.go @@ -0,0 +1,67 @@ +package resendfixture_test + +import ( + "testing" + "time" + + "lincodex/backend/internal/adapter/secondary/mail/resend" + "lincodex/backend/internal/adapter/secondary/mail/resend/resendfixture" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +func newMail(t *testing.T, subject, key string) outbound.OutgoingMail { + t.Helper() + to, err := domain.NewEmailAddress("fixture.user@example.com") + if err != nil { + t.Fatalf("NewEmailAddress() error = %v", err) + } + return outbound.OutgoingMail{To: to, Subject: subject, TextBody: "text\n", IdempotencyKey: key} +} + +func TestFixtureAnswersLikeResendForTheLoopbackTransport(t *testing.T) { + fixture := resendfixture.New() + defer fixture.Close() + sender, err := resend.NewLoopbackSender(resendfixture.APIKey, "Lincodex ", 5*time.Second, fixture.URL(), time.Now) + if err != nil { + t.Fatalf("NewLoopbackSender() error = %v", err) + } + + first, err := sender.Send(t.Context(), newMail(t, "Subject", "delivery/1")) + if err != nil || first.Outcome != outbound.MailOutcomeAccepted || first.ProviderMessageID == "" { + t.Fatalf("first Send() = %+v, %v; want accepted with a message ID", first, err) + } + // The same key and body gets the original answer and creates no message. + again, err := sender.Send(t.Context(), newMail(t, "Subject", "delivery/1")) + if err != nil || again.ProviderMessageID != first.ProviderMessageID { + t.Fatalf("repeated Send() = %+v, %v; want the original message ID %q", again, err, first.ProviderMessageID) + } + if fixture.Messages() != 1 || len(fixture.Requests()) != 2 || !fixture.Requests()[1].Replayed { + t.Fatalf("messages = %d, requests = %+v; want one message and a replayed second call", fixture.Messages(), fixture.Requests()) + } + // The same key with another body is the documented conflict. + conflict, err := sender.Send(t.Context(), newMail(t, "Other subject", "delivery/1")) + if err != nil || conflict.Outcome != outbound.MailOutcomeUnknown || conflict.ProviderCode != "invalid_idempotent_request" { + t.Fatalf("conflicting Send() = %+v, %v; want unknown invalid_idempotent_request", conflict, err) + } + + fixture.Script(resendfixture.Reply{Status: 429, Name: "daily_quota_exceeded"}) + quota, err := sender.Send(t.Context(), newMail(t, "Subject", "delivery/2")) + if err != nil || quota.Outcome != outbound.MailOutcomeRejected || quota.Rejection != outbound.MailRejectionQuotaExhausted { + t.Fatalf("scripted Send() = %+v, %v; want a quota refusal", quota, err) + } +} + +func TestLoopbackSenderRefusesAnyOtherHost(t *testing.T) { + for _, endpoint := range []string{ + "https://api.resend.com/emails", + "http://api.resend.com/emails", + "http://192.0.2.10:8080/emails", + "https://127.0.0.1:8080/emails", + "not a url", + } { + if _, err := resend.NewLoopbackSender(resendfixture.APIKey, "no-reply@example.com", time.Second, endpoint, time.Now); err == nil { + t.Fatalf("NewLoopbackSender(%q) accepted a non-loopback endpoint", endpoint) + } + } +} diff --git a/backend/internal/adapter/secondary/postgres/delivery.go b/backend/internal/adapter/secondary/postgres/delivery.go index 582f9a8..d53ea95 100644 --- a/backend/internal/adapter/secondary/postgres/delivery.go +++ b/backend/internal/adapter/secondary/postgres/delivery.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "strings" "time" "github.com/google/uuid" @@ -22,6 +23,7 @@ import ( // constraint name, never by text. var deliveryConstraintErrors = map[constraintViolation]error{ {foreignKeyViolationCode, "deliveries_recipient_user_id_fkey"}: outbound.ErrUserNotFound, + {foreignKeyViolationCode, "deliveries_email_token_id_fkey"}: outbound.ErrEmailTokenNotFound, {foreignKeyViolationCode, "delivery_attempts_delivery_id_fkey"}: outbound.ErrDeliveryNotFound, {integrityConstraintViolationCode, "deliveries_content_immutable"}: outbound.ErrDeliveryContentImmutable, {integrityConstraintViolationCode, "delivery_attempts_immutable"}: outbound.ErrDeliveryContentImmutable, @@ -45,7 +47,21 @@ func mapDeliveryError(err error) error { 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}) + return markRowFault(markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName})) +} + +// markRowFault makes an error that the row itself causes (SQLSTATE class 22, +// data exception, or 23, integrity constraint violation) also match +// outbound.ErrRowFault. Anything else stays transient to the caller. +func markRowFault(err error) error { + var stateError sqlStateError + if !errors.As(err, &stateError) { + return err + } + if code := stateError.SQLState(); strings.HasPrefix(code, "22") || strings.HasPrefix(code, "23") { + return fmt.Errorf("postgres.markRowFault - SQLSTATE %s: %w: %w", code, outbound.ErrRowFault, err) + } + return err } // DeliveryStore provides the delivery repository outside a transaction. Every @@ -106,6 +122,7 @@ func (repository deliveryRepository) Create(ctx context.Context, delivery domain NextAttemptAt: pgZeroableTime(delivery.NextAttemptAt()), LastAttemptAt: pgZeroableTime(delivery.LastAttemptAt()), ProviderMessageID: pgOptionalText(delivery.ProviderMessageID()), + EmailTokenID: pgOptionalUUID(delivery.EmailTokenID()), Version: delivery.Version(), CreatedAt: pgTime(delivery.CreatedAt()), UpdatedAt: pgTime(delivery.UpdatedAt()), @@ -185,7 +202,19 @@ func (repository deliveryRepository) LatestForRecipient(ctx context.Context, rec } func (repository deliveryRepository) RecordAttempt(ctx context.Context, next domain.Delivery, attempt domain.DeliveryAttempt) error { - const location = "deliveryRepository.RecordAttempt" + return repository.recordAttempt(ctx, "deliveryRepository.RecordAttempt", uuid.Nil, next, attempt) +} + +func (repository deliveryRepository) RecordClaimedAttempt(ctx context.Context, owner uuid.UUID, next domain.Delivery, attempt domain.DeliveryAttempt) error { + if owner == uuid.Nil { + return fmt.Errorf("deliveryRepository.RecordClaimedAttempt - lease owner must be set: %w", domain.ErrInvalidDelivery) + } + return repository.recordAttempt(ctx, "deliveryRepository.RecordClaimedAttempt", owner, next, attempt) +} + +// recordAttempt stores an attempt over the version before it; a non-nil owner +// also has to hold the lease. +func (repository deliveryRepository) recordAttempt(ctx context.Context, location string, owner uuid.UUID, next domain.Delivery, attempt domain.DeliveryAttempt) error { 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) } @@ -202,6 +231,7 @@ func (repository deliveryRepository) RecordAttempt(ctx context.Context, next dom UpdatedAt: pgTime(next.UpdatedAt()), DeliveryID: pgUUID(next.ID()), ExpectedVersion: next.Version() - 1, + LeaseOwner: pgOptionalUUID(owner), }) if err != nil { return fmt.Errorf("%s - update delivery and insert attempt: %w", location, mapDeliveryError(err)) @@ -216,27 +246,38 @@ func (repository deliveryRepository) WaitForQuota(ctx context.Context, next doma 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) + return repository.updateState(ctx, "deliveryRepository.WaitForQuota", next, true) } 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) + // The sending worker rebinds a delivery it holds and then sends it, so + // its lease stays. + return repository.updateState(ctx, "deliveryRepository.Rebind", next, false) +} + +func (repository deliveryRepository) Cancel(ctx context.Context, next domain.Delivery) error { + if next.Status() != domain.DeliveryStatusCancelled { + return fmt.Errorf("deliveryRepository.Cancel - state was not built by domain.Delivery.Cancel: %w", domain.ErrInvalidDelivery) + } + return repository.updateState(ctx, "deliveryRepository.Cancel", next, true) } // 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 { +// before it. releaseClaim ends the sending worker's lease with the change. +func (repository deliveryRepository) updateState(ctx context.Context, location string, next domain.Delivery, releaseClaim bool) 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()), + CancelReason: pgOptionalText(string(next.CancelReason())), Provider: next.ProviderAccount().Provider(), ProviderAccount: next.ProviderAccount().Account(), + ReleaseClaim: releaseClaim, UpdatedAt: pgTime(next.UpdatedAt()), ID: pgUUID(next.ID()), ExpectedVersion: next.Version() - 1, @@ -250,12 +291,170 @@ func (repository deliveryRepository) updateState(ctx context.Context, location s return nil } +func (repository deliveryRepository) ClaimDue(ctx context.Context, claim outbound.DeliveryClaim) (outbound.ClaimedDelivery, error) { + const location = "deliveryRepository.ClaimDue" + if claim.Owner == uuid.Nil || claim.Account.IsZero() || len(claim.Kinds) == 0 || claim.Now.IsZero() || claim.Lease <= 0 { + return outbound.ClaimedDelivery{}, fmt.Errorf("%s - owner, account, kinds, time, and lease must be set: %w", location, domain.ErrInvalidDelivery) + } + kinds := make([]string, 0, len(claim.Kinds)) + for _, kind := range claim.Kinds { + if _, err := domain.ParseMailKind(string(kind)); err != nil { + return outbound.ClaimedDelivery{}, fmt.Errorf("%s - kind: %w", location, err) + } + kinds = append(kinds, string(kind)) + } + row, err := repository.queries.ClaimDueDelivery(ctx, sqlc.ClaimDueDeliveryParams{ + LeaseOwner: pgUUID(claim.Owner), + LeaseSeconds: claim.Lease.Seconds(), + Kinds: kinds, + Now: pgTime(claim.Now), + Provider: claim.Account.Provider(), + ProviderAccount: claim.Account.Account(), + RebindProvider: claim.RebindProvider, + }) + if errors.Is(err, pgx.ErrNoRows) { + return outbound.ClaimedDelivery{}, outbound.ErrNoDeliveryDue + } + if err != nil { + return outbound.ClaimedDelivery{}, fmt.Errorf("%s - claim due delivery: %w", location, mapDeliveryError(err)) + } + delivery, err := deliveryFromRow(sqlc.Delivery{ + ID: row.ID, + SourceEventID: row.SourceEventID, + RecipientUserID: row.RecipientUserID, + RecipientEmail: row.RecipientEmail, + Kind: row.Kind, + TemplateVersion: row.TemplateVersion, + Subject: row.Subject, + TextBody: row.TextBody, + HtmlBody: row.HtmlBody, + ContentSha256: row.ContentSha256, + Provider: row.Provider, + ProviderAccount: row.ProviderAccount, + IdempotencyKey: row.IdempotencyKey, + Status: row.Status, + AttemptCount: row.AttemptCount, + NextAttemptAt: row.NextAttemptAt, + LastAttemptAt: row.LastAttemptAt, + ProviderMessageID: row.ProviderMessageID, + EmailTokenID: row.EmailTokenID, + CancelReason: row.CancelReason, + BodyRedactedAt: row.BodyRedactedAt, + Version: row.Version, + CreatedAt: row.CreatedAt, + UpdatedAt: row.UpdatedAt, + }) + if err != nil { + unreadable := &outbound.UnreadableDeliveryError{DeliveryID: uuid.UUID(row.ID.Bytes), FailureCount: row.FailureCount, Err: err} + // Only a content hash mismatch is permanent: the row was changed + // outside the application. It is cancelled here, in the caller's + // transaction, so it does not stay at the head of the queue. Any + // other cause may be transient, so the row is left alone and the + // caller records a failure of the row. + if errors.Is(err, domain.ErrMailContentIntegrity) { + if _, cancelErr := repository.queries.CancelUnreadableDelivery(ctx, sqlc.CancelUnreadableDeliveryParams{ + Now: pgTime(claim.Now), + ID: row.ID, + }); cancelErr != nil { + return outbound.ClaimedDelivery{}, fmt.Errorf("%s - cancel unreadable delivery: %w", location, mapDeliveryError(cancelErr)) + } + unreadable.Cancelled = true + } + return outbound.ClaimedDelivery{}, fmt.Errorf("%s - decode claimed delivery: %w", location, unreadable) + } + claimed := outbound.ClaimedDelivery{ + Delivery: delivery, + PreviousClaimedUntil: zeroableTime(row.PreviousClaimedUntil), + FailureCount: row.FailureCount, + } + if row.SinceFirstSendSeconds >= 0 { + claimed.FirstSendStarted = true + claimed.SinceFirstSend = time.Duration(row.SinceFirstSendSeconds * float64(time.Second)) + } + return claimed, nil +} + +func (repository deliveryRepository) LockClaimed(ctx context.Context, id, owner uuid.UUID) (bool, error) { + _, err := repository.queries.LockClaimedDelivery(ctx, sqlc.LockClaimedDeliveryParams{ID: pgUUID(id), LeaseOwner: pgUUID(owner)}) + if errors.Is(err, pgx.ErrNoRows) { + return false, nil + } + if err != nil { + return false, fmt.Errorf("deliveryRepository.LockClaimed - lock delivery: %w", mapDeliveryError(err)) + } + return true, nil +} + +func (repository deliveryRepository) MarkSendStarted(ctx context.Context, id, owner uuid.UUID) error { + if _, err := repository.queries.MarkDeliverySendStarted(ctx, sqlc.MarkDeliverySendStartedParams{ID: pgUUID(id), LeaseOwner: pgUUID(owner)}); err != nil { + return fmt.Errorf("deliveryRepository.MarkSendStarted - mark send started: %w", mapDeliveryError(err)) + } + return nil +} + +func (repository deliveryRepository) RecordFailure(ctx context.Context, id, owner uuid.UUID, at, nextAttemptAt time.Time, maxFailures int32, countFailure bool) (bool, error) { + status, err := repository.queries.RecordDeliveryFailure(ctx, sqlc.RecordDeliveryFailureParams{ + CountFailure: countFailure, + LeaseOwner: pgUUID(owner), + MaxFailures: maxFailures, + NextAttemptAt: pgTime(nextAttemptAt), + Now: pgTime(at), + ID: pgUUID(id), + }) + if errors.Is(err, pgx.ErrNoRows) { + return false, nil + } + if err != nil { + return false, fmt.Errorf("deliveryRepository.RecordFailure - record failure: %w", mapDeliveryError(err)) + } + return status == string(domain.DeliveryStatusCancelled), nil +} + +func (repository deliveryRepository) ReleaseClaim(ctx context.Context, id, owner uuid.UUID) (bool, error) { + released, err := repository.queries.ReleaseDeliveryClaim(ctx, sqlc.ReleaseDeliveryClaimParams{ + ID: pgUUID(id), + LeaseOwner: pgUUID(owner), + }) + if err != nil { + return false, fmt.Errorf("deliveryRepository.ReleaseClaim - release lease: %w", mapDeliveryError(err)) + } + return released == 1, nil +} + +func (repository deliveryRepository) ServiceMailState(ctx context.Context, id uuid.UUID) (domain.ServiceMailState, error) { + const location = "deliveryRepository.ServiceMailState" + row, err := repository.queries.GetServiceMailState(ctx, pgUUID(id)) + if errors.Is(err, pgx.ErrNoRows) { + return domain.ServiceMailState{}, fmt.Errorf("%s - select state: %w", location, outbound.ErrDeliveryNotFound) + } + if err != nil { + return domain.ServiceMailState{}, fmt.Errorf("%s - select state: %w", location, mapDeliveryError(err)) + } + return domain.ServiceMailState{ + TokenFound: row.TokenFound, + TokenPurpose: domain.EmailTokenPurpose(row.TokenPurpose.String), + TokenUserID: optionalUUID(row.TokenUserID), + TokenRegistrationVersion: row.TokenRegistrationVersion.Int64, + TokenConsumedAt: zeroableTime(row.TokenConsumedAt), + TokenInvalidatedAt: zeroableTime(row.TokenInvalidatedAt), + TokenExpiresAt: zeroableTime(row.TokenExpiresAt), + AccountRegistrationVersion: row.AccountRegistrationVersion, + AccountEmailVerified: row.AccountEmailVerified, + AccountEmailKey: row.AccountEmailKey, + }, 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) + var content domain.MailContent + if row.BodyRedactedAt.Valid { + content, err = domain.RestoreRedactedMailContent(kind, row.TemplateVersion, row.Subject, row.ContentSha256) + } else { + 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) } @@ -276,6 +475,8 @@ func deliveryFromRow(row sqlc.Delivery) (domain.Delivery, error) { NextAttemptAt: zeroableTime(row.NextAttemptAt), LastAttemptAt: zeroableTime(row.LastAttemptAt), ProviderMessageID: row.ProviderMessageID.String, + EmailTokenID: optionalUUID(row.EmailTokenID), + CancelReason: domain.DeliveryCancelReason(row.CancelReason.String), Version: row.Version, CreatedAt: row.CreatedAt.Time, UpdatedAt: row.UpdatedAt.Time, diff --git a/backend/internal/adapter/secondary/postgres/delivery_statistics.go b/backend/internal/adapter/secondary/postgres/delivery_statistics.go index da64e64..37e8649 100644 --- a/backend/internal/adapter/secondary/postgres/delivery_statistics.go +++ b/backend/internal/adapter/secondary/postgres/delivery_statistics.go @@ -36,6 +36,11 @@ func (store *DeliveryStatisticsStore) DeliveryStatistics(ctx context.Context) (o } statistics.Counts = append(statistics.Counts, count) earliest := row.EarliestPendingAttemptAt + // Only service mail is picked up by a worker; a due notification + // waits for TASK-462 and must not count as overdue. + if !count.Kind.IsServiceMail() { + continue + } if earliest.Valid && (statistics.EarliestPendingAttemptAt.IsZero() || earliest.Time.Before(statistics.EarliestPendingAttemptAt)) { statistics.EarliestPendingAttemptAt = earliest.Time } diff --git a/backend/internal/adapter/secondary/postgres/delivery_test.go b/backend/internal/adapter/secondary/postgres/delivery_test.go index 5389d3f..635cafb 100644 --- a/backend/internal/adapter/secondary/postgres/delivery_test.go +++ b/backend/internal/adapter/secondary/postgres/delivery_test.go @@ -61,3 +61,26 @@ func TestMapDeliveryErrorDropsTheTextOfOtherPostgreSQLErrors(t *testing.T) { t.Fatalf("mapped error lost the constraint name: %v", err) } } + +func TestMapDeliveryErrorMarksOnlyDataFaultsAsRowFaults(t *testing.T) { + for code, wantRowFault := range map[string]bool{ + "22001": true, // string data right truncation + "23514": true, // check violation + "23505": true, // unique violation without a known constraint + "40P01": false, // deadlock + "40001": false, // serialization failure + "08006": false, // connection failure + "53300": false, // too many connections + "57014": false, // statement timeout (query canceled) + "57P01": false, // admin shutdown + "XX000": false, // internal error + } { + err := mapDeliveryError(&pgconn.PgError{Code: code, ConstraintName: "some_constraint", Message: privateRowValue}) + if got := errors.Is(err, outbound.ErrRowFault); got != wantRowFault { + t.Fatalf("SQLSTATE %s: ErrRowFault = %t, want %t", code, got, wantRowFault) + } + if strings.Contains(err.Error(), privateRowValue) { + t.Fatalf("SQLSTATE %s: the error quotes the row", code) + } + } +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/delivery.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/delivery.sql.go index 6f3640c..179edd2 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/delivery.sql.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/delivery.sql.go @@ -11,6 +11,225 @@ import ( "github.com/jackc/pgx/v5/pgtype" ) +const cancelUnreadableDelivery = `-- name: CancelUnreadableDelivery :execrows +UPDATE deliveries +SET + status = 'cancelled', + cancel_reason = 'content_invalid', + next_attempt_at = NULL, + claim_owner = NULL, + claimed_until = NULL, + text_body = CASE + WHEN deliveries.kind IN ('verification', 'password_reset') THEN '' ELSE deliveries.text_body + END, + html_body = CASE + WHEN deliveries.kind IN ('verification', 'password_reset') THEN '' ELSE deliveries.html_body + END, + body_redacted_at = CASE + WHEN + deliveries.kind IN ('verification', 'password_reset') + THEN greatest(deliveries.updated_at, $1::timestamptz) + ELSE deliveries.body_redacted_at + END, + version = deliveries.version + 1, + updated_at = greatest(deliveries.updated_at, $1::timestamptz) +WHERE + id = $2 + AND status IN ('pending', 'waiting_quota') +` + +type CancelUnreadableDeliveryParams struct { + Now pgtype.Timestamptz + ID pgtype.UUID +} + +// Ends a claimed delivery whose stored content no longer matches its hash, so +// one broken row never blocks the delivery queue. It matches only a delivery +// that the worker could still send, ends the lease, advances the version, and +// redacts the bodies of a token mail like any other cancellation. now is the +// application clock. +func (q *Queries) CancelUnreadableDelivery(ctx context.Context, arg CancelUnreadableDeliveryParams) (int64, error) { + result, err := q.db.Exec(ctx, cancelUnreadableDelivery, arg.Now, arg.ID) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const claimDueDelivery = `-- name: ClaimDueDelivery :one +WITH candidate AS ( + SELECT + due.id, + due.claimed_until AS previous_claimed_until, + coalesce( + extract(EPOCH FROM clock_timestamp() - due.first_send_started_at), + -1 + )::float8 AS since_first_send_seconds + FROM deliveries AS due + WHERE + due.kind IN ('verification', 'password_reset') + AND due.kind = any($3::text []) + AND due.status IN ('pending', 'waiting_quota') + AND due.next_attempt_at IS NOT NULL + AND due.next_attempt_at <= $4::timestamptz + AND ( + ( + due.provider = $5 + AND due.provider_account = $6 + ) + OR ( + due.provider = $7::text + AND due.attempt_count = 0 + ) + ) + AND ( + due.claim_owner IS NULL + OR due.claimed_until <= clock_timestamp() + ) + ORDER BY due.next_attempt_at, due.id + LIMIT 1 + FOR UPDATE SKIP LOCKED +) + +UPDATE deliveries AS claimed +SET + claim_owner = $1::uuid, + claimed_until = clock_timestamp() + + make_interval(secs => $2::float8) +FROM candidate +WHERE claimed.id = candidate.id +RETURNING + claimed.id, + claimed.source_event_id, + claimed.recipient_user_id, + claimed.recipient_email, + claimed.kind, + claimed.template_version, + claimed.subject, + claimed.text_body, + claimed.html_body, + claimed.content_sha256, + claimed.provider, + claimed.provider_account, + claimed.idempotency_key, + claimed.status, + claimed.attempt_count, + claimed.next_attempt_at, + claimed.last_attempt_at, + claimed.provider_message_id, + claimed.email_token_id, + claimed.cancel_reason, + claimed.body_redacted_at, + claimed.failure_count, + claimed.version, + claimed.created_at, + claimed.updated_at, + candidate.previous_claimed_until, + candidate.since_first_send_seconds +` + +type ClaimDueDeliveryParams struct { + LeaseOwner pgtype.UUID + LeaseSeconds float64 + Kinds []string + Now pgtype.Timestamptz + Provider string + ProviderAccount string + RebindProvider string +} + +type ClaimDueDeliveryRow 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 + EmailTokenID pgtype.UUID + CancelReason pgtype.Text + BodyRedactedAt pgtype.Timestamptz + FailureCount int32 + Version int64 + CreatedAt pgtype.Timestamptz + UpdatedAt pgtype.Timestamptz + PreviousClaimedUntil pgtype.Timestamptz + SinceFirstSendSeconds float64 +} + +// Claims the most overdue delivery that the sending worker may send, in one +// statement: a pending or waiting_quota delivery of the service mail kinds +// (the literals match the predicate of deliveries_due_idx, so an idle poll +// reads only that small index) whose next_attempt_at has passed, pinned to the +// configured provider account (or to rebind_provider before its first +// attempt, which the worker moves to the configured account), and held by no +// live lease. A row that another worker locks is skipped without waiting, so +// several processes never take the same delivery, and a delivery whose lease +// expired, because its worker stopped, is claimed again. +// The lease is measured by the database clock, never by the clock of an +// application instance: it lasts lease_seconds from clock_timestamp(), and a +// lease is live while claimed_until is later than clock_timestamp(). Due times +// stay on the application clock that wrote them. Neither the version nor +// updated_at changes: a claim is not a change of the delivery. +// previous_claimed_until is the deadline of an abandoned lease, NULL for a +// delivery nobody held; since_first_send_seconds is how long ago, by the +// database clock, its first request started, -1 when none did. now is the +// application clock. Deliveries that are unknown or wait for an unknown quota +// reset have no due time here and wait for an operator. +func (q *Queries) ClaimDueDelivery(ctx context.Context, arg ClaimDueDeliveryParams) (ClaimDueDeliveryRow, error) { + row := q.db.QueryRow(ctx, claimDueDelivery, + arg.LeaseOwner, + arg.LeaseSeconds, + arg.Kinds, + arg.Now, + arg.Provider, + arg.ProviderAccount, + arg.RebindProvider, + ) + var i ClaimDueDeliveryRow + 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.EmailTokenID, + &i.CancelReason, + &i.BodyRedactedAt, + &i.FailureCount, + &i.Version, + &i.CreatedAt, + &i.UpdatedAt, + &i.PreviousClaimedUntil, + &i.SinceFirstSendSeconds, + ) + return i, err +} + const deleteMailRequest = `-- name: DeleteMailRequest :execrows DELETE FROM mail_requests WHERE id = $1 @@ -46,7 +265,14 @@ SELECT provider_message_id, version, created_at, - updated_at + updated_at, + email_token_id, + cancel_reason, + claim_owner, + claimed_until, + first_send_started_at, + failure_count, + body_redacted_at FROM deliveries WHERE id = $1 ` @@ -76,6 +302,13 @@ func (q *Queries) GetDeliveryByID(ctx context.Context, id pgtype.UUID) (Delivery &i.Version, &i.CreatedAt, &i.UpdatedAt, + &i.EmailTokenID, + &i.CancelReason, + &i.ClaimOwner, + &i.ClaimedUntil, + &i.FirstSendStartedAt, + &i.FailureCount, + &i.BodyRedactedAt, ) return i, err } @@ -176,6 +409,60 @@ func (q *Queries) GetLatestDeliveryStatus(ctx context.Context, arg GetLatestDeli return i, err } +const getServiceMailState = `-- name: GetServiceMailState :one +SELECT + (token.id IS NOT NULL)::boolean AS token_found, + token.purpose AS token_purpose, + token.user_id AS token_user_id, + token.registration_version AS token_registration_version, + token.consumed_at AS token_consumed_at, + token.invalidated_at AS token_invalidated_at, + token.expires_at AS token_expires_at, + owner.registration_version AS account_registration_version, + (owner.email_verified_at IS NOT NULL)::boolean AS account_email_verified, + owner.email_normalized AS account_email_key +FROM deliveries AS delivery +INNER JOIN users AS owner ON delivery.recipient_user_id = owner.id +LEFT JOIN email_tokens AS token ON delivery.email_token_id = token.id +WHERE delivery.id = $1 +` + +type GetServiceMailStateRow struct { + TokenFound bool + TokenPurpose pgtype.Text + TokenUserID pgtype.UUID + TokenRegistrationVersion pgtype.Int8 + TokenConsumedAt pgtype.Timestamptz + TokenInvalidatedAt pgtype.Timestamptz + TokenExpiresAt pgtype.Timestamptz + AccountRegistrationVersion int64 + AccountEmailVerified bool + AccountEmailKey string +} + +// Reads the token a delivery is bound to and the account it is addressed to +// in one statement, for the check right before a service mail is sent. It +// takes no lock. It reads the account address only as the comparison key and +// selects no token hash. A missing binding or token row gives NULL token +// columns. +func (q *Queries) GetServiceMailState(ctx context.Context, id pgtype.UUID) (GetServiceMailStateRow, error) { + row := q.db.QueryRow(ctx, getServiceMailState, id) + var i GetServiceMailStateRow + err := row.Scan( + &i.TokenFound, + &i.TokenPurpose, + &i.TokenUserID, + &i.TokenRegistrationVersion, + &i.TokenConsumedAt, + &i.TokenInvalidatedAt, + &i.TokenExpiresAt, + &i.AccountRegistrationVersion, + &i.AccountEmailVerified, + &i.AccountEmailKey, + ) + return i, err +} + const insertDelivery = `-- name: InsertDelivery :execrows INSERT INTO deliveries ( id, @@ -196,6 +483,7 @@ INSERT INTO deliveries ( next_attempt_at, last_attempt_at, provider_message_id, + email_token_id, version, created_at, updated_at @@ -220,7 +508,8 @@ INSERT INTO deliveries ( $18, $19, $20, - $21 + $21, + $22 ) ON CONFLICT (id) DO NOTHING ` @@ -244,6 +533,7 @@ type InsertDeliveryParams struct { NextAttemptAt pgtype.Timestamptz LastAttemptAt pgtype.Timestamptz ProviderMessageID pgtype.Text + EmailTokenID pgtype.UUID Version int64 CreatedAt pgtype.Timestamptz UpdatedAt pgtype.Timestamptz @@ -274,6 +564,7 @@ func (q *Queries) InsertDelivery(ctx context.Context, arg InsertDeliveryParams) arg.NextAttemptAt, arg.LastAttemptAt, arg.ProviderMessageID, + arg.EmailTokenID, arg.Version, arg.CreatedAt, arg.UpdatedAt, @@ -375,6 +666,31 @@ func (q *Queries) ListDeliveryAttempts(ctx context.Context, deliveryID pgtype.UU return items, nil } +const lockClaimedDelivery = `-- name: LockClaimedDelivery :one +SELECT id +FROM deliveries +WHERE + id = $1 + AND claim_owner = $2 +FOR UPDATE +` + +type LockClaimedDeliveryParams struct { + ID pgtype.UUID + LeaseOwner pgtype.UUID +} + +// Locks the delivery row of the lease holder until the transaction ends, so +// every path that settles a send takes the delivery lock before the quota +// rows, the same order as the claim. No row means that owner no longer holds +// the lease. +func (q *Queries) LockClaimedDelivery(ctx context.Context, arg LockClaimedDeliveryParams) (pgtype.UUID, error) { + row := q.db.QueryRow(ctx, lockClaimedDelivery, arg.ID, arg.LeaseOwner) + var id pgtype.UUID + err := row.Scan(&id) + return id, err +} + const lockMailRequest = `-- name: LockMailRequest :one SELECT id, @@ -409,6 +725,34 @@ func (q *Queries) LockMailRequest(ctx context.Context, id pgtype.UUID) (MailRequ return i, err } +const markDeliverySendStarted = `-- name: MarkDeliverySendStarted :execrows +UPDATE deliveries +SET + first_send_started_at = coalesce(deliveries.first_send_started_at, clock_timestamp()), + failure_count = 0 +WHERE + id = $1 + AND claim_owner = $2 +` + +type MarkDeliverySendStartedParams struct { + ID pgtype.UUID + LeaseOwner pgtype.UUID +} + +// Notes that the first request of a claimed delivery is about to start, by the +// database clock, and clears the count of worker failures: the claim and the +// preparation succeeded, so the failures are no longer consecutive. The provider keeps the idempotency key for a window counted +// from this moment, so a later claim can tell whether repeating the request is +// still safe. It never moves. +func (q *Queries) MarkDeliverySendStarted(ctx context.Context, arg MarkDeliverySendStartedParams) (int64, error) { + result, err := q.db.Exec(ctx, markDeliverySendStarted, arg.ID, arg.LeaseOwner) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + const recordDeliveryAttempt = `-- name: RecordDeliveryAttempt :execrows WITH advanced AS ( UPDATE deliveries @@ -420,11 +764,39 @@ WITH advanced AS ( provider_message_id = coalesce( $6, deliveries.provider_message_id ), + claim_owner = NULL, + claimed_until = NULL, + failure_count = 0, + text_body = CASE + WHEN + $8::text IN ('accepted', 'rejected') + AND deliveries.kind IN ('verification', 'password_reset') + THEN '' + ELSE deliveries.text_body + END, + html_body = CASE + WHEN + $8::text IN ('accepted', 'rejected') + AND deliveries.kind IN ('verification', 'password_reset') + THEN '' + ELSE deliveries.html_body + END, + body_redacted_at = CASE + WHEN + $8::text IN ('accepted', 'rejected') + AND deliveries.kind IN ('verification', 'password_reset') + THEN $10 + ELSE deliveries.body_redacted_at + END, version = deliveries.version + 1, updated_at = $10 WHERE deliveries.id = $11 AND deliveries.version = $12 + AND ( + $13::uuid IS NULL + OR deliveries.claim_owner = $13::uuid + ) RETURNING deliveries.id ) @@ -467,6 +839,7 @@ type RecordDeliveryAttemptParams struct { UpdatedAt pgtype.Timestamptz DeliveryID pgtype.UUID ExpectedVersion int64 + LeaseOwner pgtype.UUID } // Advances a delivery past one attempt and appends the attempt in one @@ -474,8 +847,12 @@ type RecordDeliveryAttemptParams struct { // transaction. The update applies only while the stored version still // equals expected_version; otherwise nothing is written and the statement // returns 0 rows. Two workers that record the same attempt number therefore -// cannot both succeed. Content columns are not touched; a trigger refuses -// any change to them. +// cannot both succeed. The lease of the sending worker ends with the +// attempt, and so does the count of worker failures. When lease_owner is +// given, the update applies only while that worker still holds the lease. +// A token mail that reaches a terminal status loses its bodies in the same +// statement, so the one-time token does not stay at rest; the trigger allows +// exactly this change of the content columns. func (q *Queries) RecordDeliveryAttempt(ctx context.Context, arg RecordDeliveryAttemptParams) (int64, error) { result, err := q.db.Exec(ctx, recordDeliveryAttempt, arg.AttemptNumber, @@ -490,6 +867,7 @@ func (q *Queries) RecordDeliveryAttempt(ctx context.Context, arg RecordDeliveryA arg.UpdatedAt, arg.DeliveryID, arg.ExpectedVersion, + arg.LeaseOwner, ) if err != nil { return 0, err @@ -497,40 +875,203 @@ func (q *Queries) RecordDeliveryAttempt(ctx context.Context, arg RecordDeliveryA return result.RowsAffected(), nil } +const recordDeliveryFailure = `-- name: RecordDeliveryFailure :one +UPDATE deliveries +SET + failure_count = CASE + WHEN $1::boolean THEN deliveries.failure_count + 1 ELSE deliveries.failure_count + END, + status = CASE + WHEN + $1::boolean + AND deliveries.failure_count + 1 >= $2::integer + THEN 'cancelled' + ELSE deliveries.status + END, + cancel_reason = CASE + WHEN + $1::boolean + AND deliveries.failure_count + 1 >= $2::integer + THEN 'processing_failed' + ELSE deliveries.cancel_reason + END, + next_attempt_at = CASE + WHEN + $1::boolean + AND deliveries.failure_count + 1 >= $2::integer + THEN NULL + ELSE $3::timestamptz + END, + text_body = CASE + WHEN + $1::boolean + AND deliveries.failure_count + 1 >= $2::integer + AND deliveries.kind IN ('verification', 'password_reset') + THEN '' + ELSE deliveries.text_body + END, + html_body = CASE + WHEN + $1::boolean + AND deliveries.failure_count + 1 >= $2::integer + AND deliveries.kind IN ('verification', 'password_reset') + THEN '' + ELSE deliveries.html_body + END, + body_redacted_at = CASE + WHEN + $1::boolean + AND deliveries.failure_count + 1 >= $2::integer + AND deliveries.kind IN ('verification', 'password_reset') + THEN greatest(deliveries.updated_at, $4::timestamptz) + ELSE deliveries.body_redacted_at + END, + claim_owner = NULL, + claimed_until = NULL, + version = deliveries.version + 1, + updated_at = greatest(deliveries.updated_at, $4::timestamptz) +WHERE + id = $5 + AND status IN ('pending', 'waiting_quota') + AND ( + claim_owner IS NULL + OR claim_owner = $6::uuid + OR claimed_until <= clock_timestamp() + ) +RETURNING status +` + +type RecordDeliveryFailureParams struct { + CountFailure bool + MaxFailures int32 + NextAttemptAt pgtype.Timestamptz + Now pgtype.Timestamptz + ID pgtype.UUID + LeaseOwner pgtype.UUID +} + +// Records that the sending worker failed on a delivery, so a broken row does +// not stay at the head of the queue: the delivery is due again at +// next_attempt_at and its lease ends. With count_failure the failure is +// counted; after max_failures consecutive failures the delivery is cancelled +// with the reason processing_failed, which an operator sees, and a token mail +// loses its bodies. Without it nothing is counted and nothing is cancelled: +// the failure says nothing about the row (a transient storage error, or a +// stretch of failures across many rows). The row is touched only when no other +// worker holds a live lease on it: lease_owner may hold it, or the lease is +// free or expired. It returns the status after the change; no row means that +// the delivery is no longer pending or waiting, or another worker holds it. +// now is the application clock. +func (q *Queries) RecordDeliveryFailure(ctx context.Context, arg RecordDeliveryFailureParams) (string, error) { + row := q.db.QueryRow(ctx, recordDeliveryFailure, + arg.CountFailure, + arg.MaxFailures, + arg.NextAttemptAt, + arg.Now, + arg.ID, + arg.LeaseOwner, + ) + var status string + err := row.Scan(&status) + return status, err +} + +const releaseDeliveryClaim = `-- name: ReleaseDeliveryClaim :execrows +UPDATE deliveries +SET + claim_owner = NULL, + claimed_until = NULL +WHERE + id = $1 + AND claim_owner = $2 +` + +type ReleaseDeliveryClaimParams struct { + ID pgtype.UUID + LeaseOwner pgtype.UUID +} + +// Gives a claimed delivery back without changing it, so the next pass may +// claim it. It matches only the lease of lease_owner: a delivery that another +// worker took over after the lease expired is left alone. +func (q *Queries) ReleaseDeliveryClaim(ctx context.Context, arg ReleaseDeliveryClaimParams) (int64, error) { + result, err := q.db.Exec(ctx, releaseDeliveryClaim, arg.ID, arg.LeaseOwner) + 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, + cancel_reason = $3, + failure_count = 0, + provider = $4, + provider_account = $5, + claim_owner = CASE + WHEN $6::boolean THEN NULL ELSE deliveries.claim_owner + END, + claimed_until = CASE + WHEN $6::boolean THEN NULL ELSE deliveries.claimed_until + END, + text_body = CASE + WHEN + $1::text = 'cancelled' + AND deliveries.kind IN ('verification', 'password_reset') + THEN '' + ELSE deliveries.text_body + END, + html_body = CASE + WHEN + $1::text = 'cancelled' + AND deliveries.kind IN ('verification', 'password_reset') + THEN '' + ELSE deliveries.html_body + END, + body_redacted_at = CASE + WHEN + $1::text = 'cancelled' + AND deliveries.kind IN ('verification', 'password_reset') + THEN $7 + ELSE deliveries.body_redacted_at + END, version = deliveries.version + 1, - updated_at = $5 + updated_at = $7 WHERE - deliveries.id = $6 - AND deliveries.version = $7 + deliveries.id = $8 + AND deliveries.version = $9 ` type UpdateDeliveryStateParams struct { Status string NextAttemptAt pgtype.Timestamptz + CancelReason pgtype.Text Provider string ProviderAccount string + ReleaseClaim bool 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. +// Stores a change of the delivery state that is not an attempt: a quota wait, +// a cancellation, or a new provider account before the first attempt. It +// applies only while the stored version still equals expected_version and +// returns 0 rows otherwise. The trigger refuses a provider change after an +// attempt. release_claim ends the lease of the sending worker with the +// change; a new provider account keeps it, because the worker rebinds a +// delivery it holds and then sends it. func (q *Queries) UpdateDeliveryState(ctx context.Context, arg UpdateDeliveryStateParams) (int64, error) { result, err := q.db.Exec(ctx, updateDeliveryState, arg.Status, arg.NextAttemptAt, + arg.CancelReason, arg.Provider, arg.ProviderAccount, + arg.ReleaseClaim, arg.UpdatedAt, arg.ID, arg.ExpectedVersion, diff --git a/backend/internal/adapter/secondary/postgres/sqlc/models.go b/backend/internal/adapter/secondary/postgres/sqlc/models.go index 5e81fe8..79bcab1 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/models.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/models.go @@ -113,6 +113,20 @@ type Delivery struct { Version int64 CreatedAt pgtype.Timestamptz UpdatedAt pgtype.Timestamptz + // The token whose link the body carries; set for verification and password reset mail, NULL for notifications. The worker checks the token before it sends. + EmailTokenID pgtype.UUID + // Why a cancelled delivery was not sent; set exactly when the status is cancelled. + CancelReason pgtype.Text + // Lease owner of the sending worker that claimed the delivery; NULL when no worker holds it. + ClaimOwner pgtype.UUID + // When the lease of claim_owner expires; another worker may claim the delivery after it. + ClaimedUntil pgtype.Timestamptz + // When the first request of this delivery was started, by the database clock; the provider keeps the idempotency key for a window counted from here. + FirstSendStartedAt pgtype.Timestamptz + // Consecutive failures of the sending worker on this row (not provider answers); reset by a recorded attempt. + FailureCount int32 + // Set when the bodies of a token mail were cleared after the delivery reached a terminal status, so a database dump holds no live or dead token. + BodyRedactedAt pgtype.Timestamptz } type DeliveryAttempt struct { diff --git a/backend/internal/adapter/secondary/postgres/sqlc/querier.go b/backend/internal/adapter/secondary/postgres/sqlc/querier.go index 1516add..8a669e5 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/querier.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/querier.go @@ -19,6 +19,32 @@ type Querier interface { // handler committed the job is done and nothing is canceled; otherwise the // worker finds its lease gone and does not run or complete the job. CancelScheduledJob(ctx context.Context, arg CancelScheduledJobParams) (int64, error) + // Ends a claimed delivery whose stored content no longer matches its hash, so + // one broken row never blocks the delivery queue. It matches only a delivery + // that the worker could still send, ends the lease, advances the version, and + // redacts the bodies of a token mail like any other cancellation. now is the + // application clock. + CancelUnreadableDelivery(ctx context.Context, arg CancelUnreadableDeliveryParams) (int64, error) + // Claims the most overdue delivery that the sending worker may send, in one + // statement: a pending or waiting_quota delivery of the service mail kinds + // (the literals match the predicate of deliveries_due_idx, so an idle poll + // reads only that small index) whose next_attempt_at has passed, pinned to the + // configured provider account (or to rebind_provider before its first + // attempt, which the worker moves to the configured account), and held by no + // live lease. A row that another worker locks is skipped without waiting, so + // several processes never take the same delivery, and a delivery whose lease + // expired, because its worker stopped, is claimed again. + // The lease is measured by the database clock, never by the clock of an + // application instance: it lasts lease_seconds from clock_timestamp(), and a + // lease is live while claimed_until is later than clock_timestamp(). Due times + // stay on the application clock that wrote them. Neither the version nor + // updated_at changes: a claim is not a change of the delivery. + // previous_claimed_until is the deadline of an abandoned lease, NULL for a + // delivery nobody held; since_first_send_seconds is how long ago, by the + // database clock, its first request started, -1 when none did. now is the + // application clock. Deliveries that are unknown or wait for an unknown quota + // reset have no due time here and wait for an operator. + ClaimDueDelivery(ctx context.Context, arg ClaimDueDeliveryParams) (ClaimDueDeliveryRow, error) // Claims up to batch_limit jobs of the listed kinds in one statement: jobs // whose available_at has passed, and running jobs whose lease expired // because their worker stopped without finishing them. Rows that another @@ -156,6 +182,12 @@ type Querier interface { // the handler transaction that holds its row lock: only that transaction // can have changed it, for example by canceling its own job. GetScheduledJobStatus(ctx context.Context, id int64) (string, error) + // Reads the token a delivery is bound to and the account it is addressed to + // in one statement, for the check right before a service mail is sent. It + // takes no lock. It reads the account address only as the comparison key and + // selects no token hash. A missing binding or token row gives NULL token + // columns. + GetServiceMailState(ctx context.Context, id pgtype.UUID) (GetServiceMailStateRow, error) GetUnrevokedConsentRecordByVersion(ctx context.Context, arg GetUnrevokedConsentRecordByVersionParams) (GetUnrevokedConsentRecordByVersionRow, error) GetUserByEmailNormalized(ctx context.Context, emailNormalized string) (User, error) GetUserByID(ctx context.Context, id pgtype.UUID) (User, error) @@ -253,6 +285,11 @@ type Querier interface { // published or open the category, until the transaction ends. The key is // namespaced, so it cannot collide with another use of advisory locks. LockAssessmentCategory(ctx context.Context, category string) error + // Locks the delivery row of the lease holder until the transaction ends, so + // every path that settles a send takes the delivery lock before the quota + // rows, the same order as the claim. No row means that owner no longer holds + // the lease. + LockClaimedDelivery(ctx context.Context, arg LockClaimedDeliveryParams) (pgtype.UUID, error) // Locks a claimed job for its handler transaction and checks that the lease // still belongs to this attempt. It returns no row when the job was // canceled, or reclaimed after the lease expired. While the lock is held, @@ -279,6 +316,12 @@ type Querier interface { // because aggregate writers check the expected version, so scanning without a // position watermark cannot overtake an earlier version. LockPendingOutboxEvents(ctx context.Context, batchLimit int32) ([]LockPendingOutboxEventsRow, error) + // Notes that the first request of a claimed delivery is about to start, by the + // database clock, and clears the count of worker failures: the claim and the + // preparation succeeded, so the failures are no longer consecutive. The provider keeps the idempotency key for a window counted + // from this moment, so a later claim can tell whether repeating the request is + // still safe. It never moves. + MarkDeliverySendStarted(ctx context.Context, arg MarkDeliverySendStartedParams) (int64, error) // Records that the provider refused a send because the quota of a window is // used up: the usage rises to at least the configured limit, so the local // gate stops admitting sends until the window resets or an operator raises @@ -304,11 +347,32 @@ type Querier interface { // transaction. The update applies only while the stored version still // equals expected_version; otherwise nothing is written and the statement // returns 0 rows. Two workers that record the same attempt number therefore - // cannot both succeed. Content columns are not touched; a trigger refuses - // any change to them. + // cannot both succeed. The lease of the sending worker ends with the + // attempt, and so does the count of worker failures. When lease_owner is + // given, the update applies only while that worker still holds the lease. + // A token mail that reaches a terminal status loses its bodies in the same + // statement, so the one-time token does not stay at rest; the trigger allows + // exactly this change of the content columns. RecordDeliveryAttempt(ctx context.Context, arg RecordDeliveryAttemptParams) (int64, error) + // Records that the sending worker failed on a delivery, so a broken row does + // not stay at the head of the queue: the delivery is due again at + // next_attempt_at and its lease ends. With count_failure the failure is + // counted; after max_failures consecutive failures the delivery is cancelled + // with the reason processing_failed, which an operator sees, and a token mail + // loses its bodies. Without it nothing is counted and nothing is cancelled: + // the failure says nothing about the row (a transient storage error, or a + // stretch of failures across many rows). The row is touched only when no other + // worker holds a live lease on it: lease_owner may hold it, or the lease is + // free or expired. It returns the status after the change; no row means that + // the delivery is no longer pending or waiting, or another worker holds it. + // now is the application clock. + RecordDeliveryFailure(ctx context.Context, arg RecordDeliveryFailureParams) (string, error) // Records the latest settled outcome of a send under the reservation. RecordMailQuotaOutcome(ctx context.Context, arg RecordMailQuotaOutcomeParams) (int64, error) + // Gives a claimed delivery back without changing it, so the next pass may + // claim it. It matches only the lease of lease_owner: a delivery that another + // worker took over after the lease expired is left alone. + ReleaseDeliveryClaim(ctx context.Context, arg ReleaseDeliveryClaimParams) (int64, error) // Marks a reservation released. It matches only an open reservation, so a // repeated release changes nothing and returns 0 rows. ReleaseMailQuotaReservation(ctx context.Context, arg ReleaseMailQuotaReservationParams) (int64, error) @@ -365,10 +429,13 @@ 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. + // Stores a change of the delivery state that is not an attempt: a quota wait, + // a cancellation, or a new provider account before the first attempt. It + // applies only while the stored version still equals expected_version and + // returns 0 rows otherwise. The trigger refuses a provider change after an + // attempt. release_claim ends the lease of the sending worker with the + // change; a new provider account keeps it, because the worker rebinds a + // delivery it holds and then sends it. UpdateDeliveryState(ctx context.Context, arg UpdateDeliveryStateParams) (int64, error) // Changes the profile of an organization over the version the caller read // and advances the version in the same statement. It names no verification diff --git a/backend/internal/adapter/secondary/prometheus/mail.go b/backend/internal/adapter/secondary/prometheus/mail.go index b818bbb..257b47e 100644 --- a/backend/internal/adapter/secondary/prometheus/mail.go +++ b/backend/internal/adapter/secondary/prometheus/mail.go @@ -32,6 +32,13 @@ type mailMetrics struct { quotaUsed *client.GaugeVec quotaLimit *client.GaugeVec quotaProviderExhausted *client.GaugeVec + // senderRunning is 1 while this process's mail sending loop runs. It is + // per process, not database-wide, so dashboards and alerts aggregate it + // with max across instances. + senderRunning client.Gauge + // senderCancelled counts deliveries that the sending worker ended without + // sending, by cancel reason, a closed set from the domain. + senderCancelled *client.CounterVec } // deliveryKinds and deliveryStatuses list the series that always exist, so a @@ -48,18 +55,19 @@ var ( domain.DeliveryStatusUnknown, domain.DeliveryStatusAccepted, domain.DeliveryStatusRejected, + domain.DeliveryStatusCancelled, } ) func newMailMetrics() mailMetrics { - return mailMetrics{ + metrics := mailMetrics{ deliveries: client.NewGaugeVec(client.GaugeOpts{ Name: "lincodex_mail_deliveries", - Help: "Stored mail deliveries by kind and status at the last statistics read: pending, waiting_quota, unknown, accepted, or rejected.", + Help: "Stored mail deliveries by kind and status at the last statistics read: pending, waiting_quota, unknown, accepted (by the provider, not delivered to a person), rejected, or cancelled.", }, []string{"kind", "status"}), oldestDuePendingAge: client.NewGaugeVec(client.GaugeOpts{ Name: "lincodex_mail_delivery_oldest_due_pending_age_seconds", - Help: "How long the earliest pending delivery has been due for its next attempt, by the application clock, at the last statistics read; 0 without due pending deliveries, absent before the first read.", + Help: "How long the earliest pending service mail (verification or password reset, the kinds the sending worker handles) has been due for its next attempt, by the application clock, at the last statistics read; 0 without due pending service mail, absent before the first read. Notifications are not counted until they are sent.", }, nil), lastSuccess: client.NewGaugeVec(client.GaugeOpts{ Name: "lincodex_mail_metrics_last_success_timestamp_seconds", @@ -77,13 +85,28 @@ func newMailMetrics() mailMetrics { Name: "lincodex_mail_quota_provider_exhausted", Help: "1 when the provider itself reported the quota of the current UTC window used up, 0 otherwise, by provider and window.", }, []string{"provider", "window"}), + senderCancelled: client.NewCounterVec(client.CounterOpts{ + Name: "lincodex_mail_sender_cancelled_total", + Help: "Deliveries that the mail sending worker of this process ended without sending, by cancel reason. content_invalid and processing_failed mean a broken row or a defect.", + }, []string{"reason"}), + senderRunning: client.NewGauge(client.GaugeOpts{ + Name: "lincodex_mail_sender_running", + Help: "1 while the mail sending loop of this process runs, 0 while it does not, for example with EMAIL_PROVIDER=disabled or after shutdown began.", + }), } + // Every reason exists at zero, so an alert on an increase sees the first + // cancellation instead of a new series. + for _, reason := range domain.DeliveryCancelReasons() { + metrics.senderCancelled.WithLabelValues(string(reason)) + } + return metrics } func (mail mailMetrics) collectors() []client.Collector { return []client.Collector{ mail.deliveries, mail.oldestDuePendingAge, mail.lastSuccess, mail.quotaUsed, mail.quotaLimit, mail.quotaProviderExhausted, + mail.senderRunning, mail.senderCancelled, } } @@ -112,6 +135,27 @@ func (metrics *Metrics) ObserveDeliveryStates(counts []outbound.DeliveryStatusCo metrics.mail.oldestDuePendingAge.WithLabelValues().Set(oldestDuePending.Seconds()) } +// ObserveMailCancelled counts one cancelled delivery by its cancel reason. A +// reason outside the domain set counts as processing_failed, so the label stays +// bounded. +func (metrics *Metrics) ObserveMailCancelled(reason string) { + if _, err := domain.ParseDeliveryCancelReason(reason); err != nil { + reason = string(domain.DeliveryCancelProcessingFailed) + } + metrics.mail.senderCancelled.WithLabelValues(reason).Inc() +} + +// SetMailSenderRunning reports whether this process's mail sending loop +// runs: 1 from the moment it starts until it stops, 0 otherwise. The series +// exists at 0 from startup, also when the loop never starts. +func (metrics *Metrics) SetMailSenderRunning(running bool) { + value := 0.0 + if running { + value = 1 + } + metrics.mail.senderRunning.Set(value) +} + // PrepareMailMetricsReads exposes the last success time at 0 when the // sampler starts, so an alert sees a sampler that never reads successfully. func (metrics *Metrics) PrepareMailMetricsReads() { diff --git a/backend/internal/adapter/secondary/prometheus/mail_test.go b/backend/internal/adapter/secondary/prometheus/mail_test.go new file mode 100644 index 0000000..646ab5a --- /dev/null +++ b/backend/internal/adapter/secondary/prometheus/mail_test.go @@ -0,0 +1,41 @@ +package prometheus + +import ( + "strings" + "testing" +) + +func TestMetricsHandlerExposesWhetherTheMailSenderRuns(t *testing.T) { + metrics := New() + // The series exists before any loop starts, so an alert that needs + // "the sender runs" sees 0 instead of a missing series. + requireSeries(t, scrape(t, metrics), "lincodex_mail_sender_running 0") + + metrics.SetMailSenderRunning(true) + requireSeries(t, scrape(t, metrics), "lincodex_mail_sender_running 1") + + metrics.SetMailSenderRunning(false) + requireSeries(t, scrape(t, metrics), "lincodex_mail_sender_running 0") +} + +func TestMetricsHandlerCountsCancelledMailByABoundedReason(t *testing.T) { + metrics := New() + // Every reason exists at zero before the first cancellation. + body := scrape(t, metrics) + requireSeries(t, body, + `lincodex_mail_sender_cancelled_total{reason="content_invalid"} 0`, + `lincodex_mail_sender_cancelled_total{reason="processing_failed"} 0`, + `lincodex_mail_sender_cancelled_total{reason="token_revoked"} 0`, + ) + metrics.ObserveMailCancelled("content_invalid") + metrics.ObserveMailCancelled("content_invalid") + // A reason outside the domain set cannot become a label. + metrics.ObserveMailCancelled("someone@example.com") + requireSeries(t, scrape(t, metrics), + `lincodex_mail_sender_cancelled_total{reason="content_invalid"} 2`, + `lincodex_mail_sender_cancelled_total{reason="processing_failed"} 1`, + ) + if strings.Contains(scrape(t, metrics), "someone@example.com") { + t.Fatal("an arbitrary reason became a label") + } +} diff --git a/backend/internal/adapter/secondary/prometheus/product_metrics_test.go b/backend/internal/adapter/secondary/prometheus/product_metrics_test.go index ae10e89..42c96da 100644 --- a/backend/internal/adapter/secondary/prometheus/product_metrics_test.go +++ b/backend/internal/adapter/secondary/prometheus/product_metrics_test.go @@ -60,6 +60,7 @@ func TestMetricsHandlerExposesEveryDeliveryState(t *testing.T) { `lincodex_mail_deliveries{kind="password_reset",status="waiting_quota"} 0`, `lincodex_mail_deliveries{kind="verification",status="accepted"} 0`, `lincodex_mail_deliveries{kind="notification",status="rejected"} 0`, + `lincodex_mail_deliveries{kind="verification",status="cancelled"} 0`, "lincodex_mail_delivery_oldest_due_pending_age_seconds 90", ) diff --git a/backend/internal/bootstrap/app.go b/backend/internal/bootstrap/app.go index 952e76d..ff01098 100644 --- a/backend/internal/bootstrap/app.go +++ b/backend/internal/bootstrap/app.go @@ -20,6 +20,7 @@ import ( "lincodex/backend/internal/port/outbound" "lincodex/backend/internal/worker/deliverymetrics" "lincodex/backend/internal/worker/jobrunner" + "lincodex/backend/internal/worker/mailsender" "lincodex/backend/internal/worker/outboxrelay" ) @@ -33,8 +34,8 @@ type Application struct { apiHandler http.Handler metrics *prometheus.Metrics logger *slog.Logger - // mailSender is the transport selected by EMAIL_PROVIDER. No usecase - // sends mail yet; the delivery layer will take it from here. + // mailSender is the transport selected by EMAIL_PROVIDER. Only the mail + // sending worker calls it. mailSender outbound.MailSender // relay publishes outbox events while the servers run. It is nil when // the relay is disabled or the database is not configured. @@ -46,6 +47,10 @@ type Application struct { // is nil when the worker is disabled, no job kind is registered, or the // database is not configured. jobs *jobrunner.Worker + // mailSending sends the stored service mail of the account flows while + // the servers run. It is nil with EMAIL_PROVIDER=disabled or when the + // database is not configured. + mailSending *mailsender.Worker // deliveryMetrics reads the delivery and quota gauges while the servers // run. It is nil when the database is not configured. deliveryMetrics *deliverymetrics.Sampler @@ -60,6 +65,7 @@ func NewApplication( relay *outboxrelay.Relay, consumers eventConsumers, jobs *jobrunner.Worker, + mailSending *mailsender.Worker, deliveryMetrics *deliverymetrics.Sampler, ) *Application { return &Application{ @@ -71,6 +77,7 @@ func NewApplication( relay: relay, consumers: consumers, jobs: jobs, + mailSending: mailSending, deliveryMetrics: deliveryMetrics, } } @@ -189,16 +196,18 @@ func (application *Application) run(ctx context.Context) error { stopRun() // The relay finishes its pass in progress within SHUTDOWN_TIMEOUT, each // consumer its record in progress within CONSUMER_SHUTDOWN_GRACE plus - // one offset commit, and the job worker its job in progress within - // JOBS_SHUTDOWN_GRACE plus one release, so the cleanup that closes their - // pools, producer, and group members runs after all of them stopped. + // one offset commit, the job worker its job in progress within + // JOBS_SHUTDOWN_GRACE plus one release, and the mail sending worker its + // send in progress within its shutdown grace plus one settlement, so the + // cleanup that closes their pools, producer, and group members runs after + // all of them stopped. <-workersStopped application.logger.Info("workers stopped") return err } -// startWorkers runs the relay, every consumer, the scheduled job worker, and -// the delivery metrics sampler until ctx ends and returns a channel that +// startWorkers runs the relay, every consumer, the scheduled job worker, the +// mail sending worker, and the delivery metrics sampler until ctx ends and returns a channel that // closes when all of them have stopped. The workers stop together with the // servers; none of them depends on another. func (application *Application) startWorkers(ctx context.Context) <-chan struct{} { @@ -212,6 +221,9 @@ func (application *Application) startWorkers(ctx context.Context) <-chan struct{ if application.jobs != nil { workers.Go(func() { application.jobs.Run(ctx) }) } + if application.mailSending != nil { + workers.Go(func() { application.mailSending.Run(ctx) }) + } if application.deliveryMetrics != nil { workers.Go(func() { application.deliveryMetrics.Run(ctx) }) } diff --git a/backend/internal/bootstrap/consumers_test.go b/backend/internal/bootstrap/consumers_test.go index afb07a1..78ff065 100644 --- a/backend/internal/bootstrap/consumers_test.go +++ b/backend/internal/bootstrap/consumers_test.go @@ -191,7 +191,7 @@ func TestApplicationRunsConsumersWhileServingAndWaitsForThem(t *testing.T) { HTTPAddr: "127.0.0.1:0", MetricsAddr: "127.0.0.1:0", ShutdownTimeout: time.Second, - }, http.NotFoundHandler(), metrics, logger, nil, nil, eventConsumers{consumer}, nil, nil) + }, http.NotFoundHandler(), metrics, logger, nil, nil, eventConsumers{consumer}, nil, nil, nil) ctx, cancel := context.WithCancel(t.Context()) defer cancel() diff --git a/backend/internal/bootstrap/delivery_metrics_test.go b/backend/internal/bootstrap/delivery_metrics_test.go index 2751960..c07c84e 100644 --- a/backend/internal/bootstrap/delivery_metrics_test.go +++ b/backend/internal/bootstrap/delivery_metrics_test.go @@ -63,7 +63,7 @@ func TestApplicationRunsAndStopsTheDeliveryMetricsSampler(t *testing.T) { if sampler == nil { t.Fatal("newDeliveryMetrics() built no sampler with DATABASE_URL set") } - application := NewApplication(settings, http.NotFoundHandler(), metrics, logger, nil, nil, nil, nil, sampler) + application := NewApplication(settings, http.NotFoundHandler(), metrics, logger, nil, nil, nil, nil, nil, sampler) ctx, cancel := context.WithCancel(t.Context()) finished := make(chan error, 1) diff --git a/backend/internal/bootstrap/jobs_test.go b/backend/internal/bootstrap/jobs_test.go index c4746ba..8334ba6 100644 --- a/backend/internal/bootstrap/jobs_test.go +++ b/backend/internal/bootstrap/jobs_test.go @@ -87,7 +87,7 @@ func TestApplicationRunsAndStopsTheJobWorker(t *testing.T) { if worker == nil { t.Fatal("buildJobWorker() built no worker for a registered kind") } - application := NewApplication(settings, http.NotFoundHandler(), metrics, logger, nil, nil, nil, worker, nil) + application := NewApplication(settings, http.NotFoundHandler(), metrics, logger, nil, nil, nil, worker, nil, nil) ctx, cancel := context.WithCancel(t.Context()) finished := make(chan error, 1) diff --git a/backend/internal/bootstrap/mail_sender.go b/backend/internal/bootstrap/mail_sender.go new file mode 100644 index 0000000..c76748c --- /dev/null +++ b/backend/internal/bootstrap/mail_sender.go @@ -0,0 +1,154 @@ +package bootstrap + +import ( + "context" + "fmt" + "log/slog" + "time" + + "lincodex/backend/config" + "lincodex/backend/internal/adapter/secondary/mail/resend" + "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/worker/mailsender" + "lincodex/backend/internal/worker/retry" +) + +const ( + // mailSenderPoolMaxConns covers the claim or settlement transaction of + // the loop, which run one after another, and one statement next to it. + mailSenderPoolMaxConns = 2 + // mailSenderPollInterval is the wait after a pass that found nothing + // due. A verification mail is something a person waits for, so the wait + // is short; an idle pass is one indexed statement. + mailSenderPollInterval = 5 * time.Second + // mailSenderStoreTimeout bounds the claim transaction and each try to + // store a send result. + mailSenderStoreTimeout = 15 * time.Second + // mailSenderLeaseMargin is added to EMAIL_TIMEOUT to give the lease on a + // claimed delivery: the attempt, the settlement, and some slack. A lease + // is long enough that a live sender never loses it, and short enough that + // a delivery of a stopped sender is taken over within minutes. + mailSenderLeaseMargin = time.Minute + // mailSenderShutdownGrace is how long a send in progress may continue + // after shutdown began; its result is stored anyway. + mailSenderShutdownGrace = 3 * time.Second + // mailSenderSettleBudget bounds storing the answer of a send, retries + // included. It is reserved inside the lease, so the call plus this budget + // plus the claim fit in EMAIL_TIMEOUT plus mailSenderLeaseMargin. + mailSenderSettleBudget = 20 * time.Second + // mailSenderMaxShutdownSettle bounds storing an answer once shutdown began; + // the grace plus this must fit SHUTDOWN_TIMEOUT, so the budget is shortened + // when that is set lower (bootstrap.shutdownSettleBudget). + mailSenderMaxShutdownSettle = 5 * time.Second + // mailSenderMaxFailures is how many consecutive failures of the worker on + // one delivery are retried before it is cancelled as processing_failed. + mailSenderMaxFailures = 3 + // mailSenderRetryInitial and mailSenderRetryMax pace the repeat of an + // attempt that the provider refused for now (temporary or rate limited): + // one minute, doubling, at most half an hour; a longer Retry-After from + // the provider is honored as it is. + mailSenderRetryInitial = time.Minute + mailSenderRetryMax = 30 * time.Minute + // mailSenderBackoffInitial and mailSenderBackoffMax pace the loop after a + // database failure or a pass that could not send. + mailSenderBackoffInitial = 5 * time.Second + mailSenderBackoffMax = 2 * time.Minute +) + +var _ mailsender.Metrics = (*prometheus.Metrics)(nil) + +// newMailSenderWorker builds the sending loop of the service identity mail +// and the PostgreSQL pool it owns. Nothing connects here, so an unavailable +// database never blocks startup; the loop retries in the background. +// +// It returns no worker, and lincodex_mail_sender_running stays 0, when +// EMAIL_PROVIDER=disabled, because that transport sends nothing and a loop +// that claims deliveries only to find the channel unavailable would count +// quota reservations and wake the database for no effect; the stored +// deliveries wait, pinned to disabled, until a restart with a transport. +// It returns none either when DATABASE_URL is unset. The application clock is +// time.Now. +func newMailSenderWorker( + ctx context.Context, + settings config.Config, + logger *slog.Logger, + metrics *prometheus.Metrics, + mailSender outbound.MailSender, +) (*mailsender.Worker, func(), error) { + switch { + case settings.EmailProvider == config.EmailProviderDisabled: + logger.Info("mail sender worker is not started because EMAIL_PROVIDER is disabled; stored deliveries wait") + return nil, func() {}, nil + case settings.DatabaseURL == "": + logger.Warn("mail sender worker skipped because DATABASE_URL is not set") + return nil, func() {}, nil + } + account, err := domain.NewMailProviderAccount(string(settings.EmailProvider), settings.EmailAccount) + if err != nil { + return nil, nil, fmt.Errorf("bootstrap.newMailSenderWorker - provider account: %w", err) + } + limits, err := domain.NewMailQuotaLimits(int64(settings.EmailQuotaDaily), int64(settings.EmailQuotaMonthly)) + if err != nil { + return nil, nil, fmt.Errorf("bootstrap.newMailSenderWorker - quota limits: %w", err) + } + pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, mailSenderPoolMaxConns) + if err != nil { + return nil, nil, fmt.Errorf("bootstrap.newMailSenderWorker - create pool: %w", err) + } + workerLogger := logger.With(slog.String("component", "mail_sender")) + gate := notification.NewQuotaGate(account, limits, mailIdempotencyWindow(settings), time.Now, workerLogger) + sender, err := notification.NewServiceMailSender( + postgres.NewTransactor(pool), + mailSender, + gate, + notification.ServiceMailSenderSettings{ + Account: account, + RebindProvider: string(config.EmailProviderDisabled), + Lease: settings.EmailTimeout + mailSenderLeaseMargin, + StoreTimeout: mailSenderStoreTimeout, + SettleBudget: mailSenderSettleBudget, + ShutdownSettleBudget: shutdownSettleBudget(settings.ShutdownTimeout), + MaxFailures: mailSenderMaxFailures, + Retry: notification.RetryPolicy{Initial: mailSenderRetryInitial, Max: mailSenderRetryMax, Jitter: notification.RandomJitter}, + }, + time.Now, + workerLogger, + ) + if err != nil { + pool.Close() + return nil, nil, fmt.Errorf("bootstrap.newMailSenderWorker - create sender: %w", err) + } + worker, err := mailsender.New(sender, metrics, workerLogger, mailsender.Settings{ + PollInterval: mailSenderPollInterval, + Backoff: retry.Backoff{Initial: mailSenderBackoffInitial, Max: mailSenderBackoffMax}, + ShutdownGrace: mailSenderShutdownGrace, + }) + if err != nil { + pool.Close() + return nil, nil, fmt.Errorf("bootstrap.newMailSenderWorker - create worker: %w", err) + } + // The application stops the worker before this cleanup runs, so no send + // uses the pool while it closes. + return worker, pool.Close, nil +} + +// shutdownSettleBudget is the time to store the answer of a send once shutdown +// began: what SHUTDOWN_TIMEOUT leaves after the shutdown grace, at most +// mailSenderMaxShutdownSettle and at least one second. +func shutdownSettleBudget(shutdownTimeout time.Duration) time.Duration { + return min(mailSenderMaxShutdownSettle, max(shutdownTimeout-mailSenderShutdownGrace, time.Second)) +} + +// mailIdempotencyWindow is how long the selected transport's provider +// deduplicates a repeated request with the same idempotency key; zero for a +// transport without provider-side deduplication. +func mailIdempotencyWindow(settings config.Config) time.Duration { + if settings.EmailProvider == config.EmailProviderResend { + return resend.IdempotencyWindow + } + return 0 +} diff --git a/backend/internal/bootstrap/mail_sender_test.go b/backend/internal/bootstrap/mail_sender_test.go new file mode 100644 index 0000000..27e4d42 --- /dev/null +++ b/backend/internal/bootstrap/mail_sender_test.go @@ -0,0 +1,146 @@ +package bootstrap + +import ( + "context" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "lincodex/backend/config" + "lincodex/backend/internal/adapter/secondary/mail/disabled" + "lincodex/backend/internal/adapter/secondary/mail/resend" + "lincodex/backend/internal/adapter/secondary/prometheus" +) + +// resendSenderConfig is a Resend setup with a database that does not answer. +func resendSenderConfig(t *testing.T) config.Config { + t.Helper() + settings := consumerTestConfig(t) + settings.EmailProvider = config.EmailProviderResend + settings.EmailAccount = "primary" + settings.EmailTimeout = 10 * time.Second + settings.EmailQuotaDaily = 100 + settings.EmailQuotaMonthly = 3000 + return settings +} + +func TestNewMailSenderWorkerSkipsWithoutWork(t *testing.T) { + noDatabase := resendSenderConfig(t) + noDatabase.DatabaseURL = "" + tests := []struct { + name string + settings config.Config + log string + }{ + // consumerTestConfig selects the disabled transport. + {name: "transport disabled", settings: consumerTestConfig(t), log: "EMAIL_PROVIDER is disabled"}, + {name: "database not configured", settings: noDatabase, log: "DATABASE_URL is not set"}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + var logs strings.Builder + logger := slog.New(slog.NewTextHandler(&logs, nil)) + metrics := prometheus.New() + worker, cleanup, err := newMailSenderWorker(t.Context(), test.settings, logger, metrics, disabled.NewSender()) + if err != nil { + t.Fatalf("newMailSenderWorker() error = %v", err) + } + cleanup() + if worker != nil { + t.Fatal("newMailSenderWorker() built a worker without work to do") + } + if !strings.Contains(logs.String(), test.log) { + t.Fatalf("logs = %q, want %q", logs.String(), test.log) + } + // Without a loop the gauge says so, so the overdue alert stays + // silent. + if body := scrape(metrics); !strings.Contains(body, "lincodex_mail_sender_running 0\n") { + t.Fatalf("metrics lack lincodex_mail_sender_running 0:\n%s", body) + } + }) + } +} + +func TestMailIdempotencyWindowFollowsTheTransport(t *testing.T) { + if got := mailIdempotencyWindow(config.Config{EmailProvider: config.EmailProviderResend}); got != resend.IdempotencyWindow { + t.Fatalf("mailIdempotencyWindow(resend) = %s, want %s", got, resend.IdempotencyWindow) + } + // A relay has no provider-side deduplication, so every retry counts again. + if got := mailIdempotencyWindow(config.Config{EmailProvider: config.EmailProviderSMTP}); got != 0 { + t.Fatalf("mailIdempotencyWindow(smtp) = %s, want 0", got) + } +} + +// TestApplicationRunsAndStopsTheMailSenderWorker starts the loop against a +// database that does not answer: it backs off in the background, reports +// that it runs, and the application still stops within its shutdown budget +// with the gauge back at 0. +func TestApplicationRunsAndStopsTheMailSenderWorker(t *testing.T) { + settings := resendSenderConfig(t) + settings.HTTPAddr = "127.0.0.1:0" + settings.MetricsAddr = "127.0.0.1:0" + settings.ShutdownTimeout = time.Second + metrics := prometheus.New() + logger := slog.New(slog.DiscardHandler) + worker, cleanup, err := newMailSenderWorker(t.Context(), settings, logger, metrics, disabled.NewSender()) + if err != nil { + t.Fatalf("newMailSenderWorker() error = %v", err) + } + defer cleanup() + if worker == nil { + t.Fatal("newMailSenderWorker() built no worker for an active transport") + } + application := NewApplication(settings, http.NotFoundHandler(), metrics, logger, nil, nil, nil, nil, worker, nil) + + ctx, cancel := context.WithCancel(t.Context()) + finished := make(chan error, 1) + go func() { finished <- application.run(ctx) }() + deadline := time.Now().Add(relayLifecycleTimeout) + for !strings.Contains(scrape(metrics), "lincodex_mail_sender_running 1\n") { + if time.Now().After(deadline) { + t.Fatal("the loop never reported that it runs") + } + time.Sleep(10 * time.Millisecond) + } + cancel() + select { + case err := <-finished: + if err != nil { + t.Fatalf("run() error = %v", err) + } + case <-time.After(relayLifecycleTimeout): + t.Fatal("run() did not return after cancellation") + } + if body := scrape(metrics); !strings.Contains(body, "lincodex_mail_sender_running 0\n") { + t.Fatalf("the gauge did not return to 0 after the loop stopped:\n%s", body) + } +} + +func scrape(metrics *prometheus.Metrics) string { + recorder := httptest.NewRecorder() + metrics.Handler().ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/metrics", nil)) + return recorder.Body.String() +} + +func TestShutdownSettleBudgetFitsTheShutdownTimeout(t *testing.T) { + for _, test := range []struct { + shutdown time.Duration + want time.Duration + }{ + {30 * time.Second, mailSenderMaxShutdownSettle}, + {10 * time.Second, mailSenderMaxShutdownSettle}, // the default SHUTDOWN_TIMEOUT + {6 * time.Second, 3 * time.Second}, + {time.Second, time.Second}, + } { + got := shutdownSettleBudget(test.shutdown) + if got != test.want { + t.Fatalf("shutdownSettleBudget(%s) = %s, want %s", test.shutdown, got, test.want) + } + if test.shutdown >= 4*time.Second && mailSenderShutdownGrace+got > test.shutdown { + t.Fatalf("grace plus settle budget = %s, over SHUTDOWN_TIMEOUT %s", mailSenderShutdownGrace+got, test.shutdown) + } + } +} diff --git a/backend/internal/bootstrap/relay_test.go b/backend/internal/bootstrap/relay_test.go index 463ab7f..0679bad 100644 --- a/backend/internal/bootstrap/relay_test.go +++ b/backend/internal/bootstrap/relay_test.go @@ -76,7 +76,7 @@ func TestApplicationRunsTheRelayWhileServing(t *testing.T) { HTTPAddr: "127.0.0.1:0", MetricsAddr: "127.0.0.1:0", ShutdownTimeout: time.Second, - }, http.NotFoundHandler(), metrics, logger, nil, relay, nil, nil, nil) + }, http.NotFoundHandler(), metrics, logger, nil, relay, nil, nil, nil, nil) ctx, cancel := context.WithCancel(t.Context()) defer cancel() diff --git a/backend/internal/bootstrap/wire.go b/backend/internal/bootstrap/wire.go index ad38fd2..a76c097 100644 --- a/backend/internal/bootstrap/wire.go +++ b/backend/internal/bootstrap/wire.go @@ -50,6 +50,7 @@ func initialize( newOutboxRelay, newEventConsumers, newJobWorker, + newMailSenderWorker, newDeliveryMetrics, NewApplication, ), diff --git a/backend/internal/bootstrap/wire_gen.go b/backend/internal/bootstrap/wire_gen.go index 4dc5af8..c708676 100644 --- a/backend/internal/bootstrap/wire_gen.go +++ b/backend/internal/bootstrap/wire_gen.go @@ -79,7 +79,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, cleanup() return nil, nil, err } - sampler, cleanup7, err := newDeliveryMetrics(ctx, config2, logger, metrics) + mailsenderWorker, cleanup7, err := newMailSenderWorker(ctx, config2, logger, metrics, mailSender) if err != nil { cleanup6() cleanup5() @@ -89,8 +89,20 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, cleanup() return nil, nil, err } - application := NewApplication(config2, httpHandler, metrics, logger, mailSender, relay, bootstrapEventConsumers, worker, sampler) + sampler, cleanup8, err := newDeliveryMetrics(ctx, config2, logger, metrics) + if err != nil { + cleanup7() + cleanup6() + cleanup5() + cleanup4() + cleanup3() + cleanup2() + cleanup() + return nil, nil, err + } + application := NewApplication(config2, httpHandler, metrics, logger, mailSender, relay, bootstrapEventConsumers, worker, mailsenderWorker, sampler) return application, func() { + cleanup8() cleanup7() cleanup6() cleanup5() diff --git a/backend/internal/domain/delivery.go b/backend/internal/domain/delivery.go index f8f3967..1c91524 100644 --- a/backend/internal/domain/delivery.go +++ b/backend/internal/domain/delivery.go @@ -23,9 +23,9 @@ var ( 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. + // not allow: an attempt on an accepted, rejected, or cancelled delivery, + // a quota wait or a cancellation 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 @@ -47,14 +47,19 @@ var ( // Transitions: // // pending, waiting_quota, unknown --RecordAttempt--> accepted | rejected | pending | waiting_quota | unknown -// accepted, rejected --RecordAttempt--> refused (ErrDeliveryTransition) +// accepted, rejected, cancelled --RecordAttempt--> refused (ErrDeliveryTransition) // pending, waiting_quota --WaitForQuota---> waiting_quota (no attempt is recorded) +// pending, waiting_quota --Cancel---------> cancelled (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. +// +// Only accepted means that a provider took the message, and even then it is +// not delivery to a person: no status claims that the mail reached an inbox +// or was read. type DeliveryStatus string const ( @@ -62,7 +67,8 @@ const ( // 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. + // returned its ID: "accepted by the provider". 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. @@ -77,12 +83,17 @@ const ( // time the reset is unknown (for example a monthly provider quota) and an // operator or the quota rule decides. DeliveryStatusWaitingQuota DeliveryStatus = "waiting_quota" + // DeliveryStatusCancelled means the message was deliberately not sent + // and never will be: no attempt of it is recorded, and the reason says + // why (see DeliveryCancelReason). It is terminal and is not an attempt. + DeliveryStatusCancelled DeliveryStatus = "cancelled" ) // ParseDeliveryStatus accepts a known status. func ParseDeliveryStatus(value string) (DeliveryStatus, error) { switch status := DeliveryStatus(value); status { - case DeliveryStatusPending, DeliveryStatusAccepted, DeliveryStatusRejected, DeliveryStatusUnknown, DeliveryStatusWaitingQuota: + case DeliveryStatusPending, DeliveryStatusAccepted, DeliveryStatusRejected, DeliveryStatusUnknown, + DeliveryStatusWaitingQuota, DeliveryStatusCancelled: return status, nil default: return "", invalidDelivery("domain.ParseDeliveryStatus", "unknown delivery status") @@ -91,7 +102,7 @@ func ParseDeliveryStatus(value string) (DeliveryStatus, error) { // IsTerminal reports a status that accepts no further attempt. func (status DeliveryStatus) IsTerminal() bool { - return status == DeliveryStatusAccepted || status == DeliveryStatusRejected + return status == DeliveryStatusAccepted || status == DeliveryStatusRejected || status == DeliveryStatusCancelled } // requiresNextAttempt reports a status that the sending worker picks up again @@ -122,6 +133,69 @@ const ( DeliveryRejectionTemporary DeliveryRejection = "temporary" ) +// DeliveryCancelReason says why a delivery was cancelled: the message was +// deliberately not sent, and no attempt of it is recorded. The values are stored and must stay +// stable; each names the first failed check of the service mail rules (see +// Delivery.CheckServiceMail) or an invalid stored message. +type DeliveryCancelReason string + +const ( + // DeliveryCancelTokenMissing: the delivery is bound to no token, or the + // token row does not exist. + DeliveryCancelTokenMissing DeliveryCancelReason = "token_missing" + // DeliveryCancelTokenPurposeMismatch: the token authorizes another + // purpose than the kind of the mail. + DeliveryCancelTokenPurposeMismatch DeliveryCancelReason = "token_purpose_mismatch" + // DeliveryCancelTokenOwnerMismatch: the token belongs to another account + // than the recipient. + DeliveryCancelTokenOwnerMismatch DeliveryCancelReason = "token_owner_mismatch" + // DeliveryCancelTokenConsumed: the token was already used. + DeliveryCancelTokenConsumed DeliveryCancelReason = "token_consumed" + // DeliveryCancelTokenRevoked: a resend, a re-registration, or another + // revocation replaced the token. + DeliveryCancelTokenRevoked DeliveryCancelReason = "token_revoked" + // DeliveryCancelTokenExpired: the token passed its lifetime. + DeliveryCancelTokenExpired DeliveryCancelReason = "token_expired" + // DeliveryCancelAccountNotCurrent: the account moved on since the token + // was issued: it was registered again, or its state no longer calls for + // the mail (for example the address is verified already). + DeliveryCancelAccountNotCurrent DeliveryCancelReason = "account_not_current" + // DeliveryCancelRecipientMismatch: the address stored with the delivery is + // no longer the address of the account. + DeliveryCancelRecipientMismatch DeliveryCancelReason = "recipient_mismatch" + // DeliveryCancelContentInvalid: the stored message is one that no + // transport accepts, so retrying cannot help. + DeliveryCancelContentInvalid DeliveryCancelReason = "content_invalid" + // DeliveryCancelProcessingFailed: the sending worker failed on this row + // again and again for a reason of its own, so it stopped trying and left + // the row to an operator. + DeliveryCancelProcessingFailed DeliveryCancelReason = "processing_failed" +) + +// DeliveryCancelReasons lists every cancel reason, for metrics that expose +// their series at zero. +func DeliveryCancelReasons() []DeliveryCancelReason { + return []DeliveryCancelReason{ + DeliveryCancelTokenMissing, DeliveryCancelTokenPurposeMismatch, DeliveryCancelTokenOwnerMismatch, + DeliveryCancelTokenConsumed, DeliveryCancelTokenRevoked, DeliveryCancelTokenExpired, + DeliveryCancelAccountNotCurrent, DeliveryCancelRecipientMismatch, DeliveryCancelContentInvalid, + DeliveryCancelProcessingFailed, + } +} + +// ParseDeliveryCancelReason accepts a known reason. +func ParseDeliveryCancelReason(value string) (DeliveryCancelReason, error) { + switch reason := DeliveryCancelReason(value); reason { + case DeliveryCancelTokenMissing, DeliveryCancelTokenPurposeMismatch, DeliveryCancelTokenOwnerMismatch, + DeliveryCancelTokenConsumed, DeliveryCancelTokenRevoked, DeliveryCancelTokenExpired, + DeliveryCancelAccountNotCurrent, DeliveryCancelRecipientMismatch, DeliveryCancelContentInvalid, + DeliveryCancelProcessingFailed: + return reason, nil + default: + return "", invalidDelivery("domain.ParseDeliveryCancelReason", "unknown cancel reason") + } +} + // 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 @@ -172,6 +246,8 @@ type Delivery struct { nextAttemptAt time.Time lastAttemptAt time.Time providerMessageID string + emailTokenID uuid.UUID + cancelReason DeliveryCancelReason version int64 createdAt time.Time updatedAt time.Time @@ -189,7 +265,13 @@ type NewDeliveryInput struct { Recipient EmailAddress Content MailContent ProviderAccount MailProviderAccount - CreatedAt time.Time + // EmailTokenID is the token whose link the content carries. Set it for a + // kind that CarriesBearerToken, so the sending worker can check the token + // before it sends; a delivery of such a kind without it is cancelled by + // the worker with the reason token_missing. It must be uuid.Nil for a + // notification. + EmailTokenID uuid.UUID + CreatedAt time.Time } // NewDelivery validates input and returns a pending delivery that is due at @@ -209,6 +291,8 @@ func NewDelivery(input NewDeliveryInput) (Delivery, error) { return Delivery{}, invalidDelivery(location, "provider account must be set") case input.CreatedAt.IsZero(): return Delivery{}, invalidDelivery(location, "creation time must be set") + case input.EmailTokenID != uuid.Nil && !input.Content.Kind().CarriesBearerToken(): + return Delivery{}, invalidDelivery(location, "only a delivery of a token kind is bound to a token") } return Delivery{ id: input.ID, @@ -217,6 +301,7 @@ func NewDelivery(input NewDeliveryInput) (Delivery, error) { recipient: input.Recipient, content: input.Content, providerAccount: input.ProviderAccount, + emailTokenID: input.EmailTokenID, idempotencyKey: deliveryIdempotencyKeyPrefix + input.ID.String(), status: DeliveryStatusPending, nextAttemptAt: input.CreatedAt, @@ -240,9 +325,13 @@ type DeliverySnapshot struct { NextAttemptAt time.Time LastAttemptAt time.Time ProviderMessageID string - Version int64 - CreatedAt time.Time - UpdatedAt time.Time + // EmailTokenID is uuid.Nil for a delivery without a token binding. + EmailTokenID uuid.UUID + // CancelReason is set exactly for a cancelled delivery. + CancelReason DeliveryCancelReason + Version int64 + CreatedAt time.Time + UpdatedAt time.Time } // RestoreDelivery rebuilds a stored delivery and checks the invariants that @@ -258,21 +347,11 @@ func RestoreDelivery(snapshot DeliverySnapshot) (Delivery, error) { 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 := checkStoredFields(location, snapshot); err != nil { + return Delivery{}, err + } + if err := checkCancellationAndBinding(location, snapshot); err != nil { + return Delivery{}, err } if err := checkNextAttempt(location, snapshot.Status, snapshot.NextAttemptAt); err != nil { return Delivery{}, err @@ -290,12 +369,54 @@ func RestoreDelivery(snapshot DeliverySnapshot) (Delivery, error) { nextAttemptAt: snapshot.NextAttemptAt, lastAttemptAt: snapshot.LastAttemptAt, providerMessageID: snapshot.ProviderMessageID, + emailTokenID: snapshot.EmailTokenID, + cancelReason: snapshot.CancelReason, version: snapshot.Version, createdAt: snapshot.CreatedAt, updatedAt: snapshot.UpdatedAt, }, nil } +// checkStoredFields checks the invariants of a stored row that do not +// depend on its cancellation or token binding. +func checkStoredFields(location string, snapshot DeliverySnapshot) error { + switch { + case snapshot.ID == uuid.Nil || snapshot.RecipientUserID == uuid.Nil: + return invalidDelivery(location, "delivery and recipient user IDs must not be nil") + case snapshot.Content.IsZero() || snapshot.ProviderAccount.IsZero(): + return invalidDelivery(location, "content and provider account must be set") + case !idempotencyKeyPattern.MatchString(snapshot.IdempotencyKey): + return invalidDelivery(location, "idempotency key must have 1 to 256 printable ASCII characters") + case snapshot.Version <= 0 || snapshot.AttemptCount < 0: + return invalidDelivery(location, "version must be positive and the attempt count not negative") + case snapshot.CreatedAt.IsZero() || snapshot.UpdatedAt.Before(snapshot.CreatedAt): + return invalidDelivery(location, "update time must not precede the creation time") + case (snapshot.AttemptCount == 0) != snapshot.LastAttemptAt.IsZero(): + return invalidDelivery(location, "last attempt time must be set exactly when an attempt was made") + case (snapshot.Status == DeliveryStatusAccepted) != (snapshot.ProviderMessageID != ""): + return invalidDelivery(location, "provider message ID must be set exactly for an accepted delivery") + } + return nil +} + +// checkCancellationAndBinding checks the cancel reason and the token binding +// of a stored row. A token kind may lack its binding (rows older than the +// binding), and the sending worker cancels it; a notification never has one. +func checkCancellationAndBinding(location string, snapshot DeliverySnapshot) error { + switch { + case (snapshot.Status == DeliveryStatusCancelled) != (snapshot.CancelReason != ""): + return invalidDelivery(location, "cancel reason must be set exactly for a cancelled delivery") + case snapshot.EmailTokenID != uuid.Nil && !snapshot.Content.Kind().CarriesBearerToken(): + return invalidDelivery(location, "only a delivery of a token kind is bound to a token") + } + if snapshot.CancelReason != "" { + if _, err := ParseDeliveryCancelReason(string(snapshot.CancelReason)); err != nil { + return fmt.Errorf("%s - restore cancel reason: %w", location, err) + } + } + return nil +} + func checkNextAttempt(location string, status DeliveryStatus, nextAttemptAt time.Time) error { switch { case status.IsTerminal() && !nextAttemptAt.IsZero(): @@ -343,7 +464,14 @@ func (delivery Delivery) LastAttemptAt() time.Time { return delivery.lastAttempt // 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. +// EmailTokenID is the token the content's link carries, or uuid.Nil. +func (delivery Delivery) EmailTokenID() uuid.UUID { return delivery.emailTokenID } + +// CancelReason says why a cancelled delivery was not sent; empty for any +// other status. +func (delivery Delivery) CancelReason() DeliveryCancelReason { return delivery.cancelReason } + +// Version is the optimistic concurrency version, advanced by every change. func (delivery Delivery) Version() int64 { return delivery.version } func (delivery Delivery) CreatedAt() time.Time { return delivery.createdAt } @@ -462,6 +590,33 @@ func (delivery Delivery) WaitForQuota(at, until time.Time) (Delivery, error) { return next, nil } +// Cancel ends a pending or waiting_quota delivery without an attempt: the +// message must not be sent, for the given reason. at is the decision time. +// It returns the next state with the next version and no next attempt; no +// attempt record is written, because the message is not sent. An unknown +// delivery is refused like in WaitForQuota: an earlier attempt may have been +// accepted, so it must not be reported as not sent. The terminal statuses are +// refused as well. +func (delivery Delivery) Cancel(at time.Time, reason DeliveryCancelReason) (Delivery, error) { + const location = "Delivery.Cancel" + if err := delivery.checkChangeTime(location, at); err != nil { + return Delivery{}, err + } + if _, err := ParseDeliveryCancelReason(string(reason)); err != nil { + return Delivery{}, fmt.Errorf("%s - %w", location, err) + } + if delivery.status != DeliveryStatusPending && delivery.status != DeliveryStatusWaitingQuota { + return Delivery{}, fmt.Errorf("%s - delivery is %s: %w", location, delivery.status, ErrDeliveryTransition) + } + next := delivery + next.status = DeliveryStatusCancelled + next.cancelReason = reason + next.nextAttemptAt = time.Time{} + 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 diff --git a/backend/internal/domain/delivery_guard.go b/backend/internal/domain/delivery_guard.go new file mode 100644 index 0000000..60d33bb --- /dev/null +++ b/backend/internal/domain/delivery_guard.go @@ -0,0 +1,80 @@ +package domain + +import ( + "time" + + "github.com/google/uuid" +) + +// ServiceMailState is what the sending worker reads right before it sends a +// service mail that carries a one-time token: the token the delivery is +// bound to and the account it is addressed to, as one consistent snapshot. +// A zero time means "not set". +// +// It holds no raw token and no address in a loggable form: the account +// address is only the comparison key, used to compare it with the address +// stored in the delivery. +type ServiceMailState struct { + // TokenFound is false when the delivery has no token binding or the + // token row does not exist. + TokenFound bool + TokenPurpose EmailTokenPurpose + TokenUserID uuid.UUID + TokenRegistrationVersion int64 + TokenConsumedAt time.Time + TokenInvalidatedAt time.Time + TokenExpiresAt time.Time + AccountRegistrationVersion int64 + AccountEmailVerified bool + // AccountEmailKey is the normalized address of the account now. + AccountEmailKey string +} + +// CheckServiceMail decides whether a verification or password reset mail may +// still be sent at the given time, and returns the reason when it may not. +// An empty reason means that the mail is sendable. The checks run in this +// order and the first failure decides: +// +// 1. a token is bound to the delivery and exists; +// 2. its purpose is the one the mail kind carries, and it belongs to the +// recipient account; +// 3. it is not consumed, revoked, or expired; +// 4. the account is current: it still has the registration the token was +// issued for, and a verification mail is not sent to an address that is +// verified already; +// 5. the address stored in the delivery is still the address of the +// account. +// +// Publishing consent (C2) and every other product consent play no part: a +// service mail is part of the account flow, not a product notification. +// A kind without a bearer token is refused with token_missing, because the +// sending worker never claims it. +// +// The check is a snapshot: a token consumed or revoked after it, before the +// provider call, still lets the mail go. That is harmless, because the link +// is checked again when it is used. +func (delivery Delivery) CheckServiceMail(state ServiceMailState, at time.Time) DeliveryCancelReason { + purpose, carriesToken := delivery.Kind().TokenPurpose() + switch { + case !carriesToken || !state.TokenFound: + return DeliveryCancelTokenMissing + case state.TokenPurpose != purpose: + return DeliveryCancelTokenPurposeMismatch + case state.TokenUserID != delivery.recipientUserID: + return DeliveryCancelTokenOwnerMismatch + case !state.TokenConsumedAt.IsZero(): + return DeliveryCancelTokenConsumed + case !state.TokenInvalidatedAt.IsZero(): + return DeliveryCancelTokenRevoked + case !at.Before(state.TokenExpiresAt): + return DeliveryCancelTokenExpired + case state.TokenRegistrationVersion != state.AccountRegistrationVersion: + return DeliveryCancelAccountNotCurrent + case delivery.Kind() == MailKindVerification && state.AccountEmailVerified: + return DeliveryCancelAccountNotCurrent + case state.AccountEmailKey != delivery.recipient.Normalized(): + return DeliveryCancelRecipientMismatch + default: + return "" + } +} diff --git a/backend/internal/domain/delivery_guard_test.go b/backend/internal/domain/delivery_guard_test.go new file mode 100644 index 0000000..6dafeca --- /dev/null +++ b/backend/internal/domain/delivery_guard_test.go @@ -0,0 +1,337 @@ +package domain + +import ( + "errors" + "strings" + "testing" + "time" + + "github.com/google/uuid" +) + +var testTokenID = uuid.MustParse("01926f3a-7c00-7000-8000-0000000000a1") + +// newTokenDelivery is a verification delivery bound to testTokenID. +func newTokenDelivery(t *testing.T, kind MailKind) Delivery { + t.Helper() + version := string(kind) + ".v1" + content, err := NewMailContent(kind, version, testDeliverySubject, testDeliveryText, testDeliveryHTML) + if err != nil { + t.Fatalf("NewMailContent() error = %v", err) + } + input := testDeliveryInput(t) + input.Content = content + input.EmailTokenID = testTokenID + delivery, err := NewDelivery(input) + if err != nil { + t.Fatalf("NewDelivery() error = %v", err) + } + return delivery +} + +// currentState is the state in which a verification mail may be sent: the +// token is the delivery's, unused, unexpired, issued for the registration the +// account still has, and the address is unchanged and not yet verified. +func currentState(delivery Delivery, purpose EmailTokenPurpose) ServiceMailState { + return ServiceMailState{ + TokenFound: true, + TokenPurpose: purpose, + TokenUserID: delivery.RecipientUserID(), + TokenRegistrationVersion: 3, + TokenExpiresAt: testDeliveryCreated.Add(24 * time.Hour), + AccountRegistrationVersion: 3, + AccountEmailKey: delivery.Recipient().Normalized(), + } +} + +func TestCheckServiceMailAllowsAMailWhoseTokenAndAccountAreCurrent(t *testing.T) { + for kind, purpose := range map[MailKind]EmailTokenPurpose{ + MailKindVerification: EmailTokenPurposeEmailVerification, + MailKindPasswordReset: EmailTokenPurposePasswordReset, + } { + delivery := newTokenDelivery(t, kind) + if reason := delivery.CheckServiceMail(currentState(delivery, purpose), after(1)); reason != "" { + t.Fatalf("CheckServiceMail(%s) = %q for a current mail, want it sendable", kind, reason) + } + } +} + +func TestCheckServiceMailNamesTheFirstFailedRule(t *testing.T) { + verification := newTokenDelivery(t, MailKindVerification) + reset := newTokenDelivery(t, MailKindPasswordReset) + revokedAt := after(5) + tests := []struct { + name string + delivery Delivery + purpose EmailTokenPurpose + change func(*ServiceMailState) + at time.Time + want DeliveryCancelReason + }{ + {"token row missing", verification, EmailTokenPurposeEmailVerification, func(state *ServiceMailState) { state.TokenFound = false }, after(1), DeliveryCancelTokenMissing}, + {"reset token for a verification mail", verification, EmailTokenPurposePasswordReset, func(*ServiceMailState) {}, after(1), DeliveryCancelTokenPurposeMismatch}, + {"verification token for a reset mail", reset, EmailTokenPurposeEmailVerification, func(*ServiceMailState) {}, after(1), DeliveryCancelTokenPurposeMismatch}, + {"token of another account", verification, EmailTokenPurposeEmailVerification, func(state *ServiceMailState) { state.TokenUserID = uuid.New() }, after(1), DeliveryCancelTokenOwnerMismatch}, + {"token consumed", verification, EmailTokenPurposeEmailVerification, func(state *ServiceMailState) { state.TokenConsumedAt = after(2) }, after(3), DeliveryCancelTokenConsumed}, + {"token revoked", verification, EmailTokenPurposeEmailVerification, func(state *ServiceMailState) { state.TokenInvalidatedAt = revokedAt }, after(6), DeliveryCancelTokenRevoked}, + {"token expired at its deadline", verification, EmailTokenPurposeEmailVerification, func(*ServiceMailState) {}, testDeliveryCreated.Add(24 * time.Hour), DeliveryCancelTokenExpired}, + {"account registered again", verification, EmailTokenPurposeEmailVerification, func(state *ServiceMailState) { state.AccountRegistrationVersion = 4 }, after(1), DeliveryCancelAccountNotCurrent}, + {"address already verified", verification, EmailTokenPurposeEmailVerification, func(state *ServiceMailState) { state.AccountEmailVerified = true }, after(1), DeliveryCancelAccountNotCurrent}, + {"address of the account changed", verification, EmailTokenPurposeEmailVerification, func(state *ServiceMailState) { state.AccountEmailKey = "other@example.com" }, after(1), DeliveryCancelRecipientMismatch}, + {"reset mail to a changed address", reset, EmailTokenPurposePasswordReset, func(state *ServiceMailState) { state.AccountEmailKey = "other@example.com" }, after(1), DeliveryCancelRecipientMismatch}, + // A reset goes to a verified account, so verification state does not + // apply to it. + {"reset mail to a verified account stays sendable", reset, EmailTokenPurposePasswordReset, func(state *ServiceMailState) { state.AccountEmailVerified = true }, after(1), ""}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + state := currentState(test.delivery, test.purpose) + test.change(&state) + if got := test.delivery.CheckServiceMail(state, test.at); got != test.want { + t.Fatalf("CheckServiceMail() = %q, want %q", got, test.want) + } + }) + } +} + +func TestCheckServiceMailRefusesADeliveryWithoutATokenBinding(t *testing.T) { + // A verification mail stored without a token binding reads no token row + // from the database, so it cannot be checked. + unbound := newTestDelivery(t) + if got := unbound.CheckServiceMail(ServiceMailState{}, after(1)); got != DeliveryCancelTokenMissing { + t.Fatalf("CheckServiceMail(unbound verification) = %q, want token_missing", got) + } + // A notification is not service mail: the worker never claims it, and the + // check refuses it even when a token row is offered. + content, err := NewMailContent(MailKindNotification, "notification.v1", "s", "t\n", "") + if err != nil { + t.Fatalf("NewMailContent() error = %v", err) + } + input := testDeliveryInput(t) + input.Content = content + plain, err := NewDelivery(input) + if err != nil { + t.Fatalf("NewDelivery() error = %v", err) + } + if got := plain.CheckServiceMail(ServiceMailState{TokenFound: true}, after(1)); got != DeliveryCancelTokenMissing { + t.Fatalf("CheckServiceMail(notification) = %q, want token_missing", got) + } +} + +func TestNewDeliveryBindsOnlyTokenKindsToATokenAndKeepsItWhenRestored(t *testing.T) { + bound := newTokenDelivery(t, MailKindVerification) + if bound.EmailTokenID() != testTokenID { + t.Fatal("the delivery lost its token binding") + } + restored, err := RestoreDelivery(deliverySnapshot(bound)) + if err != nil || restored.EmailTokenID() != testTokenID { + t.Fatalf("RestoreDelivery() = %v, %v; want the binding kept", restored.EmailTokenID(), err) + } + + content, err := NewMailContent(MailKindNotification, "notification.v1", "s", "t\n", "") + if err != nil { + t.Fatalf("NewMailContent() error = %v", err) + } + input := testDeliveryInput(t) + input.Content = content + input.EmailTokenID = testTokenID + if _, err := NewDelivery(input); !errors.Is(err, ErrInvalidDelivery) { + t.Fatalf("NewDelivery(notification with a token) error = %v, want ErrInvalidDelivery", err) + } +} + +func TestCancelEndsAPendingOrWaitingDeliveryWithoutAnAttempt(t *testing.T) { + pending := newTokenDelivery(t, MailKindVerification) + waiting, err := pending.WaitForQuota(after(1), after(60)) + if err != nil { + t.Fatalf("WaitForQuota() error = %v", err) + } + for name, delivery := range map[string]Delivery{"pending": pending, "waiting_quota": waiting} { + t.Run(name, func(t *testing.T) { + cancelled, err := delivery.Cancel(after(30), DeliveryCancelTokenRevoked) + if err != nil { + t.Fatalf("Cancel() error = %v", err) + } + switch { + case cancelled.Status() != DeliveryStatusCancelled || cancelled.CancelReason() != DeliveryCancelTokenRevoked: + t.Fatalf("status = %s, reason = %q", cancelled.Status(), cancelled.CancelReason()) + case !cancelled.NextAttemptAt().IsZero() || cancelled.AttemptCount() != delivery.AttemptCount() || !cancelled.LastAttemptAt().IsZero(): + t.Fatal("a cancellation scheduled or recorded an attempt") + case cancelled.Version() != delivery.Version()+1 || !cancelled.UpdatedAt().Equal(after(30)): + t.Fatal("a cancellation did not advance the version and the update time") + case cancelled.IdempotencyKey() != delivery.IdempotencyKey() || cancelled.Content().Hash() != delivery.Content().Hash(): + t.Fatal("a cancellation changed the key or the content") + case !cancelled.Status().IsTerminal(): + t.Fatal("cancelled is not terminal") + } + if delivery.Status() == DeliveryStatusCancelled { + t.Fatal("Cancel() changed its receiver") + } + // The terminal status accepts nothing else. + if _, _, err := cancelled.RecordAttempt(DeliveryAttemptInput{At: after(31), Outcome: DeliveryOutcomeUnknown}); !errors.Is(err, ErrDeliveryTransition) { + t.Fatalf("RecordAttempt() on a cancelled delivery error = %v, want ErrDeliveryTransition", err) + } + if _, err := cancelled.WaitForQuota(after(31), time.Time{}); !errors.Is(err, ErrDeliveryTransition) { + t.Fatalf("WaitForQuota() on a cancelled delivery error = %v, want ErrDeliveryTransition", err) + } + if _, err := cancelled.Cancel(after(31), DeliveryCancelTokenExpired); !errors.Is(err, ErrDeliveryTransition) { + t.Fatalf("Cancel() on a cancelled delivery error = %v, want ErrDeliveryTransition", err) + } + restored, err := RestoreDelivery(deliverySnapshot(cancelled)) + if err != nil || restored.Status() != DeliveryStatusCancelled || restored.CancelReason() != DeliveryCancelTokenRevoked { + t.Fatalf("RestoreDelivery() = %s, %v; want the cancelled state back", restored.Status(), err) + } + }) + } +} + +func TestCancelRefusesWhatItCannotHonestlyReportAsNotSent(t *testing.T) { + unknown := mustRecord(t, newTokenDelivery(t, MailKindVerification), DeliveryAttemptInput{At: after(1), Outcome: DeliveryOutcomeUnknown}) + if _, err := unknown.Cancel(after(2), DeliveryCancelTokenRevoked); !errors.Is(err, ErrDeliveryTransition) { + t.Fatalf("Cancel() on an unknown delivery error = %v, want ErrDeliveryTransition: an earlier attempt may have been accepted", err) + } + accepted := mustRecord(t, newTokenDelivery(t, MailKindVerification), DeliveryAttemptInput{At: after(1), Outcome: DeliveryOutcomeAccepted, ProviderMessageID: testMessageID}) + if _, err := accepted.Cancel(after(2), DeliveryCancelTokenRevoked); !errors.Is(err, ErrDeliveryTransition) { + t.Fatalf("Cancel() on an accepted delivery error = %v, want ErrDeliveryTransition", err) + } + pending := newTokenDelivery(t, MailKindVerification) + if _, err := pending.Cancel(after(1), "because"); !errors.Is(err, ErrInvalidDelivery) { + t.Fatalf("Cancel() with an unknown reason error = %v, want ErrInvalidDelivery", err) + } + if _, err := pending.Cancel(testDeliveryCreated.Add(-time.Minute), DeliveryCancelTokenRevoked); !errors.Is(err, ErrInvalidDelivery) { + t.Fatalf("Cancel() before the last change error = %v, want ErrInvalidDelivery", err) + } +} + +func TestRestoreDeliveryChecksTheCancelReasonAndTheBinding(t *testing.T) { + cancelled, err := newTokenDelivery(t, MailKindVerification).Cancel(after(1), DeliveryCancelTokenExpired) + if err != nil { + t.Fatalf("Cancel() error = %v", err) + } + tests := map[string]func(*DeliverySnapshot){ + "cancelled without a reason": func(snapshot *DeliverySnapshot) { snapshot.CancelReason = "" }, + "unknown reason": func(snapshot *DeliverySnapshot) { snapshot.CancelReason = "because" }, + "reason on a pending delivery": func(snapshot *DeliverySnapshot) { + snapshot.Status, snapshot.NextAttemptAt = DeliveryStatusPending, after(5) + }, + "cancelled with a next attempt": func(snapshot *DeliverySnapshot) { snapshot.NextAttemptAt = after(5) }, + } + for name, change := range tests { + t.Run(name, func(t *testing.T) { + snapshot := deliverySnapshot(cancelled) + change(&snapshot) + if _, err := RestoreDelivery(snapshot); err == nil { + t.Fatal("RestoreDelivery() accepted a broken row") + } + }) + } + // A notification row with a token binding is not a state the schema allows. + content, err := NewMailContent(MailKindNotification, "notification.v1", "s", "t\n", "") + if err != nil { + t.Fatalf("NewMailContent() error = %v", err) + } + input := testDeliveryInput(t) + input.Content = content + plain, err := NewDelivery(input) + if err != nil { + t.Fatalf("NewDelivery() error = %v", err) + } + snapshot := deliverySnapshot(plain) + snapshot.EmailTokenID = testTokenID + if _, err := RestoreDelivery(snapshot); err == nil { + t.Fatal("RestoreDelivery() accepted a notification bound to a token") + } +} + +func TestDeliveryStatusAcceptedIsNamedForTheProviderNotThePerson(t *testing.T) { + // The only status that reports success says what happened: the provider + // accepted the message. No status claims delivery to an inbox. + for _, status := range []DeliveryStatus{DeliveryStatusPending, DeliveryStatusAccepted, DeliveryStatusRejected, DeliveryStatusUnknown, DeliveryStatusWaitingQuota, DeliveryStatusCancelled} { + if _, err := ParseDeliveryStatus(string(status)); err != nil { + t.Fatalf("ParseDeliveryStatus(%s) error = %v", status, err) + } + if strings.Contains(string(status), "deliver") || strings.Contains(string(status), "sent") { + t.Fatalf("status %q names delivery to a person", status) + } + } + if _, err := ParseDeliveryStatus("delivered"); err == nil { + t.Fatal("ParseDeliveryStatus() accepted delivered") + } +} + +func TestMailKindTokenPurposeMatchesTheKindsThatCarryAToken(t *testing.T) { + for _, kind := range []MailKind{MailKindVerification, MailKindPasswordReset, MailKindNotification} { + purpose, carries := kind.TokenPurpose() + if carries != kind.CarriesBearerToken() || (carries && purpose == "") { + t.Fatalf("TokenPurpose(%s) = %q, %t, want it to follow CarriesBearerToken", kind, purpose, carries) + } + if carries { + if _, err := ParseEmailTokenPurpose(string(purpose)); err != nil { + t.Fatalf("ParseEmailTokenPurpose(%s) error = %v", purpose, err) + } + } + } +} + +func TestRestoreRedactedMailContentKeepsOnlyTheSubjectAndTheHash(t *testing.T) { + content := testMailContent(t) + hash := content.Hash() + redacted, err := RestoreRedactedMailContent(MailKindVerification, "verification.v1", testDeliverySubject, hash[:]) + if err != nil { + t.Fatalf("RestoreRedactedMailContent() error = %v", err) + } + if !redacted.Redacted() || redacted.Text() != "" || redacted.HTML() != "" || redacted.Hash() != hash || redacted.IsZero() { + t.Fatal("redacted content keeps a body, or lost its hash") + } + if got := redacted.String(); strings.Contains(got, testDeliverySubject) { + t.Fatalf("String() = %q shows the subject", got) + } + for name, call := range map[string]func() error{ + "a notification": func() error { + _, err := RestoreRedactedMailContent(MailKindNotification, "notification.v1", "s", hash[:]) + return err + }, + "another version": func() error { + _, err := RestoreRedactedMailContent(MailKindVerification, "password_reset.v1", "s", hash[:]) + return err + }, + "a short hash": func() error { + _, err := RestoreRedactedMailContent(MailKindVerification, "verification.v1", "s", hash[:4]) + return err + }, + } { + if err := call(); !errors.Is(err, ErrInvalidMailContent) { + t.Fatalf("%s: error = %v, want ErrInvalidMailContent", name, err) + } + } + // A redacted terminal delivery restores. + cancelled, err := newTokenDelivery(t, MailKindVerification).Cancel(after(1), DeliveryCancelProcessingFailed) + if err != nil { + t.Fatalf("Cancel() error = %v", err) + } + snapshot := deliverySnapshot(cancelled) + snapshot.Content = redacted + if restored, err := RestoreDelivery(snapshot); err != nil || !restored.Content().Redacted() { + t.Fatalf("RestoreDelivery() = %v, %v; want a redacted delivery", restored.Content().Redacted(), err) + } +} + +func TestServiceMailKindsAreTheKindsThatCarryATokenAndEveryCancelReasonParses(t *testing.T) { + kinds := ServiceMailKinds() + if len(kinds) != 2 { + t.Fatalf("ServiceMailKinds() = %v, want verification and password_reset", kinds) + } + for _, kind := range kinds { + if !kind.IsServiceMail() || !kind.CarriesBearerToken() { + t.Fatalf("%s is listed as service mail but carries no token", kind) + } + } + if MailKindNotification.IsServiceMail() { + t.Fatal("a notification is service mail") + } + for _, reason := range DeliveryCancelReasons() { + if _, err := ParseDeliveryCancelReason(string(reason)); err != nil { + t.Fatalf("ParseDeliveryCancelReason(%s) error = %v", reason, err) + } + } +} diff --git a/backend/internal/domain/delivery_test.go b/backend/internal/domain/delivery_test.go index 7e6e649..324ab78 100644 --- a/backend/internal/domain/delivery_test.go +++ b/backend/internal/domain/delivery_test.go @@ -331,6 +331,8 @@ func deliverySnapshot(delivery Delivery) DeliverySnapshot { NextAttemptAt: delivery.NextAttemptAt(), LastAttemptAt: delivery.LastAttemptAt(), ProviderMessageID: delivery.ProviderMessageID(), + EmailTokenID: delivery.EmailTokenID(), + CancelReason: delivery.CancelReason(), Version: delivery.Version(), CreatedAt: delivery.CreatedAt(), UpdatedAt: delivery.UpdatedAt(), diff --git a/backend/internal/domain/email_token.go b/backend/internal/domain/email_token.go index c29924c..7d169d1 100644 --- a/backend/internal/domain/email_token.go +++ b/backend/internal/domain/email_token.go @@ -10,21 +10,26 @@ import ( var ErrInvalidEmailToken = errors.New("invalid email token") -// EmailTokenPurpose names what an email token authorizes. New purposes, such -// as a planned password reset, are added here and in the email_tokens CHECK -// constraint together. +// EmailTokenPurpose names what an email token authorizes. New purposes are +// added here and in the email_tokens CHECK constraint together. type EmailTokenPurpose string -// EmailTokenPurposeEmailVerification authorizes confirming the account email. -const EmailTokenPurposeEmailVerification EmailTokenPurpose = "email_verification" //nolint:gosec // A purpose name, not a credential. +const ( + // EmailTokenPurposeEmailVerification authorizes confirming the account + // email. + EmailTokenPurposeEmailVerification EmailTokenPurpose = "email_verification" //nolint:gosec // A purpose name, not a credential. + // EmailTokenPurposePasswordReset authorizes setting a new password. + EmailTokenPurposePasswordReset EmailTokenPurpose = "password_reset" +) // ParseEmailTokenPurpose accepts a known purpose. func ParseEmailTokenPurpose(value string) (EmailTokenPurpose, error) { - purpose := EmailTokenPurpose(value) - if purpose != EmailTokenPurposeEmailVerification { + switch purpose := EmailTokenPurpose(value); purpose { + case EmailTokenPurposeEmailVerification, EmailTokenPurposePasswordReset: + return purpose, nil + default: return "", fmt.Errorf("domain.ParseEmailTokenPurpose - unknown purpose: %w", ErrInvalidEmailToken) } - return purpose, nil } // EmailToken is the stored record of a one-time token sent by email. It holds diff --git a/backend/internal/domain/email_token_test.go b/backend/internal/domain/email_token_test.go index 5750668..08d3e43 100644 --- a/backend/internal/domain/email_token_test.go +++ b/backend/internal/domain/email_token_test.go @@ -48,7 +48,7 @@ func TestNewEmailTokenRejectsInvalidInput(t *testing.T) { } tests := map[string]func(*NewEmailTokenInput){ "nil user": func(input *NewEmailTokenInput) { input.UserID = uuid.Nil }, - "unknown purpose": func(input *NewEmailTokenInput) { input.Purpose = "password_reset" }, + "unknown purpose": func(input *NewEmailTokenInput) { input.Purpose = "something_else" }, "zero hash": func(input *NewEmailTokenInput) { input.TokenHash = SecretTokenHash{} }, "zero version": func(input *NewEmailTokenInput) { input.RegistrationVersion = 0 }, "zero issue time": func(input *NewEmailTokenInput) { input.IssuedAt = time.Time{} }, diff --git a/backend/internal/domain/mail_content.go b/backend/internal/domain/mail_content.go index 8b85028..0c5e39c 100644 --- a/backend/internal/domain/mail_content.go +++ b/backend/internal/domain/mail_content.go @@ -57,12 +57,39 @@ func ParseMailKind(value string) (MailKind, error) { } } +// ServiceMailKinds lists the kinds of service identity mail, the kinds the +// sending worker claims and sends. Notifications are not among them until +// their sending is connected (TASK-462). The delivery metrics of due mail, +// the sending worker, and the due index of the deliveries table follow this +// list; changing it changes the predicate of deliveries_due_idx too. +func ServiceMailKinds() []MailKind { + return []MailKind{MailKindVerification, MailKindPasswordReset} +} + +// IsServiceMail reports a kind of service identity mail. +func (kind MailKind) IsServiceMail() bool { return kind.CarriesBearerToken() } + // 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 } +// TokenPurpose returns the email token purpose that the link of a mail of +// this kind carries, and false for a kind without a bearer token. +func (kind MailKind) TokenPurpose() (EmailTokenPurpose, bool) { + switch kind { + case MailKindVerification: + return EmailTokenPurposeEmailVerification, true + case MailKindPasswordReset: + return EmailTokenPurposePasswordReset, true + case MailKindNotification: + return "", false + default: + return "", false + } +} + // 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 @@ -98,6 +125,9 @@ type mailContentValue struct { text string html string hash [MailContentHashSize]byte + // redacted is set for the content of a terminal token mail whose bodies + // were cleared; only the subject and the hash remain. + redacted bool } // NewMailContent validates a rendering and computes its hash. The template @@ -134,6 +164,30 @@ func RestoreMailContent(kind MailKind, templateVersion, subject, text, html stri return content, nil } +// RestoreRedactedMailContent rebuilds the content of a token mail whose bodies +// were cleared after it reached a terminal status. Nothing can be checked +// against the hash any more, so the stored hash is kept as it is; the content +// has no bodies and can never be sent. +func RestoreRedactedMailContent(kind MailKind, templateVersion, subject string, hash []byte) (MailContent, error) { + const location = "domain.RestoreRedactedMailContent" + if _, err := ParseMailKind(string(kind)); err != nil || !kind.CarriesBearerToken() { + return MailContent{}, invalidMailContent("only a token mail has redacted content") + } + if !mailTemplateVersionPattern.MatchString(templateVersion) || !strings.HasPrefix(templateVersion, string(kind)+".v") || + strings.TrimSpace(subject) == "" || utf8.RuneCountInString(subject) > maxMailSubjectRunes { + return MailContent{}, fmt.Errorf("%s - stored version or subject is invalid: %w", location, ErrInvalidMailContent) + } + if len(hash) != MailContentHashSize { + return MailContent{}, fmt.Errorf("%s - stored hash has the wrong size: %w", location, ErrInvalidMailContent) + } + value := &mailContentValue{kind: kind, templateVersion: templateVersion, subject: subject, redacted: true} + copy(value.hash[:], hash) + return MailContent{value: value}, nil +} + +// Redacted reports content whose bodies were cleared after the mail ended. +func (content MailContent) Redacted() bool { return content.read().redacted } + func validateMailContent(kind MailKind, templateVersion, subject, text, html string) error { switch { case !mailTemplateVersionPattern.MatchString(templateVersion) || !strings.HasPrefix(templateVersion, string(kind)+".v"): diff --git a/backend/internal/port/inbound/mail_sender.go b/backend/internal/port/inbound/mail_sender.go new file mode 100644 index 0000000..f697201 --- /dev/null +++ b/backend/internal/port/inbound/mail_sender.go @@ -0,0 +1,77 @@ +package inbound + +import ( + "context" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" +) + +// MailPassOutcome is what one pass of the sending worker did. The values +// are closed and safe to log and to use as a label. +type MailPassOutcome string + +const ( + // MailPassIdle: no delivery was due. + MailPassIdle MailPassOutcome = "idle" + // MailPassAccepted: the provider accepted the message. It is not + // delivery to a person. + MailPassAccepted MailPassOutcome = "accepted" + // MailPassRejected: the provider refused the message for good. + MailPassRejected MailPassOutcome = "rejected" + // MailPassRetry: the provider refused for now; the delivery is pending + // again at its scheduled time. + MailPassRetry MailPassOutcome = "retry" + // MailPassWaitingQuota: the local or the provider quota is used up; the + // delivery waits for the reset. + MailPassWaitingQuota MailPassOutcome = "waiting_quota" + // MailPassUnknown: the attempt may have reached the provider without a + // conclusive answer, or an earlier attempt that lost its worker is in + // doubt beyond the provider's idempotency window. + MailPassUnknown MailPassOutcome = "unknown" + // MailPassCancelled: the message must not be sent, and the delivery + // ended with a reason. + MailPassCancelled MailPassOutcome = "cancelled" + // MailPassChannelUnavailable: no transport is active + // (EMAIL_PROVIDER=disabled). Nothing was sent, and the delivery is left + // as it was. + MailPassChannelUnavailable MailPassOutcome = "channel_unavailable" + // MailPassInterrupted: the context ended before the request was sent. + // Nothing was sent, and the delivery is left as it was. + MailPassInterrupted MailPassOutcome = "interrupted" + // MailPassRowFailed: the worker itself failed on a delivery (not a + // provider answer); it is due again later and counted, and is cancelled + // as processing_failed after repeated failures. + MailPassRowFailed MailPassOutcome = "row_failed" + // MailPassLeaseLost: another worker recorded the result of this delivery + // first; nothing of this attempt is kept. + MailPassLeaseLost MailPassOutcome = "lease_lost" +) + +// MailPassResult is the outcome of one pass. It carries identifiers and +// closed values only, never the address or the content. +type MailPassResult struct { + Outcome MailPassOutcome + DeliveryID uuid.UUID + Kind domain.MailKind + // CancelReason is set for MailPassCancelled. + CancelReason domain.DeliveryCancelReason +} + +// MailPass runs one pass of the sending worker: it takes the next due +// delivery through the claim, the single transport call, and the stored +// result. +type MailPass interface { + // ProcessNext claims no new work once ctx ends; workCtx bounds the + // transport call and should outlive ctx by a shutdown grace. An error + // reports a database failure, after which the delivery stays under its + // lease until it expires. + ProcessNext(ctx, workCtx context.Context) (MailPassResult, error) + + // PauseFailureCounting tells the pass not to count failures of single rows + // (a failing row is still moved back, but not counted and never + // cancelled). The worker pauses it when failures hit one row after another, + // which points at a global fault, and resumes it when a pass succeeds. + PauseFailureCounting(paused bool) +} diff --git a/backend/internal/port/outbound/delivery.go b/backend/internal/port/outbound/delivery.go index be48dfc..57961a0 100644 --- a/backend/internal/port/outbound/delivery.go +++ b/backend/internal/port/outbound/delivery.go @@ -30,6 +30,21 @@ var ( // refuses it; domain.Delivery.Rebind refuses it first. ErrDeliveryProviderPinned = errors.New("delivery provider account is pinned") + // ErrNoDeliveryDue reports that ClaimDue found no delivery to send: none + // is due, every due one is held by a live lease or locked by another + // worker, or none is pinned to the configured provider account. + ErrNoDeliveryDue = errors.New("no delivery is due") + + // ErrRowFault marks a storage error that the row itself causes and that + // repeating cannot cure: a value that violates a data or integrity + // constraint (SQLSTATE classes 22 and 23). Every other storage error + // (deadlock, timeout, lost connection, resource or admin shutdown) is + // transient and says nothing about the row. + ErrRowFault = errors.New("storage refused the row") + + // ErrDeliveryUnreadable is matched by UnreadableDeliveryError. + ErrDeliveryUnreadable = errors.New("claimed delivery cannot be restored") + // 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") @@ -76,10 +91,126 @@ type DeliveryRepository interface { // 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. + // after an attempt with ErrDeliveryProviderPinned. A lease of the sending + // worker survives it. Rebind(ctx context.Context, next domain.Delivery) error + + // Cancel stores next as returned by domain.Delivery.Cancel, without an + // attempt record, under the same version rule as WaitForQuota, and ends + // the sending worker's lease. + Cancel(ctx context.Context, next domain.Delivery) error + + // ClaimDue gives the claim's owner a lease on the most overdue delivery + // it may send and returns it, or returns ErrNoDeliveryDue. A claimed row + // that cannot be restored is reported as an *UnreadableDeliveryError; + // a content hash mismatch also cancels it, so it never blocks the queue. It never + // waits for a row that another transaction holds, so concurrent callers, + // in one process or many, never claim the same delivery. The lease does + // not change the delivery's version or update time. It reads the stored + // content with the same integrity check as Get. + ClaimDue(ctx context.Context, claim DeliveryClaim) (ClaimedDelivery, error) + + // RecordClaimedAttempt is RecordAttempt that also requires owner to hold + // the delivery's lease; otherwise it writes nothing and returns + // ErrDeliveryVersionConflict. An expired lease that nobody took over still + // counts as held. + RecordClaimedAttempt(ctx context.Context, owner uuid.UUID, next domain.Delivery, attempt domain.DeliveryAttempt) error + + // LockClaimed locks the delivery row of the lease holder until the + // transaction ends and reports false when owner no longer holds the + // lease. Settlement calls it first, so that every path takes the delivery + // lock before the quota rows, as the claim does. + LockClaimed(ctx context.Context, id, owner uuid.UUID) (bool, error) + + // MarkSendStarted records, by the database clock and only the first time, + // that the first request of the claimed delivery is about to start. + MarkSendStarted(ctx context.Context, id, owner uuid.UUID) error + + // RecordFailure counts a failure of the sending worker on the delivery + // (not a provider answer), ends its lease, and makes it due again at + // nextAttemptAt. After maxFailures consecutive failures it cancels the + // delivery with domain.DeliveryCancelProcessingFailed instead and reports + // cancelled. A delivery that is no longer pending or waiting is left + // alone. + // + // owner is the caller's lease owner: the row is left alone when another + // worker holds a live lease on it. With countFailure false the failure is + // not counted and the row is never cancelled; it only moves back by + // nextAttemptAt and its lease ends. + RecordFailure(ctx context.Context, id, owner uuid.UUID, at, nextAttemptAt time.Time, maxFailures int32, countFailure bool) (cancelled bool, err error) + + // ReleaseClaim ends the lease of owner on the delivery without changing + // it. It reports false when owner no longer holds the delivery: the lease + // expired and another worker took it, or it finished. + ReleaseClaim(ctx context.Context, id uuid.UUID, owner uuid.UUID) (bool, error) + + // ServiceMailState reads the token the delivery is bound to and the + // recipient account right now, for the check before a service mail is + // sent. It locks nothing. It returns ErrDeliveryNotFound when the + // delivery does not exist. + ServiceMailState(ctx context.Context, id uuid.UUID) (domain.ServiceMailState, error) } +// DeliveryClaim selects and leases the next delivery for a sending worker. +type DeliveryClaim struct { + // Owner identifies the worker; a lease belongs to it. + Owner uuid.UUID + // Account is the configured provider account. Only deliveries pinned to + // it are claimed, because a delivery sent through another account would + // bypass its quota and idempotency window. + Account domain.MailProviderAccount + // RebindProvider is the provider name whose deliveries may be claimed + // before their first attempt although they are pinned elsewhere, so the + // caller can move them with domain.Delivery.Rebind; empty for none. It is + // the disabled transport: mail stored while no transport ran. + RebindProvider string + // Kinds lists the kinds to send. Mail of other kinds is never claimed. + Kinds []domain.MailKind + // Now is the application clock reading: due times and lease expiry are + // compared with it. + Now time.Time + // Lease is how long the claim holds the delivery. + Lease time.Duration +} + +// ClaimedDelivery is a delivery under the lease of its claim. +type ClaimedDelivery struct { + Delivery domain.Delivery + // PreviousClaimedUntil is the deadline of the lease that a worker held + // and let expire without finishing, so an attempt may be in doubt; zero + // when no worker held the delivery before. + PreviousClaimedUntil time.Time + // SinceFirstSend is how long ago, by the database clock, the first + // request of the delivery started; meaningful only when FirstSendStarted. + // The provider keeps the idempotency key for a window counted from then. + SinceFirstSend time.Duration + FirstSendStarted bool + // FailureCount is the number of consecutive failures of the worker on + // this delivery so far. + FailureCount int32 +} + +// UnreadableDeliveryError reports that ClaimDue claimed a delivery whose +// stored row cannot be restored. When the content no longer matches its hash +// ClaimDue has cancelled the row in the caller's transaction (status +// cancelled, reason content_invalid, Cancelled set), so it does not block the +// queue; the caller commits that and reports it. Any other cause may be +// transient, so the row is left as it was and the caller records a failure of +// the row (RecordFailure). Err names the broken rule and never quotes the +// row. It matches ErrDeliveryUnreadable. +type UnreadableDeliveryError struct { + DeliveryID uuid.UUID + FailureCount int32 + Cancelled bool + Err error +} + +func (err *UnreadableDeliveryError) Error() string { + return "delivery " + err.DeliveryID.String() + " cannot be restored: " + err.Err.Error() +} + +func (err *UnreadableDeliveryError) Unwrap() []error { return []error{ErrDeliveryUnreadable, err.Err} } + // DeliveryStatusSnapshot is the state of a delivery without its recipient // address or content. A zero NextAttemptAt means none is scheduled. type DeliveryStatusSnapshot struct { diff --git a/backend/internal/port/outbound/delivery_statistics.go b/backend/internal/port/outbound/delivery_statistics.go index 3de9fdc..f6f0cbd 100644 --- a/backend/internal/port/outbound/delivery_statistics.go +++ b/backend/internal/port/outbound/delivery_statistics.go @@ -21,8 +21,10 @@ type DeliveryStatistics struct { // Counts has one entry per kind and status that has deliveries. Counts []DeliveryStatusCount // EarliestPendingAttemptAt is the earliest NextAttemptAt of a pending - // delivery, by the application clock that wrote it; zero without - // pending deliveries. + // service mail delivery (domain.ServiceMailKinds, the kinds a worker + // sends), by the application clock that wrote it; zero without one. A + // notification waits for its sending to be connected (TASK-462) and is + // not counted, so it never looks overdue. EarliestPendingAttemptAt time.Time } diff --git a/backend/internal/usecase/notification/delivery_status.go b/backend/internal/usecase/notification/delivery_status.go index 7c1db61..570f98f 100644 --- a/backend/internal/usecase/notification/delivery_status.go +++ b/backend/internal/usecase/notification/delivery_status.go @@ -23,9 +23,13 @@ import ( // time is not known yet"; // - pending and unknown: "your email is being sent". unknown is not shown // as a failure: the message may have been accepted; -// - accepted: "your email was sent". It means that the provider accepted -// it, not that it reached the inbox; -// - rejected: "your email could not be sent". +// - accepted: "your email was handed to the email provider, which +// accepted it". It is acceptance by the provider, not delivery to the +// person: nothing confirms that it reached the inbox, and the text must +// not say so; +// - rejected: "your email could not be sent"; +// - cancelled: "your email was not sent because its link is no longer +// valid; request a new one". type UserDeliveryStatus struct { Kind domain.MailKind Status domain.DeliveryStatus diff --git a/backend/internal/usecase/notification/mail_request.go b/backend/internal/usecase/notification/mail_request.go index f1d1510..fe7f957 100644 --- a/backend/internal/usecase/notification/mail_request.go +++ b/backend/internal/usecase/notification/mail_request.go @@ -6,8 +6,13 @@ // 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. +// Delivery, and deletes the request. Sending notifications is planned +// (TASK-462); no worker claims them yet. +// +// Service mail of the account flows (email verification and password reset) +// takes a shorter path: ServiceMailer stores its delivery directly in the +// transaction that issues the token, bound to that token, and +// ServiceMailSender (service_sender.go) claims, checks, and sends it. package notification import ( @@ -51,6 +56,13 @@ type NotificationRenderer interface { RenderNotification(data mailtemplate.NotificationData) (domain.MailContent, error) } +// ServiceMailRenderer renders the service mail of the account flows, which +// carry a one-time token in their link, as the content a delivery stores. +type ServiceMailRenderer interface { + RenderVerification(data mailtemplate.VerificationData) (domain.MailContent, error) + RenderPasswordReset(data mailtemplate.PasswordResetData) (domain.MailContent, error) +} + // TemplateRenderer renders with the current versions of the embedded mail // templates. type TemplateRenderer struct { @@ -73,6 +85,30 @@ func (renderer TemplateRenderer) RenderNotification(data mailtemplate.Notificati return content, nil } +func (renderer TemplateRenderer) RenderVerification(data mailtemplate.VerificationData) (domain.MailContent, error) { + rendered, err := renderer.renderer.RenderVerification(data) + if err != nil { + return domain.MailContent{}, fmt.Errorf("TemplateRenderer.RenderVerification - render: %w", err) + } + content, err := rendered.Content() + if err != nil { + return domain.MailContent{}, fmt.Errorf("TemplateRenderer.RenderVerification - convert rendering: %w", err) + } + return content, nil +} + +func (renderer TemplateRenderer) RenderPasswordReset(data mailtemplate.PasswordResetData) (domain.MailContent, error) { + rendered, err := renderer.renderer.RenderPasswordReset(data) + if err != nil { + return domain.MailContent{}, fmt.Errorf("TemplateRenderer.RenderPasswordReset - render: %w", err) + } + content, err := rendered.Content() + if err != nil { + return domain.MailContent{}, fmt.Errorf("TemplateRenderer.RenderPasswordReset - convert rendering: %w", err) + } + return content, nil +} + // NotificationRequest asks for one notification mail to one account. type NotificationRequest struct { RecipientUserID uuid.UUID diff --git a/backend/internal/usecase/notification/quota.go b/backend/internal/usecase/notification/quota.go index eedefb5..dbe1185 100644 --- a/backend/internal/usecase/notification/quota.go +++ b/backend/internal/usecase/notification/quota.go @@ -40,8 +40,8 @@ var ( // is used up: the delivery waits for the reset in waiting_quota, and an // operator may decide otherwise. // -// The sending worker (TASK-016) uses it in two transactions around one -// transport call: +// The sending worker (ServiceMailSender, TASK-016) uses it in two +// transactions around one transport call: // // 1. PrepareSend in the transaction that claims a due delivery. It either // returns a permit, or parks the delivery in waiting_quota until the @@ -82,6 +82,9 @@ type QuotaPermit struct { reused bool } +// IdempotencyWindow returns the window the gate was built with. +func (gate *QuotaGate) IdempotencyWindow() time.Duration { return gate.idempotencyWindow } + func (permit QuotaPermit) IsZero() bool { return permit.reservation.ID == uuid.Nil } // Reused reports a permit that continues the open reservation of an earlier diff --git a/backend/internal/usecase/notification/send_retry.go b/backend/internal/usecase/notification/send_retry.go new file mode 100644 index 0000000..51a4249 --- /dev/null +++ b/backend/internal/usecase/notification/send_retry.go @@ -0,0 +1,58 @@ +package notification + +import ( + "math/rand/v2" + "time" +) + +// jitterShare is the share of a retry delay that jitter may add: up to a fifth, +// so deliveries refused together do not all return in the same second, and +// the wait never exceeds a fifth over the schedule. +const jitterShare = 5 + +// RetryPolicy schedules the next attempt of a delivery whose last attempt the +// provider refused for a reason that a later attempt may overcome +// (temporary or rate_limited), and of a delivery on which the sending worker +// itself failed. It is the minimum that the delivery state machine needs, +// because a pending delivery must say when it is due; the attempt limit, the +// unknown outcome policy, and manual retries belong to TASK-017. +// +// There is no limit on provider refusals on purpose: service mail carries a +// token that expires, and the sending worker cancels the delivery with the +// reason token_expired once it does, so those retries end by themselves. +type RetryPolicy struct { + // Initial is the wait after the first refused attempt; every further + // refusal doubles it. + Initial time.Duration + // Max caps the doubling. A longer wait that the provider itself asked + // for (Retry-After) is honored as it is. + Max time.Duration + // Jitter returns a value in [0, limit] that is added to the scheduled + // delay, bounded by a fifth of it. Nil means none, which tests use to + // get exact times; RandomJitter is the production source. + Jitter func(limit time.Duration) time.Duration +} + +// RandomJitter is a uniformly random jitter source. +func RandomJitter(limit time.Duration) time.Duration { + if limit <= 0 { + return 0 + } + return rand.N(limit + 1) //nolint:gosec // Retry jitter needs no cryptographic randomness. +} + +// NextAttemptAt returns when the delivery is due again after attempt number +// attempt (counted from 1) that ended at at. retryAfter is the provider's own +// hint, zero when it gave none; the wait is never shorter than it. +func (policy RetryPolicy) NextAttemptAt(at time.Time, attempt int32, retryAfter time.Duration) time.Time { + delay := policy.Initial + for step := int32(1); step < attempt && delay < policy.Max; step++ { + delay = min(delay*2, policy.Max) + } + delay = min(delay, policy.Max) + if policy.Jitter != nil { + limit := delay / jitterShare + delay += min(max(policy.Jitter(limit), 0), limit) + } + return at.Add(max(delay, retryAfter)) +} diff --git a/backend/internal/usecase/notification/service_mail.go b/backend/internal/usecase/notification/service_mail.go new file mode 100644 index 0000000..bc52734 --- /dev/null +++ b/backend/internal/usecase/notification/service_mail.go @@ -0,0 +1,141 @@ +package notification + +import ( + "context" + "fmt" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/notification/mailtemplate" +) + +// TokenMailRequest asks for one service mail that carries a one-time token. +// +// The token record must be stored already, in the same transaction, because +// the delivery is bound to it. RawToken is the secret that goes into the link +// of the message; it exists only in memory and is stored nowhere except in +// the rendered body, which the delivery keeps until the mail is sent or +// cancelled. +type TokenMailRequest struct { + // Recipient is the address of the account now; the delivery keeps it as + // the address to send to, and the worker compares it with the account + // again before it sends. + Recipient domain.EmailAddress + Token domain.EmailToken + RawToken domain.SecretToken + // Lifetime is the validity of the token that the message states, in + // whole hours. + Lifetime domain.Hours +} + +// ServiceMailer stores service mail of the account flows (email verification +// and password reset) as deliveries, in the transaction that issues the +// token. No event or request row carries the token: the rendered body goes +// straight into the delivery, which the account's deletion removes by +// cascade. +// +// Service mail needs no consent of any purpose. It is part of the account +// flow, not a product notification, so nothing here reads the consent +// ledger; the worker checks the token and the account instead (see +// ServiceMailSender). +type ServiceMailer struct { + renderer ServiceMailRenderer + account domain.MailProviderAccount + clock func() time.Time +} + +// NewServiceMailer pins new deliveries to account, the transport and account +// configured when the mail is requested. clock is the application clock for +// the creation time. +func NewServiceMailer(renderer ServiceMailRenderer, account domain.MailProviderAccount, clock func() time.Time) *ServiceMailer { + return &ServiceMailer{renderer: renderer, account: account, clock: clock} +} + +// EnqueueVerification stores the email verification message for request.Token +// through unit, which must be the caller's transaction, and returns the +// delivery ID. The delivery ID is the token ID, so repeating the call for +// the same token stores nothing new. The mail is sent only if the +// transaction commits and the token is still current when the worker gets +// to it. +func (mailer *ServiceMailer) EnqueueVerification(ctx context.Context, unit outbound.UnitOfWork, request TokenMailRequest) (uuid.UUID, error) { + const location = "ServiceMailer.EnqueueVerification" + if err := checkTokenMailRequest(location, request, domain.EmailTokenPurposeEmailVerification); err != nil { + return uuid.Nil, err + } + content, err := mailer.renderer.RenderVerification(mailtemplate.VerificationData{Token: request.RawToken, TokenLifetime: request.Lifetime}) + if err != nil { + return uuid.Nil, fmt.Errorf("%s - render message: %w", location, err) + } + return mailer.store(ctx, unit, location, request, content) +} + +// EnqueuePasswordReset stores the password reset message for request.Token; +// see EnqueueVerification. +func (mailer *ServiceMailer) EnqueuePasswordReset(ctx context.Context, unit outbound.UnitOfWork, request TokenMailRequest) (uuid.UUID, error) { + const location = "ServiceMailer.EnqueuePasswordReset" + if err := checkTokenMailRequest(location, request, domain.EmailTokenPurposePasswordReset); err != nil { + return uuid.Nil, err + } + content, err := mailer.renderer.RenderPasswordReset(mailtemplate.PasswordResetData{Token: request.RawToken, TokenLifetime: request.Lifetime}) + if err != nil { + return uuid.Nil, fmt.Errorf("%s - render message: %w", location, err) + } + return mailer.store(ctx, unit, location, request, content) +} + +func (mailer *ServiceMailer) store( + ctx context.Context, + unit outbound.UnitOfWork, + location string, + request TokenMailRequest, + content domain.MailContent, +) (uuid.UUID, error) { + delivery, err := domain.NewDelivery(domain.NewDeliveryInput{ + ID: request.Token.ID, + RecipientUserID: request.Token.UserID, + Recipient: request.Recipient, + Content: content, + ProviderAccount: mailer.account, + EmailTokenID: request.Token.ID, + CreatedAt: mailer.clock(), + }) + if err != nil { + return uuid.Nil, fmt.Errorf("%s - build delivery: %w", location, err) + } + created, err := unit.Deliveries().Create(ctx, delivery) + if err != nil { + return uuid.Nil, fmt.Errorf("%s - store delivery: %w", location, err) + } + if !created { + // The same token was enqueued before; the stored message stays as it + // is, because a retry under the same idempotency key must repeat the + // same body. + existing, err := unit.Deliveries().Get(ctx, request.Token.ID) + if err != nil { + return uuid.Nil, fmt.Errorf("%s - read existing delivery: %w", location, err) + } + if existing.RecipientUserID() != request.Token.UserID || existing.Kind() != content.Kind() { + return uuid.Nil, fmt.Errorf("%s - a delivery for another recipient or kind has the token ID: %w", location, domain.ErrInvalidDelivery) + } + } + return request.Token.ID, nil +} + +// checkTokenMailRequest refuses a request whose token is not of the purpose +// the message needs or has no ID, before anything is rendered. +func checkTokenMailRequest(location string, request TokenMailRequest, purpose domain.EmailTokenPurpose) error { + switch { + case request.Token.ID == uuid.Nil || request.Token.UserID == uuid.Nil: + return fmt.Errorf("%s - token must be built by domain.NewEmailToken: %w", location, domain.ErrInvalidEmailToken) + case request.Token.Purpose != purpose: + return fmt.Errorf("%s - token purpose does not match the message: %w", location, domain.ErrInvalidEmailToken) + case request.RawToken.IsZero(): + return fmt.Errorf("%s - raw token must be set: %w", location, domain.ErrInvalidEmailToken) + case request.Recipient.IsZero(): + return fmt.Errorf("%s - recipient must be set: %w", location, domain.ErrInvalidDelivery) + } + return nil +} diff --git a/backend/internal/usecase/notification/service_mail_test.go b/backend/internal/usecase/notification/service_mail_test.go new file mode 100644 index 0000000..31352be --- /dev/null +++ b/backend/internal/usecase/notification/service_mail_test.go @@ -0,0 +1,138 @@ +package notification + +import ( + "errors" + "strings" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/usecase/notification/mailtemplate" +) + +type serviceMailHarness struct { + mailer *ServiceMailer + unit fakeUnit + user uuid.UUID +} + +func newServiceMailHarness(t *testing.T) *serviceMailHarness { + t.Helper() + renderer, err := mailtemplate.NewRenderer(testOrigin) + if err != nil { + t.Fatalf("NewRenderer() error = %v", err) + } + return &serviceMailHarness{ + mailer: NewServiceMailer(NewTemplateRenderer(renderer), testAccount(t, "resend"), func() time.Time { return testNow }), + unit: fakeUnit{deliveries: &fakeDeliveries{stored: make(map[uuid.UUID]domain.Delivery)}}, + user: uuid.MustParse("01926f3a-7c00-7000-8000-0000000000bb"), + } +} + +func (h *serviceMailHarness) request(t *testing.T, purpose domain.EmailTokenPurpose) TokenMailRequest { + t.Helper() + raw, err := domain.NewSecretToken() + if err != nil { + t.Fatalf("NewSecretToken() error = %v", err) + } + token, err := domain.NewEmailToken(domain.NewEmailTokenInput{ + UserID: h.user, Purpose: purpose, TokenHash: raw.Hash(), RegistrationVersion: 1, IssuedAt: testNow, Lifetime: 24 * time.Hour, + }) + if err != nil { + t.Fatalf("NewEmailToken() error = %v", err) + } + recipient, err := domain.NewEmailAddress(testRecipientAddress) + if err != nil { + t.Fatalf("NewEmailAddress() error = %v", err) + } + return TokenMailRequest{Recipient: recipient, Token: token, RawToken: raw, Lifetime: 24} +} + +func TestServiceMailerStoresATokenBoundDeliveryUnderTheTokenID(t *testing.T) { + h := newServiceMailHarness(t) + for name, test := range map[string]struct { + purpose domain.EmailTokenPurpose + enqueue func(*ServiceMailer, TokenMailRequest) (uuid.UUID, error) + kind domain.MailKind + path string + }{ + "verification": {domain.EmailTokenPurposeEmailVerification, func(mailer *ServiceMailer, request TokenMailRequest) (uuid.UUID, error) { + return mailer.EnqueueVerification(t.Context(), h.unit, request) + }, domain.MailKindVerification, "/verify-email"}, + "password reset": {domain.EmailTokenPurposePasswordReset, func(mailer *ServiceMailer, request TokenMailRequest) (uuid.UUID, error) { + return mailer.EnqueuePasswordReset(t.Context(), h.unit, request) + }, domain.MailKindPasswordReset, "/reset-password"}, + } { + t.Run(name, func(t *testing.T) { + request := h.request(t, test.purpose) + id, err := test.enqueue(h.mailer, request) + if err != nil { + t.Fatalf("enqueue error = %v", err) + } + if id != request.Token.ID { + t.Fatalf("delivery ID = %s, want the token ID %s", id, request.Token.ID) + } + stored := h.unit.deliveries.stored[id] + switch { + case stored.Kind() != test.kind || stored.EmailTokenID() != request.Token.ID: + t.Fatalf("delivery is %s bound to %s", stored.Kind(), stored.EmailTokenID()) + case stored.Status() != domain.DeliveryStatusPending || !stored.NextAttemptAt().Equal(testNow): + t.Fatalf("delivery is %s due %s, want pending and due now", stored.Status(), stored.NextAttemptAt()) + case stored.RecipientUserID() != h.user || stored.ProviderAccount() != testAccount(t, "resend"): + t.Fatal("the delivery is not addressed to the token's account on the configured provider account") + } + // The token travels in the fragment of the link, never in the + // path or the query, where an access log would record it. + link := testOrigin + test.path + "#token=" + request.RawToken.Reveal() + if !strings.Contains(stored.Content().Text(), link) || !strings.Contains(stored.Content().HTML(), link) { + t.Fatal("the stored message lacks the link with the token in its fragment") + } + if strings.Contains(stored.Content().Text(), "?token=") || strings.Contains(stored.Content().Text(), test.path+"/") { + t.Fatal("the token is outside the fragment") + } + }) + } +} + +func TestServiceMailerRepeatsAreHarmless(t *testing.T) { + h := newServiceMailHarness(t) + request := h.request(t, domain.EmailTokenPurposeEmailVerification) + first, err := h.mailer.EnqueueVerification(t.Context(), h.unit, request) + if err != nil { + t.Fatalf("first EnqueueVerification() error = %v", err) + } + second, err := h.mailer.EnqueueVerification(t.Context(), h.unit, request) + if err != nil || second != first || len(h.unit.deliveries.stored) != 1 { + t.Fatalf("second EnqueueVerification() = %s, %v with %d deliveries; want the same delivery", second, err, len(h.unit.deliveries.stored)) + } +} + +func TestServiceMailerRefusesAWrongTokenBeforeRendering(t *testing.T) { + h := newServiceMailHarness(t) + reset := h.request(t, domain.EmailTokenPurposePasswordReset) + if _, err := h.mailer.EnqueueVerification(t.Context(), h.unit, reset); !errors.Is(err, domain.ErrInvalidEmailToken) { + t.Fatalf("EnqueueVerification(reset token) error = %v, want ErrInvalidEmailToken", err) + } + verification := h.request(t, domain.EmailTokenPurposeEmailVerification) + if _, err := h.mailer.EnqueuePasswordReset(t.Context(), h.unit, verification); !errors.Is(err, domain.ErrInvalidEmailToken) { + t.Fatalf("EnqueuePasswordReset(verification token) error = %v, want ErrInvalidEmailToken", err) + } + for name, change := range map[string]func(*TokenMailRequest){ + "no token ID": func(request *TokenMailRequest) { request.Token = domain.EmailToken{} }, + "no raw token": func(request *TokenMailRequest) { request.RawToken = domain.SecretToken{} }, + "no recipient": func(request *TokenMailRequest) { request.Recipient = domain.EmailAddress{} }, + "zero lifetime": func(request *TokenMailRequest) { request.Lifetime = 0 }, + "lifetime >7d": func(request *TokenMailRequest) { request.Lifetime = 24 * 8 }, + } { + request := h.request(t, domain.EmailTokenPurposeEmailVerification) + change(&request) + if _, err := h.mailer.EnqueueVerification(t.Context(), h.unit, request); err == nil { + t.Fatalf("%s: EnqueueVerification() accepted the request", name) + } + } + if len(h.unit.deliveries.stored) != 0 { + t.Fatal("a refused request stored a delivery") + } +} diff --git a/backend/internal/usecase/notification/service_sender.go b/backend/internal/usecase/notification/service_sender.go new file mode 100644 index 0000000..a83c10e --- /dev/null +++ b/backend/internal/usecase/notification/service_sender.go @@ -0,0 +1,725 @@ +package notification + +import ( + "context" + "errors" + "fmt" + "log/slog" + "sync/atomic" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/inbound" + "lincodex/backend/internal/port/outbound" +) + +const ( + // settleAttempts bounds how often the transaction that stores a send + // result is repeated after a database failure. The provider answer lives + // only in memory until it is stored, so one failure should not lose it. + settleAttempts = 3 + // settleRetryDelay separates two attempts to store a send result. + settleRetryDelay = 200 * time.Millisecond +) + +// dedupSafetyMargin is taken off the provider's idempotency window before it +// is compared with the age of the first request: clocks of the provider and the +// database differ a little, and a key about to expire is as good as expired. +const dedupSafetyMargin = time.Hour + +// errLeaseLost reports a result that another worker recorded first: the +// settlement transaction is rolled back and nothing of this attempt is kept. +var errLeaseLost = errors.New("delivery was recorded by another worker") + +// ServiceMailSenderSettings are the named limits of the sending worker. +type ServiceMailSenderSettings struct { + // Account is the configured provider account. The sender claims only + // deliveries pinned to it, and moves deliveries stored while no + // transport ran onto it. + Account domain.MailProviderAccount + // RebindProvider is the provider name whose deliveries, before their + // first attempt, are moved onto Account: the disabled transport. Empty + // for none. + RebindProvider string + // Lease is how long a claimed delivery belongs to this sender, measured by + // the database clock. Claim, the call, and the settlement all fit inside + // it: the call is bounded by what is left of the lease after the claim and + // the settlement budget. + Lease time.Duration + // StoreTimeout bounds the claim transaction, the check before the send, + // and each try to store a result. + StoreTimeout time.Duration + // SettleBudget bounds the whole of storing a send result, retries + // included; it is reserved inside the lease. + SettleBudget time.Duration + // ShutdownSettleBudget replaces SettleBudget when shutdown has begun, so + // the process stops within its shutdown timeout. + ShutdownSettleBudget time.Duration + // MaxFailures is how many consecutive failures of the worker itself on one + // delivery are retried before the delivery is cancelled with the reason + // processing_failed. + MaxFailures int32 + Retry RetryPolicy +} + +func (settings ServiceMailSenderSettings) validate() error { + switch { + case settings.Account.IsZero(): + return errors.New("notification.NewServiceMailSender - provider account must be set") + case settings.Lease <= 0 || settings.StoreTimeout <= 0 || settings.SettleBudget <= 0 || settings.ShutdownSettleBudget <= 0 || settings.MaxFailures < 1: + return errors.New("notification.NewServiceMailSender - lease, timeouts, and settle budgets must be positive and the failure limit at least 1") + case settings.SettleBudget >= settings.Lease: + return errors.New("notification.NewServiceMailSender - the settle budget must be shorter than the lease") + case settings.Retry.Initial <= 0 || settings.Retry.Max < settings.Retry.Initial: + return errors.New("notification.NewServiceMailSender - retry delays must be positive and the maximum not below the initial delay") + } + return nil +} + +// ServiceMailSender sends the service mail of the account flows (email +// verification and password reset) that ServiceMailer stored. Several +// senders may run against one database, in one process or many. +// +// One pass takes one delivery through three steps: +// +// 1. Claim transaction: ClaimDue leases the most overdue due delivery with +// FOR UPDATE SKIP LOCKED, so no two senders hold the same one. The +// token and the account are checked (domain.Delivery.CheckServiceMail); +// a mail that must not go out is cancelled with a reason. Otherwise +// QuotaGate.PrepareSend reserves the quota, or parks the delivery in +// waiting_quota. The transaction commits before the transport is called, +// so a slow provider never holds a row lock. +// 2. One call to MailSender.Send with the stored content and the stable +// idempotency key. The sender never retries: a failed attempt becomes the +// delivery's next state and due time. +// 3. Settlement transaction: QuotaGate.SettleSend and +// DeliveryRepository.RecordAttempt in one transaction. The attempt is +// recorded over the delivery's version, so of two senders that both +// reached this step only the first is kept. +// +// A sender that stops after the claim leaves its lease to expire; another +// sender then claims the delivery and calls the provider with the same +// idempotency key, which the provider answers with the original result +// instead of sending twice, and the quota gate reuses the open reservation. +// Past the provider's idempotency window the earlier attempt is in doubt, +// so the delivery is recorded as unknown instead of being sent again. +// +// Logs and results name a delivery only by its ID, never by address or +// content. +type ServiceMailSender struct { + owner uuid.UUID + // countingPaused stops counting failures of single rows; see + // PauseFailureCounting. + countingPaused atomic.Bool + transactor outbound.Transactor + sender outbound.MailSender + gate *QuotaGate + settings ServiceMailSenderSettings + clock func() time.Time + logger *slog.Logger +} + +// NewServiceMailSender builds a sender with a random lease owner ID. gate +// must be built for settings.Account. clock is the application clock: due, +// lease, and quota decisions use it, so tests move time with a fake one. +func NewServiceMailSender( + transactor outbound.Transactor, + sender outbound.MailSender, + gate *QuotaGate, + settings ServiceMailSenderSettings, + clock func() time.Time, + logger *slog.Logger, +) (*ServiceMailSender, error) { + if err := settings.validate(); err != nil { + return nil, err + } + owner := uuid.New() + return &ServiceMailSender{ + owner: owner, + transactor: transactor, + sender: sender, + gate: gate, + settings: settings, + clock: clock, + logger: logger.With(slog.String("lease_owner", owner.String())), + }, nil +} + +// claimedSend is a delivery that passed the claim transaction and is ready to +// be sent, or the final result of a delivery the transaction already decided. +type claimedSend struct { + delivery domain.Delivery + permit QuotaPermit + // decided is set when the claim transaction ended the pass: the result + // is final and nothing is sent. + decided bool + result inbound.MailPassResult + // failureCount is the number of consecutive failures of the worker on the + // delivery before this pass. + failureCount int32 +} + +var _ inbound.MailPass = (*ServiceMailSender)(nil) + +// PauseFailureCounting implements inbound.MailPass. +func (sender *ServiceMailSender) PauseFailureCounting(paused bool) { + sender.countingPaused.Store(paused) +} + +// isRowFault reports an error that the delivery itself causes and that +// repeating cannot cure: it breaks a domain rule, cannot be restored, or is +// refused by a data or integrity constraint. Every other error (a context that +// ended, a timeout, a deadlock, a lost connection, a missing quota +// configuration) says nothing about the row, so it is never counted against +// it. +func isRowFault(err error) bool { + var unreadable *outbound.UnreadableDeliveryError + return errors.As(err, &unreadable) || + errors.Is(err, domain.ErrInvalidDelivery) || + errors.Is(err, domain.ErrDeliveryTransition) || + errors.Is(err, domain.ErrInvalidMailContent) || + errors.Is(err, domain.ErrMailContentIntegrity) || + errors.Is(err, domain.ErrInvalidEmailAddress) || + errors.Is(err, outbound.ErrRowFault) +} + +// ProcessNext runs one pass. ctx ends the claim of new work; workCtx bounds +// the transport call and should outlive ctx by a shutdown grace, so a send in +// progress is not cut off at the first sign of shutdown. An error reports a +// database failure; the delivery it concerned is left under its lease, which +// expires, or was never claimed. +func (sender *ServiceMailSender) ProcessNext(ctx, workCtx context.Context) (inbound.MailPassResult, error) { + // The lease runs by the database clock from the claim, which is later + // than this reading, so the budget below errs on the short side. + started := time.Now() + claim, err := sender.claim(ctx) + if err != nil { + return inbound.MailPassResult{}, fmt.Errorf("ServiceMailSender.ProcessNext - claim delivery: %w", err) + } + if claim.decided { + return claim.result, nil + } + if decided, err := sender.beforeSend(workCtx, claim); err != nil || decided != nil { + if err != nil { + return inbound.MailPassResult{}, fmt.Errorf("ServiceMailSender.ProcessNext - check before sending: %w", err) + } + return *decided, nil + } + delivery := claim.delivery + content := delivery.Content() + // What is left of the lease after the claim and the reserve for storing + // the answer is the most the call may take. + callBudget := sender.settings.Lease - time.Since(started) - sender.settings.SettleBudget + if callBudget <= 0 { + return sender.releaseUnsent(ctx, claim) + } + sendCtx, cancel := context.WithTimeout(workCtx, callBudget) + result, sendErr := sender.sender.Send(sendCtx, outbound.OutgoingMail{ + To: delivery.Recipient(), + Subject: content.Subject(), + TextBody: content.Text(), + HTMLBody: content.HTML(), + IdempotencyKey: delivery.IdempotencyKey(), + }) + cancel() + return sender.settle(ctx, claim, result, sendErr) +} + +// failingRow names a claimed delivery on which the claim transaction failed, +// so a failure can be recorded for it outside that transaction. +type failingRow struct { + id uuid.UUID + count int32 +} + +func (sender *ServiceMailSender) claim(ctx context.Context) (claimedSend, error) { + var claim claimedSend + var failing *failingRow + claimCtx, cancel := context.WithTimeout(ctx, sender.settings.StoreTimeout) + defer cancel() + err := sender.transactor.WithinTransaction(claimCtx, func(ctx context.Context, unit outbound.UnitOfWork) error { + now := sender.clock() + claimed, err := unit.Deliveries().ClaimDue(ctx, outbound.DeliveryClaim{ + Owner: sender.owner, + Account: sender.settings.Account, + RebindProvider: sender.settings.RebindProvider, + Kinds: domain.ServiceMailKinds(), + Now: now, + Lease: sender.settings.Lease, + }) + if errors.Is(err, outbound.ErrNoDeliveryDue) { + claim = claimedSend{decided: true, result: inbound.MailPassResult{Outcome: inbound.MailPassIdle}} + return nil + } + var unreadable *outbound.UnreadableDeliveryError + if errors.As(err, &unreadable) { + if unreadable.Cancelled { + // The store cancelled the broken row; committing keeps it + // from blocking the queue. Its content is left as it is for + // an operator. + sender.logger.ErrorContext(ctx, "a due delivery does not match its content hash and was cancelled; an operator should inspect it", + slog.String("delivery_id", unreadable.DeliveryID.String()), + slog.String("reason", string(domain.DeliveryCancelContentInvalid))) + claim = claimedSend{decided: true, result: inbound.MailPassResult{ + Outcome: inbound.MailPassCancelled, + DeliveryID: unreadable.DeliveryID, + CancelReason: domain.DeliveryCancelContentInvalid, + }} + return nil + } + failing = &failingRow{id: unreadable.DeliveryID, count: unreadable.FailureCount} + return fmt.Errorf("claim due delivery: %w", err) + } + if err != nil { + return fmt.Errorf("claim due delivery: %w", err) + } + failing = &failingRow{id: claimed.Delivery.ID(), count: claimed.FailureCount} + claim, err = sender.prepare(ctx, unit, claimed, now) + if err != nil { + return err + } + failing = nil + claim.failureCount = claimed.FailureCount + return nil + }) + if err != nil { + // The transaction rolled back, and with it the lease: the same row + // would be claimed again and fail again, and every delivery behind + // it would wait. Record the failure in a transaction of its own so + // the row moves back in the queue. + if failing != nil && ctx.Err() == nil && isRowFault(err) { + if result, recordErr := sender.recordRowFailure(ctx, *failing, err); recordErr == nil { + return claimedSend{decided: true, result: result}, nil + } + } + return claimedSend{}, err + } + return claim, nil +} + +// recordRowFailure counts a failure of the worker on a delivery in a short +// transaction of its own and makes the row due later by the retry schedule; +// after MaxFailures it cancels the row with processing_failed. +func (sender *ServiceMailSender) recordRowFailure(ctx context.Context, failing failingRow, cause error) (inbound.MailPassResult, error) { + var cancelled bool + recordCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), sender.settings.StoreTimeout) + defer cancel() + err := sender.transactor.WithinTransaction(recordCtx, func(ctx context.Context, unit outbound.UnitOfWork) error { + now := sender.clock() + var err error + cancelled, err = unit.Deliveries().RecordFailure(ctx, failing.id, sender.owner, now, + sender.settings.Retry.NextAttemptAt(now, failing.count+1, 0), sender.settings.MaxFailures, !sender.countingPaused.Load()) + return err + }) + if err != nil { + return inbound.MailPassResult{}, fmt.Errorf("record failure: %w", err) + } + // The cause is a wrapped chain of rules and sentinels; it never quotes + // the row. + sender.logger.ErrorContext(ctx, "the sending worker failed on a delivery; it is retried later and cancelled after repeated failures", + slog.String("delivery_id", failing.id.String()), + slog.Int("consecutive_failures", int(failing.count)+1), + slog.Bool("cancelled", cancelled), + slog.Any("error", cause)) + if cancelled { + return inbound.MailPassResult{Outcome: inbound.MailPassCancelled, DeliveryID: failing.id, CancelReason: domain.DeliveryCancelProcessingFailed}, nil + } + return inbound.MailPassResult{Outcome: inbound.MailPassRowFailed, DeliveryID: failing.id}, nil +} + +// beforeSend runs right before the transport is called: it takes the delivery +// lock, reads the token and the account again, so a revocation after the claim +// committed is honored, and notes the start of the first request. A mail that +// is no longer valid is cancelled and its reservation given back. +func (sender *ServiceMailSender) beforeSend(ctx context.Context, claim claimedSend) (*inbound.MailPassResult, error) { + var decided *inbound.MailPassResult + checkCtx, cancel := context.WithTimeout(ctx, sender.settings.StoreTimeout) + defer cancel() + err := sender.transactor.WithinTransaction(checkCtx, func(ctx context.Context, unit outbound.UnitOfWork) error { + delivery := claim.delivery + held, err := unit.Deliveries().LockClaimed(ctx, delivery.ID(), sender.owner) + if err != nil { + return fmt.Errorf("lock delivery: %w", err) + } + if !held { + result := resultOf(inbound.MailPassLeaseLost, delivery) + decided = &result + return nil + } + state, err := unit.Deliveries().ServiceMailState(ctx, delivery.ID()) + if err != nil { + return fmt.Errorf("read token and account: %w", err) + } + now := sender.clock() + if reason := delivery.CheckServiceMail(state, now); reason != "" { + if _, err := sender.gate.SettleSend(ctx, unit, claim.permit, outbound.SendResult{}, errNotSent); err != nil { + return fmt.Errorf("give the reservation back: %w", err) + } + cancelled, err := sender.cancel(ctx, unit, delivery, now, reason) + if err != nil { + return err + } + decided = &cancelled.result + return nil + } + if err := unit.Deliveries().MarkSendStarted(ctx, delivery.ID(), sender.owner); err != nil { + return fmt.Errorf("mark send started: %w", err) + } + return nil + }) + if err != nil { + return nil, err + } + return decided, nil +} + +// errNotSent stands for "the message did not leave the process" when a +// reservation is given back before the transport was called. +var errNotSent = errors.New("message was not sent") + +// releaseUnsent gives a claimed delivery back when no time is left to call +// the transport, and the reservation with it. +func (sender *ServiceMailSender) releaseUnsent(ctx context.Context, claim claimedSend) (inbound.MailPassResult, error) { + return sender.settle(ctx, claim, outbound.SendResult{}, context.DeadlineExceeded) +} + +// prepare decides what a claimed delivery needs before the transport is +// called, in the claim transaction. +func (sender *ServiceMailSender) prepare(ctx context.Context, unit outbound.UnitOfWork, claimed outbound.ClaimedDelivery, now time.Time) (claimedSend, error) { + delivery := claimed.Delivery + if delivery.ProviderAccount() != sender.settings.Account { + // Mail stored while no transport ran has no attempt, so no provider + // holds its idempotency key and the account may change. + rebound, err := delivery.Rebind(latest(now, delivery.UpdatedAt()), sender.settings.Account) + if err != nil { + return claimedSend{}, fmt.Errorf("rebind delivery: %w", err) + } + if err := unit.Deliveries().Rebind(ctx, rebound); err != nil { + return claimedSend{}, fmt.Errorf("store rebound delivery: %w", err) + } + delivery = rebound + } + if sender.abandonedBeyondDeduplication(claimed) { + return sender.recordInDoubt(ctx, unit, delivery, now) + } + state, err := unit.Deliveries().ServiceMailState(ctx, delivery.ID()) + if err != nil { + return claimedSend{}, fmt.Errorf("read token and account: %w", err) + } + if reason := delivery.CheckServiceMail(state, now); reason != "" { + return sender.cancel(ctx, unit, delivery, now, reason) + } + decision, err := sender.gate.PrepareSend(ctx, unit, delivery) + if err != nil { + return claimedSend{}, fmt.Errorf("prepare send: %w", err) + } + if !decision.Proceed() { + return claimedSend{decided: true, result: resultOf(inbound.MailPassWaitingQuota, decision.Delivery)}, nil + } + return claimedSend{delivery: decision.Delivery, permit: decision.Permit}, nil +} + +// abandonedBeyondDeduplication reports a delivery whose earlier sender let its +// lease expire after it had started the first request, and so long ago that +// the provider may have forgotten the idempotency key: repeating the request +// could send the mail twice. The provider keeps the key for its window from +// the first request, so the age is counted from there, by the database clock, +// however often the delivery was claimed since and whatever the lease is, +// less a safety margin. A transport without provider-side deduplication +// (window zero) never repeats a request that may have been sent. A lease +// that never reached the request leaves nothing in doubt. +func (sender *ServiceMailSender) abandonedBeyondDeduplication(claimed outbound.ClaimedDelivery) bool { + if claimed.PreviousClaimedUntil.IsZero() || !claimed.FirstSendStarted { + return false + } + window := sender.gate.IdempotencyWindow() + if window <= 0 { + return true + } + return claimed.SinceFirstSend >= max(window-dedupSafetyMargin, 0) +} + +// recordInDoubt records the lost attempt as unknown, without a next attempt, +// so an operator decides; it is never treated as not sent. +func (sender *ServiceMailSender) recordInDoubt(ctx context.Context, unit outbound.UnitOfWork, delivery domain.Delivery, now time.Time) (claimedSend, error) { + next, attempt, err := delivery.RecordAttempt(domain.DeliveryAttemptInput{ + At: latest(now, delivery.UpdatedAt()), + Outcome: domain.DeliveryOutcomeUnknown, + }) + if err != nil { + return claimedSend{}, fmt.Errorf("record lost attempt: %w", err) + } + if err := unit.Deliveries().RecordClaimedAttempt(ctx, sender.owner, next, attempt); err != nil { + return claimedSend{}, fmt.Errorf("store lost attempt: %w", err) + } + sender.logger.WarnContext(ctx, "an earlier attempt of the delivery stopped without a result beyond the provider's idempotency window; the delivery is unknown and needs an operator", + slog.String("delivery_id", delivery.ID().String()), + slog.String("kind", string(delivery.Kind()))) + return claimedSend{decided: true, result: resultOf(inbound.MailPassUnknown, next)}, nil +} + +func (sender *ServiceMailSender) cancel( + ctx context.Context, + unit outbound.UnitOfWork, + delivery domain.Delivery, + now time.Time, + reason domain.DeliveryCancelReason, +) (claimedSend, error) { + cancelled, err := delivery.Cancel(latest(now, delivery.UpdatedAt()), reason) + if err != nil { + return claimedSend{}, fmt.Errorf("cancel delivery: %w", err) + } + if err := unit.Deliveries().Cancel(ctx, cancelled); err != nil { + return claimedSend{}, fmt.Errorf("store cancelled delivery: %w", err) + } + sender.logger.InfoContext(ctx, "service mail was not sent because it is no longer valid", + slog.String("delivery_id", delivery.ID().String()), + slog.String("kind", string(delivery.Kind())), + slog.String("reason", string(reason))) + return claimedSend{decided: true, result: resultOf(inbound.MailPassCancelled, cancelled)}, nil +} + +// settle stores the result of the transport call, repeating the transaction +// after a database failure: the answer lives only here until it is stored. +// When every try fails, the delivery stays under its lease; once it expires, +// another claim repeats the request under the same idempotency key. +func (sender *ServiceMailSender) settle(ctx context.Context, claim claimedSend, result outbound.SendResult, sendErr error) (inbound.MailPassResult, error) { + const location = "ServiceMailSender.settle" + result, sendErr = sender.checkedSendResult(ctx, claim.delivery, result, sendErr) + // The result is stored even when ctx ended: shutdown must not lose it. The + // whole of storing is bounded by the budget reserved inside the lease, and + // by the shorter shutdown budget once shutdown has begun, so the process + // stops within its shutdown timeout. + budget := sender.settings.SettleBudget + if ctx.Err() != nil { + budget = min(budget, sender.settings.ShutdownSettleBudget) + } + storeCtx, cancelStore := context.WithTimeout(context.WithoutCancel(ctx), budget) + defer cancelStore() + var lastErr error + for attempt := 1; attempt <= settleAttempts; attempt++ { + var final inbound.MailPassResult + tryCtx, cancel := context.WithTimeout(storeCtx, sender.settings.StoreTimeout) + lastErr = sender.transactor.WithinTransaction(tryCtx, func(ctx context.Context, unit outbound.UnitOfWork) error { + var err error + final, err = sender.applyResult(ctx, unit, claim, result, sendErr) + return err + }) + cancel() + switch { + case lastErr == nil: + sender.logFinished(storeCtx, final) + return final, nil + case errors.Is(lastErr, errLeaseLost): + sender.logger.InfoContext(storeCtx, "service mail was recorded by another worker first; this attempt is dropped", + slog.String("delivery_id", claim.delivery.ID().String())) + return resultOf(inbound.MailPassLeaseLost, claim.delivery), nil + } + if attempt < settleAttempts && !waitFor(storeCtx, settleRetryDelay) { + break + } + } + sender.logger.ErrorContext(storeCtx, "the result of a mail send could not be stored; the delivery stays under its lease and is claimed again after it expires, with the same idempotency key", + slog.String("delivery_id", claim.delivery.ID().String()), + slog.String("kind", string(claim.delivery.Kind()))) + return inbound.MailPassResult{}, fmt.Errorf("%s - store result: %w", location, lastErr) +} + +// checkedSendResult guards the stored state against a transport that breaks +// the MailSender contract: a nil error with no outcome may mean that the +// message left, so it counts as unknown, never as not sent. +func (sender *ServiceMailSender) checkedSendResult(ctx context.Context, delivery domain.Delivery, result outbound.SendResult, sendErr error) (outbound.SendResult, error) { + if sendErr != nil { + return outbound.SendResult{}, sendErr + } + switch result.Outcome { + case outbound.MailOutcomeAccepted, outbound.MailOutcomeRejected, outbound.MailOutcomeUnknown: + return result, nil + default: + sender.logger.ErrorContext(ctx, "the mail transport returned no outcome; the attempt is recorded as unknown", + slog.String("delivery_id", delivery.ID().String())) + return outbound.SendResult{Outcome: outbound.MailOutcomeUnknown}, nil + } +} + +// applyResult runs in the settlement transaction: the quota settlement and +// the delivery's next state commit together. +func (sender *ServiceMailSender) applyResult( + ctx context.Context, + unit outbound.UnitOfWork, + claim claimedSend, + result outbound.SendResult, + sendErr error, +) (inbound.MailPassResult, error) { + delivery := claim.delivery + // The delivery row is locked before the quota rows, the order of the claim, + // and only while this worker still holds the lease. + held, err := unit.Deliveries().LockClaimed(ctx, delivery.ID(), sender.owner) + if err != nil { + return inbound.MailPassResult{}, fmt.Errorf("lock delivery: %w", err) + } + if !held { + return inbound.MailPassResult{}, errLeaseLost + } + until, err := sender.gate.SettleSend(ctx, unit, claim.permit, result, sendErr) + if err != nil { + return inbound.MailPassResult{}, fmt.Errorf("settle quota: %w", err) + } + now := sender.clock() + if sendErr != nil { + return sender.applyNotSent(ctx, unit, claim, now, sendErr) + } + at := latest(now, delivery.UpdatedAt()) + next, attempt, err := delivery.RecordAttempt(sender.attemptInput(delivery, result, at, until)) + if err != nil { + return inbound.MailPassResult{}, fmt.Errorf("record attempt: %w", err) + } + if err := unit.Deliveries().RecordClaimedAttempt(ctx, sender.owner, next, attempt); err != nil { + if errors.Is(err, outbound.ErrDeliveryVersionConflict) { + return inbound.MailPassResult{}, errLeaseLost + } + return inbound.MailPassResult{}, fmt.Errorf("store attempt: %w", err) + } + return resultOf(outcomeOfStatus(next.Status()), next), nil +} + +// attemptInput maps a transport answer to the attempt the delivery records. +// until is the quota reset that SettleSend returned for a provider quota +// refusal. +func (sender *ServiceMailSender) attemptInput(delivery domain.Delivery, result outbound.SendResult, at, until time.Time) domain.DeliveryAttemptInput { + input := domain.DeliveryAttemptInput{ + At: at, + Outcome: domain.DeliveryAttemptOutcome(result.Outcome), + Rejection: domain.DeliveryRejection(result.Rejection), + ProviderCode: string(result.ProviderCode), + ProviderMessageID: result.ProviderMessageID, + RetryAfter: result.RetryAfter, + } + switch { + case result.Outcome == outbound.MailOutcomeAccepted: + // An accepted attempt carries no code or wait hint. + input.ProviderCode = "" + input.RetryAfter = 0 + case result.Outcome == outbound.MailOutcomeRejected && (result.Rejection == outbound.MailRejectionTemporary || result.Rejection == outbound.MailRejectionRateLimited): + input.NextAttemptAt = sender.settings.Retry.NextAttemptAt(at, delivery.AttemptCount()+1, result.RetryAfter) + case result.Outcome == outbound.MailOutcomeRejected && result.Rejection == outbound.MailRejectionQuotaExhausted && !until.IsZero(): + // Zero means that the reset is unknown, and the delivery waits for an + // operator. + input.NextAttemptAt = latest(until, at) + } + return input +} + +// applyNotSent handles a Send error: nothing left the process, and SettleSend +// gave the reservation back. +// +// - An invalid stored message ends the delivery (content_invalid). +// - No transport, or a context that ended (shutdown, an exhausted call +// budget) is nobody's fault: the lease ends and the delivery stays due. +// - Any other error is a fault on this delivery or in the transport that a +// plain retry may repeat forever, with the row at the head of the queue. +// It is counted as a failure of the row: the delivery is due later by the +// retry schedule, and after MaxFailures it is cancelled with +// processing_failed for an operator. +func (sender *ServiceMailSender) applyNotSent( + ctx context.Context, + unit outbound.UnitOfWork, + claim claimedSend, + now time.Time, + sendErr error, +) (inbound.MailPassResult, error) { + delivery := claim.delivery + switch { + case errors.Is(sendErr, outbound.ErrInvalidOutgoingMail): + cancelled, err := delivery.Cancel(latest(now, delivery.UpdatedAt()), domain.DeliveryCancelContentInvalid) + if err != nil { + return inbound.MailPassResult{}, fmt.Errorf("cancel delivery: %w", err) + } + if err := unit.Deliveries().Cancel(ctx, cancelled); err != nil { + return inbound.MailPassResult{}, fmt.Errorf("store cancelled delivery: %w", err) + } + return resultOf(inbound.MailPassCancelled, cancelled), nil + case errors.Is(sendErr, outbound.ErrMailChannelUnavailable), errors.Is(sendErr, context.Canceled), errors.Is(sendErr, context.DeadlineExceeded): + if _, err := unit.Deliveries().ReleaseClaim(ctx, delivery.ID(), sender.owner); err != nil { + return inbound.MailPassResult{}, fmt.Errorf("release claim: %w", err) + } + outcome := inbound.MailPassInterrupted + if errors.Is(sendErr, outbound.ErrMailChannelUnavailable) { + outcome = inbound.MailPassChannelUnavailable + } + return resultOf(outcome, delivery), nil + default: + // An error without an answer that is neither a cancellation nor the + // missing transport says nothing certain about this row, so it is not + // counted against it; the row only moves back by the retry schedule, + // so it does not stay at the head of the queue, and the worker backs + // off as for any pass that could not send. + at := latest(now, delivery.UpdatedAt()) + if _, err := unit.Deliveries().RecordFailure(ctx, delivery.ID(), sender.owner, at, + sender.settings.Retry.NextAttemptAt(at, claim.failureCount+1, 0), sender.settings.MaxFailures, false); err != nil { + return inbound.MailPassResult{}, fmt.Errorf("record failure: %w", err) + } + sender.logger.ErrorContext(ctx, "the mail transport failed without an answer; the delivery is retried later", + slog.String("delivery_id", delivery.ID().String())) + return resultOf(inbound.MailPassInterrupted, delivery), nil + } +} + +func (sender *ServiceMailSender) logFinished(ctx context.Context, result inbound.MailPassResult) { + attributes := []any{ + slog.String("delivery_id", result.DeliveryID.String()), + slog.String("kind", string(result.Kind)), + slog.String("outcome", string(result.Outcome)), + } + switch result.Outcome { + case inbound.MailPassRejected, inbound.MailPassUnknown: + sender.logger.WarnContext(ctx, "service mail was not accepted by the provider", attributes...) + case inbound.MailPassCancelled: + sender.logger.InfoContext(ctx, "service mail was not sent because it is invalid", append(attributes, slog.String("reason", string(result.CancelReason)))...) + case inbound.MailPassIdle, inbound.MailPassAccepted, inbound.MailPassRetry, inbound.MailPassWaitingQuota, + inbound.MailPassChannelUnavailable, inbound.MailPassInterrupted, inbound.MailPassLeaseLost, inbound.MailPassRowFailed: + sender.logger.InfoContext(ctx, "service mail pass finished", attributes...) + } +} + +func outcomeOfStatus(status domain.DeliveryStatus) inbound.MailPassOutcome { + switch status { + case domain.DeliveryStatusAccepted: + return inbound.MailPassAccepted + case domain.DeliveryStatusRejected: + return inbound.MailPassRejected + case domain.DeliveryStatusPending: + return inbound.MailPassRetry + case domain.DeliveryStatusWaitingQuota: + return inbound.MailPassWaitingQuota + case domain.DeliveryStatusCancelled: + return inbound.MailPassCancelled + case domain.DeliveryStatusUnknown: + return inbound.MailPassUnknown + default: + return inbound.MailPassUnknown + } +} + +func resultOf(outcome inbound.MailPassOutcome, delivery domain.Delivery) inbound.MailPassResult { + return inbound.MailPassResult{ + Outcome: outcome, + DeliveryID: delivery.ID(), + Kind: delivery.Kind(), + CancelReason: delivery.CancelReason(), + } +} + +// waitFor sleeps for delay and reports false when ctx ends first. +func waitFor(ctx context.Context, delay time.Duration) bool { + timer := time.NewTimer(delay) + defer timer.Stop() + select { + case <-ctx.Done(): + return false + case <-timer.C: + return true + } +} diff --git a/backend/internal/usecase/notification/service_sender_test.go b/backend/internal/usecase/notification/service_sender_test.go new file mode 100644 index 0000000..dcdb389 --- /dev/null +++ b/backend/internal/usecase/notification/service_sender_test.go @@ -0,0 +1,969 @@ +package notification + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "log/slog" + "net" + "strings" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/inbound" + "lincodex/backend/internal/port/outbound" +) + +const ( + testSenderLease = 2 * time.Minute + testTokenSecret = "SyntheticTokenSecret_0123456789-abcdefghij" + testMessageID = "4ef9a417-02e9-4d39-ad75-9611e0fcc33c" +) + +var errSettlementDown = errors.New("settlement unavailable") + +// leasedRow is a stored delivery with its lease. +type leasedRow struct { + delivery domain.Delivery + owner uuid.UUID + until time.Time + attempts []domain.DeliveryAttempt + // firstSend is when the first request started, by the fake clock; zero + // when none did. failures counts failures of the worker on the row. + firstSend time.Time + failures int32 +} + +// memoryDeliveries stores deliveries with the version rule and the lease of +// the PostgreSQL store. Rollback is not modelled; the integration tests +// cover the transactions and the concurrency. +type memoryDeliveries struct { + outbound.DeliveryRepository + + now func() time.Time + rows map[uuid.UUID]*leasedRow + state domain.ServiceMailState + // unreadable names a delivery that the store cannot restore: ClaimDue + // cancels it and reports it, as the PostgreSQL store does. + unreadable uuid.UUID + // brokenDecode names a delivery whose row cannot be restored for a reason + // other than a hash mismatch; ClaimDue reports it without cancelling. + brokenDecode uuid.UUID + // stateErr makes the token and account read fail; stateSeq, when set, + // answers successive reads with successive states. + stateErr error + stateSeq []domain.ServiceMailState +} + +func (store *memoryDeliveries) Get(_ context.Context, id uuid.UUID) (domain.Delivery, error) { + row, ok := store.rows[id] + if !ok { + return domain.Delivery{}, outbound.ErrDeliveryNotFound + } + return row.delivery, nil +} + +func (store *memoryDeliveries) ClaimDue(_ context.Context, claim outbound.DeliveryClaim) (outbound.ClaimedDelivery, error) { + for _, row := range store.rows { + delivery := row.delivery + due := !delivery.NextAttemptAt().IsZero() && !delivery.NextAttemptAt().After(claim.Now) + pinned := delivery.ProviderAccount() == claim.Account || + (delivery.ProviderAccount().Provider() == claim.RebindProvider && delivery.AttemptCount() == 0) + waiting := delivery.Status() == domain.DeliveryStatusPending || delivery.Status() == domain.DeliveryStatusWaitingQuota + free := row.owner == uuid.Nil || !row.until.After(claim.Now) + if !due || !pinned || !waiting || !free || !containsKind(claim.Kinds, delivery.Kind()) { + continue + } + previous := time.Time{} + if row.owner != uuid.Nil { + previous = row.until + } + if delivery.ID() == store.brokenDecode { + return outbound.ClaimedDelivery{}, &outbound.UnreadableDeliveryError{DeliveryID: delivery.ID(), FailureCount: row.failures, Err: errors.New("restore row")} + } + if delivery.ID() == store.unreadable { + cancelled, err := delivery.Cancel(claim.Now, domain.DeliveryCancelContentInvalid) + if err != nil { + return outbound.ClaimedDelivery{}, err + } + row.delivery = cancelled + return outbound.ClaimedDelivery{}, &outbound.UnreadableDeliveryError{DeliveryID: delivery.ID(), Cancelled: true, Err: domain.ErrMailContentIntegrity} + } + row.owner, row.until = claim.Owner, claim.Now.Add(claim.Lease) + claimed := outbound.ClaimedDelivery{Delivery: delivery, PreviousClaimedUntil: previous, FailureCount: row.failures} + if !row.firstSend.IsZero() { + claimed.FirstSendStarted, claimed.SinceFirstSend = true, claim.Now.Sub(row.firstSend) + } + return claimed, nil + } + return outbound.ClaimedDelivery{}, outbound.ErrNoDeliveryDue +} + +func containsKind(kinds []domain.MailKind, kind domain.MailKind) bool { + for _, candidate := range kinds { + if candidate == kind { + return true + } + } + return false +} + +func (store *memoryDeliveries) ReleaseClaim(_ context.Context, id, owner uuid.UUID) (bool, error) { + row := store.rows[id] + if row == nil || row.owner != owner { + return false, nil + } + row.owner, row.until = uuid.Nil, time.Time{} + return true, nil +} + +func (store *memoryDeliveries) ServiceMailState(context.Context, uuid.UUID) (domain.ServiceMailState, error) { + if store.stateErr != nil { + return domain.ServiceMailState{}, store.stateErr + } + if len(store.stateSeq) > 0 { + state := store.stateSeq[0] + store.stateSeq = store.stateSeq[1:] + return state, nil + } + return store.state, nil +} + +// replace stores next over the version before it and, when release is set, +// ends the lease. +func (store *memoryDeliveries) replace(next domain.Delivery, release bool) error { + row := store.rows[next.ID()] + if row == nil || row.delivery.Version() != next.Version()-1 { + return outbound.ErrDeliveryVersionConflict + } + row.delivery = next + if release { + row.owner, row.until = uuid.Nil, time.Time{} + } + return nil +} + +func (store *memoryDeliveries) RecordAttempt(_ context.Context, next domain.Delivery, attempt domain.DeliveryAttempt) error { + if err := store.replace(next, true); err != nil { + return err + } + row := store.rows[next.ID()] + row.attempts = append(row.attempts, attempt) + return nil +} + +func (store *memoryDeliveries) RecordClaimedAttempt(ctx context.Context, owner uuid.UUID, next domain.Delivery, attempt domain.DeliveryAttempt) error { + row := store.rows[next.ID()] + if row == nil || row.owner != owner { + return outbound.ErrDeliveryVersionConflict + } + row.failures = 0 + return store.RecordAttempt(ctx, next, attempt) +} + +func (store *memoryDeliveries) LockClaimed(_ context.Context, id, owner uuid.UUID) (bool, error) { + row := store.rows[id] + return row != nil && row.owner == owner, nil +} + +func (store *memoryDeliveries) MarkSendStarted(_ context.Context, id, owner uuid.UUID) error { + if row := store.rows[id]; row != nil && row.owner == owner && row.firstSend.IsZero() { + row.firstSend = store.now() + } + return nil +} + +func (store *memoryDeliveries) RecordFailure(_ context.Context, id, owner uuid.UUID, at, nextAttemptAt time.Time, maxFailures int32, countFailure bool) (bool, error) { + row := store.rows[id] + if row == nil || (row.owner != uuid.Nil && row.owner != owner && row.until.After(store.now())) { + return false, nil + } + if countFailure { + row.failures++ + } + row.owner, row.until = uuid.Nil, time.Time{} + if countFailure && row.failures >= maxFailures { + cancelled, err := row.delivery.Cancel(at, domain.DeliveryCancelProcessingFailed) + if err != nil { + return false, err + } + row.delivery = cancelled + return true, nil + } + // The row is due later; the fake keeps the state and moves the due time. + moved, err := domain.RestoreDelivery(domain.DeliverySnapshot{ + ID: row.delivery.ID(), SourceEventID: row.delivery.SourceEventID(), RecipientUserID: row.delivery.RecipientUserID(), + RecipientAddress: row.delivery.Recipient().Address(), Content: row.delivery.Content(), ProviderAccount: row.delivery.ProviderAccount(), + IdempotencyKey: row.delivery.IdempotencyKey(), Status: row.delivery.Status(), AttemptCount: row.delivery.AttemptCount(), + NextAttemptAt: nextAttemptAt, LastAttemptAt: row.delivery.LastAttemptAt(), ProviderMessageID: row.delivery.ProviderMessageID(), + EmailTokenID: row.delivery.EmailTokenID(), Version: row.delivery.Version() + 1, CreatedAt: row.delivery.CreatedAt(), UpdatedAt: at, + }) + if err != nil { + return false, err + } + row.delivery = moved + return false, nil +} + +func (store *memoryDeliveries) WaitForQuota(_ context.Context, next domain.Delivery) error { + return store.replace(next, true) +} + +func (store *memoryDeliveries) Cancel(_ context.Context, next domain.Delivery) error { + return store.replace(next, true) +} + +func (store *memoryDeliveries) Rebind(_ context.Context, next domain.Delivery) error { + return store.replace(next, false) +} + +type senderUnit struct { + outbound.UnitOfWork + + deliveries *memoryDeliveries + quotas *memoryQuotas +} + +func (unit senderUnit) Deliveries() outbound.DeliveryRepository { return unit.deliveries } +func (unit senderUnit) MailQuotas() outbound.MailQuotaRepository { return unit.quotas } + +// memoryTransactor runs the callback at once; settlementDown makes every +// transaction after the claim and the check before the send fail, as a +// database lost after the send does. +type memoryTransactor struct { + unit senderUnit + calls int + settlementDown bool +} + +func (transactor *memoryTransactor) WithinTransaction(ctx context.Context, fn func(ctx context.Context, unit outbound.UnitOfWork) error) error { + transactor.calls++ + if transactor.settlementDown && transactor.calls > 2 { + return errSettlementDown + } + return fn(ctx, transactor.unit) +} + +// scriptedMailSender answers every Send with one scripted result and keeps +// what it was asked to send. +type scriptedMailSender struct { + result outbound.SendResult + err error + mails []outbound.OutgoingMail + // onSend runs inside Send; deadline is the deadline of the call's context. + onSend func() + deadline time.Time +} + +func (sender *scriptedMailSender) Send(ctx context.Context, mail outbound.OutgoingMail) (outbound.SendResult, error) { + sender.mails = append(sender.mails, mail) + sender.deadline, _ = ctx.Deadline() + if sender.onSend != nil { + sender.onSend() + } + return sender.result, sender.err +} + +type senderTestHarness struct { + now time.Time + deliveries *memoryDeliveries + quotas *memoryQuotas + transport *scriptedMailSender + transactor *memoryTransactor + service *ServiceMailSender + delivery domain.Delivery + logs *bytes.Buffer +} + +func newSenderTestHarness(t *testing.T, window time.Duration) *senderTestHarness { + t.Helper() + h := &senderTestHarness{now: time.Date(2026, 10, 6, 12, 0, 0, 0, time.UTC), logs: &bytes.Buffer{}} + clock := func() time.Time { return h.now } + account := testAccount(t, "resend") + limits, err := domain.NewMailQuotaLimits(100, 3000) + if err != nil { + t.Fatalf("NewMailQuotaLimits() error = %v", err) + } + logger := slog.New(slog.NewJSONHandler(h.logs, nil)) + h.quotas = newMemoryQuotas() + h.deliveries = &memoryDeliveries{now: clock, rows: make(map[uuid.UUID]*leasedRow)} + h.transport = &scriptedMailSender{} + h.transactor = &memoryTransactor{unit: senderUnit{deliveries: h.deliveries, quotas: h.quotas}} + h.service, err = NewServiceMailSender(h.transactor, h.transport, NewQuotaGate(account, limits, window, clock, logger), ServiceMailSenderSettings{ + Account: account, + RebindProvider: "disabled", + Lease: testSenderLease, + StoreTimeout: time.Second, + SettleBudget: time.Minute, + ShutdownSettleBudget: time.Second, + MaxFailures: 3, + Retry: RetryPolicy{Initial: time.Minute, Max: 30 * time.Minute}, + }, clock, logger) + if err != nil { + t.Fatalf("NewServiceMailSender() error = %v", err) + } + h.delivery = h.addDelivery(t, account) + return h +} + +// addDelivery stores a verification delivery bound to a token, due now, and +// makes the token and the account current. +func (h *senderTestHarness) addDelivery(t *testing.T, account domain.MailProviderAccount) domain.Delivery { + t.Helper() + content, err := domain.NewMailContent(domain.MailKindVerification, "verification.v1", testSubject, + "https://lincodex.example/verify-email#token="+testTokenSecret+"\n", "

"+testBody+"

\n") + if err != nil { + t.Fatalf("NewMailContent() error = %v", err) + } + recipient, err := domain.NewEmailAddress(testRecipientAddress) + if err != nil { + t.Fatalf("NewEmailAddress() error = %v", err) + } + delivery, err := domain.NewDelivery(domain.NewDeliveryInput{ + ID: uuid.Must(uuid.NewV7()), + RecipientUserID: uuid.Must(uuid.NewV7()), + Recipient: recipient, + Content: content, + ProviderAccount: account, + EmailTokenID: uuid.Must(uuid.NewV7()), + CreatedAt: h.now, + }) + if err != nil { + t.Fatalf("NewDelivery() error = %v", err) + } + h.deliveries.rows[delivery.ID()] = &leasedRow{delivery: delivery} + h.deliveries.state = domain.ServiceMailState{ + TokenFound: true, + TokenPurpose: domain.EmailTokenPurposeEmailVerification, + TokenUserID: delivery.RecipientUserID(), + TokenRegistrationVersion: 1, + TokenExpiresAt: h.now.Add(72 * time.Hour), + AccountRegistrationVersion: 1, + AccountEmailKey: recipient.Normalized(), + } + return delivery +} + +func (h *senderTestHarness) pass(t *testing.T) inbound.MailPassResult { + t.Helper() + result, err := h.service.ProcessNext(t.Context(), t.Context()) + if err != nil { + t.Fatalf("ProcessNext() error = %v", err) + } + return result +} + +func (h *senderTestHarness) stored() *leasedRow { return h.deliveries.rows[h.delivery.ID()] } + +func (h *senderTestHarness) assertNoSecretsInLogs(t *testing.T) { + t.Helper() + for _, marker := range append([]string{testTokenSecret, "verify-email"}, privateMarkers...) { + if strings.Contains(h.logs.String(), marker) { + t.Fatalf("%q reached the logs: %s", marker, h.logs.String()) + } + } +} + +func TestServiceMailSenderMapsEveryTransportResultToTheDeliveryState(t *testing.T) { + midnight := time.Date(2026, 10, 7, 0, 0, 0, 0, time.UTC) + start := time.Date(2026, 10, 6, 12, 0, 0, 0, time.UTC) + tests := []struct { + name string + result outbound.SendResult + err error + wantOutcome inbound.MailPassOutcome + wantStatus domain.DeliveryStatus + wantNext time.Time + wantAttempts int + wantUsed int64 + }{ + { + name: "accepted by the provider", + result: outbound.SendResult{Outcome: outbound.MailOutcomeAccepted, ProviderMessageID: testMessageID}, + wantOutcome: inbound.MailPassAccepted, wantStatus: domain.DeliveryStatusAccepted, wantAttempts: 1, wantUsed: 1, + }, + { + name: "permanent refusal", + result: outbound.SendResult{Outcome: outbound.MailOutcomeRejected, Rejection: outbound.MailRejectionPermanent, ProviderCode: "validation_error"}, + wantOutcome: inbound.MailPassRejected, wantStatus: domain.DeliveryStatusRejected, wantAttempts: 1, + }, + { + name: "refused request", + result: outbound.SendResult{Outcome: outbound.MailOutcomeRejected, Rejection: outbound.MailRejectionInvalidRequest, ProviderCode: "invalid_api_key"}, + wantOutcome: inbound.MailPassRejected, wantStatus: domain.DeliveryStatusRejected, wantAttempts: 1, + }, + { + name: "temporary refusal is due after the first backoff", + result: outbound.SendResult{Outcome: outbound.MailOutcomeRejected, Rejection: outbound.MailRejectionTemporary}, + wantOutcome: inbound.MailPassRetry, wantStatus: domain.DeliveryStatusPending, wantNext: start.Add(time.Minute), wantAttempts: 1, + }, + { + name: "the provider's longer wait hint is honored", + result: outbound.SendResult{Outcome: outbound.MailOutcomeRejected, Rejection: outbound.MailRejectionRateLimited, RetryAfter: 2 * time.Hour}, + wantOutcome: inbound.MailPassRetry, wantStatus: domain.DeliveryStatusPending, wantNext: start.Add(2 * time.Hour), wantAttempts: 1, + }, + { + name: "the provider's daily quota answer waits for midnight UTC", + result: outbound.SendResult{ + Outcome: outbound.MailOutcomeRejected, Rejection: outbound.MailRejectionQuotaExhausted, ProviderCode: "daily_quota_exceeded", + QuotaPeriod: domain.MailQuotaPeriodDay, RetryAfter: 12 * time.Hour, + }, + wantOutcome: inbound.MailPassWaitingQuota, wantStatus: domain.DeliveryStatusWaitingQuota, wantNext: midnight, wantAttempts: 1, wantUsed: 100, + }, + { + name: "a quota answer without a reset waits for an operator", + result: outbound.SendResult{Outcome: outbound.MailOutcomeRejected, Rejection: outbound.MailRejectionQuotaExhausted}, + wantOutcome: inbound.MailPassWaitingQuota, wantStatus: domain.DeliveryStatusWaitingQuota, wantAttempts: 1, + }, + { + name: "an uncertain answer is unknown, counted, and not retried", + result: outbound.SendResult{Outcome: outbound.MailOutcomeUnknown, ProviderCode: "application_error"}, + wantOutcome: inbound.MailPassUnknown, wantStatus: domain.DeliveryStatusUnknown, wantAttempts: 1, wantUsed: 1, + }, + { + name: "a transport that answers without an outcome is unknown, never not sent", + result: outbound.SendResult{}, + wantOutcome: inbound.MailPassUnknown, wantStatus: domain.DeliveryStatusUnknown, wantAttempts: 1, wantUsed: 1, + }, + { + name: "no transport leaves the delivery as it was", + err: outbound.ErrMailChannelUnavailable, + wantOutcome: inbound.MailPassChannelUnavailable, wantStatus: domain.DeliveryStatusPending, wantNext: start, + }, + { + name: "an interrupted call leaves the delivery as it was", + err: context.Canceled, + wantOutcome: inbound.MailPassInterrupted, wantStatus: domain.DeliveryStatusPending, wantNext: start, + }, + { + name: "a message no transport accepts ends the delivery", + err: outbound.ErrInvalidOutgoingMail, + wantOutcome: inbound.MailPassCancelled, wantStatus: domain.DeliveryStatusCancelled, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + h := newSenderTestHarness(t, testIdempotencyWindow) + h.transport.result, h.transport.err = test.result, test.err + result := h.pass(t) + if result.Outcome != test.wantOutcome || result.DeliveryID != h.delivery.ID() || result.Kind != domain.MailKindVerification { + t.Fatalf("pass = %+v, want %s for the delivery", result, test.wantOutcome) + } + row := h.stored() + if row.delivery.Status() != test.wantStatus || !row.delivery.NextAttemptAt().Equal(test.wantNext) || len(row.attempts) != test.wantAttempts { + t.Fatalf("delivery is %s due %s with %d attempts, want %s due %s with %d", + row.delivery.Status(), row.delivery.NextAttemptAt(), len(row.attempts), test.wantStatus, test.wantNext, test.wantAttempts) + } + if row.owner != uuid.Nil { + t.Fatal("the delivery still holds a lease after the pass") + } + if used := h.quotas.used(domain.MailQuotaPeriodDay, h.now); used != test.wantUsed { + t.Fatalf("recipients counted today = %d, want %d", used, test.wantUsed) + } + // One call, with the stored message and the stable key. + mail := h.transport.mails[0] + if len(h.transport.mails) != 1 || mail.IdempotencyKey != "delivery/"+h.delivery.ID().String() || + mail.To.Address() != testRecipientAddress || !strings.Contains(mail.TextBody, testTokenSecret) { + t.Fatal("the transport was not called once with the stored message and its key") + } + h.assertNoSecretsInLogs(t) + }) + } +} + +func TestServiceMailSenderCancelsBeforeTheTransportWhenTheMailIsNoLongerValid(t *testing.T) { + tests := map[string]struct { + change func(*domain.ServiceMailState, time.Time) + want domain.DeliveryCancelReason + }{ + "token revoked": {func(state *domain.ServiceMailState, now time.Time) { state.TokenInvalidatedAt = now }, domain.DeliveryCancelTokenRevoked}, + "token consumed": {func(state *domain.ServiceMailState, now time.Time) { state.TokenConsumedAt = now }, domain.DeliveryCancelTokenConsumed}, + "token expired": {func(state *domain.ServiceMailState, now time.Time) { state.TokenExpiresAt = now }, domain.DeliveryCancelTokenExpired}, + "token missing": {func(state *domain.ServiceMailState, _ time.Time) { state.TokenFound = false }, domain.DeliveryCancelTokenMissing}, + "account moved": {func(state *domain.ServiceMailState, _ time.Time) { state.AccountRegistrationVersion++ }, domain.DeliveryCancelAccountNotCurrent}, + "address changed": {func(state *domain.ServiceMailState, _ time.Time) { state.AccountEmailKey = "moved@example.com" }, domain.DeliveryCancelRecipientMismatch}, + } + for name, test := range tests { + t.Run(name, func(t *testing.T) { + h := newSenderTestHarness(t, testIdempotencyWindow) + test.change(&h.deliveries.state, h.now) + result := h.pass(t) + if result.Outcome != inbound.MailPassCancelled || result.CancelReason != test.want { + t.Fatalf("pass = %+v, want cancelled with %s", result, test.want) + } + row := h.stored() + if row.delivery.Status() != domain.DeliveryStatusCancelled || row.delivery.CancelReason() != test.want || + len(row.attempts) != 0 || row.owner != uuid.Nil { + t.Fatalf("delivery is %s (%s) with %d attempts, want cancelled with that reason and no attempt", row.delivery.Status(), row.delivery.CancelReason(), len(row.attempts)) + } + if len(h.transport.mails) != 0 || len(h.quotas.journal) != 0 { + t.Fatal("an invalid mail reached the transport or the quota") + } + if again := h.pass(t); again.Outcome != inbound.MailPassIdle { + t.Fatalf("pass after the cancellation = %+v, want idle", again) + } + h.assertNoSecretsInLogs(t) + }) + } +} + +func TestServiceMailSenderCancelsAnUnreadableDeliveryInsteadOfBlockingTheQueue(t *testing.T) { + h := newSenderTestHarness(t, testIdempotencyWindow) + h.deliveries.unreadable = h.delivery.ID() + result := h.pass(t) + if result.Outcome != inbound.MailPassCancelled || result.DeliveryID != h.delivery.ID() || result.CancelReason != domain.DeliveryCancelContentInvalid { + t.Fatalf("pass = %+v, want cancelled as content_invalid", result) + } + if row := h.stored(); row.delivery.Status() != domain.DeliveryStatusCancelled || row.owner != uuid.Nil { + t.Fatalf("delivery is %s, want cancelled without a lease", row.delivery.Status()) + } + if len(h.transport.mails) != 0 { + t.Fatal("an unreadable delivery reached the transport") + } + if !strings.Contains(h.logs.String(), h.delivery.ID().String()) { + t.Fatal("the log does not name the cancelled delivery") + } + h.assertNoSecretsInLogs(t) + if again := h.pass(t); again.Outcome != inbound.MailPassIdle { + t.Fatalf("pass after the cancellation = %+v, want idle", again) + } +} + +func TestServiceMailSenderWaitsForALocalQuotaWithoutCallingTheTransport(t *testing.T) { + h := newSenderTestHarness(t, testIdempotencyWindow) + // The day is full. + limits, err := domain.NewMailQuotaLimits(1, 3000) + if err != nil { + t.Fatalf("NewMailQuotaLimits() error = %v", err) + } + h.service.gate.limits = limits + h.transport.result = outbound.SendResult{Outcome: outbound.MailOutcomeAccepted, ProviderMessageID: testMessageID} + if result := h.pass(t); result.Outcome != inbound.MailPassAccepted { + t.Fatalf("first pass = %+v, want accepted", result) + } + second := h.addDelivery(t, testAccount(t, "resend")) + result := h.pass(t) + midnight := time.Date(2026, 10, 7, 0, 0, 0, 0, time.UTC) + row := h.deliveries.rows[second.ID()] + if result.Outcome != inbound.MailPassWaitingQuota || row.delivery.Status() != domain.DeliveryStatusWaitingQuota || !row.delivery.NextAttemptAt().Equal(midnight) { + t.Fatalf("pass = %+v, delivery %s due %s; want waiting_quota until %s", result, row.delivery.Status(), row.delivery.NextAttemptAt(), midnight) + } + if len(h.transport.mails) != 1 { + t.Fatal("the transport was called for a delivery that the local quota deferred") + } + // A pass before the reset has nothing to do; at the reset it sends. + if again := h.pass(t); again.Outcome != inbound.MailPassIdle { + t.Fatalf("pass before the reset = %+v, want idle", again) + } + h.now = midnight + if result := h.pass(t); result.Outcome != inbound.MailPassAccepted || result.DeliveryID != second.ID() { + t.Fatalf("pass at the reset = %+v, want the waiting delivery accepted", result) + } +} + +func TestServiceMailSenderKeepsTheLeaseWhenTheResultCannotBeStored(t *testing.T) { + h := newSenderTestHarness(t, testIdempotencyWindow) + h.transactor.settlementDown = true + h.transport.result = outbound.SendResult{Outcome: outbound.MailOutcomeAccepted, ProviderMessageID: testMessageID} + if _, err := h.service.ProcessNext(t.Context(), t.Context()); !errors.Is(err, errSettlementDown) { + t.Fatalf("ProcessNext() error = %v, want the settlement failure", err) + } + row := h.stored() + if row.owner == uuid.Nil || row.delivery.Status() != domain.DeliveryStatusPending || len(row.attempts) != 0 { + t.Fatal("a result that was not stored changed the delivery or freed it before its lease ended") + } + if got := h.transactor.calls; got != 2+settleAttempts { + t.Fatalf("transactions = %d, want the claim, the check, and %d tries to store the result", got, settleAttempts) + } + h.assertNoSecretsInLogs(t) + + // While the lease lives nobody sends it; afterwards a replacement + // repeats the request under the same key and reuses the reservation. + h.transactor.settlementDown = false + if result := h.pass(t); result.Outcome != inbound.MailPassIdle { + t.Fatalf("pass under a live lease = %+v, want idle", result) + } + h.now = h.now.Add(testSenderLease) + if result := h.pass(t); result.Outcome != inbound.MailPassAccepted { + t.Fatalf("pass after the lease expired = %+v, want accepted", result) + } + if len(h.transport.mails) != 2 || h.transport.mails[0].IdempotencyKey != h.transport.mails[1].IdempotencyKey { + t.Fatal("the replacement did not reuse the idempotency key") + } + if used := h.quotas.used(domain.MailQuotaPeriodDay, h.now); used != 1 { + t.Fatalf("recipients counted today = %d, want 1: the open reservation is reused", used) + } +} + +func TestServiceMailSenderDoesNotRepeatAnAttemptLostBeyondTheDeduplicationWindow(t *testing.T) { + for name, window := range map[string]time.Duration{"after the provider's window": testIdempotencyWindow, "for a transport without deduplication": 0} { + t.Run(name, func(t *testing.T) { + h := newSenderTestHarness(t, window) + h.transactor.settlementDown = true + h.transport.result = outbound.SendResult{Outcome: outbound.MailOutcomeAccepted, ProviderMessageID: testMessageID} + if _, err := h.service.ProcessNext(t.Context(), t.Context()); err == nil { + t.Fatal("ProcessNext() with a failing settlement returned no error") + } + h.transactor.settlementDown = false + h.now = h.now.Add(testSenderLease + max(window, time.Hour)) + result := h.pass(t) + row := h.stored() + if result.Outcome != inbound.MailPassUnknown || row.delivery.Status() != domain.DeliveryStatusUnknown || !row.delivery.NextAttemptAt().IsZero() { + t.Fatalf("pass = %+v, delivery %s due %s; want unknown for an operator", result, row.delivery.Status(), row.delivery.NextAttemptAt()) + } + if len(h.transport.mails) != 1 { + t.Fatal("the request was repeated although the provider may have forgotten its key") + } + }) + } +} + +func TestServiceMailSenderMovesMailStoredWhileNoTransportRanOntoItsAccount(t *testing.T) { + h := newSenderTestHarness(t, testIdempotencyWindow) + // Replace the stored delivery by one pinned to the disabled transport. + delete(h.deliveries.rows, h.delivery.ID()) + disabled, err := domain.NewMailProviderAccount("disabled", "main") + if err != nil { + t.Fatalf("NewMailProviderAccount() error = %v", err) + } + h.delivery = h.addDelivery(t, disabled) + h.transport.result = outbound.SendResult{Outcome: outbound.MailOutcomeAccepted, ProviderMessageID: testMessageID} + + if result := h.pass(t); result.Outcome != inbound.MailPassAccepted { + t.Fatalf("pass = %+v, want accepted", result) + } + if got := h.stored().delivery.ProviderAccount(); got != testAccount(t, "resend") { + t.Fatalf("delivery is pinned to %s, want the configured account", got.Provider()) + } + + // A delivery pinned to another real account is not this worker's. + other, err := domain.NewMailProviderAccount("resend", "other") + if err != nil { + t.Fatalf("NewMailProviderAccount() error = %v", err) + } + foreign := h.addDelivery(t, other) + calls := len(h.transport.mails) + if result := h.pass(t); result.Outcome != inbound.MailPassIdle || len(h.transport.mails) != calls || h.deliveries.rows[foreign.ID()].delivery.Status() != domain.DeliveryStatusPending { + t.Fatalf("pass = %+v; a delivery of another account must wait untouched", result) + } +} + +func TestServiceMailSenderIsIdleWithoutADueDelivery(t *testing.T) { + h := newSenderTestHarness(t, testIdempotencyWindow) + delete(h.deliveries.rows, h.delivery.ID()) + if result := h.pass(t); result.Outcome != inbound.MailPassIdle || result.DeliveryID != uuid.Nil { + t.Fatalf("pass = %+v, want idle", result) + } + if len(h.transport.mails) != 0 { + t.Fatal("the transport was called without a delivery") + } +} + +func TestNewServiceMailSenderRejectsUnusableSettings(t *testing.T) { + account := testAccount(t, "resend") + valid := ServiceMailSenderSettings{ + Account: account, Lease: time.Minute, StoreTimeout: time.Second, SettleBudget: time.Second, ShutdownSettleBudget: time.Second, + MaxFailures: 1, Retry: RetryPolicy{Initial: time.Second, Max: time.Minute}, + } + for name, change := range map[string]func(*ServiceMailSenderSettings){ + "no account": func(settings *ServiceMailSenderSettings) { settings.Account = domain.MailProviderAccount{} }, + "no lease": func(settings *ServiceMailSenderSettings) { settings.Lease = 0 }, + "no store timeout": func(settings *ServiceMailSenderSettings) { settings.StoreTimeout = 0 }, + "no settle budget": func(settings *ServiceMailSenderSettings) { settings.SettleBudget = 0 }, + "budget over lease": func(settings *ServiceMailSenderSettings) { settings.SettleBudget = time.Minute }, + "no failure limit": func(settings *ServiceMailSenderSettings) { settings.MaxFailures = 0 }, + "no initial delay": func(settings *ServiceMailSenderSettings) { settings.Retry.Initial = 0 }, + "maximum below start": func(settings *ServiceMailSenderSettings) { settings.Retry.Max = time.Millisecond }, + } { + t.Run(name, func(t *testing.T) { + settings := valid + change(&settings) + if _, err := NewServiceMailSender(nil, nil, nil, settings, time.Now, slog.New(slog.DiscardHandler)); err == nil { + t.Fatal("NewServiceMailSender() accepted unusable settings") + } + }) + } +} + +func TestRetryPolicyDoublesTheWaitUpToItsMaximumAndHonorsALongerHint(t *testing.T) { + policy := RetryPolicy{Initial: time.Minute, Max: 30 * time.Minute} + at := time.Date(2026, 10, 6, 12, 0, 0, 0, time.UTC) + tests := []struct { + attempt int32 + retryAfter time.Duration + want time.Duration + }{ + {1, 0, time.Minute}, + {2, 0, 2 * time.Minute}, + {3, 0, 4 * time.Minute}, + {6, 0, 30 * time.Minute}, + {40, 0, 30 * time.Minute}, + {1, 10 * time.Minute, 10 * time.Minute}, + {1, 10 * time.Second, time.Minute}, + {10, 2 * time.Hour, 2 * time.Hour}, + } + for _, test := range tests { + if got := policy.NextAttemptAt(at, test.attempt, test.retryAfter); !got.Equal(at.Add(test.want)) { + t.Fatalf("NextAttemptAt(attempt %d, hint %s) = +%s, want +%s", test.attempt, test.retryAfter, got.Sub(at), test.want) + } + } +} + +func TestServiceMailSenderMovesAFailingRowBackInTheQueueAndCancelsItAfterRepeatedFailures(t *testing.T) { + causes := map[string]func(*senderTestHarness){ + "the token and account cannot be read": func(h *senderTestHarness) { h.deliveries.stateErr = fmt.Errorf("state: %w", domain.ErrInvalidDelivery) }, + "the row cannot be restored": func(h *senderTestHarness) { h.deliveries.brokenDecode = h.delivery.ID() }, + } + for name, cause := range causes { + t.Run(name, func(t *testing.T) { + h := newSenderTestHarness(t, testIdempotencyWindow) + cause(h) + poisoned := h.delivery + healthy := h.addDelivery(t, testAccount(t, "resend")) + h.deliveries.stateErr = nil + if name == "the token and account cannot be read" { + h.deliveries.stateErr = fmt.Errorf("state: %w", domain.ErrInvalidDelivery) + } + h.transport.result = outbound.SendResult{Outcome: outbound.MailOutcomeAccepted, ProviderMessageID: testMessageID} + + // The first failure moves the row back by the retry schedule; the + // delivery behind it is not blocked. + result := h.pass(t) + if result.Outcome != inbound.MailPassRowFailed || result.DeliveryID != poisoned.ID() { + t.Fatalf("first pass = %+v, want row_failed for the failing delivery", result) + } + row := h.deliveries.rows[poisoned.ID()] + if row.owner != uuid.Nil || row.failures != 1 || !row.delivery.NextAttemptAt().Equal(h.now.Add(time.Minute)) { + t.Fatalf("failing row: lease %v, %d failures, due %s; want no lease, 1 failure, due in a minute", row.owner, row.failures, row.delivery.NextAttemptAt()) + } + h.deliveries.stateErr = nil + if next := h.pass(t); next.Outcome != inbound.MailPassAccepted || next.DeliveryID != healthy.ID() { + t.Fatalf("second pass = %+v, want the healthy delivery sent", next) + } + + // It fails again each time it is due, and after MaxFailures it is + // cancelled for an operator. + if name == "the token and account cannot be read" { + h.deliveries.stateErr = fmt.Errorf("state: %w", domain.ErrInvalidDelivery) + } + h.now = h.now.Add(time.Hour) + if second := h.pass(t); second.Outcome != inbound.MailPassRowFailed { + t.Fatalf("pass at the second due time = %+v, want row_failed", second) + } + h.now = h.now.Add(2 * time.Hour) + final := h.pass(t) + if final.Outcome != inbound.MailPassCancelled || final.CancelReason != domain.DeliveryCancelProcessingFailed { + t.Fatalf("third failure = %+v, want cancelled as processing_failed", final) + } + if got := h.deliveries.rows[poisoned.ID()].delivery; got.Status() != domain.DeliveryStatusCancelled || got.CancelReason() != domain.DeliveryCancelProcessingFailed { + t.Fatalf("delivery is %s (%s), want cancelled as processing_failed", got.Status(), got.CancelReason()) + } + h.assertNoSecretsInLogs(t) + }) + } +} + +func TestServiceMailSenderMovesBackAFailingTransportCallWithoutCountingItAgainstTheRow(t *testing.T) { + h := newSenderTestHarness(t, testIdempotencyWindow) + h.transport.err = errors.New("transport misconfigured") + for range 5 { + result := h.pass(t) + row := h.stored() + if result.Outcome != inbound.MailPassInterrupted || row.failures != 0 || row.owner != uuid.Nil || + row.delivery.Status() != domain.DeliveryStatusPending || !row.delivery.NextAttemptAt().After(h.now) { + t.Fatalf("pass = %+v; row: %d failures, %s due %s; want an uncounted failure, pending, due later", result, row.failures, row.delivery.Status(), row.delivery.NextAttemptAt()) + } + if again := h.pass(t); again.Outcome != inbound.MailPassIdle { + t.Fatalf("pass before the due time = %+v, want idle: the row must not stay at the head", again) + } + h.now = h.now.Add(time.Hour) + } + // However often the transport failed, the row was never cancelled; a + // working transport sends it. + h.transport.err, h.transport.result = nil, outbound.SendResult{Outcome: outbound.MailOutcomeAccepted, ProviderMessageID: testMessageID} + if result := h.pass(t); result.Outcome != inbound.MailPassAccepted { + t.Fatalf("pass with a working transport = %+v, want accepted", result) + } + if used := h.quotas.used(domain.MailQuotaPeriodDay, h.now); used != 1 { + t.Fatalf("recipients counted = %d, want 1", used) + } +} + +func TestServiceMailSenderDoesNotCountTransientErrorsAgainstTheRow(t *testing.T) { + transient := map[string]error{ + "deadline": context.DeadlineExceeded, + "canceled": fmt.Errorf("claim: %w", context.Canceled), + "deadlock": fmt.Errorf("postgres: %w", outbound.ErrTransactionConflict), + "connection": &net.OpError{Op: "read", Err: errors.New("connection reset")}, + "io": io.ErrUnexpectedEOF, + "quota setup": ErrQuotaNotConfigured, + } + for name, cause := range transient { + t.Run(name, func(t *testing.T) { + h := newSenderTestHarness(t, testIdempotencyWindow) + h.deliveries.stateErr = cause + for range 10 { + if _, err := h.service.ProcessNext(t.Context(), t.Context()); err == nil { + t.Fatal("a transient error was swallowed instead of reported to the worker") + } + // The real transaction rolls the lease back; the fake does not. + h.stored().owner = uuid.Nil + } + row := h.stored() + if row.failures != 0 || row.delivery.Status() != domain.DeliveryStatusPending { + t.Fatalf("row: %d failures, %s; want no count and not cancelled after ten transient errors", row.failures, row.delivery.Status()) + } + }) + } +} + +func TestServiceMailSenderPausedCountingMovesRowsBackWithoutCountingThem(t *testing.T) { + h := newSenderTestHarness(t, testIdempotencyWindow) + h.deliveries.stateErr = fmt.Errorf("state: %w", domain.ErrInvalidDelivery) + h.service.PauseFailureCounting(true) + for range 5 { + if result := h.pass(t); result.Outcome != inbound.MailPassRowFailed { + t.Fatalf("pass = %+v, want row_failed", result) + } + h.now = h.now.Add(time.Hour) + } + if row := h.stored(); row.failures != 0 || row.delivery.Status() != domain.DeliveryStatusPending { + t.Fatalf("row: %d failures, %s; want none counted while counting is paused", row.failures, row.delivery.Status()) + } + h.service.PauseFailureCounting(false) + h.pass(t) + if row := h.stored(); row.failures != 1 { + t.Fatalf("failures after counting resumed = %d, want 1", row.failures) + } +} + +func TestServiceMailSenderSuccessfulPreparationClearsTheFailureCount(t *testing.T) { + h := newSenderTestHarness(t, testIdempotencyWindow) + h.deliveries.stateErr = fmt.Errorf("state: %w", domain.ErrInvalidDelivery) + h.pass(t) + h.deliveries.stateErr = nil + h.transport.result = outbound.SendResult{Outcome: outbound.MailOutcomeAccepted, ProviderMessageID: testMessageID} + h.now = h.now.Add(time.Hour) + h.pass(t) + if got := h.stored().failures; got != 0 { + t.Fatalf("failure count after a successful pass = %d, want 0", got) + } +} + +func TestServiceMailSenderRecordsAFailureOnlyForARowNobodyElseHolds(t *testing.T) { + h := newSenderTestHarness(t, testIdempotencyWindow) + other := uuid.New() + row := h.stored() + row.owner, row.until = other, h.now.Add(time.Minute) + moved, err := h.deliveries.RecordFailure(t.Context(), h.delivery.ID(), h.service.owner, h.now, h.now.Add(time.Hour), 3, true) + if err != nil || moved || row.failures != 0 || row.owner != other { + t.Fatalf("RecordFailure() = %t, %v with %d failures and owner %v; want the row left alone under another worker's live lease", moved, err, row.failures, row.owner) + } +} + +func TestServiceMailSenderCountsTheDeduplicationWindowFromTheFirstRequest(t *testing.T) { + h := newSenderTestHarness(t, testIdempotencyWindow) + h.transport.result = outbound.SendResult{Outcome: outbound.MailOutcomeAccepted, ProviderMessageID: testMessageID} + // Several workers in a row stop after the call. Each lease is short and + // each takeover is within a day of the one before, but the first request + // is older with every cycle. + for cycle := range 3 { + h.transactor.calls, h.transactor.settlementDown = 0, true + if _, err := h.service.ProcessNext(t.Context(), t.Context()); err == nil { + t.Fatalf("cycle %d: ProcessNext() with a failing settlement returned no error", cycle) + } + h.now = h.now.Add(testSenderLease + 8*time.Hour) + } + h.transactor.settlementDown = false + // 24 hours and three leases after the first request: the provider may + // have forgotten the key, whatever the latest lease says. + result := h.pass(t) + if result.Outcome != inbound.MailPassUnknown || len(h.transport.mails) != 3 { + t.Fatalf("pass = %+v after %d calls, want unknown without a fourth call", result, len(h.transport.mails)) + } +} + +func TestServiceMailSenderKeepsTheKeyWithinTheSafetyMarginOfTheWindow(t *testing.T) { + h := newSenderTestHarness(t, testIdempotencyWindow) + h.transport.result = outbound.SendResult{Outcome: outbound.MailOutcomeAccepted, ProviderMessageID: testMessageID} + h.transactor.settlementDown = true + if _, err := h.service.ProcessNext(t.Context(), t.Context()); err == nil { + t.Fatal("ProcessNext() with a failing settlement returned no error") + } + h.transactor.settlementDown = false + // 22 hours after the first request is inside the 23-hour margin. + h.now = h.now.Add(22 * time.Hour) + if result := h.pass(t); result.Outcome != inbound.MailPassAccepted { + t.Fatalf("pass 22 hours after the first request = %+v, want accepted under the same key", result) + } +} + +func TestServiceMailSenderHonorsARevocationAfterTheClaimCommitted(t *testing.T) { + h := newSenderTestHarness(t, testIdempotencyWindow) + revoked := h.deliveries.state + revoked.TokenInvalidatedAt = h.now + // The claim reads a current state; the check right before the send finds + // the token revoked. + h.deliveries.stateSeq = []domain.ServiceMailState{h.deliveries.state, revoked} + result := h.pass(t) + if result.Outcome != inbound.MailPassCancelled || result.CancelReason != domain.DeliveryCancelTokenRevoked { + t.Fatalf("pass = %+v, want cancelled as token_revoked", result) + } + if len(h.transport.mails) != 0 { + t.Fatal("a revoked token was sent") + } + if used := h.quotas.used(domain.MailQuotaPeriodDay, h.now); used != 0 { + t.Fatalf("recipients counted = %d, want the reservation given back", used) + } + if row := h.stored(); row.owner != uuid.Nil || row.delivery.Status() != domain.DeliveryStatusCancelled { + t.Fatal("the cancelled delivery still holds a lease or is not cancelled") + } +} + +func TestServiceMailSenderDropsAResultWhenItLostTheLeaseDuringTheCall(t *testing.T) { + h := newSenderTestHarness(t, testIdempotencyWindow) + h.transport.result = outbound.SendResult{Outcome: outbound.MailOutcomeAccepted, ProviderMessageID: testMessageID} + // Another worker takes the delivery while this one is in the call. + h.transport.onSend = func() { h.stored().owner = uuid.New() } + result := h.pass(t) + if result.Outcome != inbound.MailPassLeaseLost || len(h.stored().attempts) != 0 { + t.Fatalf("pass = %+v with %d attempts, want lease_lost and none recorded", result, len(h.stored().attempts)) + } +} + +func TestServiceMailSenderBoundsTheCallByWhatIsLeftOfTheLease(t *testing.T) { + h := newSenderTestHarness(t, testIdempotencyWindow) + h.transport.result = outbound.SendResult{Outcome: outbound.MailOutcomeAccepted, ProviderMessageID: testMessageID} + before := time.Now() + h.pass(t) + // Lease 2 minutes, settle budget 1 minute: the call gets at most a minute. + if limit := h.transport.deadline.Sub(before); limit > testSenderLease-time.Minute+time.Second || limit <= 0 { + t.Fatalf("the call may take %s, want at most the lease minus the settle budget", limit) + } +} + +func TestRetryPolicyJitterIsBoundedAndInjectable(t *testing.T) { + at := time.Date(2026, 10, 6, 12, 0, 0, 0, time.UTC) + full := RetryPolicy{Initial: 10 * time.Minute, Max: time.Hour, Jitter: func(limit time.Duration) time.Duration { return limit }} + if got := full.NextAttemptAt(at, 1, 0); !got.Equal(at.Add(12 * time.Minute)) { + t.Fatalf("NextAttemptAt() with the largest jitter = +%s, want +12m (a fifth over)", got.Sub(at)) + } + wild := RetryPolicy{Initial: 10 * time.Minute, Max: time.Hour, Jitter: func(time.Duration) time.Duration { return time.Hour }} + if got := wild.NextAttemptAt(at, 1, 0); !got.Equal(at.Add(12 * time.Minute)) { + t.Fatalf("NextAttemptAt() with a source over its limit = +%s, want it clamped to +12m", got.Sub(at)) + } + none := RetryPolicy{Initial: 10 * time.Minute, Max: time.Hour} + if got := none.NextAttemptAt(at, 1, 0); !got.Equal(at.Add(10 * time.Minute)) { + t.Fatalf("NextAttemptAt() without jitter = +%s, want +10m", got.Sub(at)) + } + for range 200 { + if got := (RetryPolicy{Initial: time.Minute, Max: time.Hour, Jitter: RandomJitter}).NextAttemptAt(at, 1, 0).Sub(at); got < time.Minute || got > 72*time.Second { + t.Fatalf("random jitter gave +%s, want within [1m, 1m12s]", got) + } + } +} diff --git a/backend/internal/worker/mailsender/worker.go b/backend/internal/worker/mailsender/worker.go new file mode 100644 index 0000000..aa6c81e --- /dev/null +++ b/backend/internal/worker/mailsender/worker.go @@ -0,0 +1,187 @@ +// Package mailsender runs the sending loop of the service identity mail: +// it repeats passes of the sending usecase until it is stopped, waits when +// nothing is due, and backs off when a pass fails, so it never spins on a +// persistent failure. Several workers may run against one database, in one +// process or many; the claim in the usecase keeps them off each other's +// deliveries. +package mailsender + +import ( + "context" + "errors" + "log/slog" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/port/inbound" + "lincodex/backend/internal/worker/retry" +) + +// rowStreakLimit is how many passes in a row may fail on different rows +// before the failures stop being counted against rows. +const rowStreakLimit = 3 + +// Metrics exposes whether the sending loop runs. The alert on overdue +// deliveries needs it: a delivery that waits while no sender runs is a +// different problem from one that waits while a sender runs. +type Metrics interface { + // SetMailSenderRunning reports 1 while the loop runs and 0 otherwise. + SetMailSenderRunning(running bool) + // ObserveMailCancelled counts a delivery that the worker ended without + // sending, by its cancel reason, a closed set. content_invalid and + // processing_failed point at a defect or a broken row and are alerted on. + ObserveMailCancelled(reason string) +} + +// Settings are the named limits of the loop. +type Settings struct { + // PollInterval is the wait after a pass that found no due delivery. + PollInterval time.Duration + // Backoff is the wait after a pass that failed in the database and after + // a pass that sent nothing because no transport is active or the call was + // interrupted; it grows across consecutive failures. + Backoff retry.Backoff + // ShutdownGrace is how long a send in progress may continue after Run's + // context ends. When it expires the call is canceled; the result is + // stored anyway. + ShutdownGrace time.Duration +} + +func (settings Settings) validate() error { + if settings.PollInterval <= 0 || settings.ShutdownGrace <= 0 || settings.Backoff.Initial <= 0 || settings.Backoff.Max < settings.Backoff.Initial { + return errors.New("mailsender.New - poll interval, shutdown grace, and backoff must be positive, and the maximum backoff not below the initial one") + } + return nil +} + +// Worker repeats passes of the sending usecase. +type Worker struct { + pass inbound.MailPass + metrics Metrics + logger *slog.Logger + settings Settings +} + +// New builds a worker around the sending usecase. +func New(pass inbound.MailPass, metrics Metrics, logger *slog.Logger, settings Settings) (*Worker, error) { + if err := settings.validate(); err != nil { + return nil, err + } + return &Worker{pass: pass, metrics: metrics, logger: logger, settings: settings}, nil +} + +// Run sends due mail until ctx ends. A pass that handled a delivery is +// followed at once by the next one, because more may be due; after an idle +// pass the worker waits PollInterval. After a database failure, a missing +// transport, or an interrupted call it waits Backoff, which grows with every +// consecutive failure. Run claims nothing once ctx ends, lets a send in +// progress continue for ShutdownGrace, stores its result, and returns. +// lincodex_mail_sender_running is 1 while it loops. +func (worker *Worker) Run(ctx context.Context) { + workCtx, stopWork := worker.workContext(ctx) + defer stopWork() + worker.metrics.SetMailSenderRunning(true) + defer worker.metrics.SetMailSenderRunning(false) + worker.logger.Info("mail sender worker started", slog.Duration("poll_interval", worker.settings.PollInterval)) + defer worker.logger.Info("mail sender worker stopped") + + failures := 0 + // rowStreak counts consecutive passes that failed on a row, each on a + // different row than the one before. Failures that hit row after row do not + // say that rows are broken but that something around them is, so they stop + // being counted against rows (the breaker) until a pass succeeds. + breaker := rowBreaker{pass: worker.pass} + defer worker.pass.PauseFailureCounting(false) + for ctx.Err() == nil { + result, err := worker.pass.ProcessNext(ctx, workCtx) + if err == nil && result.Outcome == inbound.MailPassCancelled { + worker.metrics.ObserveMailCancelled(string(result.CancelReason)) + } + var delay time.Duration + rowStreak := breaker.observe(result, err) + switch { + case ctx.Err() != nil: + return + case err != nil: + failures++ + delay = worker.settings.Backoff.Delay(failures) + worker.logger.Warn("mail sender pass failed in the database; the delivery waits under its lease", + slog.Int("consecutive_failures", failures), + slog.Duration("retry_in", delay), + slog.Any("error", err)) + case result.Outcome == inbound.MailPassChannelUnavailable || result.Outcome == inbound.MailPassInterrupted: + failures++ + delay = worker.settings.Backoff.Delay(failures) + worker.logger.Warn("mail was not sent because no transport is active or the call was interrupted; the delivery stays due", + slog.String("outcome", string(result.Outcome)), + slog.Int("consecutive_failures", failures), + slog.Duration("retry_in", delay)) + case result.Outcome == inbound.MailPassRowFailed: + // A failing row has left the head of the queue, but a tight loop + // over many of them is what the breaker exists to stop: wait, + // longer the longer it goes on. + delay = worker.settings.Backoff.Delay(max(rowStreak, 1)) + worker.logger.Warn("mail sender pass failed on a delivery; it is retried later", + slog.Int("rows_in_a_row", rowStreak), + slog.Bool("counting_paused", rowStreak >= rowStreakLimit), + slog.Duration("retry_in", delay)) + case result.Outcome == inbound.MailPassIdle: + failures = 0 + delay = worker.settings.PollInterval + default: + failures = 0 + } + if !retry.Wait(ctx, delay) { + return + } + } +} + +// rowBreaker is the circuit breaker over failures that hit row after row. +type rowBreaker struct { + pass inbound.MailPass + streak int + lastRow uuid.UUID +} + +// observe records the outcome of a pass and returns how many passes in a row +// have failed on different rows. At rowStreakLimit it pauses failure counting +// in the pass, and any pass that does not fail on a row resumes it. A pass that +// failed in the database leaves the state as it was. +func (breaker *rowBreaker) observe(result inbound.MailPassResult, err error) int { + switch { + case err != nil: + case result.Outcome == inbound.MailPassRowFailed: + if result.DeliveryID != breaker.lastRow { + breaker.streak++ + } + breaker.lastRow = result.DeliveryID + default: + breaker.streak, breaker.lastRow = 0, uuid.Nil + breaker.pass.PauseFailureCounting(false) + } + if breaker.streak >= rowStreakLimit { + breaker.pass.PauseFailureCounting(true) + } + return breaker.streak +} + +// workContext returns a context for the transport call that outlives ctx by +// at most ShutdownGrace. stop releases the watcher goroutine. +func (worker *Worker) workContext(ctx context.Context) (context.Context, func()) { + workCtx, cancel := context.WithCancel(context.WithoutCancel(ctx)) + stopWatching := context.AfterFunc(ctx, func() { + timer := time.NewTimer(worker.settings.ShutdownGrace) + defer timer.Stop() + select { + case <-timer.C: + cancel() + case <-workCtx.Done(): + } + }) + return workCtx, func() { + stopWatching() + cancel() + } +} diff --git a/backend/internal/worker/mailsender/worker_test.go b/backend/internal/worker/mailsender/worker_test.go new file mode 100644 index 0000000..18e8790 --- /dev/null +++ b/backend/internal/worker/mailsender/worker_test.go @@ -0,0 +1,306 @@ +package mailsender + +import ( + "context" + "errors" + "log/slog" + "sync" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/inbound" + "lincodex/backend/internal/worker/retry" +) + +const testWait = 5 * time.Second + +type scriptedPass struct { + mu sync.Mutex + steps []step + calls []time.Time + called chan struct{} + workCtx context.Context + paused []bool +} + +type step struct { + result inbound.MailPassResult + err error +} + +func newScriptedPass(steps ...step) *scriptedPass { + return &scriptedPass{steps: steps, called: make(chan struct{}, 64)} +} + +func (pass *scriptedPass) ProcessNext(_, workCtx context.Context) (inbound.MailPassResult, error) { + pass.mu.Lock() + pass.calls = append(pass.calls, time.Now()) + pass.workCtx = workCtx + next := step{result: inbound.MailPassResult{Outcome: inbound.MailPassIdle}} + if len(pass.steps) > 0 { + next, pass.steps = pass.steps[0], pass.steps[1:] + } + pass.mu.Unlock() + pass.called <- struct{}{} + return next.result, next.err +} + +func (pass *scriptedPass) PauseFailureCounting(paused bool) { + pass.mu.Lock() + defer pass.mu.Unlock() + pass.paused = append(pass.paused, paused) +} + +func (pass *scriptedPass) count() int { + pass.mu.Lock() + defer pass.mu.Unlock() + return len(pass.calls) +} + +type gauge struct { + mu sync.Mutex + history []bool + cancelled []string +} + +func (g *gauge) ObserveMailCancelled(reason string) { + g.mu.Lock() + defer g.mu.Unlock() + g.cancelled = append(g.cancelled, reason) +} + +func (g *gauge) SetMailSenderRunning(running bool) { + g.mu.Lock() + defer g.mu.Unlock() + g.history = append(g.history, running) +} + +func (g *gauge) values() []bool { + g.mu.Lock() + defer g.mu.Unlock() + return append([]bool(nil), g.history...) +} + +func testSettings() Settings { + return Settings{ + PollInterval: 20 * time.Millisecond, + Backoff: retry.Backoff{Initial: 40 * time.Millisecond, Max: 80 * time.Millisecond}, + ShutdownGrace: 50 * time.Millisecond, + } +} + +func newTestWorker(t *testing.T, pass inbound.MailPass, metrics Metrics, settings Settings) *Worker { + t.Helper() + worker, err := New(pass, metrics, slog.New(slog.DiscardHandler), settings) + if err != nil { + t.Fatalf("New() error = %v", err) + } + return worker +} + +func runWorker(t *testing.T, worker *Worker) (stop func()) { + t.Helper() + ctx, cancel := context.WithCancel(t.Context()) + stopped := make(chan struct{}) + go func() { + defer close(stopped) + worker.Run(ctx) + }() + return func() { + cancel() + select { + case <-stopped: + case <-time.After(testWait): + t.Fatal("Run() did not return after its context ended") + } + } +} + +func waitForCalls(t *testing.T, pass *scriptedPass, want int) { + t.Helper() + deadline := time.After(testWait) + for pass.count() < want { + select { + case <-pass.called: + case <-deadline: + t.Fatalf("pass called %d times, want at least %d", pass.count(), want) + } + } +} + +func TestNewRejectsUnusableSettings(t *testing.T) { + for name, change := range map[string]func(*Settings){ + "no poll interval": func(settings *Settings) { settings.PollInterval = 0 }, + "no shutdown grace": func(settings *Settings) { settings.ShutdownGrace = 0 }, + "no initial backoff": func(settings *Settings) { settings.Backoff.Initial = 0 }, + "maximum below start": func(settings *Settings) { + settings.Backoff = retry.Backoff{Initial: time.Second, Max: time.Millisecond} + }, + } { + t.Run(name, func(t *testing.T) { + settings := testSettings() + change(&settings) + if _, err := New(newScriptedPass(), &gauge{}, slog.New(slog.DiscardHandler), settings); err == nil { + t.Fatal("New() accepted unusable settings") + } + }) + } +} + +func TestRunReportsThatItRunsOnlyWhileTheLoopDoes(t *testing.T) { + metrics := &gauge{} + worker := newTestWorker(t, newScriptedPass(), metrics, testSettings()) + if got := metrics.values(); len(got) != 0 { + t.Fatalf("gauge was set before Run: %v", got) + } + stop := runWorker(t, worker) + deadline := time.After(testWait) + for len(metrics.values()) == 0 { + select { + case <-deadline: + t.Fatal("the loop never reported that it runs") + case <-time.After(time.Millisecond): + } + } + if got := metrics.values(); got[0] != true { + t.Fatalf("first gauge value = %v, want true", got[0]) + } + stop() + if got := metrics.values(); got[len(got)-1] != false { + t.Fatalf("last gauge value = %v, want false after the loop stopped", got[len(got)-1]) + } +} + +func TestRunWaitsAfterAnIdlePassAndContinuesAtOnceAfterAHandledDelivery(t *testing.T) { + handled := step{result: inbound.MailPassResult{Outcome: inbound.MailPassAccepted}} + pass := newScriptedPass(handled, handled, handled) + settings := testSettings() + settings.PollInterval = time.Hour // an idle pass would stall the test + stop := runWorker(t, newTestWorker(t, pass, &gauge{}, settings)) + defer stop() + // Three handled passes run back to back; the fourth is idle and the + // worker then waits for the poll interval. + waitForCalls(t, pass, 4) + time.Sleep(100 * time.Millisecond) + if got := pass.count(); got != 4 { + t.Fatalf("pass called %d times, want 4: an idle pass must wait for the poll interval", got) + } +} + +func TestRunBacksOffInsteadOfSpinningWhenNothingCanBeSent(t *testing.T) { + for name, failing := range map[string]step{ + "no transport": {result: inbound.MailPassResult{Outcome: inbound.MailPassChannelUnavailable}}, + "interrupted call": {result: inbound.MailPassResult{Outcome: inbound.MailPassInterrupted}}, + "database failure": {err: errors.New("database unavailable")}, + } { + t.Run(name, func(t *testing.T) { + steps := make([]step, 50) + for index := range steps { + steps[index] = failing + } + pass := newScriptedPass(steps...) + stop := runWorker(t, newTestWorker(t, pass, &gauge{}, testSettings())) + time.Sleep(300 * time.Millisecond) + stop() + // The delay starts at 20..40 ms and doubles to 40..80 ms: a loop + // that did not back off would have made hundreds of passes. + if got := pass.count(); got < 3 || got > 15 { + t.Fatalf("pass called %d times in 300 ms, want a few spaced by the backoff", got) + } + pass.mu.Lock() + defer pass.mu.Unlock() + for index := 1; index < len(pass.calls); index++ { + if gap := pass.calls[index].Sub(pass.calls[index-1]); gap < 15*time.Millisecond { + t.Fatalf("passes %d and %d were %s apart, want the backoff between them", index, index+1, gap) + } + } + }) + } +} + +func TestRunReleasesItsWorkContextWhenItStops(t *testing.T) { + pass := newScriptedPass() + worker := newTestWorker(t, pass, &gauge{}, testSettings()) + stop := runWorker(t, worker) + waitForCalls(t, pass, 1) + pass.mu.Lock() + workCtx := pass.workCtx + pass.mu.Unlock() + if workCtx.Err() != nil { + t.Fatal("the work context ended while the loop runs") + } + stop() + // Run returned after its own context ended; the work context is released + // by then, so no goroutine waits for a grace that nobody needs. A send in + // progress at shutdown keeps running for the grace first, which the + // integration tests cover with a real transport. + select { + case <-workCtx.Done(): + case <-time.After(testWait): + t.Fatal("the work context was not released when Run returned") + } +} + +func TestRunCountsCancelledDeliveriesByReasonAndDoesNotBackOffForARowFailure(t *testing.T) { + metrics := &gauge{} + pass := newScriptedPass( + step{result: inbound.MailPassResult{Outcome: inbound.MailPassCancelled, CancelReason: domain.DeliveryCancelContentInvalid}}, + step{result: inbound.MailPassResult{Outcome: inbound.MailPassRowFailed}}, + step{result: inbound.MailPassResult{Outcome: inbound.MailPassCancelled, CancelReason: domain.DeliveryCancelProcessingFailed}}, + ) + settings := testSettings() + settings.PollInterval = time.Hour + stop := runWorker(t, newTestWorker(t, pass, metrics, settings)) + defer stop() + // The first three passes follow each other at once, because a failing row + // has left the head of the queue; the fourth is idle and waits. + waitForCalls(t, pass, 4) + metrics.mu.Lock() + defer metrics.mu.Unlock() + if len(metrics.cancelled) != 2 || metrics.cancelled[0] != "content_invalid" || metrics.cancelled[1] != "processing_failed" { + t.Fatalf("cancelled reasons = %v, want content_invalid and processing_failed", metrics.cancelled) + } +} + +func TestRunPausesFailureCountingWhenFailuresHitRowAfterRowAndResumesAfterASuccess(t *testing.T) { + failed := func() step { + return step{result: inbound.MailPassResult{Outcome: inbound.MailPassRowFailed, DeliveryID: uuid.New()}} + } + pass := newScriptedPass(failed(), failed(), failed(), failed(), step{result: inbound.MailPassResult{Outcome: inbound.MailPassAccepted}}) + settings := testSettings() + settings.PollInterval = time.Hour + stop := runWorker(t, newTestWorker(t, pass, &gauge{}, settings)) + waitForCalls(t, pass, 6) + stop() + pass.mu.Lock() + defer pass.mu.Unlock() + // Paused from the third different row on, resumed by the success. + var sawPause bool + for _, paused := range pass.paused { + sawPause = sawPause || paused + } + if !sawPause || pass.paused[len(pass.paused)-1] { + t.Fatalf("pause calls = %v, want a pause after three different rows and no pause at the end", pass.paused) + } +} + +func TestRunDoesNotPauseWhenTheSameRowFailsAgain(t *testing.T) { + id := uuid.New() + same := step{result: inbound.MailPassResult{Outcome: inbound.MailPassRowFailed, DeliveryID: id}} + pass := newScriptedPass(same, same, same, same) + settings := testSettings() + settings.PollInterval = time.Hour + stop := runWorker(t, newTestWorker(t, pass, &gauge{}, settings)) + waitForCalls(t, pass, 5) + stop() + pass.mu.Lock() + defer pass.mu.Unlock() + for _, paused := range pass.paused { + if paused { + t.Fatalf("pause calls = %v; one row failing repeatedly is not a global fault", pass.paused) + } + } +} diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index 9580755..e186887 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -190,7 +190,7 @@ Metrics: `lincodex_scheduled_jobs_total{kind,outcome}` counts claimed jobs by `d ### 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: 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). +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. The only caller is the sending worker for service identity mail (TASK-016, see [Sending service mail](#sending-service-mail)); product notifications are stored as deliveries but not sent until TASK-462. 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: @@ -224,11 +224,11 @@ The Resend transport uses `net/http` without an SDK. One `Send` is one `POST htt | Failure before the request was written: DNS, connect, TLS, or the attempt timeout | `rejected`, `temporary`: no complete request reached Resend | | The caller's context ended before the request was written | the context error; nothing was sent | -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, the attempt limit, and the stop at the end of the 24-hour key window belong to the planned delivery layer; waiting for a quota reset is decided by the quota gate described in [Mail quotas](#mail-quotas). +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 and the attempt limit belong to the retry policy (TASK-017), the sending worker applies only the minimum schedule described in [Sending service mail](#sending-service-mail), and the stop at the end of the 24-hour key window is the sending worker's rule for an attempt whose worker was lost; waiting for a quota reset is decided by the quota gate described in [Mail quotas](#mail-quotas). ### 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`. The quota gate that admits or defers a send is implemented with TASK-018; see [Mail quotas](#mail-quotas). Planned: the worker that claims due deliveries, passes them through the quota gate, and calls `MailSender` (TASK-016), retries and the unknown outcome policy (TASK-017), and the permission check before a send (TASK-462). The delivery state gauges are implemented with TASK-022; see [Metrics, telemetry, and alerts](#metrics-telemetry-and-alerts). No product flow calls `MailRequester` yet, and nothing sends a stored delivery. +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`. The quota gate that admits or defers a send is implemented with TASK-018; see [Mail quotas](#mail-quotas). Implemented (TASK-016): the worker that claims due service mail, checks its token and account, passes it through the quota gate, and calls `MailSender`, with migration `00012_add_delivery_sending.sql`; see [Sending service mail](#sending-service-mail). Planned: retries and the unknown outcome policy (TASK-017), and sending product notifications with the permission check before a send (TASK-462). The delivery state gauges are implemented with TASK-022; see [Metrics, telemetry, and alerts](#metrics-telemetry-and-alerts). No product flow calls `MailRequester` yet, and no identity flow calls `ServiceMailer` yet (registration and reset are separate tasks), so a stored notification waits and no service mail exists outside the tests. A delivery is the durable state of sending one message to one recipient. A `deliveries` row holds: @@ -248,7 +248,7 @@ Creation path: 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. +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 created by the identity flows directly in the transaction that issues the token, through `ServiceMailer` (TASK-016), which uses `domain.NewDelivery` and `DeliveryRepository.Create` and binds the delivery to the token; the identity flows that call it (registration, resend, reset) are separate 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. @@ -256,7 +256,7 @@ Personal data at rest. A delivery row holds the recipient address and the bodies - 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. +- The bodies of a token mail are cleared when the delivery reaches `accepted`, `rejected`, or `cancelled` (`body_redacted_at`, see [Sending service mail](#sending-service-mail)), so a database dump or backup holds no token of a finished mail; a retention rule that deletes other terminal deliveries after a bounded period is not implemented yet, and until it exists those 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. The delivery metrics (TASK-022) carry only the kind, status, provider, and quota window labels, never the address, a user or delivery ID, the provider account label, or the subject. Statuses. The values follow the `MailSender` outcomes: @@ -264,15 +264,17 @@ 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 | +| `accepted` | The provider accepted the message and returned `provider_message_id`: "accepted by the provider". Not delivery to or reading by a person; no status claims that | 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 | +| `cancelled` | The message was deliberately not sent and never will be: the token or the account no longer matches, or the stored message is unsendable. `cancel_reason` says why; no attempt is recorded | None; terminal | | `waiting_quota` | A provider quota or the local quota is used up | Optional: the expected reset (see [Mail quotas](#mail-quotas)); none when the reset is unknown, for example after a provider quota answer that names neither a window nor a wait, and an operator 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.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`, `rejected`, and `cancelled` 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.Cancel(at, reason)` ends a `pending` or `waiting_quota` delivery in `cancelled` without an attempt; the reason is one of `token_missing`, `token_purpose_mismatch`, `token_owner_mismatch`, `token_consumed`, `token_revoked`, `token_expired`, `account_not_current`, `recipient_mismatch`, `content_invalid`, or `processing_failed`. It refuses `unknown`, like `WaitForQuota`: an earlier attempt may have been accepted, so it is never reported as not sent. `DeliveryRepository.Cancel` 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`. @@ -283,17 +285,13 @@ Quota accounting is not derived from this history: the cascade from an account d 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: +Migration `00012_add_delivery_sending.sql` (TASK-016) is additive; existing rows stay valid. It adds to `deliveries`: `email_token_id` (a nullable foreign key to `email_tokens.id` for token mail, immutable like the rest of the content, NULL for notifications), `cancel_reason` (set exactly when the status is `cancelled`, CHECK-limited to the reasons above), the lease columns `claim_owner` and `claimed_until` (both or neither; only a delivery the worker may still send holds one), `first_send_started_at` (when the first request started, by the database clock), `failure_count` (consecutive failures of the worker on the row), `body_redacted_at` (the bodies of a token mail were cleared), the status `cancelled` with its CHECKs, and two partial indexes: `deliveries_due_idx` on `(next_attempt_at, id)` whose predicate names the service kinds and the statuses that are picked up again, so notification rows never enter it and an idle poll does not scan them, and one on `email_token_id`. The trigger `deliveries_refuse_content_change` also allows exactly one change of the bodies: a terminal token mail may have both set to empty together with `body_redacted_at`, once. It adds the `password_reset` token purpose to `email_tokens`. The down migration turns cancelled deliveries into rejected ones and deletes reset tokens. Planned: a cancelled delivery for a revoked permission (TASK-462). -- 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 store already provides `Get`, `ListAttempts`, the version-checked `RecordAttempt`, `WaitForQuota`, and `Rebind`. +The store provides `Get`, `ListAttempts`, the version-checked `RecordAttempt`, `WaitForQuota`, `Cancel`, and `Rebind`, and for the sending worker `ClaimDue`, `ReleaseClaim`, and `ServiceMailState`. ### Mail quotas -Implemented (TASK-018): quota windows and limits in `backend/internal/domain/mail_quota.go`; the `outbound.MailQuotaRepository` port (`port/outbound/mail_quota.go`), whose writes go through `UnitOfWork.MailQuotas()` and whose reads also go through `postgres.MailQuotaStore`; migration `00007_create_mail_quota_usage.sql` with the `mail_quota_usage` and `mail_quota_reservations` tables; the queries in `backend/db/queries/mail_quota.sql`; in `backend/internal/usecase/notification/`, `QuotaGate` with `PrepareSend` and `SettleSend` (`quota.go`), the startup report `ReportQuotaUsage`, and the user status reader `DeliveryStatusReader` (`delivery_status.go`); `SendResult.QuotaPeriod` in the mail port, filled by the Resend adapter; and the startup report in bootstrap (`bootstrap/mail_quota.go`). Planned: the sending worker that calls the gate around `MailSender.Send` and builds it from configuration with `resend.IdempotencyWindow` or zero for SMTP (TASK-016) and the API or identity flow that shows the status reader's result. Nothing sends yet, so the current build counts nothing. +Implemented (TASK-018): quota windows and limits in `backend/internal/domain/mail_quota.go`; the `outbound.MailQuotaRepository` port (`port/outbound/mail_quota.go`), whose writes go through `UnitOfWork.MailQuotas()` and whose reads also go through `postgres.MailQuotaStore`; migration `00007_create_mail_quota_usage.sql` with the `mail_quota_usage` and `mail_quota_reservations` tables; the queries in `backend/db/queries/mail_quota.sql`; in `backend/internal/usecase/notification/`, `QuotaGate` with `PrepareSend` and `SettleSend` (`quota.go`), the startup report `ReportQuotaUsage`, and the user status reader `DeliveryStatusReader` (`delivery_status.go`); `SendResult.QuotaPeriod` in the mail port, filled by the Resend adapter; and the startup report in bootstrap (`bootstrap/mail_quota.go`). The sending worker (TASK-016) calls the gate around `MailSender.Send` and `bootstrap/mail_sender.go` builds it from configuration with `resend.IdempotencyWindow` or zero for SMTP; see [Sending service mail](#sending-service-mail). Planned: the API or identity flow that shows the status reader's result. Only service identity mail counts against the quota while TASK-462 is open. Limits. `EMAIL_QUOTA_DAILY` and `EMAIL_QUOTA_MONTHLY` limit the recipients sent through the configured provider account (`EMAIL_PROVIDER` and `EMAIL_ACCOUNT`) per UTC day, from 00:00 to 00:00 UTC, and per UTC calendar month. Every recipient counts, as Resend counts them; a delivery has one recipient. The defaults are the Resend Free limits checked on 2026-10-05, 100 and 3000; they apply to `resend` and to `disabled`, which sends nothing. `smtp` has no default and does not start without both values, because a relay's limits are not Resend's. Values range from 1 to 1000000000, and the daily limit must not exceed the monthly one. No value turns the quota off, so no provider runs without the gate. Limits are configuration, not domain constants, and are not stored: a changed limit applies from the next reservation, and a limit lowered below the current usage defers every new send until the window resets. @@ -330,11 +328,82 @@ What the user sees. `notification.DeliveryStatusReader.LatestForUser(ctx, userID | `waiting_quota` with `WaitingUntil` | Your email is waiting until `` | | `waiting_quota` without `WaitingUntil` | Your email is waiting; the time is not known yet | | `pending`, `unknown` | Your email is being sent. `unknown` is not shown as a failure: the message may have been accepted | -| `accepted` | Your email was sent. It means that the provider accepted it, not that it reached the inbox | +| `accepted` | Your email was handed to the email provider, which accepted it. We cannot confirm that it reached your inbox | | `rejected` | Your email could not be sent | +| `cancelled` | Your email was not sent because the link in it is no longer valid; request a new one | Operators read the same rows with the queries in [DEPLOY.md](DEPLOY.md#mail-quotas). The gate logs `mail quota is used up; the delivery waits for the reset` at info level and `the mail provider reported its quota used up; local sending stops until the reset` at warn level, with only the delivery ID, provider, period, and reset time. The quota gauges (TASK-022) come from `MailQuotaUsageReader.Usage` for the configured account, with the labels provider and window only; see [Metrics, telemetry, and alerts](#metrics-telemetry-and-alerts). +### Sending service mail + +Implemented (TASK-016): the sending usecase `ServiceMailSender` (`backend/internal/usecase/notification/service_sender.go`), the enqueue usecase `ServiceMailer` (`service_mail.go`), the minimum retry schedule `RetryPolicy` (`send_retry.go`), `Delivery.CheckServiceMail` and `Delivery.Cancel` with the cancel reasons (`backend/internal/domain/delivery.go`, `delivery_guard.go`), the loop in `backend/internal/worker/mailsender/`, the inbound port `inbound.MailPass` (`port/inbound/mail_sender.go`), the repository methods `ClaimDue`, `ReleaseClaim`, `Cancel`, and `ServiceMailState`, migration `00012_add_delivery_sending.sql`, the gauge `lincodex_mail_sender_running`, and the wiring in `bootstrap/mail_sender.go`. Not implemented: sending product notifications (TASK-462), the retry and unknown outcome policy (TASK-017), and the identity flows that call `ServiceMailer`. + +Scope. The worker claims only the kinds `verification` and `password_reset`. A product notification is never claimed here, whatever its state. Service mail needs no consent record of any purpose: it is part of the account flow, so nothing reads the consent ledger, and C2 (publication of the candidate card) and the other product consents play no part. What stands between the account and the mail is the check below, not a consent. + +Enqueue. `ServiceMailer.EnqueueVerification` and `EnqueuePasswordReset` run in the transaction that inserts the token, with the token record, the raw token, the recipient address, and the lifetime in hours. They check that the token purpose fits the message, render the message once with the current template version, and store a `pending` delivery bound to the token (`email_token_id`) under the token's ID as the delivery ID. A repeated call for the same token stores nothing new, and the stored body stays as it was. + +Links. The token travels only in the URL fragment: `/verify-email#token=` and `/reset-password#token=`, built by `mailtemplate` (`tokenLink`). A browser never sends the fragment to a server, so the token stays out of the nginx access log, which records `$uri`, out of Referer headers, and out of the Go request log; it is not in the path and not in the query. The frontend route reads the fragment and sends the token in the body of an API request. A query would be needed only if a frontend route could not read the fragment, and then the page would have to send the token onward and the access log would see it, so the fragment is the choice. The renderer rejects a token in any other place, its golden files and tests fix the format, and the delivery tests check that the stored body holds the link with the fragment and no `?token=`. The body in `deliveries` holds the live token until the mail is sent or cancelled; see Personal data at rest. + +One pass of `ServiceMailSender.ProcessNext` takes one delivery through three steps: + +1. Claim transaction. `DeliveryRepository.ClaimDue` takes the most overdue due delivery with `FOR UPDATE SKIP LOCKED`: kind `verification` or `password_reset` (literals that match the predicate of `deliveries_due_idx`, so the poll reads only that small index), status `pending` or `waiting_quota`, `next_attempt_at` passed, pinned to the configured provider account, and held by no live lease. It sets `claim_owner` and `claimed_until` (the lease) without changing the version or the update time, so several processes never take one delivery. The lease is measured by the database clock (`clock_timestamp()` plus the lease length, and live while `claimed_until` is later than `clock_timestamp()`), never by the clock of an application instance, so instances whose clocks differ cannot take over a live lease or hold a dead one; due times stay on the application clock that wrote them. A delivery in `unknown`, or in `waiting_quota` without a time, has no due time and waits for an operator. In the same transaction the sender rebinds mail stored while `EMAIL_PROVIDER=disabled` to the configured account (allowed before the first attempt only, so no provider holds its key), runs the check below, and then `QuotaGate.PrepareSend`, which reserves the recipient or parks the delivery in `waiting_quota`. The transaction commits before the transport is called, so a slow provider never holds a row lock. A failure inside it (a deterministic one, such as a row that cannot be restored) rolls the lease back too, so the failure is then recorded for the row in a transaction of its own; see Failing rows. +2. Check right before the send, one short transaction: it locks the delivery row (only for the lease holder), reads the token and the account again with `ServiceMailState`, so a revocation after the claim committed is honored, and notes `first_send_started_at` the first time. A mail that is no longer valid is cancelled and its reservation given back. Then one call to `MailSender.Send` with the stored content and the stable idempotency key `delivery/`. The sender never retries. The call is bounded by what is left of the lease after the claim and the settlement budget, and by the shutdown grace. +3. Settlement transaction. It locks the delivery row first (only while this worker still holds the lease), then `QuotaGate.SettleSend` and `DeliveryRepository.RecordClaimedAttempt` commit together, and the lease ends with the attempt. `RecordClaimedAttempt` applies only over the delivery's version and only for the lease owner, so a worker whose lease was taken over cannot record, and if two workers reach this step for one delivery only the first is kept; the other rolls back, including its quota settlement, and reports `lease_lost`. A database failure while storing the answer is repeated up to three times inside a settlement budget, because the answer exists only in memory until it is stored. + +Time budget. The lease is `EMAIL_TIMEOUT` plus one minute. The claim and the check come first; the call gets what remains of the lease minus the settlement budget (20 seconds), so claim, call, and the whole settlement fit inside the lease. When shutdown has begun the settlement budget is the shorter of 5 seconds and `SHUTDOWN_TIMEOUT` minus the 3-second shutdown grace (at least 1 second), so the process stops within its shutdown timeout, which is 10 seconds by default (the Compose stop grace period is 30 seconds). A result that cannot be stored in time is covered by the takeover below. + +Lock order. Every path locks the delivery row first and the quota rows second: the claim locks the row with `FOR UPDATE SKIP LOCKED`, and the check and the settlement start with `LockClaimed` (`SELECT ... FOR UPDATE` of the row of the lease holder), so no two paths can wait for each other in opposite directions. + +Check before sending. In the claim transaction, `Delivery.CheckServiceMail` compares the delivery with a snapshot read in one statement (`ServiceMailState`: the token and the account, no lock, only the address comparison key). The first failure cancels the delivery with `cancelled` and that reason; nothing is reserved and nothing is sent: + +| Order | Rule | Reason | +| --- | --- | --- | +| 1 | A token is bound and its row exists | `token_missing` | +| 2 | Its purpose is the one the mail kind carries (`email_verification` for verification, `password_reset` for reset) | `token_purpose_mismatch` | +| 3 | It belongs to the recipient account | `token_owner_mismatch` | +| 4 | It is not consumed | `token_consumed` | +| 5 | It is not revoked (`invalidated_at`, by a resend or a re-registration) | `token_revoked` | +| 6 | It has not expired | `token_expired` | +| 7 | The account still has the registration version the token was issued for, and a verification mail does not go to an address that is verified already | `account_not_current` | +| 8 | The address in the delivery is still the account's address | `recipient_mismatch` | + +A claimed row whose content no longer matches its hash (only a manual edit can cause that) is cancelled by the claim itself with `content_invalid`, with the bodies cleared like any cancelled token mail, and logged at error level with the delivery ID. Any other failure to restore a row may be transient, so it is not cancelled for good: it is a failing row, below. + +There is no deactivated flag on an account. "Current" is rule 7 and the token rules: a re-registration moves the version and revokes the token, and a deleted account takes its deliveries with it by cascade, so nothing is left to send. A reset mail has no verification-state rule: that the reset applies only to verified accounts is a product decision for the reset flow. The check is a snapshot: a token consumed or revoked after it, before the provider call, still lets the mail go. That is harmless, because the link is checked again when it is used. + +What a provider answer becomes. The delivery state machine of `domain.Delivery` decides; the worker only fills the attempt: + +| Result | Delivery | Next attempt | Quota | +| --- | --- | --- | --- | +| `accepted` | `accepted`, provider message ID stored | none | counted | +| `rejected` `permanent` or `invalid_request` | `rejected` | none | released | +| `rejected` `temporary` or `rate_limited` | `pending` | now plus `RetryPolicy`: 1 minute, doubling to at most 30 minutes, never shorter than the provider's `Retry-After` | released | +| `rejected` `quota_exhausted` | `waiting_quota` | the reset the gate returns (next 00:00 UTC for a day, the first of the next month for a month); none when the provider named no window | window marked full | +| `unknown` | `unknown` | none: no automatic retry (TASK-017) | counted | +| `Send` error: no transport (`ErrMailChannelUnavailable`) or the context ended | unchanged, lease released | still due | released | +| `Send` error: invalid message (`ErrInvalidOutgoingMail`) | `cancelled`, `content_invalid` | none | released | +| `Send` error: anything else without an answer | not counted against the row; it moves back by `RetryPolicy` and the worker backs off | now plus `RetryPolicy` | released | + +The retry schedule has no attempt limit on purpose: the token expires, and the check then cancels the delivery with `token_expired`. Each delay gets bounded jitter, up to a fifth over the schedule, from an injectable source (nil in tests, so times are exact), so deliveries refused together do not return together. `unknown` is never read as not sent and is never repeated by the worker; an operator decides, and the alert `LincodexMailDeliveryUnknownOutcome` fires. + +A worker lost after the call. If a worker stops after it called the provider but before it stored the answer, its lease expires and another worker claims the delivery on the same attempt and repeats the request with the same idempotency key. Resend answers a repeated key and body with the original result, and the quota gate reuses the open reservation, so the message exists once and counts once. The provider keeps the key for 24 hours from the first request, so the age is counted from `first_send_started_at` (set by the database clock right before the first request), not from the latest lease: however many workers were lost in turn, and whatever the lease length, once that age reaches 23 hours (the window less a one-hour safety margin) the earlier request may be forgotten and repeating it could send twice, so the delivery is recorded as an `unknown` attempt without a next attempt instead. The same applies at once to a transport without provider-side deduplication (window zero, SMTP). A lease that never reached the first request leaves nothing in doubt. + +Failing rows. A fault in one row must not hold the head of the queue. When the claim transaction fails after it took a row, its lease rolls back with it, so the same row would be claimed again at once and every delivery behind it would wait. Only a fault that the row itself causes is counted against it: a domain rule it breaks (`ErrInvalidDelivery`, `ErrDeliveryTransition`, invalid content or address), a row that cannot be restored for a reason other than a hash mismatch, or a data or integrity constraint refusal (SQLSTATE classes 22 and 23, `outbound.ErrRowFault`). Everything else says nothing about the row and is never counted: a context that ended, a timeout, a deadlock, a lost connection (SQLSTATE 08, 40, 53, 57, XX), an I/O error, a missing quota configuration. Such an error is returned to the worker, which backs off like for any global failure, and the lease expires or rolls back. For a counted fault the sender records the failure in a short transaction of its own (`RecordFailure`): `failure_count` is incremented, the lease ends, and the row is due again by `RetryPolicy` (outcome `row_failed`; the next pass takes the delivery behind it). The statement leaves a row alone that another worker holds under a live lease, so a claim that rolled back cannot disturb a row that someone else has just claimed. The count means consecutive failures: a successful claim and preparation (the check before the send) clears it, and so does a recorded attempt. A circuit breaker in the worker stops the counting when failures hit different rows pass after pass: three passes in a row that fail on three different rows are read as a global fault, the worker waits with a growing backoff (a `row_failed` pass never loops at once), and failures are moved back but not counted, and no row is cancelled, until a pass succeeds. After 3 consecutive counted failures the row is cancelled with the reason `processing_failed`, the existing terminal status that fits: it is visible to the operator and the alert below fires, and a new status was not needed. A database outage that also stops this record leaves the row under its lease, which expires. + +`EMAIL_PROVIDER=disabled`. Bootstrap does not start the loop: `newMailSenderWorker` returns no worker and logs `mail sender worker is not started because EMAIL_PROVIDER is disabled; stored deliveries wait`, so `lincodex_mail_sender_running` stays 0 and `LincodexMailDeliveriesOverdue` stays silent. Stored mail waits, pinned to `disabled`; after the stand restarts with a transport the worker rebinds it and sends it, if the token and the account still pass the check. A worker that is run against the disabled transport anyway (tests) gets `ErrMailChannelUnavailable` from every send, records nothing, releases the lease and the reservation, and backs off (5 seconds doubling to 2 minutes) instead of claiming again at once, so it never spins. + +Loop and shutdown. `worker/mailsender` repeats passes: a pass that handled a delivery is followed at once by the next, an idle pass waits 5 seconds, and a database failure, a missing transport, or an interrupted call waits with the growing backoff. When the context ends the worker claims nothing more, lets the send in progress continue for 5 seconds, stores its result, and returns; the gauge is 0 from then on. The loop is a goroutine of the backend process on its own pool of two connections, like the other workers; more throughput comes from more instances, and each handles one delivery at a time, which suits service mail under the Resend Free quota. + +Token at rest. The body of a token mail holds the one-time token, and a reset token is an account takeover primitive for anyone who can read the database or a backup. When a token mail reaches `accepted`, `rejected`, or `cancelled` (by any path: an attempt, a cancellation, the broken-row cancellation, or `processing_failed`), the same statement sets `text_body` and `html_body` to empty and `body_redacted_at`; the subject, the content hash, and the template version stay. The trigger allows exactly that change once, for a terminal row, and refuses any other change of the bodies or of the mark; the CHECK `deliveries_body_present` accepts an empty body only with the mark; the domain restores such a row as redacted content (`RestoreRedactedMailContent`), which cannot be sent. `unknown` is not terminal and keeps its body, because a retry resends it; an operator who resolves it must clear it. Notifications are not redacted. Rolling back migration 00012 puts a placeholder in cleared bodies. + +Privacy. Logs name a delivery only by `delivery_id`, its kind, and closed values (the outcome and the cancel reason); no address, token, link, subject, or body appears in a log line, an error, or a metric label, and the metric has no labels at all. `ServiceMailSender` builds the outgoing message from the stored content and never logs it; `OutgoingMail` and `Delivery` redact themselves. + +Test fixture only. `resendfixture` and `resend.NewLoopbackSender` are never used by production code: `backend/.golangci.yml` forbids importing the fixture and calling the constructor outside `_test.go` files (depguard and forbidigo), and `bootstrap` binds the real transport with `resend.NewSender`. + +Tests. `integration_test/mail_sender_test.go` runs a local Resend fixture (`resendfixture`, an `httptest` server speaking the part of the API the transport uses, reached through `resend.NewLoopbackSender`, which accepts only a loopback endpoint) against PostgreSQL; see [TESTING.md](TESTING.md). It is a test fixture only; production binds the real Resend transport with its fixed endpoint. + +Open points. `unknown` has no automatic retry or escalation until TASK-017. Sending notifications, and the permission check they need, belong to TASK-462; until then they wait, and they are not counted in the overdue gauge, so a notification backlog does not fire `LincodexMailDeliveriesOverdue` (the gauge `lincodex_mail_delivery_oldest_due_pending_age_seconds` covers `domain.ServiceMailKinds`; its predicate is the one of `deliveries_due_idx`). Whether a password reset goes to unverified accounts is for the reset flow to decide. The poll runs every 5 seconds and the claim reads one indexed statement, which suits the current volume. + ### 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. @@ -423,7 +492,7 @@ backend/ usecase/policy/ publication of policy versions and the demo policy seed usecase/consent/ granting of consents C1-C3 and C5 and the scoped C4 with the current-text check usecase/files/ shared private file layer: policies, opaque keys, stream limits, checksums - usecase/notification/ mail requests and the consumer that stores them as deliveries + usecase/notification/ mail requests and the consumer that stores them as deliveries, the quota gate, the service mail enqueue (`ServiceMailer`), and the sender of service mail (`ServiceMailSender`) 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, consent ledger, organization and membership, policy, password hashing, and mail boundaries adapter/primary/http/ @@ -438,6 +507,7 @@ backend/ kafka/ franz-go event publisher and consumer group member: record envelope, its decoding, and events topic provisioning mail/disabled/ mail transport that sends nothing and reports the channel unavailable mail/resend/ mail transport that sends one request to the Resend HTTP API per message + mail/resend/resendfixture/ local stand-in for the Resend API, for tests only; production never imports it ml/api/ generated client from backend/codegen/ogen-ml.yml postgres/ pool, migrator, transactor, outbox writer and relay store, event consumer store, identity, consent ledger, organization, membership, and policy repositories, health check postgres/sqlc/ generated SQL adapter @@ -447,6 +517,7 @@ backend/ worker/outboxrelay/ outbox relay loop: claim, publish, mark, backoff, and shutdown worker/eventconsumer/ event consumer runtime: dedup transaction, retries, dead letters, offset commits, and shutdown worker/jobrunner/ scheduled job runtime: claim under a lease, run with the completion, retries, release, and shutdown + worker/mailsender/ sending loop of service identity mail: repeats passes, waits when idle, backs off on failures, reports lincodex_mail_sender_running worker/retry/ backoff with jitter and a context-aware wait shared by the workers worker/deliverymetrics/ periodic read of the delivery and mail quota aggregates into the metrics bootstrap/ configuration, wiring, lifecycle, shutdown @@ -459,9 +530,9 @@ Domain types live directly in `backend/internal/domain/`: `user.go`, `candidate. Product domain types and usecase modules, the SMTP and FSP adapters, and product worker jobs are reserved areas; their business behavior is not implemented. Keep `main.go` limited to starting bootstrap and handling process errors. The public generated transport uses ogen v1.24.0 and the contracts declare OpenAPI 3.2.0. Verify only the feature subset used by the repository, not every specification feature. -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 the `notification_delivery` handler, the scheduled job runtime (`worker/jobrunner`) with no registered product job kind, 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 with the shared private file layer over it, 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, product job kinds, file workflows, mail delivery, the SMTP transport, and FSP adapters remain planned. Do not create empty module directories before a real use case exists. +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 the `notification_delivery` handler, the scheduled job runtime (`worker/jobrunner`) with no registered product job kind, 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 with the shared private file layer over it, the `MailSender` port with the `disabled` and Resend transports, the mail template renderer, and the sending worker of service identity mail, which no account flow feeds yet. Account behavior (registration, verification, login, sessions), resumes, assessments, invitations, product job kinds, file workflows, sending product notifications, 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. `pkg/testutil/` holds `FakeClock`, a concurrency-safe manual clock that the worker, integration, and future usecase tests inject wherever production code takes a `func() time.Time` clock, and `FindPersonalIdentifiers`, which the metrics tests use to find email-like and UUID-like values in an exposition. A `mailer` package remains a candidate. 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/`. +`backend/pkg/` is reserved for small technical packages with a justified shared boundary, not product usecases or domain types. `pkg/testutil/` holds `FakeClock`, a concurrency-safe manual clock that the worker, integration, and future usecase tests inject wherever production code takes a `func() time.Time` clock, and `FindPersonalIdentifiers`, which the metrics tests use to find email-like and UUID-like values in an exposition. A `mailer` package remains a candidate. 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; `ServiceMailer` renders verification and password reset mail with it when the identity usecases issue a token, and those usecases (registration, resend, reset) are separate tasks. 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. @@ -719,7 +790,7 @@ The Go service exports standard Go/process metrics and the product metrics of TA - API: `lincodex_http_requests_total{method,route,status}`, `lincodex_http_request_duration_seconds{method,route,status_class}`, and `lincodex_http_problems_total{route,code}`. `route` is the chi route template of an operational route and, under `/api/v1`, the OpenAPI path template of the matched operation, such as `/api/v1/me/invitations/{invitation_id}`, which the router resolves with the generated server's `FindPath`; a path or method without an operation keeps the mount pattern `/api/v1/*` or `/api/*`, and a path outside every route is `unmatched`. `status_class` is `1xx` to `5xx`. `code` is the RFC 9457 problem code: `problem.New` records it from the closed catalogue through the request-scoped `observe` package (`adapter/primary/http/observe/`), the middleware counts it only for a 4xx or 5xx response, and the adapter counts a code outside its mirrored list as `other`. An error without a problem body, such as `/readyz` 503, is counted by status only. The request log (`middleware.RequestLog`, which replaces the go-httpkit logger) uses the same route template and logs the request ID, method, status and class, problem code, latency, response size, and the number of query parameters, never the raw path, a query key or value, a header, the client address, or the user agent; `/healthz` and `/readyz` are not logged. - Outbox and events: the relay, consumer, and scheduled job metrics in [Outbox relay](#outbox-relay), [Event consumers](#event-consumers), and [Scheduled jobs](#scheduled-jobs). Outbox lag is `lincodex_outbox_relay_oldest_pending_age_seconds`. -- Mail: `lincodex_mail_deliveries{kind,status}` for every kind and the statuses `pending`, `waiting_quota`, `unknown`, `accepted`, and `rejected`, zero included; `lincodex_mail_delivery_oldest_due_pending_age_seconds`; and, for an active transport, `lincodex_mail_quota_used_recipients`, `lincodex_mail_quota_limit_recipients`, and `lincodex_mail_quota_provider_exhausted`, each with `provider` and `window` (`day` or `month`). The sampler in `backend/internal/worker/deliverymetrics/` reads them every 30 seconds on its own one-connection pool: `postgres.DeliveryStatisticsStore` aggregates `deliveries` by kind and status, and `MailQuotaUsageReader.Usage` reads the current windows of the configured account. The delivery aggregate is the sqlc query `GetDeliveryStatistics` in `db/queries/delivery.sql`. It scans the table, which suits the current volume; add an index or per-status counters before the table holds millions of rows. `EMAIL_ACCOUNT` is not a label: it is free operator text that can name a person, and each process reports only its own account. Every instance reports the same database-wide values; aggregate them with `max`. A failed read keeps the previous values and logs `delivery metrics could not be read; the gauges are stale`; `lincodex_mail_metrics_last_success_timestamp_seconds` shows the last read in which every aggregate was read (0 from the sampler start until the first one), and the age gauge exists only after the first successful read. There is no attempt outcome counter yet, because the sending worker (TASK-016) does not exist. +- Mail: `lincodex_mail_deliveries{kind,status}` for every kind and the statuses `pending`, `waiting_quota`, `unknown`, `accepted`, `rejected`, and `cancelled`, zero included; `lincodex_mail_sender_running`, 1 while this process's mail sending loop runs and 0 otherwise (per process, so aggregate it with `max`; it stays 0 with `EMAIL_PROVIDER=disabled`, where no loop starts); `lincodex_mail_delivery_oldest_due_pending_age_seconds`, which counts only service mail (`domain.ServiceMailKinds`), so a notification backlog never looks overdue; `lincodex_mail_sender_cancelled_total{reason}`, deliveries the sending worker ended without sending, by the closed set of cancel reasons, zero included; and, for an active transport, `lincodex_mail_quota_used_recipients`, `lincodex_mail_quota_limit_recipients`, and `lincodex_mail_quota_provider_exhausted`, each with `provider` and `window` (`day` or `month`). The sampler in `backend/internal/worker/deliverymetrics/` reads them every 30 seconds on its own one-connection pool: `postgres.DeliveryStatisticsStore` aggregates `deliveries` by kind and status, and `MailQuotaUsageReader.Usage` reads the current windows of the configured account. The delivery aggregate is the sqlc query `GetDeliveryStatistics` in `db/queries/delivery.sql`. It scans the table, which suits the current volume; add an index or per-status counters before the table holds millions of rows. `EMAIL_ACCOUNT` is not a label: it is free operator text that can name a person, and each process reports only its own account. Every instance reports the same database-wide values; aggregate them with `max`. A failed read keeps the previous values and logs `delivery metrics could not be read; the gauges are stale`; `lincodex_mail_metrics_last_success_timestamp_seconds` shows the last read in which every aggregate was read (0 from the sampler start until the first one), and the age gauge exists only after the first successful read. There is no attempt outcome counter yet; the delivery states, the logs of the sending worker, and the `delivery_attempts` history show outcomes. - Assessment answers: `lincodex_assessment_answer_saves_total{format,outcome}` with the outcomes `stored`, `unchanged`, `rejected`, and `failed`. PRD 6.6 asks to observe the saving of answers; this is read as the assessment answer command `SubmitMyAssessmentAnswer`. The command is not implemented, so only the hook `Metrics.ObserveAssessmentAnswerSave` exists, and no series appears until the usecase calls it once per command. A value outside the closed sets becomes `other`. The HTTP latency and errors of the command already appear under the route `/api/v1/me/assessment-attempts/{attempt_id}/answers`. Do not use user, candidate, delivery, or request IDs, full URLs or query strings, addresses, or resume content as labels. Unit tests drive the real router and every metric hook with email and UUID fixtures and fail when the exposition contains an email-like or UUID-like value. Go runtime, PostgreSQL, Redis, SeaweedFS, Linux, and Lincodex product dashboard JSON files are maintained project sources, not imported dashboard IDs. Inference metrics are not implemented in the current scaffold. @@ -728,7 +799,7 @@ Planned observability work includes bounded measurements for queued jobs, oldest The planned browser path is Faro Web SDK -> same-origin `/telemetry` -> Alloy `faro.receiver` -> Loki. The React SDK is not connected yet. Collect cleaned Web Vitals, JavaScript errors, release, and normalized route; exclude console logs, form content, resume text, and session replay. Remove query strings, fragments, and identifiers from URLs. Limit receiver size, rate, and origin. Request/trace IDs remain log fields, not labels; complete span storage needs a separate backend such as Tempo and is not currently supported. -Alert rules in `observability/prometheus/rules/lincodex.yml` cover an unavailable backend target, a 5xx share above 5% with at least 15 requests in 5 minutes, outbox lag, dead letters and stalled consumers, dead and lagging scheduled jobs, deliveries with an unknown outcome, stale delivery and quota gauges, a used-up mail quota, and overdue deliveries; the last one also requires `lincodex_mail_sender_running`, which the sending worker of TASK-016 must export, so it stays inert until then. `promtool test rules` gives every alert a firing case and every guard a silent one. Prometheus evaluates them and shows their state on its /alerts page and in Grafana; no Alertmanager or notification channel is configured, so no alert reaches a person. Future alerts cover latency budget breaches, disk pressure, ML errors, and dropped logs. Low traffic needs a window and minimum event count to avoid unstable rates and percentiles. Configure `No Data` and datasource-error behavior explicitly. A monitoring stack cannot reliably report a host failure on that same host; that requires an independent external health check. Compose and dashboard smoke checks do not verify alert delivery. Document alert rules and notification channels as implemented only after they have been tested. +Alert rules in `observability/prometheus/rules/lincodex.yml` cover an unavailable backend target, a 5xx share above 5% with at least 15 requests in 5 minutes, outbox lag, dead letters and stalled consumers, dead and lagging scheduled jobs, deliveries with an unknown outcome, stale delivery and quota gauges, a used-up mail quota, and overdue deliveries; the last one also requires `lincodex_mail_sender_running` to be 1 on some instance, so it stays silent where no sending loop runs, for example with `EMAIL_PROVIDER=disabled`. It counts only service mail, the kinds the worker sends, so a due notification does not fire it. `LincodexMailCancelledBroken` fires on an increase of `lincodex_mail_sender_cancelled_total` with the reason `content_invalid` or `processing_failed`, the cancellations that mean a broken row or a defect rather than a user action. `promtool test rules` gives every alert a firing case and every guard a silent one. Prometheus evaluates them and shows their state on its /alerts page and in Grafana; no Alertmanager or notification channel is configured, so no alert reaches a person. Future alerts cover latency budget breaches, disk pressure, ML errors, and dropped logs. Low traffic needs a window and minimum event count to avoid unstable rates and percentiles. Configure `No Data` and datasource-error behavior explicitly. A monitoring stack cannot reliably report a host failure on that same host; that requires an independent external health check. Compose and dashboard smoke checks do not verify alert delivery. Document alert rules and notification channels as implemented only after they have been tested. ## Requirements coverage diff --git a/docs/en/DEPLOY.md b/docs/en/DEPLOY.md index 23f1984..3c129d0 100644 --- a/docs/en/DEPLOY.md +++ b/docs/en/DEPLOY.md @@ -218,7 +218,7 @@ A worker claims it within one poll interval and runs it with fresh attempts. To 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: mail requests are stored as deliveries (see [Mail deliveries](#mail-deliveries)), and the worker 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. The backend process runs a sending worker for service identity mail (email verification and password reset) whenever `EMAIL_PROVIDER` is `resend`; see [Sending service mail](#sending-service-mail). No account flow creates such mail yet, and product notifications are stored as deliveries but not sent until TASK-462, so a production stand sends no message today. `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, and outcome records belong to the planned delivery layer, and the wait for a daily or monthly quota reset is decided by the quota gate (see [Mail quotas](#mail-quotas)). 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). @@ -243,18 +243,18 @@ Compose passes these variables from the root `.env`; it passes an unset `EMAIL_Q ### 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. +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. Notification deliveries are only stored for now: the sending worker claims verification and password reset mail only, so a notification stays `pending` until TASK-462 connects product notifications. 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. +- 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. Service mail created while `EMAIL_PROVIDER=disabled` stays pinned to `disabled` until the backend runs with a transport: the sending worker then moves it with `Rebind` (allowed only before the first attempt) and sends it if its token and account still pass the check. Do not rebind by hand. - 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. -- Without SQL, the internal /metrics endpoint shows `lincodex_mail_deliveries{kind,status}` for every kind and status, zero included, and `lincodex_mail_delivery_oldest_due_pending_age_seconds`, the time the earliest pending delivery has been due. The backend reads them every 30 seconds with one aggregate over `deliveries`; every instance reports the same values, so aggregate them with `max`. A read that fails keeps the previous values and logs `delivery metrics could not be read; the gauges are stale`. Until the sending worker exists (TASK-016), every stored delivery stays `pending` and its due age only grows. The age series appears only after the first successful read, so a fresh start never claims that nothing is late; `lincodex_mail_metrics_last_success_timestamp_seconds` is the Unix time of the last read in which every aggregate was read (0 from the start until the first one), and `LincodexMailMetricsStale` fires when it is more than 5 minutes old for 5 minutes. The alert `LincodexMailDeliveryUnknownOutcome` fires while any delivery has an unknown outcome. `LincodexMailDeliveriesOverdue` (a pending delivery due for more than 15 minutes) also requires `lincodex_mail_sender_running` to be 1; that gauge belongs to the sending worker of TASK-016, which must export it while its loop runs, so the alert stays silent while no sender exists, with `EMAIL_PROVIDER=disabled`, and without traffic. +- Without SQL, the internal /metrics endpoint shows `lincodex_mail_deliveries{kind,status}` for every kind and status, zero included, and `lincodex_mail_delivery_oldest_due_pending_age_seconds`, the time the earliest pending delivery has been due. The backend reads them every 30 seconds with one aggregate over `deliveries`; every instance reports the same values, so aggregate them with `max`. A read that fails keeps the previous values and logs `delivery metrics could not be read; the gauges are stale`. Notifications stay `pending` until TASK-462; they are not counted in the due age. The age series appears only after the first successful read, so a fresh start never claims that nothing is late; `lincodex_mail_metrics_last_success_timestamp_seconds` is the Unix time of the last read in which every aggregate was read (0 from the start until the first one), and `LincodexMailMetricsStale` fires when it is more than 5 minutes old for 5 minutes. The alert `LincodexMailDeliveryUnknownOutcome` fires while any delivery has an unknown outcome. `LincodexMailDeliveriesOverdue` (a pending delivery due for more than 15 minutes) also requires `lincodex_mail_sender_running` to be 1 on some instance: the sending worker exports it, 1 while its loop runs and 0 otherwise, so the alert stays silent with `EMAIL_PROVIDER=disabled` (no loop starts) and without traffic. The age counts only service mail (verification and password reset), so a backlog of notifications, which the worker does not send until TASK-462, does not fire it. The status `cancelled` is counted like the others, and `accepted` means accepted by the provider. - 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` waits for the quota reset at `next_attempt_at`; see [Mail quotas](#mail-quotas). Without `next_attempt_at` its reset is unknown and it 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 quotas -Migration 00007 creates `mail_quota_usage` and the reservation journal `mail_quota_reservations` at startup; it needs no setting. The quota gate is implemented, but the sending worker that calls it is planned (TASK-016), so the current build counts nothing yet. The model is in [ARCHITECTURE.md](ARCHITECTURE.md#mail-quotas). +Migration 00007 creates `mail_quota_usage` and the reservation journal `mail_quota_reservations` at startup; it needs no setting. The sending worker calls the quota gate around every send (see [Sending service mail](#sending-service-mail)), so service mail counts against the quota and notifications do not until TASK-462. The model is in [ARCHITECTURE.md](ARCHITECTURE.md#mail-quotas). - Set `EMAIL_QUOTA_DAILY` and `EMAIL_QUOTA_MONTHLY` to the plan of the provider account named by `EMAIL_ACCOUNT`. The defaults are Resend Free: 100 recipients per UTC day and 3000 per month, as checked on 2026-10-05. Check the account's current quota in the Resend dashboard before the stand goes live and after any plan change. With `smtp`, set both to the relay's limits; startup fails without them. A changed value applies after a restart. - Change `EMAIL_ACCOUNT` only together with a real change of the provider account, that is, a key of another account. The local count is kept per account label, so renaming the label for the same account starts a new count from zero while the provider keeps the old one. At startup the backend logs `mail quota usage` with the provider, account, and the current day and month usage and limits, and warns when other labels of the same provider have usage this month. @@ -266,12 +266,28 @@ Migration 00007 creates `mail_quota_usage` and the reservation journal `mail_quo - Resend's monthly quota follows the account's billing cycle, while the gate's month is the UTC calendar month. After a monthly refusal the delivery retries at the next UTC month start; if the billing cycle resets later, that retry is refused again and waits another month. A manual retry with an audit record is planned with the retry policy (TASK-017). - Lowering a limit takes effect on the next reservation. During a rolling deploy, instances with the old and the new limits run side by side and each checks the limit it was started with, so a lowered limit holds only once every instance runs the new configuration. Switching `EMAIL_PROVIDER` to `smtp` starts separate counters for the relay under its own stated limits; deliveries pinned to the old account are refused by the gate rather than sent without a limit. +### Sending service mail + +The backend process runs one sending loop for service identity mail (email verification and password reset). It starts with the backend when `EMAIL_PROVIDER` is `resend` and `DATABASE_URL` is set, shares the database with the other workers on a pool of two connections, and needs no setting of its own: the poll interval (5 seconds), the lease on a claimed delivery (`EMAIL_TIMEOUT` plus one minute), the shutdown grace (5 seconds), the retry schedule (1 minute doubling to 30 minutes), and the failure backoff (5 seconds doubling to 2 minutes) are constants in `backend/internal/bootstrap/mail_sender.go`. Migration 00012 adds its columns; the model, the checks, and the outcomes are in [ARCHITECTURE.md](ARCHITECTURE.md#sending-service-mail). + +- Several backend instances may run at once. Each claims a delivery with `FOR UPDATE SKIP LOCKED` and a lease, so one delivery is sent by one instance, and the provider call carries the stable idempotency key `delivery/`. During a rolling deployment the instance that stops finishes its send within 5 seconds, stores the result, and exits. +- With `EMAIL_PROVIDER=disabled` the loop does not start and the log says `mail sender worker is not started because EMAIL_PROVIDER is disabled; stored deliveries wait`; `lincodex_mail_sender_running` is 0, nothing is sent, and stored service mail waits for the next start with a transport. The worker never spins: after a pass that could not send it backs off. +- Before it sends, the worker checks the token and the account. A delivery that must not go out ends as `cancelled` with a `cancel_reason`, no attempt, and no quota use: `token_missing`, `token_purpose_mismatch`, `token_owner_mismatch`, `token_consumed`, `token_revoked`, `token_expired`, `account_not_current`, `recipient_mismatch`, `content_invalid`, or `processing_failed`. The user-caused reasons are normal: a user asked for a new link, confirmed the address, registered again, or waited too long. To see the reasons: `SELECT cancel_reason, count(*) FROM deliveries WHERE status = 'cancelled' GROUP BY cancel_reason`. A user sees a cancelled mail as "not sent, request a new one". +- Provider answers: `accepted` means accepted by the provider, not delivered to a person; the backend has no delivery confirmation. A refusal for now (`temporary`, `rate_limited`) leaves the delivery `pending` with a later `next_attempt_at`, and the retry reuses the same key and body; it repeats until it succeeds, is refused for good, or the token expires and the delivery is cancelled. A permanent or invalid-request refusal ends it as `rejected`: read the provider code in `delivery_attempts.provider_code` (for example `validation_error` for an unverified sender domain, or `invalid_api_key`) and fix the cause. A quota answer parks it in `waiting_quota`; see [Mail quotas](#mail-quotas). +- `unknown` is never retried by the worker. It means that the provider may have accepted the mail (a lost answer, a 5xx answer) or that the worker that sent it was lost for longer than the provider's 24-hour idempotency window. Check the provider's own log for the message; the alert `LincodexMailDeliveryUnknownOutcome` fires meanwhile. A manual retry with an audit record is planned with the retry policy (TASK-017). +- A claimed delivery holds a lease: `SELECT id, kind, claimed_until FROM deliveries WHERE claim_owner IS NOT NULL`. A row whose `claimed_until` is long past means that its worker died; another instance takes it over by itself. Do not clear leases by hand. +- `content_invalid` and `processing_failed` are not user actions: the first means that a stored row does not match its content hash (a manual edit) or holds a message no transport accepts, the second that the worker failed on the row three times in a row (the retries are spaced by the retry schedule). The alert `LincodexMailCancelledBroken` fires on an increase; read the worker logs for the `delivery_id` and inspect the row's metadata. A row that keeps failing does not block the others: it is retried later (`failure_count`, `next_attempt_at`) and then cancelled. +- The bodies of a token mail are cleared when it is accepted, rejected, or cancelled (`body_redacted_at` is set), so database dumps and backups of finished token mail hold no token. A mail that is `unknown` keeps its body until an operator resolves it. Do not copy bodies of waiting mail anywhere. +- The lease is measured by the database clock, so clock differences between instances do not matter; only the database's clock does. The call to the provider is bounded by what is left of the lease; with `SHUTDOWN_TIMEOUT` at its default of 10 seconds a stopping instance finishes within 3 seconds of grace plus 5 seconds to store the answer. Lowering `SHUTDOWN_TIMEOUT` shortens the second part (at least 1 second); a result that cannot be stored in time is covered by the takeover. +- Logs name a delivery only by `delivery_id`, its kind, and the outcome or cancel reason, for example `service mail was not sent because it is no longer valid`; never an address, a token, a link, or a body. If a token or link appears in a log, treat it as a defect. +- The internal /metrics endpoint shows `lincodex_mail_sender_running` (1 while this instance's loop runs, 0 otherwise; no labels) and `lincodex_mail_sender_cancelled_total{reason}` (a counter per cancel reason, zero included) next to the delivery gauges, which also have the status `cancelled`. + ### Mail templates -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. +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, and `ServiceMailer` renders verification and password reset mail when an identity flow issues a token; the flows themselves (registration, verification, password reset) are planned, so no account triggers a message yet. - 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. +- 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 path or the query: a browser does not send the fragment to a server, so the nginx access log (which records `$uri`) and Referer headers never hold it, and the frontend route reads it in the browser and sends it in an API request body. 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. 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. diff --git a/docs/en/DEVELOPMENT.md b/docs/en/DEVELOPMENT.md index 1223151..b8d9d63 100644 --- a/docs/en/DEVELOPMENT.md +++ b/docs/en/DEVELOPMENT.md @@ -50,7 +50,7 @@ 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` 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). +- 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 notifications yet (TASK-462). With `resend` the backend runs a sending worker for service identity mail (verification and password reset, bound to their tokens, checked before the send, with a quota gate and a stable idempotency key); no account flow creates such mail 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 runs one product handler, the mail delivery consumer, and no product flow emits its event yet; see [Event consumers](#event-consumers). diff --git a/docs/en/TESTING.md b/docs/en/TESTING.md index 9a2f2c0..c4881f8 100644 --- a/docs/en/TESTING.md +++ b/docs/en/TESTING.md @@ -199,7 +199,47 @@ Unit tests (`make -C backend test`) cover the quota rules without a database: - Startup report: with usage under the label `old-label` and under the configured label, the report through `postgres.MailQuotaStore` logs the configured account's usage and warns with `old-label`. - The database refuses an unknown period kind, a month that does not start on day one, negative usage, a malformed account label, a reservation whose day is outside its month, and an unknown outcome. -`TestPostgresMigrations` also checks that migration 00007 creates and drops `mail_quota_usage` and `mail_quota_reservations` and leaves the delivery tables. The suite does not call a transport: the worker that runs `PrepareSend`, `Send`, and `SettleSend` in sequence is TASK-016. +`TestPostgresMigrations` also checks that migration 00007 creates and drops `mail_quota_usage` and `mail_quota_reservations` and leaves the delivery tables. The quota suite does not call a transport; the worker that runs `PrepareSend`, `Send`, and `SettleSend` in sequence (TASK-016) is covered by the service mail sending tests below. + +## Service mail sending tests + +Unit tests (`make -C backend test`) cover: + +- `domain`: `Delivery.CheckServiceMail` names the first failed rule (missing token, purpose, owner, consumed, revoked, expired exactly at its deadline, registration moved, verified address, changed address) and leaves a current verification or reset mail sendable; `Delivery.Cancel` works from `pending` and `waiting_quota`, refuses `unknown` and the terminal statuses, leaves no attempt, and survives a restore; a notification cannot carry a token ID; the status names contain no claim of delivery to a person. +- `usecase/notification`: `ServiceMailSender` against in-memory stores with the version rule and the lease of the PostgreSQL store, the in-memory quota of the gate, and a scripted transport. Every transport result becomes the right delivery state, due time, and quota effect (accepted, permanent and invalid-request refusal, temporary refusal after the first backoff, a provider wait hint longer than the backoff, the provider's daily quota answer until midnight UTC, a quota answer without a reset, unknown, a transport that answers without an outcome, no transport, an interrupted call, an invalid message); every cancel reason is reached without a transport call or a reservation; a full local quota parks the delivery without a call and sends it at the reset; a result that cannot be stored keeps the lease, is repeated three times, and is then covered by a replacement under the same key without counting twice; an attempt lost beyond the idempotency window, or with a transport without deduplication, is recorded as unknown and not repeated; a delivery whose content hash does not match is cancelled as `content_invalid` and reported without calling the transport; a row that fails by its own fault (unreadable for a reason other than a hash mismatch, a domain rule broken while reading its state) is counted, moved back by the retry schedule so the delivery behind it is sent, and cancelled as `processing_failed` after three failures; transient errors (deadline, cancellation, deadlock, network, EOF, missing quota configuration) are reported to the worker and never counted or cancelled however often they repeat; a `Send` error without an answer moves the row back without counting it; paused counting moves rows back without counting; a successful pass clears the count; a failure is not recorded for a row another worker holds; the idempotency window is counted from the first request across repeated lost workers and with the one-hour margin; a revocation between the claim and the call is honored; a result is dropped when the lease was lost during the call; the call is bounded by the lease minus the settle budget; jitter is bounded and injectable; mail stored while no transport ran is rebound to the configured account and a delivery of another account is left alone; logs never hold the address, the token, or the link. `ServiceMailer` stores a token-bound delivery under the token ID with the token in the fragment of the link and no `?token=`, repeats harmlessly, and refuses a token of the wrong purpose before rendering. `RetryPolicy` doubles to its maximum and honors a longer hint. +- `worker/mailsender`: cancelled deliveries are counted by reason; the breaker pauses failure counting after three different rows fail in a row and resumes after a success, and one row failing again does not trip it; a failing row makes the loop wait by the backoff; the gauge is true only while the loop runs, an idle pass waits for the poll interval, a handled delivery is followed at once by the next pass, and a missing transport, an interrupted call, or a database failure back off instead of spinning. +- `adapter/secondary/postgres`: only SQLSTATE classes 22 and 23 match `ErrRowFault`; deadlock, serialization, connection, resource, shutdown, and internal errors do not. +- `adapter/secondary/prometheus`: `lincodex_mail_sender_cancelled_total` has every reason at zero and refuses an arbitrary label; `lincodex_mail_sender_running` exists at 0 and follows `SetMailSenderRunning`; every delivery status including `cancelled` exists at zero. +- `adapter/secondary/mail/resend`: the loopback constructor accepts only an http URL on a loopback host, so the key and the messages of a deployment cannot be pointed at another host through it; `resendfixture` answers like Resend (accepts, replays a repeated key and body with the original message, refuses another body under the key, plays scripted errors). +- `bootstrap`: no worker without a transport or a database; the loop starts and stops with the application and the gauge follows. +- `observability/prometheus/tests`: `LincodexMailDeliveriesOverdue` stays silent without the gauge, while it is 0, and for a notification-only backlog (age 0), and fires while some instance reports 1; `LincodexMailCancelledBroken` fires on `content_invalid` and `processing_failed` and stays silent on user-caused reasons (`make -C observability check`). + +`TestServiceMailSending` in `backend/integration_test/mail_sender_test.go` uses `bootstrap(t, postgresService)`, the real transactor, stores, quota gate, and sending usecase, the real Resend transport pointed at the local fixture, and a fake clock. Subtests share the database and start from empty tables: + +- A service email for a synthetic account with no consent record of any purpose is enqueued with its token in one transaction and accepted by the fixture: one provider call with the key `delivery/`, the address, and the link with the token in the fragment; the delivery is `accepted` with the provider message ID, one accepted attempt, one counted recipient, no lease left, the account's status is `accepted`, and a second pass does nothing. Logs hold neither the address nor the token. +- A worker that holds a delivery keeps another off it: the fixture answers slowly, the second worker's pass is idle while the first one's request is in flight, and the fixture gets exactly one call and the database one attempt. +- Four workers drain a queue of eight deliveries at once: eight provider calls under eight distinct keys, none replayed, eight accepted deliveries with one attempt each, eight counted recipients. +- A worker that stopped after sending (the database fails when it stores the answer) is replaced after its lease expires: two calls under the same key, the second a replay, one message at the provider, one attempt, and the open reservation reused, so the recipient counts once. Beyond the 24-hour window the replacement records an unknown attempt and does not call the provider. +- A delivery whose content hash was broken by a manual edit is cancelled as `content_invalid` at version 2 without a provider call, and the delivery behind it is sent in the next pass. +- A row that fails for a reason of its own (a subject that breaks the domain rules, so the row cannot be restored although its hash is intact) is counted and moved back by a minute while the delivery behind it is sent, fails again at each due time, and is cancelled as `processing_failed` on the third failure with its bodies cleared; a transport error without an answer moves the row back by a minute without counting it, with the reservation given back and the delivery pending. +- A failure recorded by a worker whose claim rolled back leaves a row alone that another worker holds, and an uncounted failure leaves `failure_count` at 0. +- Three workers lost in turn do not hide the age of the first request: the delivery becomes `unknown` once `first_send_started_at` is 24 hours old, and the provider is not called a fourth time. +- The lease is a few seconds by the database clock; a stranger cannot record an attempt or lock the row; `RecordClaimedAttempt` succeeds for the holder. +- Over 5000 due notification rows the claim plan uses `deliveries_due_idx` and no sequential scan (`EXPLAIN`). +- A notification-only backlog does not make the earliest pending age appear; a service mail does. +- A token mail's bodies are cleared when it is accepted or cancelled and the token no longer appears in any row; a waiting mail cannot be cleared by hand; a cleared row cannot get a body back or lose its mark; the account still sees its status. +- A token revoked by a resend, a token already used, an expired token, an account registered again, an address already verified, a changed address, and a token of another purpose each end the delivery as `cancelled` with the matching reason, no attempt, no lease, no next attempt, no reservation, and no provider call; the account sees `cancelled`; a further pass is idle. A deleted account takes its delivery with it. +- Provider answers: a 503 `service_unavailable` leaves the delivery `pending` due one minute later, a pass before that is idle, the retry at the due time repeats the key and is accepted; a 500 is `unknown` with no next attempt and no retry a day later; a 403 `validation_error` is `rejected`. +- Quota: a local limit of one per day parks the second delivery in `waiting_quota` until midnight UTC without a provider call, the account sees the wait and its end, and the delivery is sent at the reset; the provider's `daily_quota_exceeded` answer parks the delivery until the next midnight. +- A product notification is never claimed. +- `EMAIL_PROVIDER=disabled`: with the disabled transport the pass reports the channel unavailable, the delivery stays untouched at version 1, the lease and the reservation are released, nothing reaches the fixture, a loop run against it makes at most four passes in under a second, and the gauge is 1 while it runs and 0 after; with a transport the same mail is rebound to the configured account and accepted. +- The schema refuses a cancelled delivery without a reason, a reason on another status, a half lease, a lease on a terminal delivery, a notification bound to a token, a change of the token binding, and the deletion of a token that a delivery references; deleting the account removes both. + +`TestDeliverySendingMigration` rolls back and applies migration 00012 over a cancelled and redacted reset delivery: the earlier schema keeps it as `rejected` with a placeholder body, drops reset tokens and the new columns, and the migration applies again. `TestPostgresMigrations` covers the generic up, down, and up path. + +`make -C backend lint` also forbids importing `resendfixture` and calling `resend.NewLoopbackSender` outside `_test.go` files (depguard and forbidigo in `backend/.golangci.yml`). + +No check calls the real Resend API: the fixture is the only provider, so these tests prove the protocol the transport speaks and the delivery rules, not Resend's behavior, deliverability, or the account's real quota. ## Scheduled job tests diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index 078ede0..89f7297 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -190,7 +190,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` после проверки своих настроек останавливает запуск. Порт пока не вызывает ни один сценарий: доставки уже сохраняются (см. [Доставки писем](#доставки-писем)), а worker, который их отправляет, запланирован (TASK-016). Настройки описаны в [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 отправки служебной почты identity (TASK-016, см. [Отправка служебной почты](#отправка-служебной-почты)); продуктовые уведомления сохраняются как доставки, но не отправляются до TASK-462. Настройки описаны в [DEPLOY.md](DEPLOY.md#почта). `Send(ctx, OutgoingMail)` делает ровно одну попытку. `OutgoingMail` содержит получателя, тему, текстовое и HTML тело и ключ идемпотентности, который не меняется для одной логической доставки между повторами (от 1 до 256 печатных ASCII символов, предел Resend, без персональных данных); отправитель берется из `EMAIL_FROM`. При nil ошибке результат один из: @@ -224,11 +224,11 @@ Offsets и партиции. Каждый обработчик - один уча | Сбой до записи запроса: DNS, соединение, TLS или таймаут попытки | `rejected`, `temporary`: полный запрос до Resend не дошел | | Контекст вызывающего завершился до записи запроса | ошибка контекста; ничего не отправлено | -Каждый ответ `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-часового окна ключа относятся к запланированному слою доставки; ожидание сброса квоты решает шлюз квот из раздела [Квоты почты](#квоты-почты). +Каждый ответ `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 и предел числа попыток относятся к политике повторов (TASK-017), worker отправки применяет только минимальное расписание из раздела [Отправка служебной почты](#отправка-служебной-почты), а остановка по окончании 24-часового окна ключа - его правило для попытки, чей worker потерян; ожидание сброса квоты решает шлюз квот из раздела [Квоты почты](#квоты-почты). ### Доставки писем -Реализовано (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`. Шлюз квот, который допускает или откладывает отправку, реализован в TASK-018; см. [Квоты почты](#квоты-почты). Запланировано: worker, который берет доставки к отправке, пропускает их через шлюз квот и вызывает `MailSender` (TASK-016), повторы и политика неизвестного исхода (TASK-017) и проверка разрешений перед отправкой (TASK-462). Gauges состояний доставки реализованы в TASK-022; см. [Метрики, телеметрия и alerts](#метрики-телеметрия-и-alerts). Ни один продуктовый сценарий пока не вызывает `MailRequester`, и сохраненные доставки никто не отправляет. +Реализовано (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`. Шлюз квот, который допускает или откладывает отправку, реализован в TASK-018; см. [Квоты почты](#квоты-почты). Реализовано (TASK-016): worker, который берет к отправке служебные письма, проверяет их токен и аккаунт, пропускает через шлюз квот и вызывает `MailSender`, вместе с миграцией `00012_add_delivery_sending.sql`; см. [Отправка служебной почты](#отправка-служебной-почты). Запланировано: повторы и политика неизвестного исхода (TASK-017) и отправка продуктовых уведомлений с проверкой разрешений перед отправкой (TASK-462). Gauges состояний доставки реализованы в TASK-022; см. [Метрики, телеметрия и alerts](#метрики-телеметрия-и-alerts). Ни один продуктовый сценарий пока не вызывает `MailRequester`, и ни один сценарий identity пока не вызывает `ServiceMailer` (регистрация и сброс пароля - отдельные задачи), поэтому сохраненное уведомление ждет, а служебных писем вне тестов нет. Доставка - устойчивое состояние отправки одного письма одному получателю. Строка `deliveries` содержит: @@ -248,7 +248,7 @@ Offsets и партиции. Каждый обработчик - один уча Почему событие несет только ссылку. События хранятся в `outbox_events` и в Kafka в пределах retention топика, а правило доменных событий разрешает только идентификаторы и минимальные факты. FR19 также требует, чтобы очередь не сохраняла доступ к отозванным данным. Поэтому текст лежит в `mail_requests`, которые удаление аккаунта убирает каскадно, и только пока он нужен: обработчик удаляет строку в той же транзакции, где сохраняет сформированную доставку. После этого текст есть только в доставке, с ее правилами хранения и доступа. Адрес обработчик читает из аккаунта в своей транзакции, поэтому это адрес, актуальный на момент создания. -Письма с токеном. Тела писем подтверждения почты и сброса пароля содержат одноразовый bearer-токен, который никогда не должен попадать в событие или строку запроса, а хранилище держит только его SHA-256. Поэтому `mail_requests` и версия схемы 1 допускают только вид `notification`. Доставки писем с токеном должны создавать сценарии identity прямо в транзакции, которая выпускает токен, через те же `domain.NewDelivery` и `DeliveryRepository.Create`; это подключение запланировано вместе с TASK-016 и задачами регистрации и сброса пароля. +Письма с токеном. Тела писем подтверждения почты и сброса пароля содержат одноразовый bearer-токен, который никогда не должен попадать в событие или строку запроса, а хранилище держит только его SHA-256. Поэтому `mail_requests` и версия схемы 1 допускают только вид `notification`. Доставки писем с токеном создают сценарии identity прямо в транзакции, которая выпускает токен, через `ServiceMailer` (TASK-016): он использует `domain.NewDelivery` и `DeliveryRepository.Create` и привязывает доставку к токену; сами сценарии identity, которые его вызывают (регистрация, повторная отправка, сброс), - отдельные задачи. Неизменяемое содержимое. Доставка хранит отрендеренное тело и никогда не рендерит его заново. Для рендеринга во время отправки нужен исходный токен, который существует только в памяти в момент выпуска, а повтор под тем же ключом идемпотентности должен повторить ровно то же тело: Resend считает измененное тело под старым ключом конфликтом. Domain пересчитывает hash содержимого при каждом чтении и при несовпадении возвращает `domain.ErrMailContentIntegrity`. Trigger `deliveries_refuse_content_change` отклоняет UPDATE, меняющий получателя, содержимое, ключ идемпотентности, исходное событие или время создания (SQLSTATE 23000, ограничение `deliveries_content_immutable`, адаптер переводит его в `outbound.ErrDeliveryContentImmutable`). Поэтому новая версия шаблона применяется только к новым доставкам, а для отправки сохраненной доставки старые файлы шаблона не нужны. @@ -256,7 +256,7 @@ Offsets и партиции. Каждый обработчик - один уча - Запросы для эксплуатации выбирают столбцы метаданных (ID, вид, статус, попытки, время, провайдер) и никогда не выбирают тела, текст запроса и адрес; см. [DEPLOY.md](DEPLOY.md#доставки-писем). - Удаление аккаунта каскадно удаляет его запросы писем, доставки и их попытки. Очистка неподтвержденных аккаунтов блокирует их через `FOR UPDATE SKIP LOCKED`, как токены и сессии, поэтому никогда не ждет обработчик доставки или worker, который держит строку. -- Правило хранения, которое удаляет или очищает завершенные доставки через ограниченный срок, еще не реализовано; пока его нет, строки остаются. Шифрование тел в хранилище тоже не реализовано. +- Тела письма с токеном очищаются, когда доставка достигает `accepted`, `rejected` или `cancelled` (`body_redacted_at`, см. [Отправка служебной почты](#отправка-служебной-почты)), поэтому дамп или резервная копия базы не содержат токена завершенного письма; правило хранения, которое удаляет остальные завершенные доставки через ограниченный срок, еще не реализовано, и пока его нет, эти строки остаются. Шифрование тел в хранилище тоже не реализовано. - `Delivery`, `MailContent`, `MailRequest`, `NotificationText` и `EmailAddress` скрывают себя в выводе `fmt` и `slog`: доставка попадает в лог только как ID, вид, статус и провайдер. Ошибки обработчика называют нарушенное правило и никогда не цитируют payload, а адаптер заменяет текст ошибки PostgreSQL на SQLSTATE и имя ограничения. Метрики доставки (TASK-022) несут только labels вида, статуса, провайдера и окна квоты, без адреса, ID пользователя или доставки, метки аккаунта провайдера и темы. Статусы. Значения следуют исходам `MailSender`: @@ -264,15 +264,17 @@ Offsets и партиции. Каждый обработчик - один уча | Статус | Значение | `next_attempt_at` | | --- | --- | --- | | `pending` | Ждет первую попытку или повтор после отказа `temporary` или `rate_limited` | Обязательно: когда доставка должна быть отправлена | -| `accepted` | Провайдер принял письмо и вернул `provider_message_id`; это не доставка человеку и не прочтение | Нет; конечный | +| `accepted` | Провайдер принял письмо и вернул `provider_message_id`: "принято провайдером". Это не доставка человеку и не прочтение; ни один статус этого не утверждает | Нет; конечный | | `rejected` | Отказ `permanent` или `invalid_request`; причину нужно устранить | Нет; конечный | | `unknown` | Попытка могла дойти до провайдера (`delivery_uncertain`). Это никогда не "не отправлено": повтор использует тот же ключ и сохраненное тело | Необязательно; отсутствие значит, что автоматического повтора нет | +| `cancelled` | Письмо намеренно не отправлено и не будет: токен или аккаунт перестали соответствовать доставке, или сохраненное письмо нельзя отправить. `cancel_reason` говорит почему; попытка не записывается | Нет; конечный | | `waiting_quota` | Исчерпана квота провайдера или локальная квота | Необязательно: ожидаемый сброс (см. [Квоты почты](#квоты-почты)); отсутствует, когда момент сброса неизвестен, например после ответа провайдера о квоте без окна и без паузы, и решение принимает оператор | Переходы: -- `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.RecordAttempt` принимает результат одной попытки транспорта и добавляет строку попытки. `pending`, `waiting_quota` и `unknown` принимают попытку: `accepted` дает `accepted`, отказ `permanent` или `invalid_request` дает `rejected`, `temporary` или `rate_limited` - `pending`, `quota_exhausted` - `waiting_quota`, а `unknown` - `unknown`. `accepted`, `rejected` и `cancelled` отклоняют любую следующую попытку с `domain.ErrDeliveryTransition`. - `Delivery.WaitForQuota(at, until)` переводит доставку из `pending` или `waiting_quota` в `waiting_quota` без попытки - для случая, когда локальная квота TASK-018 откладывает отправку до вызова транспорта; нулевой `until` значит, что момент сброса неизвестен. Переход отклоняет `unknown`, чья прошлая попытка могла быть принята и чей повтор решает политика повторов, и конечные статусы. Сохраняет его `DeliveryRepository.WaitForQuota`. +- `Delivery.Cancel(at, reason)` завершает доставку из `pending` или `waiting_quota` в `cancelled` без попытки; причина - одна из `token_missing`, `token_purpose_mismatch`, `token_owner_mismatch`, `token_consumed`, `token_revoked`, `token_expired`, `account_not_current`, `recipient_mismatch`, `content_invalid` или `processing_failed`. Переход отклоняет `unknown`, как `WaitForQuota`: прошлая попытка могла быть принята, поэтому письмо никогда не объявляется неотправленным. Сохраняет его `DeliveryRepository.Cancel`. - `Delivery.Rebind(at, account)` переносит доставку без единой попытки на другой аккаунт провайдера; см. ниже. Сохраняет его `DeliveryRepository.Rebind`. Каждое изменение увеличивает `version`, и хранилище применяет его только поверх предыдущей версии. Время следующей попытки задает политика повторов вызывающего кода (TASK-017), и оно должно соответствовать целевому статусу; CHECK `deliveries_next_attempt_matches_status` повторяет это правило, а `deliveries_provider_message_id_when_accepted` требует ID провайдера ровно для `accepted`. @@ -283,17 +285,13 @@ Offsets и партиции. Каждый обработчик - один уча Аккаунт провайдера. Каждая доставка закреплена за транспортом и аккаунтом, которые были настроены при ее создании. У провайдеров и аккаунтов нет общих ключей идемпотентности, поэтому FR19 запрещает переносить неопределенную доставку на другой; изменение конфигурации применяется только к новым доставкам, а worker отправки обязан использовать закрепленный аккаунт. `EMAIL_ACCOUNT` называет аккаунт (`default`, если не задан); меняйте его каждый раз, когда `RESEND_API_KEY` переходит к другому аккаунту Resend. Аккаунт можно сменить, только пока у доставки нет попыток, потому что до первой попытки ключ не видел ни один провайдер: `Delivery.Rebind` отклоняет доставку с попыткой или в конечном статусе, а trigger отклоняет смену провайдера после попытки (ограничение `deliveries_provider_pinned`, адаптер переводит его в `outbound.ErrDeliveryProviderPinned`). TASK-016 использует это для доставок, созданных при `EMAIL_PROVIDER=disabled`, когда стенд включит транспорт; переносить их автоматически или по запросу оператора, решает эта задача. -Запланированные аддитивные изменения для следующих задач. Каждое - новый столбец, индекс или значение CHECK в следующей миграции; существующие строки остаются корректными: +Миграция `00012_add_delivery_sending.sql` (TASK-016) аддитивна; существующие строки остаются корректными. Она добавляет в `deliveries`: `email_token_id` (необязательный внешний ключ на `email_tokens.id` для писем с токеном, неизменяемый, как остальное содержимое; NULL для уведомлений), `cancel_reason` (задан ровно когда статус `cancelled`, CHECK ограничивает его перечисленными причинами), столбцы lease `claim_owner` и `claimed_until` (оба или ни одного; lease держит только доставка, которую worker еще может отправить), `first_send_started_at` (когда начался первый запрос, по часам базы), `failure_count` (подряд идущие сбои worker на строке), `body_redacted_at` (тела письма с токеном очищены), статус `cancelled` с его CHECK и два частичных индекса: `deliveries_due_idx` по `(next_attempt_at, id)`, чей предикат называет служебные виды и статусы, которые берутся снова, поэтому строки уведомлений в него не попадают, а холостой опрос их не сканирует, и индекс по `email_token_id`. Trigger `deliveries_refuse_content_change` разрешает еще ровно одно изменение тел: у конечного письма с токеном оба тела один раз становятся пустыми вместе с `body_redacted_at`. В `email_tokens` добавляется назначение токена `password_reset`. Откат миграции превращает отмененные доставки в отклоненные и удаляет токены сброса. Запланировано: отмена доставки по отозванному разрешению (TASK-462). -- Конечный статус отмены для доставки, которую больше нельзя отправлять: токен или аккаунт аннулирован до отправки (TASK-016) или отозвано разрешение (TASK-462). -- Необязательная ссылка доставки письма с токеном на `email_tokens.id`, чтобы worker перед отправкой проверил, что токен все еще действующий для своего назначения (TASK-016). -- Для worker отправки (TASK-016): столбцы lease (например, владелец захвата и `claimed_until`) и частичный индекс по `next_attempt_at` для статусов, которые берутся снова, чтобы несколько процессов захватывали доставки через `FOR UPDATE SKIP LOCKED`, а попытка, процесс которой остановился после отправки запроса, становилась `unknown`. - -Хранилище уже дает `Get`, `ListAttempts`, `RecordAttempt` с проверкой версии, `WaitForQuota` и `Rebind`. +Хранилище дает `Get`, `ListAttempts`, `RecordAttempt` с проверкой версии, `WaitForQuota`, `Cancel` и `Rebind`, а для worker отправки - `ClaimDue`, `ReleaseClaim` и `ServiceMailState`. ### Квоты почты -Реализовано (TASK-018): окна и лимиты квот в `backend/internal/domain/mail_quota.go`; порт `outbound.MailQuotaRepository` (`port/outbound/mail_quota.go`), запись через который идет через `UnitOfWork.MailQuotas()`, а чтение еще и через `postgres.MailQuotaStore`; миграция `00007_create_mail_quota_usage.sql` с таблицами `mail_quota_usage` и `mail_quota_reservations`; запросы в `backend/db/queries/mail_quota.sql`; в `backend/internal/usecase/notification/` - `QuotaGate` с `PrepareSend` и `SettleSend` (`quota.go`), отчет при запуске `ReportQuotaUsage` и чтение статуса для пользователя `DeliveryStatusReader` (`delivery_status.go`); `SendResult.QuotaPeriod` в почтовом порте, который заполняет адаптер Resend; отчет при запуске в bootstrap (`bootstrap/mail_quota.go`). Запланировано: worker отправки, который вызывает шлюз вокруг `MailSender.Send` и собирает его из конфигурации с `resend.IdempotencyWindow` или нулем для SMTP (TASK-016) и API или сценарий identity, который показывает результат чтения статуса. Пока ничего не отправляется, поэтому текущая сборка ничего не считает. +Реализовано (TASK-018): окна и лимиты квот в `backend/internal/domain/mail_quota.go`; порт `outbound.MailQuotaRepository` (`port/outbound/mail_quota.go`), запись через который идет через `UnitOfWork.MailQuotas()`, а чтение еще и через `postgres.MailQuotaStore`; миграция `00007_create_mail_quota_usage.sql` с таблицами `mail_quota_usage` и `mail_quota_reservations`; запросы в `backend/db/queries/mail_quota.sql`; в `backend/internal/usecase/notification/` - `QuotaGate` с `PrepareSend` и `SettleSend` (`quota.go`), отчет при запуске `ReportQuotaUsage` и чтение статуса для пользователя `DeliveryStatusReader` (`delivery_status.go`); `SendResult.QuotaPeriod` в почтовом порте, который заполняет адаптер Resend; отчет при запуске в bootstrap (`bootstrap/mail_quota.go`). Worker отправки (TASK-016) вызывает шлюз вокруг `MailSender.Send`, а `bootstrap/mail_sender.go` собирает его из конфигурации с `resend.IdempotencyWindow` или нулем для SMTP; см. [Отправка служебной почты](#отправка-служебной-почты). Запланировано: API или сценарий identity, который показывает результат чтения статуса. Пока открыта TASK-462, в квоту считается только служебная почта identity. Лимиты. `EMAIL_QUOTA_DAILY` и `EMAIL_QUOTA_MONTHLY` ограничивают число получателей, отправленных через настроенный аккаунт провайдера (`EMAIL_PROVIDER` и `EMAIL_ACCOUNT`), за UTC-сутки, с 00:00 до 00:00 UTC, и за календарный месяц UTC. Считается каждый получатель, как считает Resend; у доставки один получатель. Значения по умолчанию - лимиты Resend Free, проверенные 05.10.2026: 100 и 3000; они действуют для `resend` и для `disabled`, который ничего не отправляет. У `smtp` значений по умолчанию нет, и без обоих значений он не запускается: лимиты relay не совпадают с лимитами Resend. Допустимы значения от 1 до 1000000000, суточный лимит не больше месячного. Значения, которое отключает квоту, нет, поэтому ни один провайдер не работает без шлюза. Лимиты - это конфигурация, а не доменные константы, и они не хранятся: измененный лимит действует со следующего резервирования, а лимит, сниженный ниже текущего расхода, откладывает каждую новую отправку до сброса окна. @@ -330,11 +328,82 @@ Offsets и партиции. Каждый обработчик - один уча | `waiting_quota` с `WaitingUntil` | Ваше письмо ожидает отправки до `` | | `waiting_quota` без `WaitingUntil` | Ваше письмо ожидает отправки; время пока неизвестно | | `pending`, `unknown` | Ваше письмо отправляется. `unknown` не показывается как сбой: письмо могло быть принято | -| `accepted` | Ваше письмо отправлено. Это значит, что провайдер его принял, а не что оно дошло до ящика | +| `accepted` | Ваше письмо передано почтовому провайдеру, и он его принял. Подтвердить, что оно дошло до вашего ящика, мы не можем | | `rejected` | Ваше письмо не удалось отправить | +| `cancelled` | Ваше письмо не отправлено, потому что ссылка в нем больше не действует; запросите новое | Операторы читают те же строки запросами из [DEPLOY.md](DEPLOY.md#квоты-почты). Шлюз пишет в журнал `mail quota is used up; the delivery waits for the reset` на уровне info и `the mail provider reported its quota used up; local sending stops until the reset` на уровне warn, только с ID доставки, провайдером, периодом и моментом сброса. Gauges квот (TASK-022) читаются через `MailQuotaUsageReader.Usage` для настроенного аккаунта только с labels provider и window; см. [Метрики, телеметрия и alerts](#метрики-телеметрия-и-alerts). +### Отправка служебной почты + +Реализовано (TASK-016): usecase отправки `ServiceMailSender` (`backend/internal/usecase/notification/service_sender.go`), usecase постановки `ServiceMailer` (`service_mail.go`), минимальное расписание повторов `RetryPolicy` (`send_retry.go`), `Delivery.CheckServiceMail` и `Delivery.Cancel` с причинами отмены (`backend/internal/domain/delivery.go`, `delivery_guard.go`), цикл в `backend/internal/worker/mailsender/`, входящий порт `inbound.MailPass` (`port/inbound/mail_sender.go`), методы репозитория `ClaimDue`, `ReleaseClaim`, `Cancel` и `ServiceMailState`, миграция `00012_add_delivery_sending.sql`, gauge `lincodex_mail_sender_running` и подключение в `bootstrap/mail_sender.go`. Не реализовано: отправка продуктовых уведомлений (TASK-462), политика повторов и неизвестного исхода (TASK-017) и сценарии identity, которые вызывают `ServiceMailer`. + +Область. Worker берет только виды `verification` и `password_reset`. Продуктовое уведомление он не берет никогда, в каком бы состоянии оно ни было. Служебной почте не нужна запись согласия ни для какого назначения: она часть сценария аккаунта, поэтому ничто не читает журнал согласий, а C2 (публикация карточки кандидата) и остальные продуктовые согласия не участвуют. Между аккаунтом и письмом стоит проверка ниже, а не согласие. + +Постановка. `ServiceMailer.EnqueueVerification` и `EnqueuePasswordReset` выполняются в транзакции, которая вставляет токен, и получают запись токена, исходный токен, адрес получателя и срок действия в часах. Они проверяют, что назначение токена подходит письму, один раз рендерят письмо текущей версией шаблона и сохраняют доставку `pending`, привязанную к токену (`email_token_id`), с ID токена в роли ID доставки. Повторный вызов для того же токена ничего нового не сохраняет, а сохраненное тело остается прежним. + +Ссылки. Токен передается только во фрагменте URL: `/verify-email#token=` и `/reset-password#token=`; ссылки строит `mailtemplate` (`tokenLink`). Браузер никогда не отправляет фрагмент серверу, поэтому токен не попадает в access log nginx, который пишет `$uri`, в заголовки Referer и в журнал запросов Go; его нет ни в пути, ни в query. Маршрут frontend читает фрагмент и отправляет токен в теле запроса API. Query понадобился бы, только если бы маршрут frontend не мог прочитать фрагмент, но тогда страница отправляла бы токен дальше, а access log его видел бы, поэтому выбран фрагмент. Renderer отклоняет токен в любом другом месте, golden-файлы и тесты фиксируют формат, а тесты доставок проверяют, что сохраненное тело содержит ссылку с фрагментом и не содержит `?token=`. Тело в `deliveries` хранит действующий токен, пока письмо не отправлено или не отменено; см. "Персональные данные в хранилище". + +Один проход `ServiceMailSender.ProcessNext` проводит одну доставку через три шага: + +1. Транзакция захвата. `DeliveryRepository.ClaimDue` берет самую просроченную доставку с `FOR UPDATE SKIP LOCKED`: вид `verification` или `password_reset` (литералы совпадают с предикатом `deliveries_due_idx`, поэтому опрос читает только этот малый индекс), статус `pending` или `waiting_quota`, `next_attempt_at` наступил, доставка закреплена за настроенным аккаунтом провайдера и ее не держит живой lease. Он записывает `claim_owner` и `claimed_until` (lease), не меняя версию и время обновления, поэтому несколько процессов никогда не возьмут одну доставку. Lease измеряется часами базы данных (`clock_timestamp()` плюс длина lease, и он жив, пока `claimed_until` позже `clock_timestamp()`), а не часами экземпляра приложения, поэтому экземпляры с разными часами не могут перехватить живой lease или держать мертвый; сроки доставок остаются на часах приложения, которые их записали. У доставки в `unknown` или в `waiting_quota` без времени нет срока, и она ждет оператора. В той же транзакции отправитель переносит на настроенный аккаунт письма, сохраненные при `EMAIL_PROVIDER=disabled` (это разрешено только до первой попытки, пока ключ не видел ни один провайдер), выполняет проверку ниже, а затем `QuotaGate.PrepareSend`, который резервирует получателя или переводит доставку в `waiting_quota`. Транзакция фиксируется до вызова транспорта, поэтому медленный провайдер никогда не держит блокировку строки. Сбой внутри нее (детерминированный, например строка, которую нельзя восстановить) откатывает и lease, поэтому сбой записывается для строки отдельной транзакцией; см. "Сбойные строки". +2. Проверка прямо перед отправкой, одна короткая транзакция: она блокирует строку доставки (только для владельца lease), заново читает токен и аккаунт через `ServiceMailState`, поэтому отзыв после фиксации захвата учитывается, и в первый раз записывает `first_send_started_at`. Письмо, которое больше нельзя отправлять, отменяется, а резервирование возвращается. Затем один вызов `MailSender.Send` с сохраненным содержимым и стабильным ключом идемпотентности `delivery/`. Отправитель никогда не повторяет вызов. Вызов ограничен тем, что осталось от lease после захвата и бюджета расчета, и льготным периодом остановки. +3. Транзакция расчета. Она сначала блокирует строку доставки (только пока этот worker держит lease), затем `QuotaGate.SettleSend` и `DeliveryRepository.RecordClaimedAttempt` фиксируются вместе, а lease заканчивается вместе с попыткой. `RecordClaimedAttempt` применяется только поверх версии доставки и только для владельца lease, поэтому worker, чей lease перехвачен, записать не может, а если два worker дошли до этого шага для одной доставки, сохраняется только первая; вторая откатывается вместе с расчетом квоты и сообщает `lease_lost`. Сбой базы при сохранении ответа повторяется до трех раз в пределах бюджета расчета, потому что ответ до сохранения существует только в памяти. + +Бюджет времени. Lease равен `EMAIL_TIMEOUT` плюс одна минута. Сначала идут захват и проверка; вызов получает остаток lease за вычетом бюджета расчета (20 секунд), поэтому захват, вызов и весь расчет умещаются в lease. Когда остановка началась, бюджет расчета - меньшее из 5 секунд и `SHUTDOWN_TIMEOUT` за вычетом 3 секунд льготного периода остановки (не меньше 1 секунды), поэтому процесс останавливается в пределах своего тайм-аута остановки, по умолчанию 10 секунд (период остановки в Compose - 30 секунд). Результат, который не удалось сохранить вовремя, покрывает перехват ниже. + +Порядок блокировок. Каждый путь блокирует сначала строку доставки, затем строки квоты: захват блокирует строку через `FOR UPDATE SKIP LOCKED`, а проверка и расчет начинаются с `LockClaimed` (`SELECT ... FOR UPDATE` строки владельца lease), поэтому две транзакции не могут ждать друг друга в противоположных направлениях. + +Проверка перед отправкой. В транзакции захвата `Delivery.CheckServiceMail` сравнивает доставку со снимком, прочитанным одним запросом (`ServiceMailState`: токен и аккаунт, без блокировок, из адреса - только ключ сравнения). Первая неудача отменяет доставку статусом `cancelled` с этой причиной; ничего не резервируется и не отправляется: + +| Порядок | Правило | Причина | +| --- | --- | --- | +| 1 | Токен привязан, и его строка существует | `token_missing` | +| 2 | Его назначение совпадает с тем, которое несет вид письма (`email_verification` для подтверждения, `password_reset` для сброса) | `token_purpose_mismatch` | +| 3 | Он принадлежит аккаунту получателя | `token_owner_mismatch` | +| 4 | Он не использован | `token_consumed` | +| 5 | Он не отозван (`invalidated_at`, повторной отправкой или повторной регистрацией) | `token_revoked` | +| 6 | Его срок не истек | `token_expired` | +| 7 | У аккаунта все еще та версия регистрации, для которой выпущен токен, а письмо подтверждения не идет на уже подтвержденный адрес | `account_not_current` | +| 8 | Адрес в доставке все еще адрес аккаунта | `recipient_mismatch` | + +Захваченная строка, чье содержимое больше не совпадает с хешем (это может вызвать только ручная правка), отменяется самим захватом с причиной `content_invalid`, тела очищаются, как у любого отмененного письма с токеном, а в журнал на уровне error пишется ID доставки. Любой другой сбой восстановления строки может быть временным, поэтому навсегда она не отменяется: это сбойная строка, см. ниже. + +Признака деактивированного аккаунта нет. "Актуален" - это правило 7 и правила токена: повторная регистрация сдвигает версию и отзывает токен, а удаленный аккаунт уносит свои доставки каскадом, так что отправлять нечего. У письма сброса нет правила про состояние подтверждения: что сброс применяется только к подтвержденным аккаунтам, решает сценарий сброса. Проверка - снимок: токен, использованный или отозванный после нее и до вызова провайдера, не остановит письмо. Это безвредно, потому что ссылка проверяется снова при использовании. + +Во что превращается ответ провайдера. Решает конечный автомат `domain.Delivery`; worker лишь заполняет попытку: + +| Результат | Доставка | Следующая попытка | Квота | +| --- | --- | --- | --- | +| `accepted` | `accepted`, ID сообщения провайдера сохранен | нет | считается | +| `rejected` `permanent` или `invalid_request` | `rejected` | нет | возвращается | +| `rejected` `temporary` или `rate_limited` | `pending` | сейчас плюс `RetryPolicy`: 1 минута, удвоение до 30 минут, не меньше `Retry-After` провайдера | возвращается | +| `rejected` `quota_exhausted` | `waiting_quota` | сброс, который вернул шлюз (ближайшие 00:00 UTC для суток, первое число следующего месяца для месяца); нет, если провайдер не назвал окно | окно отмечено заполненным | +| `unknown` | `unknown` | нет: автоматического повтора нет (TASK-017) | считается | +| Ошибка `Send`: нет транспорта (`ErrMailChannelUnavailable`) или context завершился | без изменений, lease освобожден | остается срок | возвращается | +| Ошибка `Send`: неверное сообщение (`ErrInvalidOutgoingMail`) | `cancelled`, `content_invalid` | нет | возвращается | +| Ошибка `Send`: любая другая без ответа | не считается против строки; она отодвигается по `RetryPolicy`, а worker делает паузу | сейчас плюс `RetryPolicy` | возвращается | + +В расписании повторов нет предела числа попыток намеренно: токен истекает, и тогда проверка отменяет доставку с `token_expired`. К каждой паузе добавляется ограниченный jitter, до пятой части сверх расписания, из подменяемого источника (в тестах nil, поэтому время точное), чтобы доставки, отклоненные вместе, не возвращались вместе. `unknown` никогда не читается как неотправленное и никогда не повторяется worker; решает оператор, и срабатывает alert `LincodexMailDeliveryUnknownOutcome`. + +Worker потерян после вызова. Если worker остановился после вызова провайдера, но до сохранения ответа, его lease истекает, и другой worker берет доставку на той же попытке и повторяет запрос с тем же ключом идемпотентности. Resend отвечает на повторный ключ и тело исходным результатом, а шлюз квот повторно использует открытое резервирование, поэтому письмо существует одно и считается один раз. Провайдер хранит ключ 24 часа от первого запроса, поэтому возраст считается от `first_send_started_at` (его по часам базы записывает проверка прямо перед первым запросом), а не от последнего lease: сколько бы worker ни потерялось подряд и какой бы длины ни был lease, когда этот возраст достигает 23 часов (окно за вычетом часового запаса), прежний запрос может быть забыт, и повтор способен отправить письмо дважды, поэтому вместо этого доставка записывается как попытка `unknown` без следующей попытки. То же применяется сразу для транспорта без дедупликации на стороне провайдера (окно ноль, SMTP). Lease, не дошедший до первого запроса, ничего не оставляет под сомнением. + +Сбойные строки. Сбой одной строки не должен занимать начало очереди. Когда транзакция захвата падает после того, как взяла строку, ее lease откатывается вместе с ней, и та же строка тут же была бы взята снова, а все доставки за ней ждали бы. Против строки считается только сбой, который вызывает сама строка: нарушаемое ею правило домена (`ErrInvalidDelivery`, `ErrDeliveryTransition`, неверное содержимое или адрес), строку нельзя восстановить по причине, отличной от несовпадения хеша, или отказ ограничения данных или целостности (классы SQLSTATE 22 и 23, `outbound.ErrRowFault`). Все остальное о строке ничего не говорит и никогда не считается: завершившийся context, тайм-аут, deadlock, потеря соединения (SQLSTATE 08, 40, 53, 57, XX), ошибка ввода-вывода, отсутствие настройки квоты. Такая ошибка возвращается worker, который делает паузу, как при любом глобальном сбое, а lease истекает или откатывается. Для считаемого сбоя отправитель записывает его короткой отдельной транзакцией (`RecordFailure`): `failure_count` растет, lease заканчивается, и строка снова должна быть отправлена по `RetryPolicy` (исход `row_failed`; следующий проход берет доставку за ней). Запрос не трогает строку, которую другой worker держит под живым lease, поэтому откатившийся захват не может помешать строке, которую кто-то только что взял. Счетчик означает сбои подряд: успешный захват и подготовка (проверка перед отправкой) его очищают, как и записанная попытка. Предохранитель в worker останавливает счет, когда сбои попадают на разные строки проход за проходом: три прохода подряд, упавших на трех разных строках, читаются как глобальный сбой, worker ждет с растущей паузой (проход `row_failed` никогда не крутится сразу), а сбои отодвигаются, но не считаются и ни одна строка не отменяется, пока проход не завершится успешно. После 3 считаемых сбоев подряд строка отменяется с причиной `processing_failed`: это существующий конечный статус, который подходит, оператор его видит, и срабатывает alert ниже, поэтому новый статус не понадобился. Если сбой базы мешает и этой записи, строка остается под своим lease, который истекает. + +`EMAIL_PROVIDER=disabled`. Bootstrap не запускает цикл: `newMailSenderWorker` не возвращает worker и пишет `mail sender worker is not started because EMAIL_PROVIDER is disabled; stored deliveries wait`, поэтому `lincodex_mail_sender_running` остается 0, а `LincodexMailDeliveriesOverdue` молчит. Сохраненные письма ждут, закрепленные за `disabled`; после перезапуска стенда с транспортом worker переносит их и отправляет, если токен и аккаунт проходят проверку. Worker, который все же запущен с транспортом disabled (в тестах), получает `ErrMailChannelUnavailable` на каждую отправку, ничего не записывает, освобождает lease и резервирование и делает паузу (5 секунд с удвоением до 2 минут) вместо немедленного нового захвата, так что он никогда не крутится вхолостую. + +Цикл и остановка. `worker/mailsender` повторяет проходы: после прохода, обработавшего доставку, сразу идет следующий, после холостого прохода worker ждет 5 секунд, а после сбоя базы, отсутствия транспорта или прерванного вызова ждет с растущей паузой. Когда context завершается, worker больше ничего не захватывает, дает выполняющейся отправке продолжиться 5 секунд, сохраняет ее результат и возвращается; после этого gauge равен 0. Цикл - горутина процесса backend на собственном pool из двух соединений, как у других worker; больший объем дают дополнительные экземпляры, а каждый обрабатывает одну доставку за раз, что подходит для служебной почты при квоте Resend Free. + +Токен в хранилище. Тело письма с токеном содержит одноразовый токен, а токен сброса - примитив захвата аккаунта для любого, кто может читать базу или резервную копию. Когда письмо с токеном достигает `accepted`, `rejected` или `cancelled` (любым путем: попыткой, отменой, отменой испорченной строки или `processing_failed`), тот же запрос делает `text_body` и `html_body` пустыми и ставит `body_redacted_at`; тема, хеш содержимого и версия шаблона остаются. Trigger разрешает ровно это изменение один раз для конечной строки и отклоняет любое другое изменение тел или метки; CHECK `deliveries_body_present` принимает пустое тело только с меткой; домен восстанавливает такую строку как очищенное содержимое (`RestoreRedactedMailContent`), которое отправить нельзя. `unknown` не конечный и сохраняет тело, потому что повтор отправляет его снова; оператор, который его разрешает, должен очистить его. Уведомления не очищаются. Откат миграции 00012 подставляет заглушку в очищенные тела. + +Приватность. Журнал называет доставку только по `delivery_id`, ее виду и закрытым значениям (исход и причина отмены); адрес, токен, ссылка, тема и тело не попадают ни в строку журнала, ни в ошибку, ни в label метрики, а у метрики вообще нет labels. `ServiceMailSender` строит исходящее письмо из сохраненного содержимого и никогда его не логирует; `OutgoingMail` и `Delivery` скрывают себя сами. + +Только тестовая подмена. `resendfixture` и `resend.NewLoopbackSender` никогда не используются production-кодом: `backend/.golangci.yml` запрещает импорт подмены и вызов конструктора вне файлов `_test.go` (depguard и forbidigo), а `bootstrap` связывает настоящий транспорт через `resend.NewSender`. + +Тесты. `integration_test/mail_sender_test.go` запускает локальную имитацию Resend (`resendfixture`, сервер `httptest`, который говорит на части API, используемой транспортом, и доступен через `resend.NewLoopbackSender`, принимающий только loopback endpoint) против PostgreSQL; см. [TESTING.md](TESTING.md). Это только тестовая подмена; production использует настоящий транспорт Resend с фиксированным endpoint. + +Открытые вопросы. У `unknown` нет автоматического повтора и эскалации до TASK-017. Отправка уведомлений и нужная ей проверка разрешений относятся к TASK-462; до нее они ждут и не учитываются в gauge просрочки, поэтому очередь уведомлений не включает `LincodexMailDeliveriesOverdue` (gauge `lincodex_mail_delivery_oldest_due_pending_age_seconds` охватывает `domain.ServiceMailKinds`; его предикат - предикат `deliveries_due_idx`). Идет ли сброс пароля на неподтвержденные аккаунты, решает сценарий сброса. Опрос выполняется каждые 5 секунд, захват читает один индексированный запрос, что подходит для текущего объема. + ### Версии продуктовой политики Реализованы хранение, публикация и начальное заполнение при старте (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/`. Ни одно продуктовое правило пока не читает политику; приглашения, квоты, оценивание, сессии и статус поиска начнут читать ее по мере реализации своих задач. @@ -423,7 +492,7 @@ backend/ usecase/policy/ публикация версий политики и начальное заполнение демонстрационной политики usecase/consent/ выдача согласий C1-C3 и C5 и C4 со scope с проверкой актуального текста usecase/files/ общий закрытый файловый слой: политики, непрозрачные ключи, лимиты потока, контрольные суммы - usecase/notification/ запросы писем и обработчик, который сохраняет их как доставки + usecase/notification/ запросы писем и обработчик, который сохраняет их как доставки, шлюз квот, постановка служебной почты (`ServiceMailer`) и отправитель служебной почты (`ServiceMailSender`) usecase/notification/mailtemplate/ чистый рендеринг версионированных служебных писем; обработчик доставки рендерит им уведомления port/outbound/ границы readiness, кеша, объектного хранилища, транзакции, outbox, relay outbox, публикации и потребления событий, identity, журнала согласий, организаций и членств, политики, хеширования паролей и почты adapter/primary/http/ @@ -438,6 +507,7 @@ backend/ kafka/ publisher событий и участник consumer group на franz-go: конверт записи, его декодирование и создание топика событий mail/disabled/ почтовый транспорт, который ничего не отправляет и сообщает о недоступности канала mail/resend/ почтовый транспорт, который отправляет одно письмо одним запросом к HTTP API Resend + mail/resend/resendfixture/ локальная замена API Resend только для тестов; production ее не импортирует ml/api/ generated client из backend/codegen/ogen-ml.yml postgres/ pool, migrator, transactor, запись outbox и хранилище relay, хранилище обработчиков событий, репозитории identity, журнала согласий, организаций, членств и политики, health check postgres/sqlc/ generated SQL adapter @@ -447,6 +517,7 @@ backend/ worker/outboxrelay/ цикл relay outbox: захват, публикация, отметка, backoff и остановка worker/eventconsumer/ runtime обработчиков событий: транзакция дедупликации, повторы, dead letters, commit offsets и остановка worker/jobrunner/ runtime заданий по сроку: захват под lease, выполнение вместе с завершением, повторы, освобождение и остановка + worker/mailsender/ цикл отправки служебной почты identity: повторяет проходы, ждет без работы, откатывается при сбоях, сообщает lincodex_mail_sender_running worker/retry/ backoff с jitter и ожидание с учетом context, общие для workers worker/deliverymetrics/ периодическое чтение агрегатов доставок и квот почты в метрики bootstrap/ конфигурация, wiring, lifecycle, shutdown @@ -459,9 +530,9 @@ backend/ `domain/`, продуктовые `usecase/`, адаптеры SMTP и FSP, а также продуктовые задания worker зарезервированы; их бизнес-логика не реализована. `main.go` только запускает bootstrap и обрабатывает ошибку процесса. Для публичного generated transport выбран ogen v1.24.0, контракты используют OpenAPI 3.2.0. Проверяется только применяемое подмножество, не вся спецификация. -Это компактная карта, а не обещание, что все запланированные продуктовые пакеты уже существуют. Сейчас Go-код включает health usecase/adapters, generated API clients, bootstrap с миграциями при старте, PostgreSQL health query, транзакционную запись outbox, relay outbox, который публикует зафиксированные события в Kafka через адаптер franz-go, runtime обработчиков событий с обработчиком `notification_delivery`, runtime заданий по сроку (`worker/jobrunner`) без зарегистрированного продуктового вида задания, репозитории identity без использующих их usecase, версионированное хранилище политики с публикацией и начальным заполнением демонстрационной политики при старте, порт `PasswordHasher` с адаптером Argon2id и проверку пароля, которую вызовет регистрация, Redis cache adapter, S3-адаптер SeaweedFS с общим закрытым файловым слоем поверх него, порт `MailSender` с транспортами `disabled` и Resend и renderer шаблонов писем, который пока не вызывает ни один сценарий. Поведение аккаунтов (регистрация, подтверждение, вход, сессии), резюме, оценивание, приглашения, продуктовые виды заданий, файловые сценарии, отправка почты, транспорт SMTP и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей. +Это компактная карта, а не обещание, что все запланированные продуктовые пакеты уже существуют. Сейчас Go-код включает health usecase/adapters, generated API clients, bootstrap с миграциями при старте, PostgreSQL health query, транзакционную запись outbox, relay outbox, который публикует зафиксированные события в Kafka через адаптер franz-go, runtime обработчиков событий с обработчиком `notification_delivery`, runtime заданий по сроку (`worker/jobrunner`) без зарегистрированного продуктового вида задания, репозитории identity без использующих их usecase, версионированное хранилище политики с публикацией и начальным заполнением демонстрационной политики при старте, порт `PasswordHasher` с адаптером Argon2id и проверку пароля, которую вызовет регистрация, Redis cache adapter, S3-адаптер SeaweedFS с общим закрытым файловым слоем поверх него, порт `MailSender` с транспортами `disabled` и Resend renderer шаблонов писем и worker отправки служебной почты identity, который пока не питает ни один сценарий аккаунта. Поведение аккаунтов (регистрация, подтверждение, вход, сессии), резюме, оценивание, приглашения, продуктовые виды заданий, файловые сценарии, отправка продуктовых уведомлений, транспорт SMTP и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей. -`backend/pkg/` зарезервирован для небольших технических пакетов с оправданной общей границей, а не для продуктовых usecase или domain types. В `pkg/testutil/` находится `FakeClock` - потокобезопасные ручные часы, которые тесты worker, интеграционные тесты и будущие тесты usecase подставляют везде, где production-код принимает часы `func() time.Time`, и `FindPersonalIdentifiers`, которым тесты метрик ищут в выдаче значения, похожие на email и UUID. Пакет `mailer` остается кандидатом. Шаблоны писем вместо этого находятся в `internal/usecase/notification/mailtemplate/`: они содержат продуктовые тексты и используют domain types, например `SecretToken`. Это чистый пакет рендеринга без I/O и логирования. Обработчик доставки в `internal/usecase/notification/` рендерит им уведомления; usecase identity (подтверждение почты и сброс пароля) должны вызывать его при создании своих доставок, это подключение запланировано. Шаблоны, версии и формат ссылок описаны в [DEPLOY.md](DEPLOY.md#шаблоны-писем). S3-клиент остается в адаптере SeaweedFS. Поведение, специфичное для этого сервиса, остается внутри `internal/`. +`backend/pkg/` зарезервирован для небольших технических пакетов с оправданной общей границей, а не для продуктовых usecase или domain types. В `pkg/testutil/` находится `FakeClock` - потокобезопасные ручные часы, которые тесты worker, интеграционные тесты и будущие тесты usecase подставляют везде, где production-код принимает часы `func() time.Time`, и `FindPersonalIdentifiers`, которым тесты метрик ищут в выдаче значения, похожие на email и UUID. Пакет `mailer` остается кандидатом. Шаблоны писем вместо этого находятся в `internal/usecase/notification/mailtemplate/`: они содержат продуктовые тексты и используют domain types, например `SecretToken`. Это чистый пакет рендеринга без I/O и логирования. Обработчик доставки в `internal/usecase/notification/` рендерит им уведомления; `ServiceMailer` рендерит им письма подтверждения и сброса пароля, когда usecase identity выпускают токен, а сами эти usecase (регистрация, повторная отправка, сброс) - отдельные задачи. Шаблоны, версии и формат ссылок описаны в [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. @@ -719,7 +790,7 @@ Go экспортирует стандартные Go/process метрики и - API: `lincodex_http_requests_total{method,route,status}`, `lincodex_http_request_duration_seconds{method,route,status_class}` и `lincodex_http_problems_total{route,code}`. `route` - шаблон маршрута chi для операционных маршрутов, а под `/api/v1` - шаблон пути OpenAPI найденной операции, например `/api/v1/me/invitations/{invitation_id}`; router находит его через `FindPath` сгенерированного сервера. Путь или метод без операции сохраняет шаблон монтирования `/api/v1/*` или `/api/*`, а путь вне всех маршрутов получает `unmatched`. `status_class` - от `1xx` до `5xx`. `code` - код problem по RFC 9457: `problem.New` записывает его из закрытого каталога через пакет `observe` уровня запроса (`adapter/primary/http/observe/`), middleware учитывает его только для ответа 4xx или 5xx, а адаптер считает код вне своего зеркального списка как `other`. Ошибка без тела problem, например 503 от `/readyz`, учитывается только по статусу. Журнал запросов (`middleware.RequestLog`, заменяет logger из go-httpkit) использует тот же шаблон маршрута и пишет request ID, метод, статус и класс, код problem, задержку, размер ответа и число параметров query, но никогда не пишет исходный путь, ключ или значение query, заголовок, адрес клиента и user agent; `/healthz` и `/readyz` не журналируются. - Outbox и события: метрики relay, обработчиков и заданий по сроку описаны в разделах [Relay outbox](#relay-outbox), [Обработчики событий](#обработчики-событий) и [Задания по сроку](#задания-по-сроку). Отставание outbox показывает `lincodex_outbox_relay_oldest_pending_age_seconds`. -- Почта: `lincodex_mail_deliveries{kind,status}` для каждого вида и статусов `pending`, `waiting_quota`, `unknown`, `accepted` и `rejected`, включая нулевые; `lincodex_mail_delivery_oldest_due_pending_age_seconds`; для активного транспорта - `lincodex_mail_quota_used_recipients`, `lincodex_mail_quota_limit_recipients` и `lincodex_mail_quota_provider_exhausted` с `provider` и `window` (`day` или `month`). Sampler в `backend/internal/worker/deliverymetrics/` читает их каждые 30 секунд через собственный pool на одно соединение: `postgres.DeliveryStatisticsStore` агрегирует `deliveries` по виду и статусу, а `MailQuotaUsageReader.Usage` читает текущие окна настроенного аккаунта. Агрегат доставок - запрос sqlc `GetDeliveryStatistics` в `db/queries/delivery.sql`. Запрос сканирует таблицу, что подходит для текущего объема; до миллионов строк нужен индекс или счетчики по статусам. `EMAIL_ACCOUNT` не становится label: это свободный текст оператора, который может назвать человека, а каждый процесс сообщает только свой аккаунт. Все экземпляры сообщают одинаковые значения по всей базе; агрегируйте их через `max`. Неудачное чтение сохраняет прежние значения и пишет в журнал `delivery metrics could not be read; the gauges are stale`; `lincodex_mail_metrics_last_success_timestamp_seconds` показывает последнее чтение, в котором прочитаны все агрегаты (0 от запуска sampler до первого такого чтения), а gauge просрочки появляется только после первого успешного чтения. Счетчика исходов попыток пока нет, потому что worker отправки (TASK-016) еще не существует. +- Почта: `lincodex_mail_deliveries{kind,status}` для каждого вида и статусов `pending`, `waiting_quota`, `unknown`, `accepted`, `rejected` и `cancelled`, включая нулевые; `lincodex_mail_sender_running` - 1, пока цикл отправки почты этого процесса работает, и 0 иначе (по процессу, поэтому агрегируйте через `max`; при `EMAIL_PROVIDER=disabled` остается 0, цикл не запускается); `lincodex_mail_delivery_oldest_due_pending_age_seconds`, который считает только служебную почту (`domain.ServiceMailKinds`), поэтому очередь уведомлений никогда не выглядит просроченной; `lincodex_mail_sender_cancelled_total{reason}` - доставки, которые worker отправки завершил без отправки, по закрытому набору причин отмены, включая нулевые; для активного транспорта - `lincodex_mail_quota_used_recipients`, `lincodex_mail_quota_limit_recipients` и `lincodex_mail_quota_provider_exhausted` с `provider` и `window` (`day` или `month`). Sampler в `backend/internal/worker/deliverymetrics/` читает их каждые 30 секунд через собственный pool на одно соединение: `postgres.DeliveryStatisticsStore` агрегирует `deliveries` по виду и статусу, а `MailQuotaUsageReader.Usage` читает текущие окна настроенного аккаунта. Агрегат доставок - запрос sqlc `GetDeliveryStatistics` в `db/queries/delivery.sql`. Запрос сканирует таблицу, что подходит для текущего объема; до миллионов строк нужен индекс или счетчики по статусам. `EMAIL_ACCOUNT` не становится label: это свободный текст оператора, который может назвать человека, а каждый процесс сообщает только свой аккаунт. Все экземпляры сообщают одинаковые значения по всей базе; агрегируйте их через `max`. Неудачное чтение сохраняет прежние значения и пишет в журнал `delivery metrics could not be read; the gauges are stale`; `lincodex_mail_metrics_last_success_timestamp_seconds` показывает последнее чтение, в котором прочитаны все агрегаты (0 от запуска sampler до первого такого чтения), а gauge просрочки появляется только после первого успешного чтения. Счетчика исходов попыток пока нет; исходы показывают состояния доставок, журнал worker отправки и история `delivery_attempts`. - Ответы теста: `lincodex_assessment_answer_saves_total{format,outcome}` с исходами `stored`, `unchanged`, `rejected` и `failed`. PRD 6.6 требует наблюдать сохранение ответов; это понимается как команда ответа теста `SubmitMyAssessmentAnswer`. Команда не реализована, поэтому есть только hook `Metrics.ObserveAssessmentAnswerSave`, и серии не появятся, пока usecase не начнет вызывать его один раз на команду. Значение вне закрытых наборов превращается в `other`. Задержка и ошибки HTTP этой команды уже видны под маршрутом `/api/v1/me/assessment-attempts/{attempt_id}/answers`. В labels нельзя помещать ID пользователя, кандидата, доставки или запроса, полный URL или query string, адреса и содержимое резюме. Unit-тесты прогоняют настоящий router и каждый hook метрик с fixture email и UUID и падают, если в выдаче есть значение, похожее на email или UUID. JSON dashboards Go runtime, PostgreSQL, Redis, SeaweedFS, Linux и продуктовый Lincodex поддерживаются в проекте; это не импортированные Grafana dashboard IDs. Метрики inference пока не реализованы. @@ -728,7 +799,7 @@ Go экспортирует стандартные Go/process метрики и План браузерного пути: Faro Web SDK -> same-origin `/telemetry` -> Alloy `faro.receiver` -> Loki. React SDK пока не подключен. Собирать очищенные Web Vitals, JS errors, release и нормализованный маршрут; исключить console logs, формы, текст резюме и session replay. Удалять query string, fragment и ID из URL. Ограничить размер, частоту и origin приемника. Request/trace IDs остаются полями логов, не labels; хранение spans требует отдельного backend, например Tempo, и пока не поддерживается. -Правила alerts в `observability/prometheus/rules/lincodex.yml` покрывают недоступный target backend, долю 5xx выше 5% при не менее чем 15 запросах за 5 минут, отставание outbox, dead letters и застрявшие обработчики, мертвые и опаздывающие задания по сроку, доставки с неизвестным исходом, устаревшие gauges доставок и квот, исчерпанную квоту почты и просроченные доставки; последнее правило требует еще `lincodex_mail_sender_running`, который должен экспортировать worker отправки из TASK-016, поэтому до него оно не срабатывает. `promtool test rules` дает каждому alert случай срабатывания, а каждому ограничению - случай молчания. Prometheus вычисляет их и показывает состояние на странице /alerts и в Grafana; Alertmanager и канал уведомлений не настроены, поэтому alert никому не приходит. Планируемые alerts: превышение latency budget, заполнение диска, ошибки ML и отброшенные логи. При низком трафике нужны окно и минимальное число событий, иначе процентили нестабильны. Настроить поведение `No Data` и ошибки datasource. Стек на том же хосте не может надежно сообщить о его остановке; для этого нужен внешний health check. Compose и dashboard smoke не проверяют доставку alerts. Правила и канал уведомления следует описывать как внедренные только после отдельной проверки. +Правила alerts в `observability/prometheus/rules/lincodex.yml` покрывают недоступный target backend, долю 5xx выше 5% при не менее чем 15 запросах за 5 минут, отставание outbox, dead letters и застрявшие обработчики, мертвые и опаздывающие задания по сроку, доставки с неизвестным исходом, устаревшие gauges доставок и квот, исчерпанную квоту почты и просроченные доставки; последнее правило требует еще, чтобы `lincodex_mail_sender_running` был 1 хотя бы на одном экземпляре, поэтому там, где цикл отправки не работает, например при `EMAIL_PROVIDER=disabled`, оно молчит. Оно считает только служебную почту, виды, которые отправляет worker, поэтому просроченное уведомление его не включает. `LincodexMailCancelledBroken` срабатывает при росте `lincodex_mail_sender_cancelled_total` с причиной `content_invalid` или `processing_failed`, то есть для отмен, означающих испорченную строку или дефект, а не действие пользователя. `promtool test rules` дает каждому alert случай срабатывания, а каждому ограничению - случай молчания. Prometheus вычисляет их и показывает состояние на странице /alerts и в Grafana; Alertmanager и канал уведомлений не настроены, поэтому alert никому не приходит. Планируемые alerts: превышение latency budget, заполнение диска, ошибки ML и отброшенные логи. При низком трафике нужны окно и минимальное число событий, иначе процентили нестабильны. Настроить поведение `No Data` и ошибки datasource. Стек на том же хосте не может надежно сообщить о его остановке; для этого нужен внешний health check. Compose и dashboard smoke не проверяют доставку alerts. Правила и канал уведомления следует описывать как внедренные только после отдельной проверки. ## Покрытие требований ТЗ diff --git a/docs/ru/DEPLOY.md b/docs/ru/DEPLOY.md index ee5ab16..1165190 100644 --- a/docs/ru/DEPLOY.md +++ b/docs/ru/DEPLOY.md @@ -220,7 +220,7 @@ Worker захватит его в течение одного интервала 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`. Пока ни один сценарий не отправляет почту: запросы писем сохраняются как доставки (см. [Доставки писем](#доставки-писем)), а worker, который вызывает транспорт, запланирован. +Текущее состояние: в этой сборке есть транспорты `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`. Процесс backend запускает worker отправки служебной почты identity (подтверждение почты и сброс пароля), когда `EMAIL_PROVIDER` равен `resend`; см. [Отправка служебной почты](#отправка-служебной-почты). Ни один сценарий аккаунта пока не создает такие письма, а продуктовые уведомления сохраняются как доставки, но не отправляются до TASK-462, так что боевой стенд сегодня не отправляет ни одного письма. `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#почтовый-транспорт). @@ -245,18 +245,18 @@ Compose передает эти переменные из корневого `.e ### Доставки писем -Запрос уведомления - строка `mail_requests`, пока обработчик `notification_delivery` не превратит его в строку `deliveries` и не удалит; модель описана в [ARCHITECTURE.md](ARCHITECTURE.md#доставки-писем). Миграция 00006 создает `mail_requests`, `deliveries` и `delivery_attempts` при запуске; настройки для этого не нужны. Пока доставки только сохраняются: worker, который их отправляет, запланирован, поэтому ни одна строка не выходит из `pending`. Уведомления создаются только для аккаунтов с подтвержденным адресом; запрос на неподтвержденный адрес отбрасывается со строкой в логе. +Запрос уведомления - строка `mail_requests`, пока обработчик `notification_delivery` не превратит его в строку `deliveries` и не удалит; модель описана в [ARCHITECTURE.md](ARCHITECTURE.md#доставки-писем). Миграция 00006 создает `mail_requests`, `deliveries` и `delivery_attempts` при запуске; настройки для этого не нужны. Доставки уведомлений пока только сохраняются: worker отправки берет только письма подтверждения и сброса пароля, поэтому уведомление остается в `pending`, пока TASK-462 не подключит продуктовые уведомления. Уведомления создаются только для аккаунтов с подтвержденным адресом; запрос на неподтвержденный адрес отбрасывается со строкой в логе. -- Каждая доставка закрепляется за `EMAIL_PROVIDER` и `EMAIL_ACCOUNT` в момент создания, а последующее изменение конфигурации применяется только к новым доставкам. Меняйте `EMAIL_ACCOUNT` вместе с `RESEND_API_KEY` каждый раз, когда ключ принадлежит другому аккаунту Resend, чтобы доставки, начатые под старым аккаунтом, никогда не отправлялись через новый. Доставки, созданные при `EMAIL_PROVIDER=disabled`, остаются закрепленными за `disabled`, пока worker отправки (TASK-016) не перенесет их через `Rebind`, что разрешено только до первой попытки. +- Каждая доставка закрепляется за `EMAIL_PROVIDER` и `EMAIL_ACCOUNT` в момент создания, а последующее изменение конфигурации применяется только к новым доставкам. Меняйте `EMAIL_ACCOUNT` вместе с `RESEND_API_KEY` каждый раз, когда ключ принадлежит другому аккаунту Resend, чтобы доставки, начатые под старым аккаунтом, никогда не отправлялись через новый. Служебная почта, созданная при `EMAIL_PROVIDER=disabled`, остается закрепленной за `disabled`, пока backend не запущен с транспортом: тогда worker отправки переносит ее через `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` и никогда не вставляйте их в задачи и чаты. -- Без SQL внутренний endpoint /metrics показывает `lincodex_mail_deliveries{kind,status}` для каждого вида и статуса, включая нулевые, и `lincodex_mail_delivery_oldest_due_pending_age_seconds` - сколько времени самая ранняя доставка в `pending` уже ждет своего срока. Backend читает их каждые 30 секунд одним агрегатом по `deliveries`; все экземпляры сообщают одинаковые значения, поэтому агрегируйте их через `max`. Неудачное чтение сохраняет прежние значения и пишет в журнал `delivery metrics could not be read; the gauges are stale`. Пока нет worker отправки (TASK-016), каждая сохраненная доставка остается в `pending`, а ее просрочка только растет. Серия просрочки появляется только после первого успешного чтения, поэтому свежий запуск не заявляет, что ничего не просрочено; `lincodex_mail_metrics_last_success_timestamp_seconds` - Unix-время последнего чтения, в котором прочитаны все агрегаты (0 от запуска до первого такого чтения), а `LincodexMailMetricsStale` срабатывает, когда оно старше 5 минут в течение 5 минут. Alert `LincodexMailDeliveryUnknownOutcome` срабатывает, пока у какой-либо доставки неизвестный исход. `LincodexMailDeliveriesOverdue` (доставка в `pending` просрочена больше чем на 15 минут) требует еще `lincodex_mail_sender_running`, равный 1; этот gauge принадлежит worker отправки из TASK-016, который должен экспортировать его, пока работает его цикл, поэтому alert молчит, пока отправителя нет, при `EMAIL_PROVIDER=disabled` и без трафика. +- Без SQL внутренний endpoint /metrics показывает `lincodex_mail_deliveries{kind,status}` для каждого вида и статуса, включая нулевые, и `lincodex_mail_delivery_oldest_due_pending_age_seconds` - сколько времени самая ранняя доставка в `pending` уже ждет своего срока. Backend читает их каждые 30 секунд одним агрегатом по `deliveries`; все экземпляры сообщают одинаковые значения, поэтому агрегируйте их через `max`. Неудачное чтение сохраняет прежние значения и пишет в журнал `delivery metrics could not be read; the gauges are stale`. Уведомления остаются в `pending` до TASK-462; в просрочку они не считаются. Серия просрочки появляется только после первого успешного чтения, поэтому свежий запуск не заявляет, что ничего не просрочено; `lincodex_mail_metrics_last_success_timestamp_seconds` - Unix-время последнего чтения, в котором прочитаны все агрегаты (0 от запуска до первого такого чтения), а `LincodexMailMetricsStale` срабатывает, когда оно старше 5 минут в течение 5 минут. Alert `LincodexMailDeliveryUnknownOutcome` срабатывает, пока у какой-либо доставки неизвестный исход. `LincodexMailDeliveriesOverdue` (доставка в `pending` просрочена больше чем на 15 минут) требует еще, чтобы `lincodex_mail_sender_running` был 1 хотя бы на одном экземпляре: его экспортирует worker отправки, 1 пока цикл работает и 0 иначе, поэтому alert молчит при `EMAIL_PROVIDER=disabled` (цикл не запускается) и без трафика. Просрочка считает только служебную почту (подтверждение и сброс пароля), поэтому очередь уведомлений, которые worker не отправляет до TASK-462, его не включает. Статус `cancelled` считается наравне с остальными, а `accepted` означает принято провайдером. - Не правьте сохраненную доставку вручную: trigger отклоняет любое изменение получателя, содержимого или ключа идемпотентности и смену аккаунта провайдера после первой попытки, а история попыток отклоняет обновления. Доставка в `waiting_quota` ждет сброса квоты в `next_attempt_at`; см. [Квоты почты](#квоты-почты). Без `next_attempt_at` момент сброса неизвестен, и нужно решение оператора. - Логи называют доставку только по `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 доставки сохраняет одну доставку на запрос. ### Квоты почты -Миграция 00007 создает `mail_quota_usage` и журнал резервирований `mail_quota_reservations` при запуске; настройка не нужна. Шлюз квот реализован, но worker отправки, который его вызывает, запланирован (TASK-016), поэтому текущая сборка пока ничего не считает. Модель описана в [ARCHITECTURE.md](ARCHITECTURE.md#квоты-почты). +Миграция 00007 создает `mail_quota_usage` и журнал резервирований `mail_quota_reservations` при запуске; настройка не нужна. Worker отправки вызывает шлюз квот при каждой отправке (см. [Отправка служебной почты](#отправка-служебной-почты)), поэтому служебная почта считается в квоту, а уведомления - нет до TASK-462. Модель описана в [ARCHITECTURE.md](ARCHITECTURE.md#квоты-почты). - Задайте `EMAIL_QUOTA_DAILY` и `EMAIL_QUOTA_MONTHLY` по тарифу аккаунта провайдера, который назван в `EMAIL_ACCOUNT`. Значения по умолчанию соответствуют Resend Free: 100 получателей за UTC-сутки и 3000 за месяц по проверке 05.10.2026. Сверьте текущую квоту аккаунта в панели Resend до запуска стенда и после любой смены тарифа. Для `smtp` задайте оба значения по лимитам relay; без них запуск завершается ошибкой. Измененное значение действует после перезапуска. - Меняйте `EMAIL_ACCOUNT` только вместе с настоящей сменой аккаунта провайдера, то есть с ключом другого аккаунта. Локальный счет ведется по метке аккаунта, поэтому переименование метки для того же аккаунта начинает счет с нуля, а у провайдера остается прежний. При запуске backend пишет в журнал `mail quota usage` с провайдером, аккаунтом, текущим расходом и лимитами суток и месяца и предупреждает, если у других меток того же провайдера есть расход в этом месяце. @@ -268,12 +268,28 @@ Compose передает эти переменные из корневого `.e - Месячная квота Resend следует платежному циклу аккаунта, а месяц шлюза - календарный месяц UTC. После месячного отказа доставка повторяется в начале следующего месяца UTC; если платежный цикл сбрасывается позже, этот повтор снова получит отказ и будет ждать еще месяц. Ручной повтор с записью в аудит запланирован вместе с политикой повторов (TASK-017). - Сниженный лимит действует со следующего резервирования. Во время поэтапного обновления экземпляры со старым и новым лимитом работают одновременно, и каждый проверяет лимит, с которым запущен, поэтому сниженный лимит соблюдается только после того, как все экземпляры работают с новой конфигурацией. Переключение `EMAIL_PROVIDER` на `smtp` начинает для relay отдельные счетчики с его явно заданными лимитами; доставки, закрепленные за прежним аккаунтом, шлюз отклоняет, а не отправляет без лимита. +### Отправка служебной почты + +Процесс backend запускает один цикл отправки служебной почты identity (подтверждение почты и сброс пароля). Он стартует вместе с backend, когда `EMAIL_PROVIDER` равен `resend` и задан `DATABASE_URL`, использует ту же базу, что и другие worker, через pool из двух соединений и не требует собственных настроек: интервал опроса (5 секунд), lease на захваченную доставку (`EMAIL_TIMEOUT` плюс одна минута), льготный период остановки (5 секунд), расписание повторов (1 минута с удвоением до 30 минут) и пауза после сбоя (5 секунд с удвоением до 2 минут) - константы в `backend/internal/bootstrap/mail_sender.go`. Миграция 00012 добавляет его столбцы; модель, проверки и исходы описаны в [ARCHITECTURE.md](ARCHITECTURE.md#отправка-служебной-почты). + +- Одновременно может работать несколько экземпляров backend. Каждый захватывает доставку через `FOR UPDATE SKIP LOCKED` и lease, поэтому одну доставку отправляет один экземпляр, а вызов провайдера несет стабильный ключ идемпотентности `delivery/`. При поэтапном обновлении останавливающийся экземпляр завершает отправку в течение 5 секунд, сохраняет результат и выходит. +- При `EMAIL_PROVIDER=disabled` цикл не запускается, а в журнале пишется `mail sender worker is not started because EMAIL_PROVIDER is disabled; stored deliveries wait`; `lincodex_mail_sender_running` равен 0, ничего не отправляется, а сохраненная служебная почта ждет следующего запуска с транспортом. Worker никогда не крутится вхолостую: после прохода, который ничего не смог отправить, он делает паузу. +- Перед отправкой worker проверяет токен и аккаунт. Доставка, которую нельзя отправлять, завершается как `cancelled` с `cancel_reason`, без попытки и без расхода квоты: `token_missing`, `token_purpose_mismatch`, `token_owner_mismatch`, `token_consumed`, `token_revoked`, `token_expired`, `account_not_current`, `recipient_mismatch`, `content_invalid` или `processing_failed`. Причины, вызванные пользователем, нормальны: пользователь запросил новую ссылку, подтвердил адрес, зарегистрировался заново или слишком долго ждал. Причины можно посмотреть так: `SELECT cancel_reason, count(*) FROM deliveries WHERE status = 'cancelled' GROUP BY cancel_reason`. Пользователь видит отмененное письмо как "не отправлено, запросите новое". +- Ответы провайдера: `accepted` означает принято провайдером, а не доставлено человеку; подтверждения доставки у backend нет. Отказ "пока" (`temporary`, `rate_limited`) оставляет доставку в `pending` с более поздним `next_attempt_at`, а повтор использует тот же ключ и тело; он повторяется, пока не удастся, пока не будет отказа навсегда или пока токен не истечет и доставка не будет отменена. Постоянный отказ или отказ из-за запроса завершает ее как `rejected`: прочитайте код провайдера в `delivery_attempts.provider_code` (например `validation_error` для неподтвержденного домена отправителя или `invalid_api_key`) и устраните причину. Ответ о квоте переводит ее в `waiting_quota`; см. [Квоты почты](#квоты-почты). +- `unknown` worker никогда не повторяет. Это значит, что провайдер мог принять письмо (потерянный ответ, ответ 5xx) или что worker, отправивший его, был потерян дольше 24-часового окна идемпотентности провайдера. Найдите сообщение в журнале самого провайдера; пока срабатывает alert `LincodexMailDeliveryUnknownOutcome`. Ручной повтор с записью аудита запланирован вместе с политикой повторов (TASK-017). +- Захваченная доставка держит lease: `SELECT id, kind, claimed_until FROM deliveries WHERE claim_owner IS NOT NULL`. Строка с давно прошедшим `claimed_until` значит, что ее worker умер; другой экземпляр подхватит ее сам. Не сбрасывайте lease вручную. +- `content_invalid` и `processing_failed` - не действия пользователя: первое значит, что сохраненная строка не совпадает со своим хешем содержимого (ручная правка) или содержит сообщение, которое не принимает ни один транспорт, второе - что worker трижды подряд потерпел сбой на строке (повторы разнесены расписанием). Alert `LincodexMailCancelledBroken` срабатывает при росте; прочитайте журнал worker по `delivery_id` и осмотрите метаданные строки. Строка, которая сбоит постоянно, не блокирует остальные: она повторяется позже (`failure_count`, `next_attempt_at`), а затем отменяется. +- Тела письма с токеном очищаются, когда оно принято, отклонено или отменено (ставится `body_redacted_at`), поэтому дампы и резервные копии завершенной почты с токеном токенов не содержат. Письмо в `unknown` сохраняет тело, пока оператор его не разрешит. Не копируйте тела ожидающих писем никуда. +- Lease измеряется часами базы, поэтому различие часов экземпляров не важно, важны только часы базы. Вызов провайдера ограничен остатком lease; при `SHUTDOWN_TIMEOUT` по умолчанию 10 секунд останавливающийся экземпляр укладывается в 3 секунды льготного периода плюс 5 секунд на сохранение ответа. Снижение `SHUTDOWN_TIMEOUT` укорачивает вторую часть (не меньше 1 секунды); результат, не сохраненный вовремя, покрывает перехват. +- Журнал называет доставку только по `delivery_id`, ее виду и исходу или причине отмены, например `service mail was not sent because it is no longer valid`; никогда не по адресу, токену, ссылке или телу. Если токен или ссылка появились в журнале, считайте это дефектом. +- Внутренний endpoint /metrics показывает `lincodex_mail_sender_running` (1, пока цикл этого экземпляра работает, иначе 0; без labels) и `lincodex_mail_sender_cancelled_total{reason}` (счетчик по причине отмены, включая нулевые) рядом с gauges доставок, у которых теперь есть и статус `cancelled`. + ### Шаблоны писем -Реализовано: renderer в `backend/internal/usecase/notification/mailtemplate/` с шаблонами подтверждения почты, сброса пароля и короткого уведомления. Обработчик доставки рендерит им уведомления, когда сохраняет доставку; регистрация, подтверждение, сброс пароля и отправка запланированы, поэтому текущая сборка не отправляет писем. +Реализовано: renderer в `backend/internal/usecase/notification/mailtemplate/` с шаблонами подтверждения почты, сброса пароля и короткого уведомления. Обработчик доставки рендерит им уведомления, когда сохраняет доставку, а `ServiceMailer` рендерит письма подтверждения и сброса пароля, когда сценарий identity выпускает токен; сами сценарии (регистрация, подтверждение, сброс пароля) запланированы, поэтому ни один аккаунт пока не вызывает письмо. - Шаблоны встроены в бинарник через `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, знак процента и сегменты `.` или `..` отклоняются. +- Ссылки начинаются с `APP_PUBLIC_URL`, который renderer повторно проверяет по тем же правилам. Подтверждение: `/verify-email#token=`; сброс пароля: `/reset-password#token=` (страница и API сброса запланированы). Токен находится только во fragment URL и никогда ни в пути, ни в query: браузер не отправляет fragment серверу, поэтому access log nginx (он пишет `$uri`) и заголовки Referer его никогда не содержат, а маршрут frontend читает его в браузере и отправляет в теле запроса API. Ссылка уведомления указывает на путь внутри приложения, например `/candidate/invitations`; абсолютный URL, `//host`, схема вроде `javascript:`, query, fragment, знак процента и сегменты `.` или `..` отклоняются. - В письмах нет имени, email или других контактов. Текст вызывающего кода в уведомлении экранируется в HTML части; управляющие и bidi символы удаляются из текстовой части, а тема сводится к одной строке, поэтому CR и LF не могут добавить строки заголовка. Тема уведомления ограничена 100 символами, текст 2000. - Тексты на русском языке. Выпущенная версия неизменяема: изменение текста добавляет следующую версию, например `verification.v2`, и переключает текущую версию в коде. Версии не делят файлы, поэтому одна версия не может изменить тело другой. Каждый результат содержит свою версию и SHA-256 content hash по версии, теме и обеим частям; одна и та же версия с теми же данными всегда дает то же тело. Доставка хранит сформированное тело вместе с hash, а повтор отправляет сохраненное тело, а не формирует его заново, поэтому новая версия применяется только к новым доставкам, а файлы старой версии для отправки сохраненной доставки не нужны. - Renderer ничего не пишет в лог. Результат и данные уведомления в выводе `fmt` и `slog` показывают только тип, версию и content hash; токены, ссылки и тела писем не печатаются. diff --git a/docs/ru/DEVELOPMENT.md b/docs/ru/DEVELOPMENT.md index ab4aab0..9d355ce 100644 --- a/docs/ru/DEVELOPMENT.md +++ b/docs/ru/DEVELOPMENT.md @@ -50,7 +50,7 @@ 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` и `resend` и выбор `EMAIL_PROVIDER` в bootstrap; `smtp` после проверки своих настроек останавливает запуск. Запросы уведомлений (`mail_requests`) превращаются в доставки (`deliveries`, `delivery_attempts`) обработчиком `notification_delivery`, но пока ничто их не отправляет. См. [DEPLOY.md](DEPLOY.md#почта) и [ARCHITECTURE.md](ARCHITECTURE.md#доставки-писем). +- Почта: outbound порт `MailSender`, транспорты `disabled` и `resend` и выбор `EMAIL_PROVIDER` в bootstrap; `smtp` после проверки своих настроек останавливает запуск. Запросы уведомлений (`mail_requests`) превращаются в доставки (`deliveries`, `delivery_attempts`) обработчиком `notification_delivery`, но пока ничто не отправляет уведомления (TASK-462). С `resend` backend запускает worker отправки служебной почты identity (подтверждение и сброс пароля, привязанные к своим токенам, с проверкой перед отправкой, шлюзом квот и стабильным ключом идемпотентности); ни один сценарий аккаунта пока не создает такие письма. См. [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 обработчиков событий запускает один продуктовый обработчик - обработчик доставки писем, а продуктовые сценарии пока не создают его событие; см. [Обработчики событий](#обработчики-событий). diff --git a/docs/ru/TESTING.md b/docs/ru/TESTING.md index 0d740e6..c3472fe 100644 --- a/docs/ru/TESTING.md +++ b/docs/ru/TESTING.md @@ -199,7 +199,47 @@ Unit-тесты (`make -C backend test`) проверяют правила кв - Отчет при запуске: при расходе под меткой `old-label` и под настроенной меткой отчет через `postgres.MailQuotaStore` пишет расход настроенного аккаунта и предупреждает об `old-label`. - База отклоняет неизвестный вид периода, месяц, который начинается не с первого числа, отрицательный расход, неверную метку аккаунта, резервирование, у которого сутки вне его месяца, и неизвестный исход. -`TestPostgresMigrations` дополнительно проверяет, что миграция 00007 создает и удаляет `mail_quota_usage` и `mail_quota_reservations` и оставляет таблицы доставок. Набор не вызывает транспорт: worker, который последовательно выполняет `PrepareSend`, `Send` и `SettleSend`, - это TASK-016. +`TestPostgresMigrations` дополнительно проверяет, что миграция 00007 создает и удаляет `mail_quota_usage` и `mail_quota_reservations` и оставляет таблицы доставок. Набор квот не вызывает транспорт; worker, который последовательно выполняет `PrepareSend`, `Send` и `SettleSend` (TASK-016), покрыт тестами отправки служебной почты ниже. + +## Тесты отправки служебной почты + +Модульные тесты (`make -C backend test`) покрывают: + +- `domain`: `Delivery.CheckServiceMail` называет первое нарушенное правило (нет токена, назначение, владелец, использован, отозван, истек ровно в свой срок, регистрация сдвинулась, адрес подтвержден, адрес изменен) и оставляет актуальное письмо подтверждения или сброса отправляемым; `Delivery.Cancel` работает из `pending` и `waiting_quota`, отклоняет `unknown` и конечные статусы, не оставляет попытки и переживает восстановление; уведомление не может нести ID токена; названия статусов не содержат утверждения о доставке человеку. +- `usecase/notification`: `ServiceMailSender` против хранилищ в памяти с правилом версии и lease хранилища PostgreSQL, квоты шлюза в памяти и транспорта по сценарию. Каждый результат транспорта дает правильное состояние доставки, срок и эффект на квоту (принято, постоянный отказ и отказ запроса, временный отказ после первой паузы, более длинная подсказка провайдера, ответ провайдера о дневной квоте до полуночи UTC, ответ о квоте без сброса, unknown, транспорт, ответивший без исхода, нет транспорта, прерванный вызов, неверное сообщение); каждая причина отмены достигается без вызова транспорта и резервирования; заполненная локальная квота откладывает доставку без вызова и отправляет ее при сбросе; результат, который не удалось сохранить, сохраняет lease, повторяется три раза, а затем его подхватывает замена с тем же ключом без двойного подсчета; попытка, потерянная за пределами окна идемпотентности или у транспорта без дедупликации, записывается как unknown и не повторяется; доставка, чей хеш содержимого не совпадает, отменяется как `content_invalid` и сообщается без вызова транспорта; строка, которая сбоит по собственной вине (нечитаемая по причине, отличной от несовпадения хеша, нарушенное правило домена при чтении состояния), считается, отодвигается расписанием повторов, чтобы доставка за ней отправилась, и после трех сбоев отменяется как `processing_failed`; временные ошибки (тайм-аут, отмена, deadlock, сеть, EOF, отсутствие настройки квоты) возвращаются worker и никогда не считаются и не отменяют строку, сколько бы ни повторялись; ошибка `Send` без ответа отодвигает строку без счета; приостановленный счет отодвигает строки без счета; успешный проход очищает счетчик; сбой не записывается для строки, которую держит другой worker; окно идемпотентности считается от первого запроса при повторных потерях worker и с часовым запасом; отзыв между захватом и вызовом учитывается; результат отбрасывается, если lease потерян во время вызова; вызов ограничен lease за вычетом бюджета расчета; jitter ограничен и подменяем; письма, сохраненные, пока транспорта не было, переносятся на настроенный аккаунт, а доставка другого аккаунта остается нетронутой; журнал никогда не содержит адрес, токен или ссылку. `ServiceMailer` сохраняет доставку, привязанную к токену, с ID токена, токеном во fragment ссылки и без `?token=`, безвредно повторяется и отклоняет токен не того назначения до рендеринга. `RetryPolicy` удваивает паузу до максимума и учитывает более длинную подсказку. +- `worker/mailsender`: отмененные доставки считаются по причине; предохранитель приостанавливает счет сбоев, когда подряд падают три разные строки, и возобновляет после успеха, а повторный сбой одной строки его не включает; сбойная строка заставляет цикл ждать по backoff; gauge равен true только пока работает цикл, холостой проход ждет интервал опроса, за обработанной доставкой сразу идет следующий проход, а отсутствие транспорта, прерванный вызов и сбой базы вызывают паузу вместо вращения вхолостую. +- `adapter/secondary/postgres`: только классы SQLSTATE 22 и 23 совпадают с `ErrRowFault`; deadlock, serialization, соединение, ресурсы, остановка и внутренние ошибки - нет. +- `adapter/secondary/prometheus`: у `lincodex_mail_sender_cancelled_total` каждая причина существует с нулем, а произвольный label отклоняется; `lincodex_mail_sender_running` существует со значением 0 и следует за `SetMailSenderRunning`; каждый статус доставки, включая `cancelled`, существует с нулем. +- `adapter/secondary/mail/resend`: loopback-конструктор принимает только http URL на loopback-хосте, поэтому ключ и письма развертывания нельзя направить через него на другой хост; `resendfixture` отвечает как Resend (принимает, повторяет исходное сообщение для повторного ключа и тела, отклоняет другое тело под тем же ключом, проигрывает заданные ошибки). +- `bootstrap`: нет worker без транспорта или базы; цикл запускается и останавливается вместе с приложением, а gauge следует за ним. +- `observability/prometheus/tests`: `LincodexMailDeliveriesOverdue` молчит без gauge, пока он равен 0 и для очереди из одних уведомлений (возраст 0), и срабатывает, пока какой-либо экземпляр сообщает 1; `LincodexMailCancelledBroken` срабатывает на `content_invalid` и `processing_failed` и молчит для причин от действий пользователя (`make -C observability check`). + +`TestServiceMailSending` в `backend/integration_test/mail_sender_test.go` использует `bootstrap(t, postgresService)`, настоящие транзакционный слой, хранилища, шлюз квот и usecase отправки, настоящий транспорт Resend, направленный на локальную имитацию, и фиктивные часы. Подтесты делят базу и начинают с пустых таблиц: + +- Служебное письмо для синтетического аккаунта без записи согласия любого назначения ставится вместе с токеном в одной транзакции и принимается имитацией: один вызов провайдера с ключом `delivery/`, адресом и ссылкой с токеном во fragment; доставка `accepted` с ID сообщения провайдера, одной принятой попыткой, одним посчитанным получателем и без оставшегося lease, аккаунт видит статус `accepted`, а второй проход ничего не делает. Журнал не содержит ни адреса, ни токена. +- Worker, который держит доставку, не пускает к ней другого: имитация отвечает медленно, проход второго worker холостой, пока запрос первого в пути, и имитация получает ровно один вызов, а база - одну попытку. +- Четыре worker одновременно разбирают очередь из восьми доставок: восемь вызовов провайдера под восемью разными ключами, ни один не повторен, восемь принятых доставок по одной попытке, восемь посчитанных получателей. +- Worker, остановившийся после отправки (база отказывает при сохранении ответа), заменяется после истечения его lease: два вызова под одним ключом, второй - повтор, одно сообщение у провайдера, одна попытка, открытое резервирование использовано повторно, поэтому получатель считается один раз. За пределами 24-часового окна замена записывает попытку unknown и не вызывает провайдера. +- Доставка с хешем содержимого, испорченным ручной правкой, отменяется как `content_invalid` на версии 2 без вызова провайдера, а следующая за ней доставка отправляется в следующем проходе. +- Строка, которая сбоит по своей причине (тема с переводом строки нарушает правила домена, поэтому строку нельзя восстановить, хотя хеш цел), считается и отодвигается на минуту, пока доставка за ней отправляется, сбоит снова в каждый срок и отменяется как `processing_failed` на третьем сбое с очищенными телами; ошибка транспорта без ответа отодвигает строку на минуту без счета, с возвращенным резервированием и доставкой в `pending`. +- Сбой, записанный worker, чей захват откатился, не трогает строку, которую держит другой worker, а несчитаемый сбой оставляет `failure_count` равным 0. +- Три потерянных подряд worker не скрывают возраст первого запроса: доставка становится `unknown`, когда `first_send_started_at` старше 24 часов, и провайдер в четвертый раз не вызывается. +- Lease - несколько секунд по часам базы; чужой worker не может записать попытку или заблокировать строку; `RecordClaimedAttempt` проходит для владельца. +- При 5000 просроченных строк уведомлений план захвата использует `deliveries_due_idx` и не использует последовательное сканирование (`EXPLAIN`). +- Очередь из одних уведомлений не создает возраст самой ранней ожидающей доставки; служебное письмо создает. +- Тела письма с токеном очищаются, когда оно принято или отменено, и токен больше не встречается ни в одной строке; ожидающее письмо вручную очистить нельзя; очищенная строка не может получить тело обратно или потерять метку; аккаунт по-прежнему видит свой статус. +- Токен, отозванный повторной отправкой, уже использованный токен, истекший токен, повторно зарегистрированный аккаунт, уже подтвержденный адрес, измененный адрес и токен другого назначения завершают доставку как `cancelled` с соответствующей причиной, без попытки, без lease, без следующей попытки, без резервирования и без вызова провайдера; аккаунт видит `cancelled`; следующий проход холостой. Удаленный аккаунт уносит свою доставку. +- Ответы провайдера: 503 `service_unavailable` оставляет доставку в `pending` со сроком через минуту, проход до срока холостой, повтор в срок использует тот же ключ и принимается; 500 дает `unknown` без следующей попытки и без повтора через сутки; 403 `validation_error` дает `rejected`. +- Квота: локальный лимит один в сутки переводит вторую доставку в `waiting_quota` до полуночи UTC без вызова провайдера, аккаунт видит ожидание и его конец, а доставка отправляется при сбросе; ответ провайдера `daily_quota_exceeded` откладывает доставку до следующей полуночи. +- Продуктовое уведомление не берется никогда. +- `EMAIL_PROVIDER=disabled`: с транспортом disabled проход сообщает, что канал недоступен, доставка остается нетронутой на версии 1, lease и резервирование освобождены, до имитации ничего не доходит, цикл с ним делает не больше четырех проходов меньше чем за секунду, а gauge равен 1, пока он работает, и 0 после; с транспортом то же письмо переносится на настроенный аккаунт и принимается. +- Схема отклоняет отмененную доставку без причины, причину у другого статуса, половину lease, lease у конечной доставки, уведомление, привязанное к токену, смену привязки токена и удаление токена, на который ссылается доставка; удаление аккаунта убирает оба. + +`TestDeliverySendingMigration` откатывает и заново применяет миграцию 00012 поверх отмененной и очищенной доставки сброса пароля: прежняя схема хранит ее как `rejected` с заглушкой в теле, удаляет токены сброса и новые столбцы, а миграция применяется снова. `TestPostgresMigrations` покрывает общий путь вверх, вниз и снова вверх. + +`make -C backend lint` также запрещает импорт `resendfixture` и вызов `resend.NewLoopbackSender` вне файлов `_test.go` (depguard и forbidigo в `backend/.golangci.yml`). + +Ни одна проверка не вызывает настоящий API Resend: единственный провайдер - имитация, поэтому эти тесты доказывают протокол, на котором говорит транспорт, и правила доставки, но не поведение Resend, доставляемость и реальную квоту аккаунта. ## Тесты заданий по сроку diff --git a/observability/grafana/dashboards/lincodex-product.json b/observability/grafana/dashboards/lincodex-product.json index 588ffb1..956a12f 100644 --- a/observability/grafana/dashboards/lincodex-product.json +++ b/observability/grafana/dashboards/lincodex-product.json @@ -627,7 +627,7 @@ "type": "prometheus", "uid": "prometheus" }, - "description": "Stored deliveries by status at the last statistics read (every 30 seconds): pending, waiting_quota, unknown, accepted, rejected.", + "description": "Stored deliveries by status at the last statistics read (every 30 seconds): pending, waiting_quota, unknown, accepted (by the provider, not delivered to a person), rejected, cancelled (not sent, with a reason).", "fieldConfig": { "defaults": { "color": { @@ -725,7 +725,7 @@ "type": "prometheus", "uid": "prometheus" }, - "description": "How long the earliest pending delivery has been due. The sending worker is planned (TASK-016); until then any stored delivery only waits.", + "description": "How long the earliest pending service mail (verification or password reset) has been due. Notifications are not counted: they wait until TASK-462 connects them. With EMAIL_PROVIDER=disabled nothing is sent and service mail waits.", "fieldConfig": { "defaults": { "color": { diff --git a/observability/prometheus/rules/lincodex.yml b/observability/prometheus/rules/lincodex.yml index e88acfb..11773d9 100644 --- a/observability/prometheus/rules/lincodex.yml +++ b/observability/prometheus/rules/lincodex.yml @@ -92,9 +92,14 @@ groups: summary: Mail deliveries have an unknown outcome. description: An attempt may have reached the provider without a conclusive answer; a retry needs the same idempotency key, and after the idempotency window an operator decides. - # Inert until the sending worker exists: TASK-016 must export - # lincodex_mail_sender_running (1 while its loop runs) as part of its - # definition of done. Without that series the rule matches nothing. + # Needs the sending worker (TASK-016), which exports + # lincodex_mail_sender_running: 1 while its loop runs, 0 otherwise, and + # 0 for the whole process lifetime with EMAIL_PROVIDER=disabled, where no + # loop starts. The rule fires only while at least one backend instance + # reports 1, so a stand without a transport stays silent. The age gauge + # counts only service mail (verification and password reset), the kinds + # the worker sends: a due notification waits for TASK-462 and is not + # counted, so a notification backlog never fires this alert. - alert: LincodexMailDeliveriesOverdue expr: | max(lincodex_mail_delivery_oldest_due_pending_age_seconds{job="backend"}) > 900 @@ -104,8 +109,16 @@ groups: labels: severity: warning annotations: - summary: A pending mail delivery has been due for more than 15 minutes. - description: The sending worker runs but does not pick up due deliveries; check its logs and the quota gauges. + summary: A pending service mail delivery has been due for more than 15 minutes. + description: The sending worker runs but does not pick up due service mail (verification or password reset); check its logs and the quota gauges. Notifications are not counted. + + - alert: LincodexMailCancelledBroken + expr: sum(increase(lincodex_mail_sender_cancelled_total{job="backend",reason=~"content_invalid|processing_failed"}[15m])) > 0 + labels: + severity: warning + annotations: + summary: The mail sending worker cancelled a delivery because of a broken row or a repeated internal failure. + description: Reason content_invalid (the stored content does not match its hash, or the message is unsendable) or processing_failed (the worker failed on the row several times) is a defect or a manual edit, not a user action. Select id, kind, and cancel_reason from deliveries where status is cancelled and read the worker logs for the delivery_id. Cancellations that follow a user action (token_revoked, token_consumed, token_expired, account_not_current) are normal and do not fire this alert. - alert: LincodexMailMetricsStale expr: time() - max(lincodex_mail_metrics_last_success_timestamp_seconds{job="backend"}) > 300 diff --git a/observability/prometheus/tests/lincodex_rules_test.yml b/observability/prometheus/tests/lincodex_rules_test.yml index cf3f8c5..0037a99 100644 --- a/observability/prometheus/tests/lincodex_rules_test.yml +++ b/observability/prometheus/tests/lincodex_rules_test.yml @@ -199,6 +199,16 @@ tests: - eval_time: 30m alertname: LincodexMailDeliveriesOverdue exp_alerts: [] +- interval: 1m + input_series: + - series: lincodex_mail_delivery_oldest_due_pending_age_seconds{job="backend",instance="a"} + values: 2000x40 + - series: lincodex_mail_sender_running{job="backend",instance="a"} + values: 0x40 + alert_rule_test: + - eval_time: 30m + alertname: LincodexMailDeliveriesOverdue + exp_alerts: [] - interval: 1m input_series: - series: lincodex_mail_delivery_oldest_due_pending_age_seconds{job="backend",instance="a"} @@ -215,8 +225,88 @@ tests: - exp_labels: severity: warning exp_annotations: - summary: A pending mail delivery has been due for more than 15 minutes. - description: The sending worker runs but does not pick up due deliveries; check its logs and the quota gauges. + summary: A pending service mail delivery has been due for more than 15 minutes. + description: The sending worker runs but does not pick up due service mail (verification or password reset); check its logs and the quota gauges. Notifications are not counted. +- interval: 1m + input_series: + - series: lincodex_mail_delivery_oldest_due_pending_age_seconds{job="backend",instance="a"} + values: 2000x40 + - series: lincodex_mail_sender_running{job="backend",instance="a"} + values: 0x40 + - series: lincodex_mail_sender_running{job="backend",instance="b"} + values: 1x40 + alert_rule_test: + - eval_time: 10m + alertname: LincodexMailDeliveriesOverdue + exp_alerts: [] + - eval_time: 20m + alertname: LincodexMailDeliveriesOverdue + exp_alerts: + - exp_labels: + severity: warning + exp_annotations: + summary: A pending service mail delivery has been due for more than 15 minutes. + description: The sending worker runs but does not pick up due service mail (verification or password reset); check its logs and the quota gauges. Notifications are not counted. +- interval: 1m + # A backlog of notifications only: the sampler reports an age of 0 for + # service mail, so the alert stays silent although the sender runs and + # notifications are due. + input_series: + - series: lincodex_mail_delivery_oldest_due_pending_age_seconds{job="backend",instance="a"} + values: 0x40 + - series: lincodex_mail_deliveries{job="backend",instance="a",kind="notification",status="pending"} + values: 500x40 + - series: lincodex_mail_sender_running{job="backend",instance="a"} + values: 1x40 + alert_rule_test: + - eval_time: 30m + alertname: LincodexMailDeliveriesOverdue + exp_alerts: [] +- interval: 1m + input_series: + - series: lincodex_mail_sender_cancelled_total{job="backend",instance="a",reason="content_invalid"} + values: 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 + - series: lincodex_mail_sender_cancelled_total{job="backend",instance="a",reason="token_revoked"} + values: 0+5x40 + alert_rule_test: + - eval_time: 9m + alertname: LincodexMailCancelledBroken + exp_alerts: [] + - eval_time: 12m + alertname: LincodexMailCancelledBroken + exp_alerts: + - exp_labels: + severity: warning + exp_annotations: + summary: The mail sending worker cancelled a delivery because of a broken row or a repeated internal failure. + description: Reason content_invalid (the stored content does not match its hash, or the message is unsendable) or processing_failed (the worker failed on the row several times) is a defect or a manual edit, not a user action. Select id, kind, and cancel_reason from deliveries where status is cancelled and read the worker logs for the delivery_id. Cancellations that follow a user action (token_revoked, token_consumed, token_expired, account_not_current) are normal and do not fire this alert. + - eval_time: 35m + alertname: LincodexMailCancelledBroken + exp_alerts: [] +- interval: 1m + # Reasons that follow a user action never fire it, however many there are. + input_series: + - series: lincodex_mail_sender_cancelled_total{job="backend",instance="a",reason="token_revoked"} + values: 0+5x40 + - series: lincodex_mail_sender_cancelled_total{job="backend",instance="a",reason="token_expired"} + values: 0+3x40 + alert_rule_test: + - eval_time: 30m + alertname: LincodexMailCancelledBroken + exp_alerts: [] +- interval: 1m + input_series: + - series: lincodex_mail_sender_cancelled_total{job="backend",instance="a",reason="processing_failed"} + values: 0 0 0 0 0 2x34 + alert_rule_test: + - eval_time: 8m + alertname: LincodexMailCancelledBroken + exp_alerts: + - exp_labels: + severity: warning + exp_annotations: + summary: The mail sending worker cancelled a delivery because of a broken row or a repeated internal failure. + description: Reason content_invalid (the stored content does not match its hash, or the message is unsendable) or processing_failed (the worker failed on the row several times) is a defect or a manual edit, not a user action. Select id, kind, and cancel_reason from deliveries where status is cancelled and read the worker logs for the delivery_id. Cancellations that follow a user action (token_revoked, token_consumed, token_expired, account_not_current) are normal and do not fire this alert. - interval: 1m input_series: - series: lincodex_mail_metrics_last_success_timestamp_seconds{job="backend",instance="a"} diff --git a/observability/scripts/verify-product-metrics.sh b/observability/scripts/verify-product-metrics.sh index a4f11af..8caefdf 100755 --- a/observability/scripts/verify-product-metrics.sh +++ b/observability/scripts/verify-product-metrics.sh @@ -7,8 +7,10 @@ # metrics nor the logs in Loki. Everything it creates is removed on exit. # # Mail: EMAIL_PROVIDER=resend with a placeholder key, so the quota gauges -# exist. Nothing sends mail in this build: the sending worker is planned -# (TASK-016), and the stored delivery stays pending. +# exist. The sending worker (TASK-016) sends only verification and password +# reset mail; the stored fixture delivery is a notification, which stays +# pending until TASK-462 connects product notifications, and no call reaches +# Resend. set -euo pipefail root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)