feat(mail): send service identity mail through a leased worker
This commit is contained in:
1 parent
204c6bae62
commit
d21fd49a42
58 files changed
+7577
-164
No files matched your search
@@ -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:
|
||||
|
||||
@@ -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')
|
||||
);
|
||||
@@ -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,
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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()
|
||||
}
|
||||
@@ -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)})
|
||||
}
|
||||
@@ -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 <no-reply@example.com>", 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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",
|
||||
)
|
||||
|
||||
|
||||
@@ -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) })
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
|
||||
@@ -50,6 +50,7 @@ func initialize(
|
||||
newOutboxRelay,
|
||||
newEventConsumers,
|
||||
newJobWorker,
|
||||
newMailSenderWorker,
|
||||
newDeliveryMetrics,
|
||||
NewApplication,
|
||||
),
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 ""
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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(),
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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{} },
|
||||
|
||||
@@ -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 ("<len>:<part>,"), 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"):
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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", "<p>"+testBody+"</p>\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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user