feat(notifications): send product notifications with a rights check right before each send

This commit is contained in:
shira committed 2026-10-09 20:38:39 +03:00
1 parent a856066316
commit 623d41b969
59 files changed
+4125 -1126

No files matched your search

+6
View File
@@ -45,6 +45,12 @@ EMAIL_TIMEOUT=10s
# mail wait for the reset; nothing buys a plan or switches the transport.
EMAIL_QUOTA_DAILY=
EMAIL_QUOTA_MONTHLY=
# Recipients per UTC day and per UTC month that product notifications leave
# free for service mail (verification and password reset). Empty means a fifth
# of the matching quota limit, 20 and 600 on the Resend Free plan. Notifications
# are admitted only while the window stays at or above the reserve after them.
EMAIL_SERVICE_RESERVE_DAILY=
EMAIL_SERVICE_RESERVE_MONTHLY=
# Public origin for links in mail. Email confirmation requires the browser's
# Origin header to match this scheme, host, and port. Use HTTPS except on
# localhost, 127.0.0.1, or [::1]. Do not add a path, query, or fragment.
+5
View File
@@ -107,6 +107,11 @@ type Config struct {
// through the configured provider account per UTC day and UTC month.
EmailQuotaDaily int
EmailQuotaMonthly int
// EmailServiceReserveDaily and EmailServiceReserveMonthly keep recipients
// of the daily and monthly quota free for service mail: product
// notifications are admitted only while the windows stay above them.
EmailServiceReserveDaily int
EmailServiceReserveMonthly int
// AppPublicURL is the public origin without a trailing slash, for links
// in mail.
AppPublicURL string
+38
View File
@@ -53,6 +53,10 @@ const (
// limits are not Resend's, so the operator states them.
defaultEmailQuotaDaily = 100
defaultEmailQuotaMonthly = 3000
// defaultEmailServiceReserveShare sets the service reserve default to one
// part of the limit of each window: a fifth, so 20 recipients a day and 600
// a month on the Resend Free plan. Product notifications share the rest.
defaultEmailServiceReserveShare = 5
// maxEmailQuota is far above any plan this project can afford; a larger
// value is a typo, not a plan.
maxEmailQuota = 1_000_000_000
@@ -124,6 +128,21 @@ func (config *Config) loadMailQuota(lookup LookupEnv) error {
if config.EmailQuotaMonthly, err = intOrDefault(setOnly, "EMAIL_QUOTA_MONTHLY", monthly); err != nil {
return err
}
return config.loadServiceReserve(setOnly)
}
// loadServiceReserve reads the recipients of each window that product
// notifications leave to service mail. An unset value takes a fifth of the
// configured limit, so the default follows the plan; a set value of 0 keeps
// the whole window for notifications too.
func (config *Config) loadServiceReserve(setOnly func(key string) (string, bool)) error {
var err error
if config.EmailServiceReserveDaily, err = intOrDefault(setOnly, "EMAIL_SERVICE_RESERVE_DAILY", config.EmailQuotaDaily/defaultEmailServiceReserveShare); err != nil {
return err
}
if config.EmailServiceReserveMonthly, err = intOrDefault(setOnly, "EMAIL_SERVICE_RESERVE_MONTHLY", config.EmailQuotaMonthly/defaultEmailServiceReserveShare); err != nil {
return err
}
return nil
}
@@ -204,6 +223,25 @@ func (config Config) validateMailQuota() error {
if config.EmailQuotaDaily > config.EmailQuotaMonthly {
return errors.New("Config.validateMailQuota - EMAIL_QUOTA_DAILY must not exceed EMAIL_QUOTA_MONTHLY")
}
return config.validateServiceReserve()
}
// validateServiceReserve accepts a reserve from 0 up to, not including, each
// limit. A reserve equal to a limit would leave product notifications no
// recipient in that window, so it is refused rather than read as "off".
func (config Config) validateServiceReserve() error {
for _, reserve := range []struct {
name string
value int
limit int
}{
{"EMAIL_SERVICE_RESERVE_DAILY", config.EmailServiceReserveDaily, config.EmailQuotaDaily},
{"EMAIL_SERVICE_RESERVE_MONTHLY", config.EmailServiceReserveMonthly, config.EmailQuotaMonthly},
} {
if reserve.value < 0 || reserve.value >= reserve.limit {
return fmt.Errorf("Config.validateServiceReserve - %s must be an integer from 0 to below its quota limit", reserve.name)
}
}
return nil
}
+40
View File
@@ -258,3 +258,43 @@ func TestLoadFromEnvRejectsMailSettings(t *testing.T) {
})
}
}
func TestLoadFromEnvServiceReserveDefaultsToAFifthOfEachLimit(t *testing.T) {
settings, err := LoadFromEnv(mailEnvironment(map[string]string{"EMAIL_PROVIDER": "resend", "RESEND_API_KEY": testResendAPIKey}))
if err != nil {
t.Fatalf("LoadFromEnv() error = %v", err)
}
if settings.EmailServiceReserveDaily != 20 || settings.EmailServiceReserveMonthly != 600 {
t.Fatalf("service reserve = %d a day and %d a month, want 20 and 600 for the Resend Free limits", settings.EmailServiceReserveDaily, settings.EmailServiceReserveMonthly)
}
// Zero is a stated reserve, not an unset one: the notifications may then use
// the whole window.
settings, err = LoadFromEnv(mailEnvironment(map[string]string{
"EMAIL_PROVIDER": "resend", "RESEND_API_KEY": testResendAPIKey,
"EMAIL_SERVICE_RESERVE_DAILY": "5", "EMAIL_SERVICE_RESERVE_MONTHLY": "0",
}))
if err != nil {
t.Fatalf("LoadFromEnv() with a stated reserve error = %v", err)
}
if settings.EmailServiceReserveDaily != 5 || settings.EmailServiceReserveMonthly != 0 {
t.Fatalf("service reserve = %d a day and %d a month, want 5 and 0", settings.EmailServiceReserveDaily, settings.EmailServiceReserveMonthly)
}
}
func TestLoadFromEnvRejectsAServiceReserveThatLeavesNoRoom(t *testing.T) {
for name, value := range map[string]map[string]string{
"daily reserve equal to the daily limit": {"EMAIL_SERVICE_RESERVE_DAILY": "100"},
"monthly reserve above the monthly limit": {"EMAIL_SERVICE_RESERVE_MONTHLY": "3001"},
"negative reserve": {"EMAIL_SERVICE_RESERVE_DAILY": "-1"},
} {
values := map[string]string{"EMAIL_PROVIDER": "resend", "RESEND_API_KEY": testResendAPIKey}
for key, reserve := range value {
values[key] = reserve
}
_, err := LoadFromEnv(mailEnvironment(values))
if err == nil || !strings.Contains(err.Error(), "EMAIL_SERVICE_RESERVE") {
t.Fatalf("%s: LoadFromEnv() error = %v, want a refusal that names the reserve", name, err)
}
}
}
@@ -0,0 +1,188 @@
-- +goose Up
-- A notification names the record it is about (its subject), so the sending
-- worker can re-check the rights the notice depends on before it calls the
-- transport. The subject is fixed when the request is stored and is copied to
-- the delivery, where the content trigger keeps it unchanged. The three
-- columns are set together. Only the kind invitation exists so far. A
-- notification without a subject stays valid: the sending worker cancels it
-- with source_closed, because it has no right to check.
--
-- Everything here is additive: existing rows keep NULL subjects.
ALTER TABLE mail_requests
ADD COLUMN subject_kind text,
ADD COLUMN subject_id uuid,
ADD COLUMN subject_organization_id uuid,
ADD CONSTRAINT mail_requests_subject_complete CHECK (
(subject_kind IS NULL) = (subject_id IS NULL)
AND (subject_kind IS NULL) = (subject_organization_id IS NULL)
AND (subject_kind IS NULL OR subject_kind IN ('invitation'))
);
COMMENT ON COLUMN mail_requests.subject_kind IS
'The kind of record the notification is about, NULL when it names none; the sending worker checks the rights of that kind.';
COMMENT ON COLUMN mail_requests.subject_id IS
'The record the notification is about, for example the invitation; an opaque ID, never an address or a contact.';
COMMENT ON COLUMN mail_requests.subject_organization_id IS
'The organization the subject record belongs to, for example the organization that sent the invitation.';
ALTER TABLE deliveries
ADD COLUMN subject_kind text,
ADD COLUMN subject_id uuid,
ADD COLUMN subject_organization_id uuid,
ADD CONSTRAINT deliveries_subject_complete CHECK (
(subject_kind IS NULL) = (subject_id IS NULL)
AND (subject_kind IS NULL) = (subject_organization_id IS NULL)
AND (subject_kind IS NULL OR subject_kind IN ('invitation'))
AND (subject_kind IS NULL OR kind = 'notification')
);
COMMENT ON COLUMN deliveries.subject_kind IS
'The kind of record a notification is about; set only for a notification, NULL when it names none. The product sending worker re-checks its rights before the send.';
COMMENT ON COLUMN deliveries.subject_id IS
'The record a notification is about; an opaque ID, never an address or a contact.';
COMMENT ON COLUMN deliveries.subject_organization_id IS
'The organization the subject record belongs to.';
-- The subject is part of what the delivery sends and is fixed, like the
-- recipient and the content. This is the function of migration 00012 with the
-- three subject columns added to the unchanged tuple.
-- +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,
NEW.subject_kind, NEW.subject_id, NEW.subject_organization_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,
OLD.subject_kind, OLD.subject_id, OLD.subject_organization_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
-- Subjects name records whose rights a later version checks; dropping them
-- would send notices that were not checked. Refuse while any row names one.
-- +goose StatementBegin
DO $$
BEGIN
IF EXISTS (SELECT 1 FROM deliveries WHERE subject_kind IS NOT NULL)
OR EXISTS (SELECT 1 FROM mail_requests WHERE subject_kind IS NOT NULL) THEN
RAISE EXCEPTION USING
ERRCODE = 'feature_not_supported',
MESSAGE = 'notification subjects are stored; cancel or export the notifications that name one before this rollback';
END IF;
END;
$$;
-- +goose StatementEnd
-- The function of migration 00012 without the subject columns.
-- +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
ALTER TABLE deliveries DROP CONSTRAINT deliveries_subject_complete;
ALTER TABLE deliveries
DROP COLUMN subject_organization_id,
DROP COLUMN subject_id,
DROP COLUMN subject_kind;
ALTER TABLE mail_requests DROP CONSTRAINT mail_requests_subject_complete;
ALTER TABLE mail_requests
DROP COLUMN subject_organization_id,
DROP COLUMN subject_id,
DROP COLUMN subject_kind;
@@ -0,0 +1,111 @@
-- +goose Up
-- Product notifications get their own sending worker. It claims them through
-- deliveries_product_due_idx, re-checks the rights of their subject before
-- the transport is called, and cancels a notice whose basis no longer holds
-- with one of the reasons below. A cancelled notification loses its bodies,
-- as a token mail does, so a withdrawn notice keeps no text in the table.
-- The service worker and deliveries_due_idx do not change.
ALTER TABLE deliveries DROP CONSTRAINT deliveries_cancel_reason_matches_status;
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',
'rights_revoked',
'recipient_ineligible',
'source_closed'
)
)
);
-- A redacted mail has no bodies. A token mail may be redacted once it is
-- terminal; a notification once it is cancelled.
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')
)
OR (kind = 'notification' AND status = 'cancelled')
)
)
);
-- Serves the claim of due product notifications. The predicate names the
-- kind literal the product claim repeats, so an idle poll of either worker
-- reads only its own index and never the other lane's backlog.
CREATE INDEX deliveries_product_due_idx
ON deliveries (next_attempt_at, id)
WHERE
status IN ('pending', 'waiting_quota', 'unknown')
AND next_attempt_at IS NOT NULL
AND kind = 'notification';
-- +goose Down
DROP INDEX deliveries_product_due_idx;
-- Rows that name the reasons of this version, or redacted notifications,
-- cannot satisfy the checks of the earlier schema. Refuse before changing
-- them, so the rollback never rewrites a cancellation.
-- +goose StatementBegin
DO $$
BEGIN
IF EXISTS (
SELECT 1 FROM deliveries
WHERE cancel_reason IN ('rights_revoked', 'recipient_ineligible', 'source_closed')
OR (kind = 'notification' AND body_redacted_at IS NOT NULL)
) THEN
RAISE EXCEPTION USING
ERRCODE = 'feature_not_supported',
MESSAGE = 'notifications cancelled by a rights check are stored; export or resend them before this rollback';
END IF;
END;
$$;
-- +goose StatementEnd
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')
)
);
ALTER TABLE deliveries DROP CONSTRAINT deliveries_cancel_reason_matches_status;
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'
)
)
);
+129 -10
View File
@@ -24,6 +24,9 @@ INSERT INTO deliveries (
last_attempt_at,
provider_message_id,
email_token_id,
subject_kind,
subject_id,
subject_organization_id,
version,
created_at,
updated_at
@@ -47,6 +50,9 @@ INSERT INTO deliveries (
sqlc.narg(last_attempt_at),
sqlc.narg(provider_message_id),
sqlc.narg(email_token_id),
sqlc.narg(subject_kind),
sqlc.narg(subject_id),
sqlc.narg(subject_organization_id),
sqlc.arg(version),
sqlc.arg(created_at),
sqlc.arg(updated_at)
@@ -82,7 +88,10 @@ SELECT
claimed_until,
first_send_started_at,
failure_count,
body_redacted_at
body_redacted_at,
subject_kind,
subject_id,
subject_organization_id
FROM deliveries
WHERE id = sqlc.arg(id);
@@ -209,21 +218,21 @@ SET
text_body = CASE
WHEN
sqlc.arg(status)::text = 'cancelled'
AND deliveries.kind IN ('verification', 'password_reset')
AND deliveries.kind IN ('verification', 'password_reset', 'notification')
THEN ''
ELSE deliveries.text_body
END,
html_body = CASE
WHEN
sqlc.arg(status)::text = 'cancelled'
AND deliveries.kind IN ('verification', 'password_reset')
AND deliveries.kind IN ('verification', 'password_reset', 'notification')
THEN ''
ELSE deliveries.html_body
END,
body_redacted_at = CASE
WHEN
sqlc.arg(status)::text = 'cancelled'
AND deliveries.kind IN ('verification', 'password_reset')
AND deliveries.kind IN ('verification', 'password_reset', 'notification')
THEN sqlc.arg(updated_at)
ELSE deliveries.body_redacted_at
END,
@@ -338,6 +347,107 @@ RETURNING
claimed.version,
claimed.created_at,
claimed.updated_at,
claimed.subject_kind,
claimed.subject_id,
claimed.subject_organization_id,
candidate.previous_claimed_until,
candidate.since_first_send_seconds,
candidate.manual_retry_pending,
candidate.manual_retry_cycle_started,
candidate.send_start_unsettled,
candidate.has_uncertain_attempt;
-- Claims the most overdue product notification, under the same rules as
-- ClaimDueDelivery: a lease in the database clock, the configured provider
-- account or a rebind of a delivery before its first attempt, and no live
-- lease. It reads deliveries_product_due_idx, whose predicate repeats the
-- literal kind below, so the backlog of service mail never enters the scan.
-- A notification is claimed here whatever its subject; the sending worker
-- checks the subject's rights after the claim and cancels a notice whose
-- basis no longer holds.
-- name: ClaimDueProductDelivery :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,
(due.manual_retry_authorized_at IS NOT NULL AND due.manual_retry_started_at IS NULL)
AS manual_retry_pending,
(due.manual_retry_started_at IS NOT NULL)::boolean AS manual_retry_cycle_started,
(
due.send_started_attempt_count IS NOT NULL
AND due.send_started_attempt_count = due.attempt_count
)::boolean AS send_start_unsettled,
EXISTS (
SELECT 1
FROM delivery_attempts AS prior_attempt
WHERE prior_attempt.delivery_id = due.id
AND prior_attempt.outcome = 'unknown'
)::boolean AS has_uncertain_attempt
FROM deliveries AS due
WHERE
due.kind = 'notification'
AND due.status IN ('pending', 'waiting_quota', 'unknown')
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,
claimed.subject_kind,
claimed.subject_id,
claimed.subject_organization_id,
candidate.previous_claimed_until,
candidate.since_first_send_seconds,
candidate.manual_retry_pending,
@@ -492,14 +602,14 @@ SET
claim_owner = NULL,
claimed_until = NULL,
text_body = CASE
WHEN deliveries.kind IN ('verification', 'password_reset') THEN '' ELSE deliveries.text_body
WHEN deliveries.kind IN ('verification', 'password_reset', 'notification') THEN '' ELSE deliveries.text_body
END,
html_body = CASE
WHEN deliveries.kind IN ('verification', 'password_reset') THEN '' ELSE deliveries.html_body
WHEN deliveries.kind IN ('verification', 'password_reset', 'notification') THEN '' ELSE deliveries.html_body
END,
body_redacted_at = CASE
WHEN
deliveries.kind IN ('verification', 'password_reset')
deliveries.kind IN ('verification', 'password_reset', 'notification')
THEN greatest(deliveries.updated_at, sqlc.arg(now)::timestamptz)
ELSE deliveries.body_redacted_at
END,
@@ -552,7 +662,7 @@ SET
WHEN
sqlc.arg(count_failure)::boolean
AND deliveries.failure_count + 1 >= sqlc.arg(max_failures)::integer
AND deliveries.kind IN ('verification', 'password_reset')
AND deliveries.kind IN ('verification', 'password_reset', 'notification')
THEN ''
ELSE deliveries.text_body
END,
@@ -560,7 +670,7 @@ SET
WHEN
sqlc.arg(count_failure)::boolean
AND deliveries.failure_count + 1 >= sqlc.arg(max_failures)::integer
AND deliveries.kind IN ('verification', 'password_reset')
AND deliveries.kind IN ('verification', 'password_reset', 'notification')
THEN ''
ELSE deliveries.html_body
END,
@@ -568,7 +678,7 @@ SET
WHEN
sqlc.arg(count_failure)::boolean
AND deliveries.failure_count + 1 >= sqlc.arg(max_failures)::integer
AND deliveries.kind IN ('verification', 'password_reset')
AND deliveries.kind IN ('verification', 'password_reset', 'notification')
THEN greatest(deliveries.updated_at, sqlc.arg(now)::timestamptz)
ELSE deliveries.body_redacted_at
END,
@@ -692,6 +802,9 @@ INSERT INTO mail_requests (
subject,
body,
link_path,
subject_kind,
subject_id,
subject_organization_id,
created_at
) VALUES (
sqlc.arg(id),
@@ -700,6 +813,9 @@ INSERT INTO mail_requests (
sqlc.arg(subject),
sqlc.arg(body),
sqlc.arg(link_path),
sqlc.narg(subject_kind),
sqlc.narg(subject_id),
sqlc.narg(subject_organization_id),
sqlc.arg(created_at)
);
@@ -716,6 +832,9 @@ SELECT
subject,
body,
link_path,
subject_kind,
subject_id,
subject_organization_id,
created_at
FROM mail_requests
WHERE id = sqlc.arg(id)
@@ -0,0 +1,37 @@
-- Reads the standing of an invitation notice in one statement, for the rights
-- check before the send. The recipient is matched by ID; the invitation must
-- be addressed to that recipient and belong to the organization of the
-- subject, otherwise it is not found. It reads no address and no contact:
-- the recipient address is returned only as its comparison key. The hiding
-- is the candidate's own current state. The publication is read through the
-- effective view, so a publication whose C2 consent was revoked does not count
-- as current. A missing account or invitation gives false flags and NULL
-- columns.
-- name: GetInvitationNoticeStanding :one
SELECT
(recipient.id IS NOT NULL)::boolean AS recipient_found,
coalesce(recipient.email_verified_at IS NOT NULL, false)::boolean AS recipient_email_verified,
coalesce(recipient.email_normalized, '')::text AS recipient_email_key,
(invitation.id IS NOT NULL)::boolean AS invitation_found,
invitation.organization_id AS invitation_organization_id,
coalesce(invitation.state, '')::text AS invitation_state,
invitation.response_deadline_at AS invitation_response_deadline_at,
EXISTS (
SELECT 1
FROM candidate_hidden_organizations AS hidden
WHERE
hidden.user_id = sqlc.arg(recipient_user_id)
AND hidden.organization_id = sqlc.arg(organization_id)
)::boolean AS organization_hidden,
EXISTS (
SELECT 1
FROM candidate_effective_publications AS publication
WHERE publication.user_id = sqlc.arg(recipient_user_id)
)::boolean AS publication_published
FROM (SELECT sqlc.arg(recipient_user_id)::uuid AS user_id) AS target
LEFT JOIN users AS recipient
ON recipient.id = target.user_id
LEFT JOIN invitations AS invitation
ON invitation.id = sqlc.arg(invitation_id)
AND invitation.candidate_id = target.user_id
AND invitation.organization_id = sqlc.arg(organization_id);
@@ -541,6 +541,10 @@ func TestInvitationExpiryMigrationBackfillsDeadlineJobsAndGuardsExpiries(t *test
}
// A rollback keeps the expiry, which the previous schema cannot represent.
// Migrations 44 and 45 sit above this one; they hold no rows that the
// expiry depends on, so they are rolled back first and the rollback of 43
// is the one that must be refused.
rollBackAboveVersion(ctx, t, migrator, invitationExpiryMigrationVersion)
if _, err := migrator.DownOne(ctx); err == nil {
t.Fatal("rollback with an expired invitation succeeded, want it refused")
}
+137 -3
View File
@@ -30,6 +30,7 @@ import (
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/consent"
"lincodex/backend/internal/usecase/notification"
"lincodex/backend/internal/usecase/notification/mailtemplate"
"lincodex/backend/internal/worker/mailsender"
@@ -321,6 +322,85 @@ func TestServiceMailSending(t *testing.T) {
harness.assertLogsHoldNoSecrets(t, user.Email.Address(), raw.Reveal(), "verify-email")
})
t.Run("a password reset email for an account without C2 is accepted by the local Resend fixture", func(t *testing.T) {
reset(t)
calls := len(fixture.Requests())
user := harness.createUser(ctx, t, true)
raw, token, deliveryID := harness.enqueuePasswordReset(ctx, t, user, mailSenderTokenLifetime)
assertRowCount(ctx, t, pool, pgx.Identifier{"consent_records"}, 0)
stored := harness.delivery(ctx, t, deliveryID)
if stored.Status() != domain.DeliveryStatusPending || stored.Kind() != domain.MailKindPasswordReset || stored.EmailTokenID() != token.ID {
t.Fatalf("enqueued delivery is %s of kind %s bound to %v", stored.Status(), stored.Kind(), stored.EmailTokenID())
}
sender := harness.newSender(t, harness.transactor, 100, 3000)
result := harness.pass(ctx, t, sender)
if result.Outcome != inbound.MailPassAccepted || result.DeliveryID != deliveryID {
t.Fatalf("pass = %+v, want accepted for the enqueued delivery", result)
}
requests := fixture.Requests()[calls:]
if len(requests) != 1 {
t.Fatalf("the fixture received %d calls, want 1", len(requests))
}
request := requests[0]
link := harness.publicURL + "/reset-password#token=" + raw.Reveal()
switch {
case len(request.To) != 1 || request.To[0] != user.Email.Address():
t.Fatal("the message was not addressed to the account")
case !strings.Contains(request.Text, link) || !strings.Contains(request.HTML, link):
t.Fatal("the message does not carry the reset link with its token in the fragment")
case strings.Contains(request.Text, "?token=") || strings.Contains(request.HTML, "?token="):
t.Fatal("the token travels in a query")
}
accepted := harness.delivery(ctx, t, deliveryID)
if accepted.Status() != domain.DeliveryStatusAccepted || accepted.AttemptCount() != 1 {
t.Fatalf("delivery is %s after %d attempts, want accepted after one attempt", accepted.Status(), accepted.AttemptCount())
}
harness.assertLogsHoldNoSecrets(t, user.Email.Address(), raw.Reveal(), "reset-password")
})
t.Run("a verification mail goes out after the account's C2 was granted and revoked before the worker runs", func(t *testing.T) {
reset(t)
calls := len(fixture.Requests())
user := harness.createUser(ctx, t, false)
_, _, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime)
// C2 is granted and revoked while the mail waits. The publication
// history must not hold the mail back: only the account and the token
// decide, as ServiceMailState reads nothing else.
c2Text, err := postgresadapter.NewConsentStore(pool).ConsentTexts().Current(ctx, domain.ConsentPurposePublication, harness.clock.Now())
if err != nil {
t.Fatalf("read the current C2 text: %v", err)
}
consentService := consent.NewService(harness.transactor, harness.clock.Now)
granted, err := consentService.GrantInSettingsInNewTransaction(ctx, consent.SettingsGrantInput{
SubjectID: user.ID, Purpose: domain.ConsentPurposePublication, TextVersion: c2Text.Version(),
})
if err != nil || !granted.Created {
t.Fatalf("grant C2 = created %t, %v; want a new record", granted.Created, err)
}
revocation, err := consentService.RevokeInSettingsInNewTransaction(ctx, consent.SettingsRevocationInput{
SubjectID: user.ID, Purpose: domain.ConsentPurposePublication,
})
if err != nil || len(revocation.Records) != 1 {
t.Fatalf("revoke C2 = %d records, %v; want one revoked record", len(revocation.Records), err)
}
if _, revoked := revocation.Records[0].RevokedAt(); !revoked {
t.Fatal("the C2 record is not revoked")
}
sender := harness.newSender(t, harness.transactor, 100, 3000)
result := harness.pass(ctx, t, sender)
if result.Outcome != inbound.MailPassAccepted || result.DeliveryID != deliveryID {
t.Fatalf("pass = %+v, want the verification mail accepted after C2 was revoked", result)
}
requests := fixture.Requests()[calls:]
if len(requests) != 1 || len(requests[0].To) != 1 || requests[0].To[0] != user.Email.Address() {
t.Fatalf("the fixture received %d calls, want one to the account", len(requests))
}
})
t.Run("an accepted request with a lost response retries under the same key within 24 hours", func(t *testing.T) {
reset(t)
calls := len(fixture.Requests())
@@ -637,6 +717,39 @@ func TestServiceMailSending(t *testing.T) {
harness.assertQuotaUsage(ctx, t, 0)
})
t.Run("a verification mail revoked before its send is cancelled, keeps its account, and stays out of the logs", func(t *testing.T) {
reset(t)
calls := len(fixture.Requests())
user := harness.createUser(ctx, t, false)
raw, _, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime)
if invalidated, err := harness.identity.EmailTokens().InvalidateActive(ctx, user.ID, domain.EmailTokenPurposeEmailVerification, harness.clock.Now()); err != nil || invalidated != 1 {
t.Fatalf("InvalidateActive() = %d, %v; want 1", invalidated, err)
}
sender := harness.newSender(t, harness.transactor, 100, 3000)
if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassCancelled || result.CancelReason != domain.DeliveryCancelTokenRevoked {
t.Fatalf("pass = %+v, want cancelled with reason %s", result, domain.DeliveryCancelTokenRevoked)
}
if again := harness.pass(ctx, t, sender); again.Outcome != inbound.MailPassIdle {
t.Fatalf("pass after the cancellation = %+v, want idle", again)
}
if got := len(fixture.Requests()[calls:]); got != 0 {
t.Fatalf("the provider received %d calls, want none for a revoked mail", got)
}
cancelled := harness.delivery(ctx, t, deliveryID)
switch {
case cancelled.Status() != domain.DeliveryStatusCancelled || cancelled.CancelReason() != domain.DeliveryCancelTokenRevoked:
t.Fatalf("delivery is %s (%s), want cancelled by a revoked token", cancelled.Status(), cancelled.CancelReason())
case cancelled.ProviderAccount() != harness.account || cancelled.AttemptCount() != 0 || cancelled.ProviderMessageID() != "":
t.Fatal("the cancellation changed the transport account or recorded an attempt")
case !cancelled.Content().Redacted() || cancelled.Content().Text() != "":
t.Fatal("the body of the cancelled mail is still stored")
}
// The address, the token, the link, and the account ID never reach the logs.
harness.assertLogsHoldNoSecrets(t, user.Email.Address(), raw.Reveal(), user.ID.String(), "verify-email")
})
t.Run("a delivery that cannot be restored is cancelled and does not block the queue", func(t *testing.T) {
reset(t)
calls := len(fixture.Requests())
@@ -1695,13 +1808,34 @@ func (harness *senderHarness) createUser(ctx context.Context, t *testing.T, veri
// enqueueVerification issues a token and stores its mail in one transaction,
// as the registration flow will.
func (harness *senderHarness) enqueueVerification(ctx context.Context, t *testing.T, user domain.User, lifetime time.Duration) (domain.SecretToken, domain.EmailToken, uuid.UUID) {
t.Helper()
return harness.enqueueToken(ctx, t, user, domain.EmailTokenPurposeEmailVerification, lifetime, harness.mailer.EnqueueVerification)
}
// enqueuePasswordReset issues a password reset token and stores its mail in
// one transaction, as the reset flow will.
func (harness *senderHarness) enqueuePasswordReset(ctx context.Context, t *testing.T, user domain.User, lifetime time.Duration) (domain.SecretToken, domain.EmailToken, uuid.UUID) {
t.Helper()
return harness.enqueueToken(ctx, t, user, domain.EmailTokenPurposePasswordReset, lifetime, harness.mailer.EnqueuePasswordReset)
}
// enqueueToken issues a token of purpose and stores the mail that enqueue
// builds for it, in the same transaction as the token.
func (harness *senderHarness) enqueueToken(
ctx context.Context,
t *testing.T,
user domain.User,
purpose domain.EmailTokenPurpose,
lifetime time.Duration,
enqueue func(context.Context, outbound.UnitOfWork, notification.TokenMailRequest) (uuid.UUID, error),
) (domain.SecretToken, domain.EmailToken, uuid.UUID) {
t.Helper()
raw, err := domain.NewSecretToken()
if err != nil {
t.Fatalf("NewSecretToken() error = %v", err)
}
token, err := domain.NewEmailToken(domain.NewEmailTokenInput{
UserID: user.ID, Purpose: domain.EmailTokenPurposeEmailVerification, TokenHash: raw.Hash(),
UserID: user.ID, Purpose: purpose, TokenHash: raw.Hash(),
RegistrationVersion: user.RegistrationVersion, IssuedAt: harness.clock.Now(), Lifetime: lifetime,
})
if err != nil {
@@ -1712,13 +1846,13 @@ func (harness *senderHarness) enqueueVerification(ctx context.Context, t *testin
if err := unit.EmailTokens().Insert(ctx, token); err != nil {
return err
}
deliveryID, err = harness.mailer.EnqueueVerification(ctx, unit, notification.TokenMailRequest{
deliveryID, err = enqueue(ctx, unit, notification.TokenMailRequest{
Recipient: user.Email, Token: token, RawToken: raw, Lifetime: domain.Hours(lifetime / time.Hour),
})
return err
})
if err != nil {
t.Fatalf("enqueue the verification mail: %v", err)
t.Fatalf("enqueue the %s mail: %v", purpose, err)
}
return raw, token, deliveryID
}
@@ -0,0 +1,108 @@
//go:build integration
package integration_test
import (
"context"
"crypto/sha256"
"strings"
"testing"
"time"
"github.com/google/uuid"
)
// notificationSubjectMigrationVersion adds the subject columns of notifications;
// productNoticeMigrationVersion adds the rights reasons, the body clearing of a
// cancelled notice, and the product due index on top of it.
const (
notificationSubjectMigrationVersion = 44
productNoticeMigrationVersion = 45
)
// TestNotificationSubjectMigrations checks the constraints that the rights
// checks rely on, and that the rollback of the two migrations refuses while
// rows name a subject or carry a rights cancellation, and runs once they are gone.
func TestNotificationSubjectMigrations(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, 9, 12, 0, 0, 0, time.UTC)
userID, deliveryID, invitationID, organizationID := uuid.New(), uuid.New(), uuid.New(), uuid.New()
exec := func(statement string, args ...any) error {
t.Helper()
_, err := pool.Exec(ctx, statement, args...)
return err
}
if err := exec(`INSERT INTO users (id, email, email_normalized, password_hash, scenario, onboarding_step, email_verified_at,
registration_version, last_registered_at, version, created_at, updated_at)
VALUES ($1, 'notice@example.com', 'notice@example.com', $2, 'candidate', 'candidate_consents', $3, 1, $3, 1, $3, $3)`,
userID, identityTestPasswordHash, now); err != nil {
t.Fatalf("insert the account: %v", err)
}
// A cancelled notice that names its invitation and has no bodies is what
// the sending worker stores after a rights check.
if err := 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, cancel_reason, body_redacted_at, subject_kind, subject_id, subject_organization_id)
VALUES ($1, $2, 'notice@example.com', 'notification', 'notification.v1', 's', '', '', $3, 'resend', 'main',
'delivery/notice', 'cancelled', 0, NULL, 2, $4, $4, 'rights_revoked', $4, 'invitation', $5, $6)`,
deliveryID, userID, make([]byte, sha256.Size), now, invitationID, organizationID); err != nil {
t.Fatalf("store a cancelled notice with its subject: %v", err)
}
// A subject belongs to a notification only, and the three subject columns
// are set together.
if err := 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, subject_kind, subject_id, subject_organization_id)
VALUES ($1, $2, 'notice@example.com', 'verification', 'verification.v1', 's', 't', '', $3, 'resend', 'main',
'delivery/subject-verification', 'pending', 0, $4, 1, $4, $4, 'invitation', $5, $6)`,
uuid.New(), userID, make([]byte, sha256.Size), now, invitationID, organizationID); err == nil || !strings.Contains(err.Error(), "deliveries_subject_complete") {
t.Fatalf("a subject on a verification mail: error = %v, want deliveries_subject_complete", err)
}
// Bodies are cleared only for a cancelled notice or a terminal token mail.
if err := 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, body_redacted_at)
VALUES ($1, $2, 'notice@example.com', 'notification', 'notification.v1', 's', '', '', $3, 'resend', 'main',
'delivery/cleared-pending', 'pending', 0, $4, 1, $4, $4, $4)`,
uuid.New(), userID, make([]byte, sha256.Size), now); err == nil || !strings.Contains(err.Error(), "deliveries_body_present") {
t.Fatalf("a pending notice without bodies: error = %v, want deliveries_body_present", err)
}
// The subject is fixed with the delivery, like its content.
// The trigger reports its refusal by message, not by constraint name.
if err := exec(`UPDATE deliveries SET subject_id = gen_random_uuid() WHERE id = $1`, deliveryID); err == nil ||
!strings.Contains(err.Error(), "content and recipient are immutable") {
t.Fatalf("changing the subject: error = %v, want the content refusal", err)
}
// The rollback refuses while the schema holds rights cancellations.
if _, err := migrator.DownOne(ctx); err == nil || !strings.Contains(err.Error(), "rights check") {
t.Fatalf("DownOne() with a rights cancellation stored: error = %v, want the refusal that names the rights check", err)
}
// Once the account is gone, its notices go with it, and the rollback runs.
if err := exec(`DELETE FROM users WHERE id = $1`, userID); err != nil {
t.Fatalf("delete the account: %v", err)
}
for _, version := range []int64{productNoticeMigrationVersion, notificationSubjectMigrationVersion} {
result, err := migrator.DownOne(ctx)
if err != nil {
t.Fatalf("DownOne() to below %d error = %v", version, err)
}
if result.Version != version {
t.Fatalf("DownOne() rolled back %d, want %d", result.Version, version)
}
}
if _, err := migrator.Up(ctx); err != nil {
t.Fatalf("Up() after the rollback error = %v", err)
}
}
@@ -0,0 +1,625 @@
//go:build integration
package integration_test
import (
"context"
"errors"
"fmt"
"log/slog"
"strings"
"sync"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool"
"lincodex/backend/internal/adapter/secondary/mail/resend"
"lincodex/backend/internal/adapter/secondary/mail/resend/resendfixture"
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/candidateview"
"lincodex/backend/internal/usecase/companyquota"
"lincodex/backend/internal/usecase/consent"
identityusecase "lincodex/backend/internal/usecase/identity"
invitationusecase "lincodex/backend/internal/usecase/invitation"
"lincodex/backend/internal/usecase/notification"
"lincodex/backend/internal/usecase/notification/mailtemplate"
"lincodex/backend/internal/usecase/policy"
)
const (
productNoticeTimeout = 5 * time.Minute
// productNoticeOrganization names the sending organization. The notice
// must never carry it, so the tests look for it in the mail and the logs.
productNoticeOrganization = "Notice company"
// productNoticeBody is the start of the neutral body of an invitation
// notice; the full text stays in the mail templates.
productNoticeBody = "Работодатель отправил вам приглашение"
// productNoticeConcurrentWorkers drain one queue at once, each with its
// own sender, as separate processes do.
productNoticeConcurrentWorkers = 4
productNoticeQueued = 6
// productNoticeBacklog is the number of due rows that the other lane holds
// while the product claim is explained.
productNoticeBacklog = 5000
)
// productNoticeFixture drives the invitation send with the real notifier, the
// consumer that stores its notice, and the notification sender, against one
// isolated database and the local Resend fixture.
type productNoticeFixture struct {
ctx context.Context
pool *pgxpool.Pool
transactor *postgresadapter.Transactor
identity identityFixture
organizations organizationFixture
clock *testClock
key domain.CandidateViewPseudonymKey
handles map[string]uuid.UUID
organization domain.Organization
owner domain.User
service *invitationusecase.Service
renderer *mailtemplate.Renderer
account domain.MailProviderAccount
mail *resendfixture.Server
transport outbound.MailSender
logs *syncBuffer
// harness reads the deliveries and runs the service sender, which the
// notice tests share.
harness *senderHarness
publicURL string
}
func newProductNoticeFixture(ctx context.Context, t *testing.T, env *testEnvironment) *productNoticeFixture {
t.Helper()
databaseURL := env.createIsolatedDatabase(ctx, t)
applyMigrations(ctx, t, databaseURL)
pool := newPoolFor(ctx, t, databaseURL)
if _, err := policy.NewPublisher(postgresadapter.NewPolicyStore(pool).Policies(), time.Now).EnsureDemoProductPolicy(ctx); err != nil {
t.Fatalf("EnsureDemoProductPolicy() error = %v", err)
}
clock := &testClock{now: time.Now().UTC().Truncate(time.Microsecond).Add(time.Second)}
transactor := postgresadapter.NewTransactor(pool)
identities := identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: clock.Now()}
organizations := organizationFixture{ctx: ctx, pool: pool, identity: identities, transactor: transactor, now: clock.Now()}
owner := organizations.employer(t, "notice-owner@example.test")
confirmEmail(ctx, t, pool, owner, clock.Now().Add(-time.Minute))
organization := organizations.create(t, owner, organizations.completeProfile(t, productNoticeOrganization), clock.Now())
keyring, err := identityusecase.NewKeyring([]byte(env.Config.IdentityKeySecret))
if err != nil {
t.Fatalf("NewKeyring() error = %v", err)
}
key, err := keyring.CandidateViewPseudonymKey()
if err != nil {
t.Fatalf("CandidateViewPseudonymKey() error = %v", err)
}
renderer, err := mailtemplate.NewRenderer(env.Config.AppPublicURL)
if err != nil {
t.Fatalf("NewRenderer() error = %v", err)
}
account, err := domain.NewMailProviderAccount("resend", mailSenderAccount)
if err != nil {
t.Fatalf("NewMailProviderAccount() error = %v", err)
}
mail := resendfixture.New()
t.Cleanup(mail.Close)
mail.SetClock(clock.Now)
transport, err := resend.NewLoopbackSender(resendfixture.APIKey, mailSenderFrom, 10*time.Second, mail.URL(), clock.Now)
if err != nil {
t.Fatalf("NewLoopbackSender() error = %v", err)
}
notifier, err := notification.NewInvitationNotifier(notification.NewMailRequester(notification.NewTemplateRenderer(renderer), clock.Now))
if err != nil {
t.Fatalf("NewInvitationNotifier() error = %v", err)
}
logs := &syncBuffer{}
fixture := &productNoticeFixture{
ctx: ctx, pool: pool, transactor: transactor, identity: identities, organizations: organizations, clock: clock,
key: key, handles: map[string]uuid.UUID{}, organization: organization, owner: owner, renderer: renderer,
account: account, mail: mail, transport: transport, logs: logs, publicURL: env.Config.AppPublicURL,
}
quota := companyquota.NewService(clock.Now)
fixture.service, err = invitationusecase.NewService(invitationusecase.Dependencies{
Transactor: transactor, Keyring: keyring, PseudonymKey: key,
Candidates: func(_ context.Context, _ outbound.UnitOfWork, _, organizationID uuid.UUID, handle string) (uuid.UUID, error) {
candidateID, ok := fixture.handles[handle]
if !ok || organizationID != organization.ID() {
return uuid.Nil, candidateview.ErrCandidateCardNotFound
}
return candidateID, nil
},
Quota: func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, invitationID uuid.UUID) (outbound.CompanyQuotaDecision, error) {
return quota.ReserveInvitation(ctx, unit, organization, invitationID)
},
Notifier: notifier, Consents: consent.NewService(transactor, clock.Now), Clock: clock.Now,
})
if err != nil {
t.Fatalf("invitation.NewService() error = %v", err)
}
// The organization is E1, so one owner may send more than the E0 quota
// allows; the rights under test do not depend on the quota.
if _, err := pool.Exec(ctx, `
UPDATE organizations
SET verification_level = 'e1', verification_basis = 'corporate_domain', verification_changed_at = $2
WHERE id = $1`, organization.ID(), clock.Now()); err != nil {
t.Fatalf("raise the organization to E1: %v", err)
}
fixture.harness = &senderHarness{
pool: pool,
transactor: transactor,
identity: postgresadapter.NewIdentityStore(pool),
deliveries: postgresadapter.NewDeliveryStore(pool).Deliveries(),
mailer: notification.NewServiceMailer(notification.NewTemplateRenderer(renderer), account, clock.Now),
fixture: mail,
transport: transport,
account: account,
clock: clock,
logs: logs,
publicURL: env.Config.AppPublicURL,
}
return fixture
}
// candidate makes a verified candidate with a current publication (C2) and
// the card handle of the organization, so that the send accepts it.
func (fixture *productNoticeFixture) candidate(t *testing.T, email string) domain.User {
t.Helper()
user := fixture.identity.createUser(t, email, domain.ScenarioCandidate, fixture.clock.Now().Add(-time.Hour))
confirmEmail(fixture.ctx, t, fixture.pool, user, fixture.clock.Now().Add(-time.Minute))
handle, err := fixture.key.ForOrganization(fixture.organization.ID(), user.ID)
if err != nil {
t.Fatalf("ForOrganization() error = %v", err)
}
fixture.handles[handle] = user.ID
fixture.publish(t, user.ID)
return user
}
// publish stores a C2 grant and a published card that names it, the state an
// invitation is sent under.
func (fixture *productNoticeFixture) publish(t *testing.T, userID uuid.UUID) {
t.Helper()
ledger := postgresadapter.NewConsentStore(fixture.pool)
text, err := ledger.ConsentTexts().Get(fixture.ctx, domain.ConsentPurposePublication, privacyC2Version)
if err != nil {
t.Fatalf("ConsentTexts().Get(c2) error = %v", err)
}
grant, err := domain.NewConsentGrant(domain.ConsentGrantInput{
SubjectID: userID, Purpose: domain.ConsentPurposePublication, TextVersion: text.Version(), TextHash: text.Hash(),
Source: domain.ConsentSourceConsentSettings, GrantedAt: fixture.clock.Now().Add(-time.Hour),
})
if err != nil {
t.Fatalf("NewConsentGrant() error = %v", err)
}
record, created, err := ledger.ConsentLedger().Grant(fixture.ctx, grant)
if err != nil || !created {
t.Fatalf("Grant(c2) = %t, %v; want a new record", created, err)
}
request, err := domain.NewPublicationRequest(domain.PublicationPublished, []domain.CardField{domain.CardFieldStack, domain.CardFieldCategories})
if err != nil {
t.Fatalf("NewPublicationRequest() error = %v", err)
}
empty, err := domain.NewPublication(userID)
if err != nil {
t.Fatalf("NewPublication() error = %v", err)
}
change, err := empty.Apply(request, 0, record.ID(), fixture.clock.Now())
if err != nil || !change.Changed {
t.Fatalf("Apply(publish) = %+v, %v; want a change", change, err)
}
if _, err := sqlc.New(fixture.pool).InsertCandidatePublication(fixture.ctx, sqlc.InsertCandidatePublicationParams{
UserID: uuidParam(userID), State: string(change.Publication.StoredState()), Fields: change.Publication.StoredFields(),
ConsentRecordID: uuidParam(record.ID()), PublishedAt: timeParam(change.Publication.PublishedAt()),
ClosedAt: pgtype.Timestamptz{}, At: timeParam(fixture.clock.Now()),
}); err != nil {
t.Fatalf("InsertCandidatePublication() error = %v", err)
}
}
func (fixture *productNoticeFixture) handleOf(t *testing.T, candidateID uuid.UUID) string {
t.Helper()
handle, err := fixture.key.ForOrganization(fixture.organization.ID(), candidateID)
if err != nil {
t.Fatalf("ForOrganization() error = %v", err)
}
return handle
}
// invite drafts an invitation for the candidate and sends it. The send records
// the notice request in the same transaction, as it does in production.
func (fixture *productNoticeFixture) invite(t *testing.T, candidateID uuid.UUID) domain.OrganizationInvitationView {
t.Helper()
key := "create-" + uuid.NewString()
draft, err := fixture.service.Create(fixture.ctx, invitationusecase.CreateCommand{
ActorID: fixture.owner.ID, OrganizationID: fixture.organization.ID(), IdempotencyKey: key,
CanonicalBody: []byte(fmt.Sprintf(`{"key":%q}`, key)), CandidateHandle: fixture.handleOf(t, candidateID),
Terms: invitationStorageTerms(),
})
if err != nil {
t.Fatalf("Create() error = %v", err)
}
sent, err := fixture.service.Send(fixture.ctx, invitationusecase.SendCommand{
ActorID: fixture.owner.ID, OrganizationID: fixture.organization.ID(), InvitationID: draft.ID,
IdempotencyKey: "send-" + uuid.NewString(), ExpectedVersion: draft.Version,
})
if err != nil {
t.Fatalf("Send() error = %v", err)
}
return sent
}
// deliverNotice runs the delivery consumer on the notice request that the send
// recorded, as the event consumer does, and returns the delivery ID.
func (fixture *productNoticeFixture) deliverNotice(t *testing.T, candidateID uuid.UUID) uuid.UUID {
t.Helper()
var event outbound.ConsumedEvent
var payload string
if err := fixture.pool.QueryRow(fixture.ctx, `
SELECT event_id, event_type, schema_version, aggregate_type, aggregate_id, aggregate_version, payload::text, occurred_at
FROM outbox_events
WHERE event_type = 'notification.mail_requested'
AND aggregate_id IN (SELECT id FROM mail_requests WHERE recipient_user_id = $1)`, candidateID).
Scan(&event.EventID, &event.EventType, &event.SchemaVersion, &event.AggregateType, &event.AggregateID,
&event.AggregateVersion, &payload, &event.OccurredAt); err != nil {
t.Fatalf("read the notice request: %v", err)
}
event.Payload = []byte(payload)
event.OccurredAt = event.OccurredAt.UTC().Truncate(time.Microsecond)
handler := notification.NewDeliveryHandler(notification.NewTemplateRenderer(fixture.renderer), fixture.account, fixture.clock.Now, slog.New(slog.DiscardHandler))
if err := fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
return handler.Handle(ctx, unit, event)
}); err != nil {
t.Fatalf("DeliveryHandler.Handle() error = %v", err)
}
var deliveryID uuid.UUID
if err := fixture.pool.QueryRow(fixture.ctx,
`SELECT id FROM deliveries WHERE recipient_user_id = $1 AND kind = 'notification'`, candidateID).Scan(&deliveryID); err != nil {
t.Fatalf("read the notice delivery: %v", err)
}
return deliveryID
}
// sender builds the notification lane with the reserve of its quota gate. The
// lane shares the transport, account, and timing of the service lane.
func (fixture *productNoticeFixture) sender(t *testing.T, daily, monthly, reserveDaily, reserveMonthly int64) *notification.DeliverySender {
t.Helper()
limits, err := domain.NewMailQuotaLimits(daily, monthly)
if err != nil {
t.Fatalf("NewMailQuotaLimits() error = %v", err)
}
logger := slog.New(slog.NewJSONHandler(fixture.logs, nil))
gate, err := notification.NewQuotaGate(fixture.account, limits, resend.IdempotencyWindow, fixture.clock.Now, logger).WithReserve(reserveDaily, reserveMonthly)
if err != nil {
t.Fatalf("WithReserve() error = %v", err)
}
sender, err := notification.NewNotificationSender(fixture.transactor, fixture.transport, gate, notification.DeliverySenderSettings{
Account: fixture.account,
Lease: mailSenderLease,
StoreTimeout: 30 * time.Second,
SettleBudget: mailSenderSettleBudget,
ShutdownSettleBudget: time.Second,
MaxFailures: 3,
Retry: notification.RetryPolicy{Initial: time.Minute, Max: 30 * time.Minute},
}, fixture.clock.Now, logger, []notification.SubjectRights{notification.NewInvitationNoticeRights()})
if err != nil {
t.Fatalf("NewNotificationSender() error = %v", err)
}
return sender
}
// deliveryRow reads the stored status, cancel reason, and bodies of a delivery,
// without decoding it, so a test sees what is in the table.
func (fixture *productNoticeFixture) deliveryRow(t *testing.T, id uuid.UUID) (status, reason, text, html string, redacted bool) {
t.Helper()
var cancelReason *string
var redactedAt *time.Time
if err := fixture.pool.QueryRow(fixture.ctx, `
SELECT status, cancel_reason, text_body, html_body, body_redacted_at FROM deliveries WHERE id = $1`, id).
Scan(&status, &cancelReason, &text, &html, &redactedAt); err != nil {
t.Fatalf("read delivery %s: %v", id, err)
}
if cancelReason != nil {
reason = *cancelReason
}
return status, reason, text, html, redactedAt != nil
}
// requestsFor returns the provider requests addressed to the address.
func (fixture *productNoticeFixture) requestsFor(address string) []resendfixture.Request {
var matching []resendfixture.Request
for _, request := range fixture.mail.Requests() {
for _, to := range request.To {
if to == address {
matching = append(matching, request)
break
}
}
}
return matching
}
func TestProductNoticeIsSentOnceByItsOwnWorker(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), productNoticeTimeout)
defer cancel()
fixture := newProductNoticeFixture(ctx, t, env)
candidate := fixture.candidate(t, "notice-sent@example.test")
fixture.invite(t, candidate.ID)
deliveryID := fixture.deliverNotice(t, candidate.ID)
calls := len(fixture.mail.Requests())
serviceSender := fixture.harness.newSender(t, fixture.transactor, 100, 3000)
if result := fixture.harness.pass(ctx, t, serviceSender); result.Outcome != inbound.MailPassIdle || len(fixture.mail.Requests()) != calls {
t.Fatalf("service pass = %+v with %d provider calls; want idle and none: the service worker takes only service mail", result, len(fixture.mail.Requests())-calls)
}
if got := fixture.harness.delivery(ctx, t, deliveryID); got.Kind() != domain.MailKindNotification || got.Status() != domain.DeliveryStatusPending || got.Subject().Kind() != domain.MailSubjectInvitation {
t.Fatalf("stored notice = %s %s with subject %v; want a pending notification that names its invitation", got.Kind(), got.Status(), got.Subject())
}
productSender := fixture.sender(t, 100, 3000, 0, 0)
if result := fixture.harness.pass(ctx, t, productSender); result.Outcome != inbound.MailPassAccepted {
t.Fatalf("product pass = %+v, want accepted", result)
}
sent := fixture.requestsFor(candidate.Email.Address())
if len(sent) != 1 {
t.Fatalf("provider requests to the candidate = %d, want exactly one", len(sent))
}
if !strings.Contains(sent[0].Text, productNoticeBody) || strings.Contains(sent[0].Text, productNoticeOrganization) ||
strings.Contains(sent[0].Text, candidate.ID.String()) || !strings.Contains(sent[0].Text, "/candidate/invitations") {
t.Fatalf("notice body = %q; want the neutral text with the inbox link and no organization or identifier", sent[0].Text)
}
if got := fixture.harness.delivery(ctx, t, deliveryID); got.Status() != domain.DeliveryStatusAccepted || got.AttemptCount() != 1 {
t.Fatalf("delivery is %s after %d attempts, want accepted after one", got.Status(), got.AttemptCount())
}
if result := fixture.harness.pass(ctx, t, productSender); result.Outcome != inbound.MailPassIdle || len(fixture.mail.Requests()) != calls+1 {
t.Fatalf("pass after the send = %+v; want idle with no second request", result)
}
fixture.harness.assertLogsHoldNoSecrets(t, candidate.Email.Address(), candidate.ID.String(), fixture.handleOf(t, candidate.ID))
}
func TestProductNoticeRightsAreCheckedBeforeEverySend(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), productNoticeTimeout)
defer cancel()
fixture := newProductNoticeFixture(ctx, t, env)
productSender := fixture.sender(t, 100, 3000, 0, 0)
t.Run("a candidate who hides the organization after the send gets no mail and the body is cleared", func(t *testing.T) {
candidate := fixture.candidate(t, "notice-hidden@example.test")
fixture.invite(t, candidate.ID)
deliveryID := fixture.deliverNotice(t, candidate.ID)
fixture.hide(t, candidate.ID)
calls := len(fixture.mail.Requests())
if result := fixture.harness.pass(ctx, t, productSender); result.Outcome != inbound.MailPassCancelled || result.CancelReason != domain.DeliveryCancelRightsRevoked {
t.Fatalf("pass = %+v, want cancelled as rights_revoked", result)
}
if len(fixture.mail.Requests()) != calls {
t.Fatal("the transport was called for a notice whose organization is hidden")
}
status, reason, text, html, redacted := fixture.deliveryRow(t, deliveryID)
if status != "cancelled" || reason != "rights_revoked" || text != "" || html != "" || !redacted {
t.Fatalf("stored notice is %s (%s) with bodies %q/%q redacted %v; want cancelled as rights_revoked with no body", status, reason, text, html, redacted)
}
if result := fixture.harness.pass(ctx, t, productSender); result.Outcome != inbound.MailPassIdle {
t.Fatalf("pass after the cancellation = %+v, want idle", result)
}
fixture.harness.assertLogsHoldNoSecrets(t, candidate.Email.Address(), candidate.ID.String(), fixture.handleOf(t, candidate.ID))
})
t.Run("an address that is no longer verified gets no mail and is cancelled as recipient_ineligible", func(t *testing.T) {
candidate := fixture.candidate(t, "notice-unverified@example.test")
fixture.invite(t, candidate.ID)
deliveryID := fixture.deliverNotice(t, candidate.ID)
if _, err := fixture.pool.Exec(ctx, `UPDATE users SET email_verified_at = NULL, version = version + 1 WHERE id = $1`, candidate.ID); err != nil {
t.Fatalf("unverify the address: %v", err)
}
calls := len(fixture.mail.Requests())
if result := fixture.harness.pass(ctx, t, productSender); result.Outcome != inbound.MailPassCancelled || result.CancelReason != domain.DeliveryCancelRecipientIneligible {
t.Fatalf("pass = %+v, want cancelled as recipient_ineligible", result)
}
if len(fixture.mail.Requests()) != calls {
t.Fatal("the transport was called for an unverified address")
}
if status, reason, _, _, _ := fixture.deliveryRow(t, deliveryID); status != "cancelled" || reason != "recipient_ineligible" {
t.Fatalf("stored notice is %s (%s), want cancelled as recipient_ineligible", status, reason)
}
})
t.Run("a notice that names no subject has no right to check and is cancelled as source_closed", func(t *testing.T) {
candidate := fixture.candidate(t, "notice-no-subject@example.test")
content, err := domain.NewMailContent(domain.MailKindNotification, "notification.v1", "Синтетическое уведомление", "PRIVATE-BODY notification\n", "")
if err != nil {
t.Fatalf("NewMailContent() error = %v", err)
}
delivery, err := domain.NewDelivery(domain.NewDeliveryInput{
ID: uuid.Must(uuid.NewV7()), RecipientUserID: candidate.ID, Recipient: candidate.Email,
Content: content, ProviderAccount: fixture.account, CreatedAt: fixture.clock.Now(),
})
if err != nil {
t.Fatalf("NewDelivery() error = %v", err)
}
if created, err := fixture.harness.deliveries.Create(ctx, delivery); err != nil || !created {
t.Fatalf("Create() = %t, %v; want the notice stored", created, err)
}
if result := fixture.harness.pass(ctx, t, productSender); result.Outcome != inbound.MailPassCancelled || result.CancelReason != domain.DeliveryCancelSourceClosed {
t.Fatalf("pass = %+v, want cancelled as source_closed", result)
}
if status, _, text, _, _ := fixture.deliveryRow(t, delivery.ID()); status != "cancelled" || text != "" {
t.Fatalf("stored notice is %s with text %q, want cancelled with no body", status, text)
}
})
// The clock moves past the response deadline, so this subtest comes last.
t.Run("an invitation that passed its response deadline gets no mail and is cancelled as rights_revoked", func(t *testing.T) {
candidate := fixture.candidate(t, "notice-expired@example.test")
fixture.invite(t, candidate.ID)
deliveryID := fixture.deliverNotice(t, candidate.ID)
fixture.clock.Advance(400 * 24 * time.Hour)
calls := len(fixture.mail.Requests())
if result := fixture.harness.pass(ctx, t, productSender); result.Outcome != inbound.MailPassCancelled || result.CancelReason != domain.DeliveryCancelRightsRevoked {
t.Fatalf("pass = %+v, want cancelled as rights_revoked", result)
}
if len(fixture.mail.Requests()) != calls {
t.Fatal("the transport was called for an expired invitation")
}
if status, reason, _, _, _ := fixture.deliveryRow(t, deliveryID); status != "cancelled" || reason != "rights_revoked" {
t.Fatalf("stored notice is %s (%s), want cancelled as rights_revoked", status, reason)
}
})
}
// hide records that the candidate hid the organization, as the privacy
// settings do.
func (fixture *productNoticeFixture) hide(t *testing.T, candidateID uuid.UUID) {
t.Helper()
if _, err := fixture.pool.Exec(fixture.ctx, `
INSERT INTO candidate_hidden_organizations (user_id, organization_id, hidden_at) VALUES ($1, $2, $3)`,
candidateID, fixture.organization.ID(), fixture.clock.Now()); err != nil {
t.Fatalf("hide the organization: %v", err)
}
}
func TestProductNoticeReserveLeavesServiceQuotaToServiceMail(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), productNoticeTimeout)
defer cancel()
fixture := newProductNoticeFixture(ctx, t, env)
// The day holds ten recipients. The notification lane keeps eight for other
// mail, so it admits two notices, and the service lane still has the full
// day.
productSender := fixture.sender(t, 10, 3000, 8, 0)
var waiting uuid.UUID
for index := range 3 {
candidate := fixture.candidate(t, fmt.Sprintf("notice-reserve-%d@example.test", index))
fixture.invite(t, candidate.ID)
id := fixture.deliverNotice(t, candidate.ID)
if index == 2 {
waiting = id
}
}
for range 2 {
if result := fixture.harness.pass(ctx, t, productSender); result.Outcome != inbound.MailPassAccepted {
t.Fatalf("notice pass = %+v, want accepted within the lane's share", result)
}
}
if result := fixture.harness.pass(ctx, t, productSender); result.Outcome != inbound.MailPassWaitingQuota {
t.Fatalf("third notice pass = %+v, want waiting_quota at the reserve", result)
}
midnight := domain.MailQuotaWindowsAt(fixture.clock.Now()).ResetAt(domain.MailQuotaPeriodDay)
if got := fixture.harness.delivery(ctx, t, waiting); got.Status() != domain.DeliveryStatusWaitingQuota || !got.NextAttemptAt().Equal(midnight) {
t.Fatalf("waiting notice is %s due %s, want waiting_quota until %s", got.Status(), got.NextAttemptAt(), midnight)
}
if result := fixture.harness.pass(ctx, t, productSender); result.Outcome != inbound.MailPassIdle {
t.Fatalf("notice pass while the reserve holds = %+v, want idle without a spin", result)
}
service := fixture.harness.createUser(ctx, t, false)
_, _, serviceID := fixture.harness.enqueueVerification(ctx, t, service, mailSenderTokenLifetime)
serviceSender := fixture.harness.newSender(t, fixture.transactor, 10, 3000)
if result := fixture.harness.pass(ctx, t, serviceSender); result.Outcome != inbound.MailPassAccepted {
t.Fatalf("service pass = %+v, want the verification mail accepted under the reserve", result)
}
if got := fixture.harness.delivery(ctx, t, serviceID); got.Status() != domain.DeliveryStatusAccepted {
t.Fatalf("service mail is %s, want accepted", got.Status())
}
fixture.harness.assertQuotaUsage(ctx, t, 3)
if got := len(fixture.mail.Requests()); got != 3 {
t.Fatalf("provider calls = %d, want two notices and the service mail", got)
}
}
func TestProductNoticeQueueIsDrainedOnceByConcurrentWorkers(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), productNoticeTimeout)
defer cancel()
fixture := newProductNoticeFixture(ctx, t, env)
ids := make([]uuid.UUID, 0, productNoticeQueued)
for index := range productNoticeQueued {
candidate := fixture.candidate(t, fmt.Sprintf("notice-queue-%d@example.test", index))
fixture.invite(t, candidate.ID)
ids = append(ids, fixture.deliverNotice(t, candidate.ID))
}
var group sync.WaitGroup
errs := make([]error, productNoticeConcurrentWorkers)
for worker := range productNoticeConcurrentWorkers {
sender := fixture.sender(t, 1000, 3000, 0, 0)
group.Go(func() {
for {
result, err := sender.ProcessNext(ctx, ctx)
if err != nil {
errs[worker] = err
return
}
if result.Outcome == inbound.MailPassIdle {
return
}
}
})
}
group.Wait()
if err := errors.Join(errs...); err != nil {
t.Fatalf("a worker failed: %v", err)
}
if got := len(fixture.mail.Requests()); got != productNoticeQueued {
t.Fatalf("provider calls = %d, want one per notice (%d)", got, productNoticeQueued)
}
for _, id := range ids {
if got := fixture.harness.delivery(ctx, t, id); got.Status() != domain.DeliveryStatusAccepted || got.AttemptCount() != 1 {
t.Fatalf("notice %s is %s after %d attempts, want accepted after one", id, got.Status(), got.AttemptCount())
}
}
}
func TestProductNoticeClaimReadsItsOwnDueIndex(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), productNoticeTimeout)
defer cancel()
fixture := newProductNoticeFixture(ctx, t, env)
// Service mail backlog: the product claim must not scan it.
if _, err := fixture.pool.Exec(ctx, `INSERT INTO deliveries (
id, recipient_user_id, recipient_email, kind, template_version, subject, text_body, html_body, content_sha256,
provider, provider_account, idempotency_key, status, attempt_count, next_attempt_at, version, created_at, updated_at
)
SELECT gen_random_uuid(), $1, 'backlog@example.com', 'verification', 'verification.v1', 's', 't', '', decode(repeat('00', 32), 'hex'),
'resend', $2, 'delivery/service-backlog-' || n, 'pending', 0, $3::timestamptz - interval '1 day', 1, $3, $3
FROM generate_series(1, $4::int) AS n`, fixture.identity.createUser(t, "backlog-owner@example.test", domain.ScenarioCandidate, fixture.clock.Now()).ID,
fixture.account.Account(), fixture.clock.Now(), productNoticeBacklog); err != nil {
t.Fatalf("insert the service backlog: %v", err)
}
if _, err := fixture.pool.Exec(ctx, "ANALYZE deliveries"); err != nil {
t.Fatalf("ANALYZE deliveries: %v", err)
}
rows, err := fixture.pool.Query(ctx, `EXPLAIN (COSTS OFF) SELECT due.id FROM deliveries AS due
WHERE due.kind = 'notification'
AND due.status IN ('pending', 'waiting_quota', 'unknown') AND due.next_attempt_at IS NOT NULL
AND due.next_attempt_at <= $1::timestamptz AND due.provider = 'resend' AND due.provider_account = $2
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`,
fixture.clock.Now(), fixture.account.Account())
if err != nil {
t.Fatalf("explain the product claim: %v", err)
}
defer rows.Close()
var plan strings.Builder
for rows.Next() {
var line string
if err := rows.Scan(&line); err != nil {
t.Fatalf("scan the plan: %v", err)
}
plan.WriteString(line + "\n")
}
if !strings.Contains(plan.String(), "deliveries_product_due_idx") || strings.Contains(plan.String(), "Seq Scan") {
t.Fatalf("the product claim does not use deliveries_product_due_idx over the service backlog:\n%s", plan.String())
}
}
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"slices"
"strings"
"time"
@@ -104,28 +105,31 @@ func (repository deliveryRepository) Create(ctx context.Context, delivery domain
content := delivery.Content()
hash := content.Hash()
inserted, err := repository.queries.InsertDelivery(ctx, sqlc.InsertDeliveryParams{
ID: pgUUID(delivery.ID()),
SourceEventID: pgOptionalUUID(delivery.SourceEventID()),
RecipientUserID: pgUUID(delivery.RecipientUserID()),
RecipientEmail: delivery.Recipient().Address(),
Kind: string(content.Kind()),
TemplateVersion: content.TemplateVersion(),
Subject: content.Subject(),
TextBody: content.Text(),
HtmlBody: content.HTML(),
ContentSha256: hash[:],
Provider: delivery.ProviderAccount().Provider(),
ProviderAccount: delivery.ProviderAccount().Account(),
IdempotencyKey: delivery.IdempotencyKey(),
Status: string(delivery.Status()),
AttemptCount: delivery.AttemptCount(),
NextAttemptAt: pgZeroableTime(delivery.NextAttemptAt()),
LastAttemptAt: pgZeroableTime(delivery.LastAttemptAt()),
ProviderMessageID: pgOptionalText(delivery.ProviderMessageID()),
EmailTokenID: pgOptionalUUID(delivery.EmailTokenID()),
Version: delivery.Version(),
CreatedAt: pgTime(delivery.CreatedAt()),
UpdatedAt: pgTime(delivery.UpdatedAt()),
ID: pgUUID(delivery.ID()),
SourceEventID: pgOptionalUUID(delivery.SourceEventID()),
RecipientUserID: pgUUID(delivery.RecipientUserID()),
RecipientEmail: delivery.Recipient().Address(),
Kind: string(content.Kind()),
TemplateVersion: content.TemplateVersion(),
Subject: content.Subject(),
TextBody: content.Text(),
HtmlBody: content.HTML(),
ContentSha256: hash[:],
Provider: delivery.ProviderAccount().Provider(),
ProviderAccount: delivery.ProviderAccount().Account(),
IdempotencyKey: delivery.IdempotencyKey(),
Status: string(delivery.Status()),
AttemptCount: delivery.AttemptCount(),
NextAttemptAt: pgZeroableTime(delivery.NextAttemptAt()),
LastAttemptAt: pgZeroableTime(delivery.LastAttemptAt()),
ProviderMessageID: pgOptionalText(delivery.ProviderMessageID()),
EmailTokenID: pgOptionalUUID(delivery.EmailTokenID()),
SubjectKind: pgOptionalText(string(delivery.Subject().Kind())),
SubjectID: pgOptionalUUID(delivery.Subject().ID()),
SubjectOrganizationID: pgOptionalUUID(delivery.Subject().OrganizationID()),
Version: delivery.Version(),
CreatedAt: pgTime(delivery.CreatedAt()),
UpdatedAt: pgTime(delivery.UpdatedAt()),
})
if err != nil {
return false, fmt.Errorf("deliveryRepository.Create - insert delivery: %w", mapDeliveryError(err))
@@ -142,34 +146,37 @@ func (repository deliveryRepository) Get(ctx context.Context, id uuid.UUID) (dom
return domain.Delivery{}, fmt.Errorf("deliveryRepository.Get - select delivery: %w", mapDeliveryError(err))
}
return 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,
Version: row.Version,
CreatedAt: row.CreatedAt,
UpdatedAt: row.UpdatedAt,
EmailTokenID: row.EmailTokenID,
CancelReason: row.CancelReason,
ClaimOwner: row.ClaimOwner,
ClaimedUntil: row.ClaimedUntil,
FirstSendStartedAt: row.FirstSendStartedAt,
FailureCount: row.FailureCount,
BodyRedactedAt: row.BodyRedactedAt,
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,
Version: row.Version,
CreatedAt: row.CreatedAt,
UpdatedAt: row.UpdatedAt,
EmailTokenID: row.EmailTokenID,
CancelReason: row.CancelReason,
ClaimOwner: row.ClaimOwner,
ClaimedUntil: row.ClaimedUntil,
FirstSendStartedAt: row.FirstSendStartedAt,
FailureCount: row.FailureCount,
BodyRedactedAt: row.BodyRedactedAt,
SubjectKind: row.SubjectKind,
SubjectID: row.SubjectID,
SubjectOrganizationID: row.SubjectOrganizationID,
})
}
@@ -406,6 +413,52 @@ func (repository deliveryRepository) updateState(ctx context.Context, location s
return nil
}
// claimKindsBelongToScope reports that every kind is one the lane's claim
// statement reads: the product statement has a literal notification predicate,
// so it must not be asked for service mail, and the reverse.
func claimKindsBelongToScope(scope outbound.ClaimScope, kinds []domain.MailKind) bool {
allowed := domain.ServiceMailKinds()
if scope == outbound.ClaimScopeNotification {
allowed = domain.ProductMailKinds()
}
for _, kind := range kinds {
if !slices.Contains(allowed, kind) {
return false
}
}
return true
}
// claimRow runs the claim statement of the claim's lane. The product statement
// returns the same columns in the same order, so its row converts to the row of
// the service statement; the conversion does not compile if the columns drift.
func (repository deliveryRepository) claimRow(ctx context.Context, claim outbound.DeliveryClaim, kinds []string) (sqlc.ClaimDueDeliveryRow, error) {
switch claim.Scope {
case outbound.ClaimScopeService:
return 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,
})
case outbound.ClaimScopeNotification:
product, err := repository.queries.ClaimDueProductDelivery(ctx, sqlc.ClaimDueProductDeliveryParams{
LeaseOwner: pgUUID(claim.Owner),
LeaseSeconds: claim.Lease.Seconds(),
Now: pgTime(claim.Now),
Provider: claim.Account.Provider(),
ProviderAccount: claim.Account.Account(),
RebindProvider: claim.RebindProvider,
})
return sqlc.ClaimDueDeliveryRow(product), err
default:
return sqlc.ClaimDueDeliveryRow{}, fmt.Errorf("deliveryRepository.claimRow - unknown claim scope %d: %w", claim.Scope, domain.ErrInvalidDelivery)
}
}
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 {
@@ -418,15 +471,10 @@ func (repository deliveryRepository) ClaimDue(ctx context.Context, claim outboun
}
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 !claimKindsBelongToScope(claim.Scope, claim.Kinds) {
return outbound.ClaimedDelivery{}, fmt.Errorf("%s - kinds do not belong to the claim scope: %w", location, domain.ErrInvalidDelivery)
}
row, err := repository.claimRow(ctx, claim, kinds)
if errors.Is(err, pgx.ErrNoRows) {
return outbound.ClaimedDelivery{}, outbound.ErrNoDeliveryDue
}
@@ -434,30 +482,33 @@ func (repository deliveryRepository) ClaimDue(ctx context.Context, claim outboun
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,
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,
SubjectKind: row.SubjectKind,
SubjectID: row.SubjectID,
SubjectOrganizationID: row.SubjectOrganizationID,
})
if err != nil {
unreadable := &outbound.UnreadableDeliveryError{DeliveryID: uuid.UUID(row.ID.Bytes), FailureCount: row.FailureCount, Err: err}
@@ -575,9 +626,12 @@ func deliveryFromRow(row sqlc.Delivery) (domain.Delivery, error) {
return domain.Delivery{}, fmt.Errorf("postgres.deliveryFromRow - decode kind: %w", err)
}
var content domain.MailContent
if row.BodyRedactedAt.Valid {
switch {
case row.BodyRedactedAt.Valid && kind == domain.MailKindNotification:
content, err = domain.RestoreRedactedNotificationContent(row.TemplateVersion, row.Subject, row.ContentSha256)
case row.BodyRedactedAt.Valid:
content, err = domain.RestoreRedactedMailContent(kind, row.TemplateVersion, row.Subject, row.ContentSha256)
} else {
default:
content, err = domain.RestoreMailContent(kind, row.TemplateVersion, row.Subject, row.TextBody, row.HtmlBody, row.ContentSha256)
}
if err != nil {
@@ -587,12 +641,17 @@ func deliveryFromRow(row sqlc.Delivery) (domain.Delivery, error) {
if err != nil {
return domain.Delivery{}, fmt.Errorf("postgres.deliveryFromRow - decode provider account: %w", err)
}
subject, err := domain.RestoreMailSubject(row.SubjectKind.String, optionalUUID(row.SubjectID), optionalUUID(row.SubjectOrganizationID))
if err != nil {
return domain.Delivery{}, fmt.Errorf("postgres.deliveryFromRow - decode subject: %w", err)
}
delivery, err := domain.RestoreDelivery(domain.DeliverySnapshot{
ID: uuid.UUID(row.ID.Bytes),
SourceEventID: optionalUUID(row.SourceEventID),
RecipientUserID: uuid.UUID(row.RecipientUserID.Bytes),
RecipientAddress: row.RecipientEmail,
Content: content,
Subject: subject,
ProviderAccount: providerAccount,
IdempotencyKey: row.IdempotencyKey,
Status: domain.DeliveryStatus(row.Status),
@@ -654,13 +713,16 @@ func (repository mailRequestRepository) Create(ctx context.Context, request doma
return fmt.Errorf("mailRequestRepository.Create - validate request: %w", err)
}
err := repository.queries.InsertMailRequest(ctx, sqlc.InsertMailRequestParams{
ID: pgUUID(request.ID),
RecipientUserID: pgUUID(request.RecipientUserID),
Kind: string(request.Kind),
Subject: request.Notification.Subject,
Body: request.Notification.Body,
LinkPath: request.Notification.LinkPath,
CreatedAt: pgTime(request.CreatedAt),
ID: pgUUID(request.ID),
RecipientUserID: pgUUID(request.RecipientUserID),
Kind: string(request.Kind),
Subject: request.Notification.Subject,
Body: request.Notification.Body,
LinkPath: request.Notification.LinkPath,
SubjectKind: pgOptionalText(string(request.Subject.Kind())),
SubjectID: pgOptionalUUID(request.Subject.ID()),
SubjectOrganizationID: pgOptionalUUID(request.Subject.OrganizationID()),
CreatedAt: pgTime(request.CreatedAt),
})
if err != nil {
return fmt.Errorf("mailRequestRepository.Create - insert mail request: %w", mapDeliveryError(err))
@@ -680,11 +742,16 @@ func (repository mailRequestRepository) Lock(ctx context.Context, id uuid.UUID)
if err != nil {
return domain.MailRequest{}, fmt.Errorf("mailRequestRepository.Lock - decode kind: %w", err)
}
subject, err := domain.RestoreMailSubject(row.SubjectKind.String, optionalUUID(row.SubjectID), optionalUUID(row.SubjectOrganizationID))
if err != nil {
return domain.MailRequest{}, fmt.Errorf("mailRequestRepository.Lock - decode subject: %w", err)
}
request, err := domain.NewMailRequest(domain.MailRequest{
ID: uuid.UUID(row.ID.Bytes),
RecipientUserID: uuid.UUID(row.RecipientUserID.Bytes),
Kind: kind,
Notification: domain.NotificationText{Subject: row.Subject, Body: row.Body, LinkPath: row.LinkPath},
Subject: subject,
CreatedAt: row.CreatedAt.Time,
})
if err != nil {
@@ -0,0 +1,49 @@
package postgres
import (
"context"
"fmt"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// NotificationRights is available only inside a transaction: the rights check
// reads the standing in the transaction that holds the delivery lock.
func (unit *UnitOfWork) NotificationRights() outbound.NotificationRightsReader {
return notificationRightsReader{queries: unit.queries}
}
type notificationRightsReader struct {
queries *sqlc.Queries
}
var _ outbound.NotificationRightsReader = notificationRightsReader{}
func (reader notificationRightsReader) InvitationNoticeStanding(
ctx context.Context,
recipientUserID, invitationID, organizationID uuid.UUID,
) (domain.InvitationNoticeStanding, error) {
row, err := reader.queries.GetInvitationNoticeStanding(ctx, sqlc.GetInvitationNoticeStandingParams{
RecipientUserID: pgUUID(recipientUserID),
InvitationID: pgUUID(invitationID),
OrganizationID: pgUUID(organizationID),
})
if err != nil {
return domain.InvitationNoticeStanding{}, fmt.Errorf("notificationRightsReader.InvitationNoticeStanding - read standing: %w", mapDeliveryError(err))
}
return domain.InvitationNoticeStanding{
RecipientFound: row.RecipientFound,
RecipientEmailVerified: row.RecipientEmailVerified,
RecipientEmailKey: row.RecipientEmailKey,
InvitationFound: row.InvitationFound,
InvitationOrganizationID: optionalUUID(row.InvitationOrganizationID),
InvitationState: domain.InvitationState(row.InvitationState),
ResponseDeadlineAt: zeroableTime(row.InvitationResponseDeadlineAt),
OrganizationHidden: row.OrganizationHidden,
PublicationPublished: row.PublicationPublished,
}, nil
}
@@ -162,14 +162,14 @@ SET
claim_owner = NULL,
claimed_until = NULL,
text_body = CASE
WHEN deliveries.kind IN ('verification', 'password_reset') THEN '' ELSE deliveries.text_body
WHEN deliveries.kind IN ('verification', 'password_reset', 'notification') THEN '' ELSE deliveries.text_body
END,
html_body = CASE
WHEN deliveries.kind IN ('verification', 'password_reset') THEN '' ELSE deliveries.html_body
WHEN deliveries.kind IN ('verification', 'password_reset', 'notification') THEN '' ELSE deliveries.html_body
END,
body_redacted_at = CASE
WHEN
deliveries.kind IN ('verification', 'password_reset')
deliveries.kind IN ('verification', 'password_reset', 'notification')
THEN greatest(deliveries.updated_at, $1::timestamptz)
ELSE deliveries.body_redacted_at
END,
@@ -279,6 +279,9 @@ RETURNING
claimed.version,
claimed.created_at,
claimed.updated_at,
claimed.subject_kind,
claimed.subject_id,
claimed.subject_organization_id,
candidate.previous_claimed_until,
candidate.since_first_send_seconds,
candidate.manual_retry_pending,
@@ -323,6 +326,9 @@ type ClaimDueDeliveryRow struct {
Version int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
SubjectKind pgtype.Text
SubjectID pgtype.UUID
SubjectOrganizationID pgtype.UUID
PreviousClaimedUntil pgtype.Timestamptz
SinceFirstSendSeconds float64
ManualRetryPending pgtype.Bool
@@ -392,6 +398,203 @@ func (q *Queries) ClaimDueDelivery(ctx context.Context, arg ClaimDueDeliveryPara
&i.Version,
&i.CreatedAt,
&i.UpdatedAt,
&i.SubjectKind,
&i.SubjectID,
&i.SubjectOrganizationID,
&i.PreviousClaimedUntil,
&i.SinceFirstSendSeconds,
&i.ManualRetryPending,
&i.ManualRetryCycleStarted,
&i.SendStartUnsettled,
&i.HasUncertainAttempt,
)
return i, err
}
const claimDueProductDelivery = `-- name: ClaimDueProductDelivery :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,
(due.manual_retry_authorized_at IS NOT NULL AND due.manual_retry_started_at IS NULL)
AS manual_retry_pending,
(due.manual_retry_started_at IS NOT NULL)::boolean AS manual_retry_cycle_started,
(
due.send_started_attempt_count IS NOT NULL
AND due.send_started_attempt_count = due.attempt_count
)::boolean AS send_start_unsettled,
EXISTS (
SELECT 1
FROM delivery_attempts AS prior_attempt
WHERE prior_attempt.delivery_id = due.id
AND prior_attempt.outcome = 'unknown'
)::boolean AS has_uncertain_attempt
FROM deliveries AS due
WHERE
due.kind = 'notification'
AND due.status IN ('pending', 'waiting_quota', 'unknown')
AND due.next_attempt_at IS NOT NULL
AND due.next_attempt_at <= $3::timestamptz
AND (
(
due.provider = $4
AND due.provider_account = $5
)
OR (
due.provider = $6::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,
claimed.subject_kind,
claimed.subject_id,
claimed.subject_organization_id,
candidate.previous_claimed_until,
candidate.since_first_send_seconds,
candidate.manual_retry_pending,
candidate.manual_retry_cycle_started,
candidate.send_start_unsettled,
candidate.has_uncertain_attempt
`
type ClaimDueProductDeliveryParams struct {
LeaseOwner pgtype.UUID
LeaseSeconds float64
Now pgtype.Timestamptz
Provider string
ProviderAccount string
RebindProvider string
}
type ClaimDueProductDeliveryRow 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
SubjectKind pgtype.Text
SubjectID pgtype.UUID
SubjectOrganizationID pgtype.UUID
PreviousClaimedUntil pgtype.Timestamptz
SinceFirstSendSeconds float64
ManualRetryPending pgtype.Bool
ManualRetryCycleStarted bool
SendStartUnsettled bool
HasUncertainAttempt bool
}
// Claims the most overdue product notification, under the same rules as
// ClaimDueDelivery: a lease in the database clock, the configured provider
// account or a rebind of a delivery before its first attempt, and no live
// lease. It reads deliveries_product_due_idx, whose predicate repeats the
// literal kind below, so the backlog of service mail never enters the scan.
// A notification is claimed here whatever its subject; the sending worker
// checks the subject's rights after the claim and cancels a notice whose
// basis no longer holds.
func (q *Queries) ClaimDueProductDelivery(ctx context.Context, arg ClaimDueProductDeliveryParams) (ClaimDueProductDeliveryRow, error) {
row := q.db.QueryRow(ctx, claimDueProductDelivery,
arg.LeaseOwner,
arg.LeaseSeconds,
arg.Now,
arg.Provider,
arg.ProviderAccount,
arg.RebindProvider,
)
var i ClaimDueProductDeliveryRow
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.SubjectKind,
&i.SubjectID,
&i.SubjectOrganizationID,
&i.PreviousClaimedUntil,
&i.SinceFirstSendSeconds,
&i.ManualRetryPending,
@@ -444,40 +647,46 @@ SELECT
claimed_until,
first_send_started_at,
failure_count,
body_redacted_at
body_redacted_at,
subject_kind,
subject_id,
subject_organization_id
FROM deliveries
WHERE id = $1
`
type GetDeliveryByIDRow struct {
ID pgtype.UUID
SourceEventID pgtype.UUID
RecipientUserID pgtype.UUID
RecipientEmail string
Kind string
TemplateVersion string
Subject string
TextBody string
HtmlBody string
ContentSha256 []byte
Provider string
ProviderAccount string
IdempotencyKey string
Status string
AttemptCount int32
NextAttemptAt pgtype.Timestamptz
LastAttemptAt pgtype.Timestamptz
ProviderMessageID pgtype.Text
Version int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
EmailTokenID pgtype.UUID
CancelReason pgtype.Text
ClaimOwner pgtype.UUID
ClaimedUntil pgtype.Timestamptz
FirstSendStartedAt pgtype.Timestamptz
FailureCount int32
BodyRedactedAt pgtype.Timestamptz
ID pgtype.UUID
SourceEventID pgtype.UUID
RecipientUserID pgtype.UUID
RecipientEmail string
Kind string
TemplateVersion string
Subject string
TextBody string
HtmlBody string
ContentSha256 []byte
Provider string
ProviderAccount string
IdempotencyKey string
Status string
AttemptCount int32
NextAttemptAt pgtype.Timestamptz
LastAttemptAt pgtype.Timestamptz
ProviderMessageID pgtype.Text
Version int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
EmailTokenID pgtype.UUID
CancelReason pgtype.Text
ClaimOwner pgtype.UUID
ClaimedUntil pgtype.Timestamptz
FirstSendStartedAt pgtype.Timestamptz
FailureCount int32
BodyRedactedAt pgtype.Timestamptz
SubjectKind pgtype.Text
SubjectID pgtype.UUID
SubjectOrganizationID pgtype.UUID
}
func (q *Queries) GetDeliveryByID(ctx context.Context, id pgtype.UUID) (GetDeliveryByIDRow, error) {
@@ -512,6 +721,9 @@ func (q *Queries) GetDeliveryByID(ctx context.Context, id pgtype.UUID) (GetDeliv
&i.FirstSendStartedAt,
&i.FailureCount,
&i.BodyRedactedAt,
&i.SubjectKind,
&i.SubjectID,
&i.SubjectOrganizationID,
)
return i, err
}
@@ -730,6 +942,9 @@ INSERT INTO deliveries (
last_attempt_at,
provider_message_id,
email_token_id,
subject_kind,
subject_id,
subject_organization_id,
version,
created_at,
updated_at
@@ -755,34 +970,40 @@ INSERT INTO deliveries (
$19,
$20,
$21,
$22
$22,
$23,
$24,
$25
)
ON CONFLICT (id) DO NOTHING
`
type InsertDeliveryParams struct {
ID pgtype.UUID
SourceEventID pgtype.UUID
RecipientUserID pgtype.UUID
RecipientEmail string
Kind string
TemplateVersion string
Subject string
TextBody string
HtmlBody string
ContentSha256 []byte
Provider string
ProviderAccount string
IdempotencyKey string
Status string
AttemptCount int32
NextAttemptAt pgtype.Timestamptz
LastAttemptAt pgtype.Timestamptz
ProviderMessageID pgtype.Text
EmailTokenID pgtype.UUID
Version int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
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
SubjectKind pgtype.Text
SubjectID pgtype.UUID
SubjectOrganizationID pgtype.UUID
Version int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
// Stores a new delivery. A delivery with the same ID already exists when the
@@ -811,6 +1032,9 @@ func (q *Queries) InsertDelivery(ctx context.Context, arg InsertDeliveryParams)
arg.LastAttemptAt,
arg.ProviderMessageID,
arg.EmailTokenID,
arg.SubjectKind,
arg.SubjectID,
arg.SubjectOrganizationID,
arg.Version,
arg.CreatedAt,
arg.UpdatedAt,
@@ -829,6 +1053,9 @@ INSERT INTO mail_requests (
subject,
body,
link_path,
subject_kind,
subject_id,
subject_organization_id,
created_at
) VALUES (
$1,
@@ -837,18 +1064,24 @@ INSERT INTO mail_requests (
$4,
$5,
$6,
$7
$7,
$8,
$9,
$10
)
`
type InsertMailRequestParams struct {
ID pgtype.UUID
RecipientUserID pgtype.UUID
Kind string
Subject string
Body string
LinkPath string
CreatedAt pgtype.Timestamptz
ID pgtype.UUID
RecipientUserID pgtype.UUID
Kind string
Subject string
Body string
LinkPath string
SubjectKind pgtype.Text
SubjectID pgtype.UUID
SubjectOrganizationID pgtype.UUID
CreatedAt pgtype.Timestamptz
}
func (q *Queries) InsertMailRequest(ctx context.Context, arg InsertMailRequestParams) error {
@@ -859,6 +1092,9 @@ func (q *Queries) InsertMailRequest(ctx context.Context, arg InsertMailRequestPa
arg.Subject,
arg.Body,
arg.LinkPath,
arg.SubjectKind,
arg.SubjectID,
arg.SubjectOrganizationID,
arg.CreatedAt,
)
return err
@@ -945,20 +1181,36 @@ SELECT
subject,
body,
link_path,
subject_kind,
subject_id,
subject_organization_id,
created_at
FROM mail_requests
WHERE id = $1
FOR UPDATE
`
type LockMailRequestRow struct {
ID pgtype.UUID
RecipientUserID pgtype.UUID
Kind string
Subject string
Body string
LinkPath string
SubjectKind pgtype.Text
SubjectID pgtype.UUID
SubjectOrganizationID pgtype.UUID
CreatedAt pgtype.Timestamptz
}
// Locks a request for the consumer transaction that turns it into a
// delivery. A concurrent consumer of the same request waits here and then
// finds the row deleted. The account cleanup and the cascade from users take
// the same row lock, so a request is never converted for an account whose
// deletion is in progress without one of the two transactions waiting.
func (q *Queries) LockMailRequest(ctx context.Context, id pgtype.UUID) (MailRequest, error) {
func (q *Queries) LockMailRequest(ctx context.Context, id pgtype.UUID) (LockMailRequestRow, error) {
row := q.db.QueryRow(ctx, lockMailRequest, id)
var i MailRequest
var i LockMailRequestRow
err := row.Scan(
&i.ID,
&i.RecipientUserID,
@@ -966,6 +1218,9 @@ func (q *Queries) LockMailRequest(ctx context.Context, id pgtype.UUID) (MailRequ
&i.Subject,
&i.Body,
&i.LinkPath,
&i.SubjectKind,
&i.SubjectID,
&i.SubjectOrganizationID,
&i.CreatedAt,
)
return i, err
@@ -1181,7 +1436,7 @@ SET
WHEN
$1::boolean
AND deliveries.failure_count + 1 >= $2::integer
AND deliveries.kind IN ('verification', 'password_reset')
AND deliveries.kind IN ('verification', 'password_reset', 'notification')
THEN ''
ELSE deliveries.text_body
END,
@@ -1189,7 +1444,7 @@ SET
WHEN
$1::boolean
AND deliveries.failure_count + 1 >= $2::integer
AND deliveries.kind IN ('verification', 'password_reset')
AND deliveries.kind IN ('verification', 'password_reset', 'notification')
THEN ''
ELSE deliveries.html_body
END,
@@ -1197,7 +1452,7 @@ SET
WHEN
$1::boolean
AND deliveries.failure_count + 1 >= $2::integer
AND deliveries.kind IN ('verification', 'password_reset')
AND deliveries.kind IN ('verification', 'password_reset', 'notification')
THEN greatest(deliveries.updated_at, $4::timestamptz)
ELSE deliveries.body_redacted_at
END,
@@ -1328,21 +1583,21 @@ SET
text_body = CASE
WHEN
$1::text = 'cancelled'
AND deliveries.kind IN ('verification', 'password_reset')
AND deliveries.kind IN ('verification', 'password_reset', 'notification')
THEN ''
ELSE deliveries.text_body
END,
html_body = CASE
WHEN
$1::text = 'cancelled'
AND deliveries.kind IN ('verification', 'password_reset')
AND deliveries.kind IN ('verification', 'password_reset', 'notification')
THEN ''
ELSE deliveries.html_body
END,
body_redacted_at = CASE
WHEN
$1::text = 'cancelled'
AND deliveries.kind IN ('verification', 'password_reset')
AND deliveries.kind IN ('verification', 'password_reset', 'notification')
THEN $7
ELSE deliveries.body_redacted_at
END,
@@ -532,6 +532,12 @@ type Delivery struct {
ManualRetryStartedAt pgtype.Timestamptz
// Attempt count when the latest provider call started. Equality with attempt_count means its result was not recorded; a greater attempt_count means a provider result was stored after that send-start.
SendStartedAttemptCount pgtype.Int4
// The kind of record a notification is about; set only for a notification, NULL when it names none. The product sending worker re-checks its rights before the send.
SubjectKind pgtype.Text
// The record a notification is about; an opaque ID, never an address or a contact.
SubjectID pgtype.UUID
// The organization the subject record belongs to.
SubjectOrganizationID pgtype.UUID
}
type DeliveryAttempt struct {
@@ -702,6 +708,12 @@ type MailRequest struct {
Body string
LinkPath string
CreatedAt pgtype.Timestamptz
// The kind of record the notification is about, NULL when it names none; the sending worker checks the rights of that kind.
SubjectKind pgtype.Text
// The record the notification is about, for example the invitation; an opaque ID, never an address or a contact.
SubjectID pgtype.UUID
// The organization the subject record belongs to, for example the organization that sent the invitation.
SubjectOrganizationID pgtype.UUID
}
type Membership struct {
@@ -0,0 +1,86 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: notification_rights.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const getInvitationNoticeStanding = `-- name: GetInvitationNoticeStanding :one
SELECT
(recipient.id IS NOT NULL)::boolean AS recipient_found,
coalesce(recipient.email_verified_at IS NOT NULL, false)::boolean AS recipient_email_verified,
coalesce(recipient.email_normalized, '')::text AS recipient_email_key,
(invitation.id IS NOT NULL)::boolean AS invitation_found,
invitation.organization_id AS invitation_organization_id,
coalesce(invitation.state, '')::text AS invitation_state,
invitation.response_deadline_at AS invitation_response_deadline_at,
EXISTS (
SELECT 1
FROM candidate_hidden_organizations AS hidden
WHERE
hidden.user_id = $1
AND hidden.organization_id = $2
)::boolean AS organization_hidden,
EXISTS (
SELECT 1
FROM candidate_effective_publications AS publication
WHERE publication.user_id = $1
)::boolean AS publication_published
FROM (SELECT $1::uuid AS user_id) AS target
LEFT JOIN users AS recipient
ON recipient.id = target.user_id
LEFT JOIN invitations AS invitation
ON invitation.id = $3
AND invitation.candidate_id = target.user_id
AND invitation.organization_id = $2
`
type GetInvitationNoticeStandingParams struct {
RecipientUserID pgtype.UUID
OrganizationID pgtype.UUID
InvitationID pgtype.UUID
}
type GetInvitationNoticeStandingRow struct {
RecipientFound bool
RecipientEmailVerified bool
RecipientEmailKey string
InvitationFound bool
InvitationOrganizationID pgtype.UUID
InvitationState string
InvitationResponseDeadlineAt pgtype.Timestamptz
OrganizationHidden bool
PublicationPublished bool
}
// Reads the standing of an invitation notice in one statement, for the rights
// check before the send. The recipient is matched by ID; the invitation must
// be addressed to that recipient and belong to the organization of the
// subject, otherwise it is not found. It reads no address and no contact:
// the recipient address is returned only as its comparison key. The hiding
// is the candidate's own current state. The publication is read through the
// effective view, so a publication whose C2 consent was revoked does not count
// as current. A missing account or invitation gives false flags and NULL
// columns.
func (q *Queries) GetInvitationNoticeStanding(ctx context.Context, arg GetInvitationNoticeStandingParams) (GetInvitationNoticeStandingRow, error) {
row := q.db.QueryRow(ctx, getInvitationNoticeStanding, arg.RecipientUserID, arg.OrganizationID, arg.InvitationID)
var i GetInvitationNoticeStandingRow
err := row.Scan(
&i.RecipientFound,
&i.RecipientEmailVerified,
&i.RecipientEmailKey,
&i.InvitationFound,
&i.InvitationOrganizationID,
&i.InvitationState,
&i.InvitationResponseDeadlineAt,
&i.OrganizationHidden,
&i.PublicationPublished,
)
return i, err
}
@@ -99,6 +99,15 @@ type Querier interface {
// now is the application clock. Unknown deliveries without a scheduled retry
// and quota waits with an unknown reset wait for an operator.
ClaimDueDelivery(ctx context.Context, arg ClaimDueDeliveryParams) (ClaimDueDeliveryRow, error)
// Claims the most overdue product notification, under the same rules as
// ClaimDueDelivery: a lease in the database clock, the configured provider
// account or a rebind of a delivery before its first attempt, and no live
// lease. It reads deliveries_product_due_idx, whose predicate repeats the
// literal kind below, so the backlog of service mail never enters the scan.
// A notification is claimed here whatever its subject; the sending worker
// checks the subject's rights after the claim and cancels a notice whose
// basis no longer holds.
ClaimDueProductDelivery(ctx context.Context, arg ClaimDueProductDeliveryParams) (ClaimDueProductDeliveryRow, 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
@@ -343,6 +352,16 @@ type Querier interface {
GetInvitationAcceptResult(ctx context.Context, scopeHash []byte) (GetInvitationAcceptResultRow, error)
GetInvitationCreationResult(ctx context.Context, scopeHash []byte) (string, error)
GetInvitationDeclineResult(ctx context.Context, scopeHash []byte) (GetInvitationDeclineResultRow, error)
// Reads the standing of an invitation notice in one statement, for the rights
// check before the send. The recipient is matched by ID; the invitation must
// be addressed to that recipient and belong to the organization of the
// subject, otherwise it is not found. It reads no address and no contact:
// the recipient address is returned only as its comparison key. The hiding
// is the candidate's own current state. The publication is read through the
// effective view, so a publication whose C2 consent was revoked does not count
// as current. A missing account or invitation gives false flags and NULL
// columns.
GetInvitationNoticeStanding(ctx context.Context, arg GetInvitationNoticeStandingParams) (GetInvitationNoticeStandingRow, error)
GetInvitationSendResult(ctx context.Context, scopeHash []byte) (GetInvitationSendResultRow, error)
// The caller holds the attempt row lock, so the last mark is stable.
GetLastAssessmentOriginMark(ctx context.Context, attemptID pgtype.UUID) (AssessmentAttemptOriginMark, error)
@@ -864,7 +883,7 @@ type Querier interface {
// finds the row deleted. The account cleanup and the cascade from users take
// the same row lock, so a request is never converted for an account whose
// deletion is in progress without one of the two transactions waiting.
LockMailRequest(ctx context.Context, id pgtype.UUID) (MailRequest, error)
LockMailRequest(ctx context.Context, id pgtype.UUID) (LockMailRequestRow, error)
// Locks the next relay batch. For each aggregate only its earliest unpublished
// event (lowest aggregate_version, then position) qualifies, so a relay never
// holds a later version while an earlier one is still pending, whether that
@@ -36,6 +36,10 @@ type mailMetrics struct {
// per process, not database-wide, so dashboards and alerts aggregate it
// with max across instances.
senderRunning client.Gauge
// notificationSenderRunning is 1 while this process's product notification
// loop runs. It is separate from senderRunning, so the service loop's alert
// keeps its meaning.
notificationSenderRunning client.Gauge
// senderCancelled counts deliveries that the sending worker ended without
// sending, by cancel reason, a closed set from the domain.
senderCancelled *client.CounterVec
@@ -100,6 +104,10 @@ func newMailMetrics() mailMetrics {
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.",
}),
notificationSenderRunning: client.NewGauge(client.GaugeOpts{
Name: "lincodex_notification_sender_running",
Help: "1 while the product notification 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.
@@ -132,7 +140,7 @@ 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, mail.identityRateLimited,
mail.senderRunning, mail.notificationSenderRunning, mail.senderCancelled, mail.identityRateLimited,
}
}
@@ -182,6 +190,16 @@ func (metrics *Metrics) SetMailSenderRunning(running bool) {
metrics.mail.senderRunning.Set(value)
}
// SetNotificationSenderRunning reports whether this process's product
// notification loop runs: 1 from its start until its stop, 0 otherwise.
func (metrics *Metrics) SetNotificationSenderRunning(running bool) {
value := 0.0
if running {
value = 1
}
metrics.mail.notificationSenderRunning.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() {
@@ -18,6 +18,19 @@ func TestMetricsHandlerExposesWhetherTheMailSenderRuns(t *testing.T) {
requireSeries(t, scrape(t, metrics), "lincodex_mail_sender_running 0")
}
func TestMetricsHandlerExposesWhetherTheNotificationSenderRuns(t *testing.T) {
metrics := New()
// The product loop has its own series, so the service loop's gauge keeps
// its meaning when only the product loop runs.
requireSeries(t, scrape(t, metrics), "lincodex_notification_sender_running 0")
metrics.SetNotificationSenderRunning(true)
requireSeries(t, scrape(t, metrics), "lincodex_notification_sender_running 1", "lincodex_mail_sender_running 0")
metrics.SetNotificationSenderRunning(false)
requireSeries(t, scrape(t, metrics), "lincodex_notification_sender_running 0")
}
func TestMetricsHandlerCountsCancelledMailByABoundedReason(t *testing.T) {
metrics := New()
// Every reason exists at zero before the first cancellation.
@@ -26,6 +39,9 @@ func TestMetricsHandlerCountsCancelledMailByABoundedReason(t *testing.T) {
`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`,
`lincodex_mail_sender_cancelled_total{reason="rights_revoked"} 0`,
`lincodex_mail_sender_cancelled_total{reason="recipient_ineligible"} 0`,
`lincodex_mail_sender_cancelled_total{reason="source_closed"} 0`,
)
metrics.ObserveMailCancelled("content_invalid")
metrics.ObserveMailCancelled("content_invalid")
+19 -10
View File
@@ -51,6 +51,10 @@ type Application struct {
// the servers run. It is nil with EMAIL_PROVIDER=disabled or when the
// database is not configured.
mailSending *mailsender.Worker
// notificationSending sends the stored product notifications while the
// servers run, after their rights checks. It is nil under the same
// conditions as mailSending.
notificationSending *notificationSendingWorker
// deliveryMetrics reads the delivery and quota gauges while the servers
// run. It is nil when the database is not configured.
deliveryMetrics *deliverymetrics.Sampler
@@ -66,19 +70,21 @@ func NewApplication(
consumers eventConsumers,
jobs *jobrunner.Worker,
mailSending *mailsender.Worker,
notificationSending *notificationSendingWorker,
deliveryMetrics *deliverymetrics.Sampler,
) *Application {
return &Application{
config: config,
apiHandler: apiHandler,
metrics: metrics,
logger: logger,
mailSender: mailSender,
relay: relay,
consumers: consumers,
jobs: jobs,
mailSending: mailSending,
deliveryMetrics: deliveryMetrics,
config: config,
apiHandler: apiHandler,
metrics: metrics,
logger: logger,
mailSender: mailSender,
relay: relay,
consumers: consumers,
jobs: jobs,
mailSending: mailSending,
notificationSending: notificationSending,
deliveryMetrics: deliveryMetrics,
}
}
@@ -224,6 +230,9 @@ func (application *Application) startWorkers(ctx context.Context) <-chan struct{
if application.mailSending != nil {
workers.Go(func() { application.mailSending.Run(ctx) })
}
if application.notificationSending != nil {
workers.Go(func() { application.notificationSending.Run(ctx) })
}
if application.deliveryMetrics != nil {
workers.Go(func() { application.deliveryMetrics.Run(ctx) })
}
+1 -1
View File
@@ -207,7 +207,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, nil)
}, http.NotFoundHandler(), metrics, logger, nil, nil, eventConsumers{consumer}, nil, 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, nil, sampler)
application := NewApplication(settings, http.NotFoundHandler(), metrics, logger, nil, nil, nil, nil, nil, nil, sampler)
ctx, cancel := context.WithCancel(t.Context())
finished := make(chan error, 1)
+1 -1
View File
@@ -93,7 +93,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, nil)
application := NewApplication(settings, http.NotFoundHandler(), metrics, logger, nil, nil, nil, worker, nil, nil, nil)
ctx, cancel := context.WithCancel(t.Context())
finished := make(chan error, 1)
+27 -15
View File
@@ -105,16 +105,7 @@ func newMailSenderWorker(
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},
},
deliverySenderSettings(settings, account),
time.Now,
workerLogger,
)
@@ -122,11 +113,7 @@ func newMailSenderWorker(
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,
})
worker, err := mailsender.New(sender, metrics, workerLogger, mailSenderLoopSettings())
if err != nil {
pool.Close()
return nil, nil, fmt.Errorf("bootstrap.newMailSenderWorker - create worker: %w", err)
@@ -136,6 +123,31 @@ func newMailSenderWorker(
return worker, pool.Close, nil
}
// deliverySenderSettings are the limits of a sending worker of any lane. The
// disabled transport is the only one whose unsent deliveries may be rebound to
// the configured account, so every lane rebinds from it.
func deliverySenderSettings(settings config.Config, account domain.MailProviderAccount) notification.DeliverySenderSettings {
return notification.DeliverySenderSettings{
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},
}
}
// mailSenderLoopSettings are the pacing limits of a sending loop of any lane.
func mailSenderLoopSettings() mailsender.Settings {
return mailsender.Settings{
PollInterval: mailSenderPollInterval,
Backoff: retry.Backoff{Initial: mailSenderBackoffInitial, Max: mailSenderBackoffMax},
ShutdownGrace: mailSenderShutdownGrace,
}
}
// 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.
@@ -93,7 +93,7 @@ func TestApplicationRunsAndStopsTheMailSenderWorker(t *testing.T) {
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)
application := NewApplication(settings, http.NotFoundHandler(), metrics, logger, nil, nil, nil, nil, worker, nil, nil)
ctx, cancel := context.WithCancel(t.Context())
finished := make(chan error, 1)
@@ -0,0 +1,107 @@
package bootstrap
import (
"context"
"fmt"
"log/slog"
"time"
"lincodex/backend/config"
"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"
)
// notificationSendingWorker is the sending loop of product notifications. Its
// own type keeps it apart from the service mail loop in the dependency graph.
type notificationSendingWorker struct {
*mailsender.Worker
}
var _ mailsender.Metrics = notificationSenderMetrics{}
// notificationSenderMetrics reports the product loop to the process metrics:
// its running state to its own gauge, and its cancellations to the counter the
// service loop also uses, by reason.
type notificationSenderMetrics struct {
metrics *prometheus.Metrics
}
func (metrics notificationSenderMetrics) SetMailSenderRunning(running bool) {
metrics.metrics.SetNotificationSenderRunning(running)
}
func (metrics notificationSenderMetrics) ObserveMailCancelled(reason string) {
metrics.metrics.ObserveMailCancelled(reason)
}
// newNotificationSenderWorker builds the sending loop of product notifications
// and the PostgreSQL pool it owns. It shares the transport, the provider
// account, and the timing of the service loop, but its quota gate keeps the
// service reserve free: a notification is admitted only while each window stays
// above EMAIL_SERVICE_RESERVE_DAILY and EMAIL_SERVICE_RESERVE_MONTHLY after it.
//
// Like the service loop, it returns no worker when EMAIL_PROVIDER=disabled or
// DATABASE_URL is unset, so a notification waits, pinned to the transport it
// was created under, until a transport runs. Nothing connects here.
func newNotificationSenderWorker(
ctx context.Context,
settings config.Config,
logger *slog.Logger,
metrics *prometheus.Metrics,
mailSender outbound.MailSender,
) (*notificationSendingWorker, func(), error) {
switch {
case settings.EmailProvider == config.EmailProviderDisabled:
logger.Info("notification sender worker is not started because EMAIL_PROVIDER is disabled; stored notifications wait")
return nil, func() {}, nil
case settings.DatabaseURL == "":
logger.Warn("notification 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.newNotificationSenderWorker - provider account: %w", err)
}
limits, err := domain.NewMailQuotaLimits(int64(settings.EmailQuotaDaily), int64(settings.EmailQuotaMonthly))
if err != nil {
return nil, nil, fmt.Errorf("bootstrap.newNotificationSenderWorker - quota limits: %w", err)
}
workerLogger := logger.With(slog.String("component", "notification_sender"))
gate, err := notification.NewQuotaGate(account, limits, mailIdempotencyWindow(settings), time.Now, workerLogger).
WithReserve(int64(settings.EmailServiceReserveDaily), int64(settings.EmailServiceReserveMonthly))
if err != nil {
return nil, nil, fmt.Errorf("bootstrap.newNotificationSenderWorker - service reserve: %w", err)
}
pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, mailSenderPoolMaxConns)
if err != nil {
return nil, nil, fmt.Errorf("bootstrap.newNotificationSenderWorker - create pool: %w", err)
}
sender, err := notification.NewNotificationSender(
postgres.NewTransactor(pool),
mailSender,
gate,
deliverySenderSettings(settings, account),
time.Now,
workerLogger,
// Every subject kind a notification may name needs its check here. A
// kind without one is refused by the sender, so it never goes out
// unchecked.
[]notification.SubjectRights{notification.NewInvitationNoticeRights()},
)
if err != nil {
pool.Close()
return nil, nil, fmt.Errorf("bootstrap.newNotificationSenderWorker - create sender: %w", err)
}
worker, err := mailsender.New(sender, notificationSenderMetrics{metrics: metrics}, workerLogger, mailSenderLoopSettings())
if err != nil {
pool.Close()
return nil, nil, fmt.Errorf("bootstrap.newNotificationSenderWorker - create worker: %w", err)
}
// The application stops the worker before this cleanup runs, so no send
// uses the pool while it closes.
return &notificationSendingWorker{Worker: worker}, pool.Close, nil
}
@@ -0,0 +1,93 @@
package bootstrap
import (
"context"
"log/slog"
"net/http"
"strings"
"testing"
"time"
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/mail/disabled"
"lincodex/backend/internal/adapter/secondary/prometheus"
)
func TestNewNotificationSenderWorkerSkipsWithoutWork(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 := newNotificationSenderWorker(t.Context(), test.settings, logger, metrics, disabled.NewSender())
if err != nil {
t.Fatalf("newNotificationSenderWorker() error = %v", err)
}
cleanup()
if worker != nil {
t.Fatal("newNotificationSenderWorker() built a worker without work to do")
}
if !strings.Contains(logs.String(), test.log) {
t.Fatalf("logs = %q, want %q", logs.String(), test.log)
}
// The product loop has its own gauge: without it the gauge reads 0,
// and the service loop's gauge is untouched.
body := scrape(metrics)
if !strings.Contains(body, "lincodex_notification_sender_running 0\n") {
t.Fatalf("metrics lack lincodex_notification_sender_running 0:\n%s", body)
}
})
}
}
func TestApplicationRunsAndStopsTheNotificationSenderWorker(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 := newNotificationSenderWorker(t.Context(), settings, logger, metrics, disabled.NewSender())
if err != nil {
t.Fatalf("newNotificationSenderWorker() error = %v", err)
}
defer cleanup()
if worker == nil {
t.Fatal("newNotificationSenderWorker() built no worker for an active transport")
}
application := NewApplication(settings, http.NotFoundHandler(), metrics, logger, nil, 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_notification_sender_running 1\n") {
if time.Now().After(deadline) {
t.Fatal("the product 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_notification_sender_running 0\n") {
t.Fatalf("the gauge did not return to 0 after the loop stopped:\n%s", body)
}
}
+1 -1
View File
@@ -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, nil)
}, http.NotFoundHandler(), metrics, logger, nil, relay, nil, nil, nil, nil, nil)
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
+1
View File
@@ -67,6 +67,7 @@ func initialize(
newEventConsumers,
newJobWorker,
newMailSenderWorker,
newNotificationSenderWorker,
newDeliveryMetrics,
NewApplication,
),
+30 -2
View File
@@ -381,7 +381,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
sampler, cleanup23, err := newDeliveryMetrics(ctx, config2, logger, metrics)
bootstrapNotificationSendingWorker, cleanup23, err := newNotificationSenderWorker(ctx, config2, logger, metrics, mailSender)
if err != nil {
cleanup22()
cleanup21()
@@ -407,8 +407,36 @@ 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, mailsenderWorker, sampler)
sampler, cleanup24, err := newDeliveryMetrics(ctx, config2, logger, metrics)
if err != nil {
cleanup23()
cleanup22()
cleanup21()
cleanup20()
cleanup19()
cleanup18()
cleanup17()
cleanup16()
cleanup15()
cleanup14()
cleanup13()
cleanup12()
cleanup11()
cleanup10()
cleanup9()
cleanup8()
cleanup7()
cleanup6()
cleanup5()
cleanup4()
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
application := NewApplication(config2, httpHandler, metrics, logger, mailSender, relay, bootstrapEventConsumers, worker, mailsenderWorker, bootstrapNotificationSendingWorker, sampler)
return application, func() {
cleanup24()
cleanup23()
cleanup22()
cleanup21()
+37 -6
View File
@@ -170,6 +170,19 @@ const (
// again and again for a reason of its own, so it stopped trying and left
// the row to an operator.
DeliveryCancelProcessingFailed DeliveryCancelReason = "processing_failed"
// DeliveryCancelRightsRevoked: a notification's basis no longer holds
// when it is about to be sent. The organization is hidden from the
// candidate, the candidate withdrew publication (C2), or the invitation
// was answered, expired, or passed its deadline (see
// Delivery.CheckInvitationNotice).
DeliveryCancelRightsRevoked DeliveryCancelReason = "rights_revoked"
// DeliveryCancelRecipientIneligible: the recipient account is gone or its
// address is not verified, so a notification may not go to it.
DeliveryCancelRecipientIneligible DeliveryCancelReason = "recipient_ineligible"
// DeliveryCancelSourceClosed: the record a notification is about does not
// exist, belongs to another organization, or the notification names no
// record at all, so there is no right to check.
DeliveryCancelSourceClosed DeliveryCancelReason = "source_closed"
)
// DeliveryCancelReasons lists every cancel reason, for metrics that expose
@@ -179,7 +192,8 @@ func DeliveryCancelReasons() []DeliveryCancelReason {
DeliveryCancelTokenMissing, DeliveryCancelTokenPurposeMismatch, DeliveryCancelTokenOwnerMismatch,
DeliveryCancelTokenConsumed, DeliveryCancelTokenRevoked, DeliveryCancelTokenExpired,
DeliveryCancelAccountNotCurrent, DeliveryCancelRecipientMismatch, DeliveryCancelContentInvalid,
DeliveryCancelProcessingFailed,
DeliveryCancelProcessingFailed, DeliveryCancelRightsRevoked, DeliveryCancelRecipientIneligible,
DeliveryCancelSourceClosed,
}
}
@@ -189,7 +203,8 @@ func ParseDeliveryCancelReason(value string) (DeliveryCancelReason, error) {
case DeliveryCancelTokenMissing, DeliveryCancelTokenPurposeMismatch, DeliveryCancelTokenOwnerMismatch,
DeliveryCancelTokenConsumed, DeliveryCancelTokenRevoked, DeliveryCancelTokenExpired,
DeliveryCancelAccountNotCurrent, DeliveryCancelRecipientMismatch, DeliveryCancelContentInvalid,
DeliveryCancelProcessingFailed:
DeliveryCancelProcessingFailed, DeliveryCancelRightsRevoked, DeliveryCancelRecipientIneligible,
DeliveryCancelSourceClosed:
return reason, nil
default:
return "", invalidDelivery("domain.ParseDeliveryCancelReason", "unknown cancel reason")
@@ -239,6 +254,7 @@ type Delivery struct {
recipientUserID uuid.UUID
recipient EmailAddress
content MailContent
subject MailSubject
providerAccount MailProviderAccount
idempotencyKey string
status DeliveryStatus
@@ -271,7 +287,11 @@ type NewDeliveryInput struct {
// the worker with the reason token_missing. It must be uuid.Nil for a
// notification.
EmailTokenID uuid.UUID
CreatedAt time.Time
// Subject names the record a notification is about; the sending worker
// checks its rights before the send. Only a notification may name one, and
// the zero value names none.
Subject MailSubject
CreatedAt time.Time
}
// NewDelivery validates input and returns a pending delivery that is due at
@@ -293,6 +313,8 @@ func NewDelivery(input NewDeliveryInput) (Delivery, error) {
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")
case !input.Subject.IsZero() && input.Content.Kind() != MailKindNotification:
return Delivery{}, invalidDelivery(location, "only a notification names a subject")
}
return Delivery{
id: input.ID,
@@ -300,6 +322,7 @@ func NewDelivery(input NewDeliveryInput) (Delivery, error) {
recipientUserID: input.RecipientUserID,
recipient: input.Recipient,
content: input.Content,
subject: input.Subject,
providerAccount: input.ProviderAccount,
emailTokenID: input.EmailTokenID,
idempotencyKey: deliveryIdempotencyKeyPrefix + input.ID.String(),
@@ -329,9 +352,11 @@ type DeliverySnapshot struct {
EmailTokenID uuid.UUID
// CancelReason is set exactly for a cancelled delivery.
CancelReason DeliveryCancelReason
Version int64
CreatedAt time.Time
UpdatedAt time.Time
// Subject is the zero value for a delivery without a subject.
Subject MailSubject
Version int64
CreatedAt time.Time
UpdatedAt time.Time
}
// RestoreDelivery rebuilds a stored delivery and checks the invariants that
@@ -362,6 +387,7 @@ func RestoreDelivery(snapshot DeliverySnapshot) (Delivery, error) {
recipientUserID: snapshot.RecipientUserID,
recipient: recipient,
content: snapshot.Content,
subject: snapshot.Subject,
providerAccount: snapshot.ProviderAccount,
idempotencyKey: snapshot.IdempotencyKey,
status: snapshot.Status,
@@ -408,6 +434,8 @@ func checkCancellationAndBinding(location string, snapshot DeliverySnapshot) err
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")
case !snapshot.Subject.IsZero() && snapshot.Content.Kind() != MailKindNotification:
return invalidDelivery(location, "only a notification names a subject")
}
if snapshot.CancelReason != "" {
if _, err := ParseDeliveryCancelReason(string(snapshot.CancelReason)); err != nil {
@@ -440,6 +468,9 @@ func (delivery Delivery) RecipientUserID() uuid.UUID { return delivery.recipient
// only to send the message; never log it.
func (delivery Delivery) Recipient() EmailAddress { return delivery.recipient }
// Subject is the record a notification is about; zero for other deliveries.
func (delivery Delivery) Subject() MailSubject { return delivery.subject }
func (delivery Delivery) Kind() MailKind { return delivery.content.Kind() }
func (delivery Delivery) Content() MailContent { return delivery.content }
@@ -0,0 +1,74 @@
package domain
import (
"time"
"github.com/google/uuid"
)
// InvitationNoticeStanding is what the rights check of an invitation notice
// reads about its recipient and its source at the time of the send. It holds
// no address and no contact: the recipient address enters only as the
// normalized key that the delivery is compared with.
type InvitationNoticeStanding struct {
RecipientFound bool
RecipientEmailVerified bool
// RecipientEmailKey is the normalized address of the account now.
RecipientEmailKey string
InvitationFound bool
InvitationOrganizationID uuid.UUID
InvitationState InvitationState
// ResponseDeadlineAt is zero when the invitation was never delivered.
ResponseDeadlineAt time.Time
// OrganizationHidden reports that the recipient hid the sending
// organization.
OrganizationHidden bool
// PublicationPublished reports that the recipient's publication (C2) is
// current, which is the state an invitation was sent under.
PublicationPublished bool
}
// CheckInvitationNotice decides whether the notice about an invitation may still
// be sent at the given time, and returns the cancel reason when it may not. An
// empty reason means that the notice is sendable. The checks run in this order
// and the first failure decides:
//
// 1. the delivery names an invitation subject;
// 2. the recipient account exists and its address is verified;
// 3. the address of the delivery is still the address of the account;
// 4. the invitation exists and belongs to the organization of the subject;
// 5. the invitation still awaits an answer (delivered or viewed) and its
// response deadline has not passed;
// 6. the recipient has not hidden the sending organization, and the
// recipient's publication (C2) is current.
//
// The notice declares no allowed fields. Its body is fixed text that names
// neither the organization nor the terms, and it carries no contact, so no
// field consent (C4) applies. A future notice that carries any candidate field
// or contact must add that field's consent check here, and must not put a
// contact into the mail at all: contacts are read on request, and every read
// re-checks the grant.
//
// The check is a snapshot taken in the sending transaction. A change after it
// and before the provider call still lets the notice go, which is the same
// rule as for service mail.
func (delivery Delivery) CheckInvitationNotice(standing InvitationNoticeStanding, at time.Time) DeliveryCancelReason {
subject := delivery.Subject()
awaitsAnswer := standing.InvitationState == InvitationDelivered || standing.InvitationState == InvitationViewed
switch {
case subject.Kind() != MailSubjectInvitation:
return DeliveryCancelSourceClosed
case !standing.RecipientFound || !standing.RecipientEmailVerified:
return DeliveryCancelRecipientIneligible
case standing.RecipientEmailKey != delivery.Recipient().Normalized():
return DeliveryCancelRecipientMismatch
case !standing.InvitationFound || standing.InvitationOrganizationID != subject.OrganizationID():
return DeliveryCancelSourceClosed
case !awaitsAnswer || !at.Before(standing.ResponseDeadlineAt):
return DeliveryCancelRightsRevoked
case standing.OrganizationHidden || !standing.PublicationPublished:
return DeliveryCancelRightsRevoked
default:
return ""
}
}
@@ -0,0 +1,173 @@
package domain
import (
"errors"
"testing"
"github.com/google/uuid"
)
var (
testInvitationID = uuid.MustParse("01926f3a-7c00-7000-8000-0000000000c1")
testSenderOrganizationID = uuid.MustParse("01926f3a-7c00-7000-8000-0000000000c3")
)
// newInvitationNotice is a notification to the test recipient that names an
// invitation of the test organization.
func newInvitationNotice(t *testing.T) Delivery {
t.Helper()
content, err := NewMailContent(MailKindNotification, "notification.v1", "Новое приглашение от работодателя", "Работодатель отправил вам приглашение\n", "")
if err != nil {
t.Fatalf("NewMailContent() error = %v", err)
}
subject, err := NewInvitationMailSubject(testInvitationID, testSenderOrganizationID)
if err != nil {
t.Fatalf("NewInvitationMailSubject() error = %v", err)
}
input := testDeliveryInput(t)
input.Content = content
input.Subject = subject
delivery, err := NewDelivery(input)
if err != nil {
t.Fatalf("NewDelivery() error = %v", err)
}
return delivery
}
// currentInvitationStanding is the standing of a notice that may be sent: the
// address is verified and unchanged, the invitation awaits an answer before its
// deadline, and the candidate neither hid the organization nor withdrew
// publication.
func currentInvitationStanding(delivery Delivery) InvitationNoticeStanding {
return InvitationNoticeStanding{
RecipientFound: true,
RecipientEmailVerified: true,
RecipientEmailKey: delivery.Recipient().Normalized(),
InvitationFound: true,
InvitationOrganizationID: testSenderOrganizationID,
InvitationState: InvitationDelivered,
ResponseDeadlineAt: after(7 * 24 * 60),
PublicationPublished: true,
}
}
func TestCheckInvitationNoticeAllowsAnInvitationThatStillAwaitsAnswer(t *testing.T) {
delivery := newInvitationNotice(t)
for _, state := range []InvitationState{InvitationDelivered, InvitationViewed} {
standing := currentInvitationStanding(delivery)
standing.InvitationState = state
if reason := delivery.CheckInvitationNotice(standing, after(1)); reason != "" {
t.Fatalf("CheckInvitationNotice(%s) = %q for an open invitation, want it sendable", state, reason)
}
}
}
// The first failed rule decides, so each row changes one fact from the current
// standing and names the reason that fact must give.
func TestCheckInvitationNoticeNamesTheReasonOfTheFirstFailedRule(t *testing.T) {
delivery := newInvitationNotice(t)
deadline := currentInvitationStanding(delivery).ResponseDeadlineAt
for _, test := range []struct {
name string
change func(*InvitationNoticeStanding)
at int
want DeliveryCancelReason
}{
{"the account is gone", func(s *InvitationNoticeStanding) { s.RecipientFound = false }, 1, DeliveryCancelRecipientIneligible},
{"the address is not verified", func(s *InvitationNoticeStanding) { s.RecipientEmailVerified = false }, 1, DeliveryCancelRecipientIneligible},
{"the address changed", func(s *InvitationNoticeStanding) { s.RecipientEmailKey = "other@example.com" }, 1, DeliveryCancelRecipientMismatch},
{"the invitation is gone", func(s *InvitationNoticeStanding) { s.InvitationFound = false }, 1, DeliveryCancelSourceClosed},
{"the invitation belongs to another organization", func(s *InvitationNoticeStanding) {
s.InvitationOrganizationID = uuid.MustParse("01926f3a-7c00-7000-8000-0000000000c9")
}, 1, DeliveryCancelSourceClosed},
{"the candidate declined", func(s *InvitationNoticeStanding) { s.InvitationState = InvitationDeclined }, 1, DeliveryCancelRightsRevoked},
{"the candidate accepted", func(s *InvitationNoticeStanding) { s.InvitationState = InvitationAccepted }, 1, DeliveryCancelRightsRevoked},
{"the invitation expired", func(s *InvitationNoticeStanding) { s.InvitationState = InvitationExpired }, 1, DeliveryCancelRightsRevoked},
{"the deadline has passed", func(*InvitationNoticeStanding) {}, 7*24*60 + 1, DeliveryCancelRightsRevoked},
{"the deadline is reached", func(*InvitationNoticeStanding) {}, 7 * 24 * 60, DeliveryCancelRightsRevoked},
{"the invitation was never delivered", func(s *InvitationNoticeStanding) {
s.ResponseDeadlineAt = deadline
s.InvitationState = InvitationDraft
}, 1, DeliveryCancelRightsRevoked},
{"the candidate hid the organization", func(s *InvitationNoticeStanding) { s.OrganizationHidden = true }, 1, DeliveryCancelRightsRevoked},
{"the candidate withdrew publication", func(s *InvitationNoticeStanding) { s.PublicationPublished = false }, 1, DeliveryCancelRightsRevoked},
{"an unverified address outranks a hidden organization", func(s *InvitationNoticeStanding) {
s.RecipientEmailVerified = false
s.OrganizationHidden = true
}, 1, DeliveryCancelRecipientIneligible},
} {
t.Run(test.name, func(t *testing.T) {
standing := currentInvitationStanding(delivery)
test.change(&standing)
if got := delivery.CheckInvitationNotice(standing, after(test.at)); got != test.want {
t.Fatalf("CheckInvitationNotice() = %q, want %q", got, test.want)
}
})
}
}
func TestCheckInvitationNoticeRefusesAMailThatNamesNoInvitation(t *testing.T) {
content, err := NewMailContent(MailKindNotification, "notification.v1", "Уведомление", "Текст\n", "")
if err != nil {
t.Fatalf("NewMailContent() error = %v", err)
}
input := testDeliveryInput(t)
input.Content = content
delivery, err := NewDelivery(input)
if err != nil {
t.Fatalf("NewDelivery() error = %v", err)
}
if reason := delivery.CheckInvitationNotice(currentInvitationStanding(delivery), after(1)); reason != DeliveryCancelSourceClosed {
t.Fatalf("CheckInvitationNotice() = %q for a notice without a subject, want source_closed", reason)
}
}
func TestNewMailSubjectNamesOnlyKnownRecords(t *testing.T) {
if _, err := NewInvitationMailSubject(uuid.Nil, testSenderOrganizationID); !errors.Is(err, ErrInvalidMailSubject) {
t.Fatalf("NewInvitationMailSubject(nil invitation) error = %v, want ErrInvalidMailSubject", err)
}
if _, err := NewInvitationMailSubject(testInvitationID, uuid.Nil); !errors.Is(err, ErrInvalidMailSubject) {
t.Fatalf("NewInvitationMailSubject(nil organization) error = %v, want ErrInvalidMailSubject", err)
}
if subject, err := RestoreMailSubject("", uuid.Nil, uuid.Nil); err != nil || !subject.IsZero() {
t.Fatalf("RestoreMailSubject(empty) = %v, %v; want the zero subject", subject, err)
}
if _, err := RestoreMailSubject("contract", testInvitationID, testSenderOrganizationID); !errors.Is(err, ErrInvalidMailSubject) {
t.Fatalf("RestoreMailSubject(unknown kind) error = %v, want ErrInvalidMailSubject", err)
}
subject, err := NewInvitationMailSubject(testInvitationID, testSenderOrganizationID)
if err != nil {
t.Fatalf("NewInvitationMailSubject() error = %v", err)
}
if text := subject.String(); text != "[mail subject invitation]" {
t.Fatalf("String() = %q; the identifiers must stay out of printed values", text)
}
}
func TestOnlyANotificationNamesASubject(t *testing.T) {
subject, err := NewInvitationMailSubject(testInvitationID, testSenderOrganizationID)
if err != nil {
t.Fatalf("NewInvitationMailSubject() error = %v", err)
}
input := testDeliveryInput(t)
input.Subject = subject
if _, err := NewDelivery(input); !errors.Is(err, ErrInvalidDelivery) {
t.Fatalf("NewDelivery(verification with subject) error = %v, want ErrInvalidDelivery", err)
}
}
func TestRightsCancelReasonsAreKnownAndExposed(t *testing.T) {
for _, value := range []string{"rights_revoked", "recipient_ineligible", "source_closed"} {
reason, err := ParseDeliveryCancelReason(value)
if err != nil {
t.Fatalf("ParseDeliveryCancelReason(%q) error = %v", value, err)
}
listed := false
for _, known := range DeliveryCancelReasons() {
listed = listed || known == reason
}
if !listed {
t.Fatalf("%q is parsed but missing from DeliveryCancelReasons, so its metric series would not exist at zero", value)
}
}
}
+21 -4
View File
@@ -58,14 +58,20 @@ 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. 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.
// service sending worker claims and sends. The delivery metrics of due mail
// 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}
}
// ProductMailKinds lists the kinds of product notifications, the kinds the
// notification sending worker claims. Its claim has its own partial index,
// deliveries_product_due_idx, which follows this list.
func ProductMailKinds() []MailKind {
return []MailKind{MailKindNotification}
}
// IsServiceMail reports a kind of service identity mail.
func (kind MailKind) IsServiceMail() bool { return kind.CarriesBearerToken() }
@@ -173,6 +179,17 @@ func RestoreRedactedMailContent(kind MailKind, templateVersion, subject string,
if _, err := ParseMailKind(string(kind)); err != nil || !kind.CarriesBearerToken() {
return MailContent{}, invalidMailContent("only a token mail has redacted content")
}
return restoreRedactedContent(location, kind, templateVersion, subject, hash)
}
// RestoreRedactedNotificationContent rebuilds the content of a notification
// whose bodies were cleared when it was cancelled. Like a redacted token mail,
// it keeps the subject and the hash and can never be sent.
func RestoreRedactedNotificationContent(templateVersion, subject string, hash []byte) (MailContent, error) {
return restoreRedactedContent("domain.RestoreRedactedNotificationContent", MailKindNotification, templateVersion, subject, hash)
}
func restoreRedactedContent(location string, kind MailKind, templateVersion, subject string, hash []byte) (MailContent, error) {
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)
+16
View File
@@ -44,6 +44,22 @@ func NewMailQuotaLimits(daily, monthly int64) (MailQuotaLimits, error) {
func (limits MailQuotaLimits) IsZero() bool { return limits.daily == 0 }
// WithReserve returns the limits that a sender may use when daily and monthly
// recipients stay free for other mail. Each window keeps its own reserve, so
// the result is checked window by window; it may not keep the rule that the
// daily limit does not exceed the monthly one, which the configuration keeps.
// A reserve must be zero or more and leave at least one recipient per window.
func (limits MailQuotaLimits) WithReserve(daily, monthly int64) (MailQuotaLimits, error) {
const location = "domain.MailQuotaLimits.WithReserve"
switch {
case daily < 0 || monthly < 0:
return MailQuotaLimits{}, fmt.Errorf("%s - reserves must not be negative: %w", location, ErrInvalidMailQuota)
case daily >= limits.daily || monthly >= limits.monthly:
return MailQuotaLimits{}, fmt.Errorf("%s - a reserve must leave room in its window: %w", location, ErrInvalidMailQuota)
}
return MailQuotaLimits{daily: limits.daily - daily, monthly: limits.monthly - monthly}, nil
}
func (limits MailQuotaLimits) Daily() int64 { return limits.daily }
func (limits MailQuotaLimits) Monthly() int64 { return limits.monthly }
@@ -118,3 +118,36 @@ func TestNewMailQuotaLimits(t *testing.T) {
})
}
}
func TestWithReserveLeavesEachWindowItsOwnShare(t *testing.T) {
limits, err := NewMailQuotaLimits(100, 3000)
if err != nil {
t.Fatalf("NewMailQuotaLimits() error = %v", err)
}
admission, err := limits.WithReserve(20, 600)
if err != nil {
t.Fatalf("WithReserve(20, 600) error = %v", err)
}
if admission.Daily() != 80 || admission.Monthly() != 2400 {
t.Fatalf("admission = %d a day and %d a month, want 80 and 2400", admission.Daily(), admission.Monthly())
}
if unchanged, err := limits.WithReserve(0, 0); err != nil || unchanged.Daily() != 100 || unchanged.Monthly() != 3000 {
t.Fatalf("WithReserve(0, 0) = %+v, %v; want the limits unchanged", unchanged, err)
}
}
func TestWithReserveRefusesAReserveThatLeavesNoRoom(t *testing.T) {
limits, err := NewMailQuotaLimits(100, 3000)
if err != nil {
t.Fatalf("NewMailQuotaLimits() error = %v", err)
}
for name, reserve := range map[string][2]int64{
"a daily reserve equal to the limit": {100, 0},
"a monthly reserve above the limit": {0, 3001},
"a negative reserve": {-1, 0},
} {
if _, err := limits.WithReserve(reserve[0], reserve[1]); !errors.Is(err, ErrInvalidMailQuota) {
t.Fatalf("%s: WithReserve() error = %v, want ErrInvalidMailQuota", name, err)
}
}
}
+22 -6
View File
@@ -60,7 +60,11 @@ type MailRequest struct {
RecipientUserID uuid.UUID
Kind MailKind
Notification NotificationText
CreatedAt time.Time
// Subject names the record the notification is about. It is copied to the
// delivery, whose sending worker checks its rights; the zero value names
// none.
Subject MailSubject
CreatedAt time.Time
}
// NewMailRequest checks the storage rules of a request. Only notification
@@ -68,7 +72,6 @@ type MailRequest struct {
// transaction that issues the token. Whether the text renders is checked by
// the template, not here.
func NewMailRequest(request MailRequest) (MailRequest, error) {
text := request.Notification
switch {
case request.ID == uuid.Nil || request.RecipientUserID == uuid.Nil:
return MailRequest{}, invalidMailRequest("request and recipient user IDs must not be nil")
@@ -76,17 +79,30 @@ func NewMailRequest(request MailRequest) (MailRequest, error) {
return MailRequest{}, invalidMailRequest("only notification mail can be requested")
case request.CreatedAt.IsZero():
return MailRequest{}, invalidMailRequest("creation time must be set")
case !request.Subject.IsZero() && request.Subject.Kind() != MailSubjectInvitation:
return MailRequest{}, invalidMailRequest("the subject kind is unknown")
}
if err := checkMailRequestText(request.Notification); err != nil {
return MailRequest{}, err
}
return request, nil
}
// checkMailRequestText bounds and checks the raw text of a request, before the
// template normalizes it.
func checkMailRequestText(text NotificationText) error {
switch {
case !utf8.ValidString(text.Subject) || !utf8.ValidString(text.Body) || !utf8.ValidString(text.LinkPath):
return MailRequest{}, invalidMailRequest("text must be valid UTF-8")
return invalidMailRequest("text must be valid UTF-8")
// PostgreSQL text cannot store NUL.
case strings.ContainsRune(text.Subject, 0) || strings.ContainsRune(text.Body, 0) || strings.ContainsRune(text.LinkPath, 0):
return MailRequest{}, invalidMailRequest("text must not contain NUL characters")
return invalidMailRequest("text must not contain NUL characters")
case utf8.RuneCountInString(text.Subject) > maxMailRequestSubjectRunes ||
utf8.RuneCountInString(text.Body) > maxMailRequestBodyRunes ||
len(text.LinkPath) > maxMailRequestLinkPathSize:
return MailRequest{}, invalidMailRequest("subject, body, or link path is too long")
return invalidMailRequest("subject, body, or link path is too long")
}
return request, nil
return nil
}
// LogValue carries the IDs and kind only.
+83
View File
@@ -0,0 +1,83 @@
package domain
import (
"errors"
"fmt"
"log/slog"
"github.com/google/uuid"
)
// ErrInvalidMailSubject reports a subject that names no record or breaks the
// rule of its kind. Errors name the rule, never an identifier.
var ErrInvalidMailSubject = errors.New("invalid mail subject")
// MailSubjectKind names the kind of record a notification is about. The
// values are stored, and each one has a rights checker in the sending usecase.
type MailSubjectKind string
const (
// MailSubjectInvitation is an invitation addressed to the recipient. The
// subject ID is the invitation and the organization is its sender.
MailSubjectInvitation MailSubjectKind = "invitation"
)
// MailSubject links a notification to the record whose rights must still hold
// when the mail is sent. The sending worker re-checks those rights before the
// transport is called, so a notification that outlives its basis is cancelled
// instead of sent. The zero value names no subject; the worker then has no
// rights to check and cancels the notification with source_closed.
type MailSubject struct {
kind MailSubjectKind
id uuid.UUID
organizationID uuid.UUID
}
// NewInvitationMailSubject names an invitation and the organization that sent
// it. Both IDs must be set.
func NewInvitationMailSubject(invitationID, organizationID uuid.UUID) (MailSubject, error) {
if invitationID == uuid.Nil || organizationID == uuid.Nil {
return MailSubject{}, fmt.Errorf("domain.NewInvitationMailSubject - invitation and organization IDs must be set: %w", ErrInvalidMailSubject)
}
return MailSubject{kind: MailSubjectInvitation, id: invitationID, organizationID: organizationID}, nil
}
// RestoreMailSubject rebuilds a stored subject. A kind of "" with nil IDs is
// the zero subject; any other combination must be a complete known subject.
func RestoreMailSubject(kind string, id, organizationID uuid.UUID) (MailSubject, error) {
if kind == "" && id == uuid.Nil && organizationID == uuid.Nil {
return MailSubject{}, nil
}
switch MailSubjectKind(kind) {
case MailSubjectInvitation:
return NewInvitationMailSubject(id, organizationID)
default:
return MailSubject{}, fmt.Errorf("domain.RestoreMailSubject - unknown subject kind: %w", ErrInvalidMailSubject)
}
}
// IsZero reports a subject that names nothing.
func (subject MailSubject) IsZero() bool { return subject.kind == "" }
func (subject MailSubject) Kind() MailSubjectKind { return subject.kind }
// ID is the identifier of the subject record.
func (subject MailSubject) ID() uuid.UUID { return subject.id }
// OrganizationID is the organization the subject record belongs to.
func (subject MailSubject) OrganizationID() uuid.UUID { return subject.organizationID }
// String shows the kind only; the identifiers stay out of printed values.
func (subject MailSubject) String() string {
if subject.IsZero() {
return "[empty mail subject]"
}
return fmt.Sprintf("[mail subject %s]", subject.kind)
}
func (subject MailSubject) GoString() string { return subject.String() }
// LogValue carries the kind only.
func (subject MailSubject) LogValue() slog.Value {
return slog.StringValue(string(subject.kind))
}
@@ -193,8 +193,26 @@ type DeliveryRetrySnapshot struct {
ManualRetryStartedAt time.Time
}
// ClaimScope names the lane a claim serves. Each lane has its own claim
// statement and partial due index, so an idle poll of one lane never reads
// the backlog of the other.
type ClaimScope int
const (
// ClaimScopeService claims service identity mail: verification and
// password reset, through deliveries_due_idx. It is the zero value, so a
// claim that names no lane is a service claim.
ClaimScopeService ClaimScope = iota
// ClaimScopeNotification claims product notifications, through
// deliveries_product_due_idx.
ClaimScopeNotification
)
// DeliveryClaim selects and leases the next delivery for a sending worker.
type DeliveryClaim struct {
// Scope selects the lane and its claim statement. Kinds must be the kinds
// of that lane.
Scope ClaimScope
// Owner identifies the worker; a lease belongs to it.
Owner uuid.UUID
// Account is the configured provider account. Only deliveries pinned to
@@ -0,0 +1,23 @@
package outbound
import (
"context"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
// NotificationRightsReader reads the standing that the rights checks of
// product notifications need. It runs inside the caller's transaction, in
// the same transaction that holds the delivery lock, and it locks nothing
// itself. It returns the facts of one record only, never an address, a
// contact, or the content of a notification.
type NotificationRightsReader interface {
// InvitationNoticeStanding reads the standing of an invitation notice: the
// recipient account, the invitation the recipient is addressed by, the
// hiding of the sending organization, and the current publication. A
// missing account or invitation is reported as not found, not as an
// error.
InvitationNoticeStanding(ctx context.Context, recipientUserID, invitationID, organizationID uuid.UUID) (domain.InvitationNoticeStanding, error)
}
@@ -79,6 +79,7 @@ type UnitOfWork interface {
Deliveries() DeliveryRepository
MailRequests() MailRequestRepository
MailQuotas() MailQuotaRepository
NotificationRights() NotificationRightsReader
Outbox() OutboxWriter
ScheduledJobs() JobScheduler
}
@@ -120,6 +120,7 @@ func (handler *DeliveryHandler) Handle(ctx context.Context, unit outbound.UnitOf
Recipient: recipient.Email,
Content: content,
ProviderAccount: handler.providerAccount,
Subject: request.Subject,
CreatedAt: handler.clock(),
})
if err != nil {
@@ -0,0 +1,900 @@
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")
// DeliverySenderSettings are the named limits of a sending worker.
type DeliverySenderSettings 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 DeliverySenderSettings) validate() error {
switch {
case settings.Account.IsZero():
return errors.New("notification.NewDeliverySender - 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.NewDeliverySender - lease, timeouts, and settle budgets must be positive and the failure limit at least 1")
case settings.SettleBudget >= settings.Lease:
return errors.New("notification.NewDeliverySender - the settle budget must be shorter than the lease")
case settings.Retry.Initial <= 0 || settings.Retry.Max < settings.Retry.Initial:
return errors.New("notification.NewDeliverySender - retry delays must be positive and the maximum not below the initial delay")
}
return nil
}
// DeliverySender sends the deliveries of one lane: service identity mail
// (ServiceMailSender) or product notifications (NotificationSender). 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 of the
// lane with FOR UPDATE SKIP LOCKED, so no two senders hold the same one.
// The lane's Eligibility decides whether the mail may still go out; one
// that may not 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. Check right before the send, in a second short transaction that takes the
// delivery lock again and runs the Eligibility a second time, so a
// revocation after the claim is honored; then 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 DeliverySender struct {
owner uuid.UUID
// countingPaused stops counting failures of single rows; see
// PauseFailureCounting.
countingPaused atomic.Bool
transactor outbound.Transactor
sender outbound.MailSender
gate *QuotaGate
lane deliveryLane
settings DeliverySenderSettings
clock func() time.Time
logger *slog.Logger
}
// deliveryLane is what one sender serves: the claim scope and kinds it leases,
// and the rule that decides before each send.
type deliveryLane struct {
scope outbound.ClaimScope
kinds []domain.MailKind
eligibility Eligibility
}
// Eligibility decides whether a claimed delivery may still be sent. It runs in
// the caller's transaction, after the delivery is locked for the lease holder,
// and returns the cancel reason, or an empty reason when the mail may go out.
// It reads the current standing of the recipient and of the record the mail
// concerns; it never reads an address or a contact into its result.
type Eligibility interface {
Check(ctx context.Context, unit outbound.UnitOfWork, delivery domain.Delivery, at time.Time) (domain.DeliveryCancelReason, error)
}
// newDeliverySender builds a sender of one lane 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 newDeliverySender(
lane deliveryLane,
transactor outbound.Transactor,
sender outbound.MailSender,
gate *QuotaGate,
settings DeliverySenderSettings,
clock func() time.Time,
logger *slog.Logger,
) (*DeliverySender, error) {
if err := settings.validate(); err != nil {
return nil, err
}
owner := uuid.New()
return &DeliverySender{
owner: owner,
transactor: transactor,
sender: sender,
gate: gate,
lane: lane,
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
firstSendStarted bool
sinceFirstSend time.Duration
manualRetryPending bool
manualRetryCycleStarted bool
sendStartUnsettled bool
requireDedupWindow bool
// 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 = (*DeliverySender)(nil)
// PauseFailureCounting implements inbound.MailPass.
func (sender *DeliverySender) 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 *DeliverySender) 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("DeliverySender.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("DeliverySender.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 *DeliverySender) 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{
Scope: sender.lane.scope,
Owner: sender.owner,
Account: sender.settings.Account,
RebindProvider: sender.settings.RebindProvider,
Kinds: sender.lane.kinds,
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 *DeliverySender) 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 and runs the lane's eligibility 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 *DeliverySender) 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
}
now := sender.clock()
if result, handled, err := sender.handleInvalidClaim(ctx, unit, claim, delivery, now); err != nil || handled {
if handled {
decided = &result
}
return err
}
started, err := unit.Deliveries().MarkSendStarted(ctx, delivery.ID(), sender.owner,
claim.requireDedupWindow, sender.safeRetryWindow())
if err != nil {
return fmt.Errorf("mark send started: %w", err)
}
if !started {
result, err := sender.handleUnmarkedSend(ctx, unit, claim, delivery, now)
if err != nil {
return err
}
decided = &result
}
return nil
})
if err != nil {
return nil, err
}
return decided, nil
}
func (sender *DeliverySender) handleInvalidClaim(
ctx context.Context,
unit outbound.UnitOfWork,
claim claimedSend,
delivery domain.Delivery,
now time.Time,
) (inbound.MailPassResult, bool, error) {
reason, err := sender.lane.eligibility.Check(ctx, unit, delivery, now)
if err != nil {
return inbound.MailPassResult{}, true, fmt.Errorf("check eligibility: %w", err)
}
if reason == "" {
return inbound.MailPassResult{}, false, nil
}
if delivery.Status() == domain.DeliveryStatusUnknown {
if err := sender.releaseUnsentReservation(ctx, unit, claim); err != nil {
return inbound.MailPassResult{}, true, err
}
stopped, err := sender.stopAutomaticRetry(ctx, unit, delivery, now)
return stopped.result, true, err
}
if _, err := sender.gate.SettleSend(ctx, unit, claim.permit, outbound.SendResult{}, errNotSent); err != nil {
return inbound.MailPassResult{}, true, fmt.Errorf("give the reservation back: %w", err)
}
cancelled, err := sender.cancel(ctx, unit, delivery, now, reason)
return cancelled.result, true, err
}
func (sender *DeliverySender) handleUnmarkedSend(
ctx context.Context,
unit outbound.UnitOfWork,
claim claimedSend,
delivery domain.Delivery,
now time.Time,
) (inbound.MailPassResult, error) {
if delivery.Status() == domain.DeliveryStatusUnknown {
if err := sender.releaseUnsentReservation(ctx, unit, claim); err != nil {
return inbound.MailPassResult{}, err
}
stopped, err := sender.stopAutomaticRetry(ctx, unit, delivery, now)
return stopped.result, err
}
if claim.sendStartUnsettled {
inDoubt, err := sender.recordInDoubt(ctx, unit, delivery, now)
return inDoubt.result, err
}
if claim.requireDedupWindow && claim.firstSendStarted {
if err := sender.releaseUnsentReservation(ctx, unit, claim); err != nil {
return inbound.MailPassResult{}, err
}
stopped, err := sender.stopAutomaticRetry(ctx, unit, delivery, now)
return stopped.result, err
}
if claim.firstSendStarted {
inDoubt, err := sender.recordInDoubt(ctx, unit, delivery, now)
return inDoubt.result, err
}
return resultOf(inbound.MailPassLeaseLost, delivery), 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 *DeliverySender) 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 *DeliverySender) 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 claimed.ManualRetryCycleStarted && claimed.SendStartUnsettled {
// A manually authorized send started but its result was not recorded.
// Do not spend that authorization on another provider call.
return sender.recordInDoubt(ctx, unit, delivery, now)
}
if sender.retryBeyondDeduplication(claimed) {
if claimed.SendStartUnsettled {
return sender.recordInDoubt(ctx, unit, delivery, now)
}
return sender.stopAutomaticRetry(ctx, unit, delivery, now)
}
reason, err := sender.lane.eligibility.Check(ctx, unit, delivery, now)
if err != nil {
return claimedSend{}, fmt.Errorf("check eligibility: %w", err)
}
if 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 sender.waitForQuota(ctx, unit, delivery, decision, now)
}
return claimedSend{
delivery: decision.Delivery,
permit: decision.Permit,
firstSendStarted: claimed.FirstSendStarted,
sinceFirstSend: claimed.SinceFirstSend,
manualRetryPending: claimed.ManualRetryPending,
manualRetryCycleStarted: claimed.ManualRetryCycleStarted,
sendStartUnsettled: claimed.SendStartUnsettled,
requireDedupWindow: sender.requiresDedupWindow(claimed),
}, nil
}
func (sender *DeliverySender) waitForQuota(
ctx context.Context,
unit outbound.UnitOfWork,
delivery domain.Delivery,
decision SendDecision,
now time.Time,
) (claimedSend, error) {
if delivery.Status() != domain.DeliveryStatusUnknown || decision.ResetAt.IsZero() {
return claimedSend{decided: true, result: resultOf(inbound.MailPassWaitingQuota, decision.Delivery)}, nil
}
at := latest(now, delivery.UpdatedAt())
deferred, err := delivery.ScheduleUnknownRetry(at, latest(decision.ResetAt, at))
if err != nil {
return claimedSend{}, fmt.Errorf("schedule uncertain quota retry: %w", err)
}
if err := unit.Deliveries().ScheduleUnknownRetry(ctx, sender.owner, deferred); err != nil {
return claimedSend{}, fmt.Errorf("store uncertain quota retry: %w", err)
}
return claimedSend{decided: true, result: resultOf(inbound.MailPassUnknown, deferred)}, 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 *DeliverySender) requiresDedupWindow(claimed outbound.ClaimedDelivery) bool {
if claimed.SendStartUnsettled {
return true
}
if claimed.ManualRetryPending {
return false
}
if claimed.Delivery.Status() == domain.DeliveryStatusUnknown {
return true
}
return claimed.HasUncertainAttempt && !claimed.ManualRetryCycleStarted
}
func (sender *DeliverySender) retryBeyondDeduplication(claimed outbound.ClaimedDelivery) bool {
if !sender.requiresDedupWindow(claimed) {
return false
}
if !claimed.FirstSendStarted {
return true
}
return claimed.SinceFirstSend >= sender.safeRetryWindow()
}
func (sender *DeliverySender) safeRetryWindow() time.Duration {
return max(sender.gate.IdempotencyWindow()-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 *DeliverySender) 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 *DeliverySender) stopAutomaticRetry(
ctx context.Context,
unit outbound.UnitOfWork,
delivery domain.Delivery,
now time.Time,
) (claimedSend, error) {
next, err := delivery.StopAutomaticRetry(latest(now, delivery.UpdatedAt()))
if err != nil {
return claimedSend{}, fmt.Errorf("stop automatic retry: %w", err)
}
if err := unit.Deliveries().StopUnknownRetry(ctx, sender.owner, next); err != nil {
return claimedSend{}, fmt.Errorf("store stopped retry: %w", err)
}
sender.logger.WarnContext(ctx, "automatic retries stopped before the provider deduplication cutoff; the delivery remains unknown for an operator decision",
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 *DeliverySender) releaseUnsentReservation(ctx context.Context, unit outbound.UnitOfWork, claim claimedSend) error {
if claim.permit.IsZero() || claim.permit.Reused() {
return nil
}
if _, err := sender.gate.SettleSend(ctx, unit, claim.permit, outbound.SendResult{}, errNotSent); err != nil {
return fmt.Errorf("release unused reservation: %w", err)
}
return nil
}
func (sender *DeliverySender) 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, "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 *DeliverySender) settle(ctx context.Context, claim claimedSend, result outbound.SendResult, sendErr error) (inbound.MailPassResult, error) {
const location = "DeliverySender.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, "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 *DeliverySender) 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 *DeliverySender) 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())
manualRetry := claim.manualRetryPending || claim.manualRetryCycleStarted
next, attempt, err := delivery.RecordAttempt(sender.attemptInput(delivery, result, at, until, manualRetry))
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 *DeliverySender) attemptInput(delivery domain.Delivery, result outbound.SendResult, at, until time.Time, manualRetry bool) 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)
case result.Outcome == outbound.MailOutcomeUnknown && !manualRetry && sender.gate.IdempotencyWindow() > 0:
input.NextAttemptAt = sender.settings.Retry.NextAttemptAt(at, delivery.AttemptCount()+1, result.RetryAfter)
}
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 *DeliverySender) 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 *DeliverySender) 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, "mail was not accepted by the provider", attributes...)
case inbound.MailPassCancelled:
sender.logger.InfoContext(ctx, "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, "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
}
}
@@ -76,11 +76,16 @@ func (notifier *InvitationNotifier) InvitationDelivered(ctx context.Context, uni
if err := unit.Outbox().Append(ctx, event); err != nil {
return fmt.Errorf("%s - append event: %w", location, err)
}
subject, err := domain.NewInvitationMailSubject(invitation.ID(), invitation.OrganizationID())
if err != nil {
return fmt.Errorf("%s - name invitation: %w", location, err)
}
if _, err := notifier.mail.RequestNotification(ctx, unit, NotificationRequest{
RecipientUserID: invitation.CandidateID(),
Notification: mailtemplate.NotificationData{
Subject: invitationMailSubject, Body: invitationMailBody, LinkPath: candidateInvitationsPath,
},
Subject: subject,
}); err != nil {
return fmt.Errorf("%s - request email: %w", location, err)
}
@@ -0,0 +1,31 @@
package notification
import (
"context"
"fmt"
"time"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// invitationNoticeRights checks the notice that tells a candidate about a
// delivered invitation: the standing it reads is the one the rule in
// domain.Delivery.CheckInvitationNotice decides on.
type invitationNoticeRights struct{}
// NewInvitationNoticeRights returns the rights check of invitation notices.
func NewInvitationNoticeRights() SubjectRights { return invitationNoticeRights{} }
func (invitationNoticeRights) Subject() domain.MailSubjectKind {
return domain.MailSubjectInvitation
}
func (invitationNoticeRights) Check(ctx context.Context, unit outbound.UnitOfWork, delivery domain.Delivery, at time.Time) (domain.DeliveryCancelReason, error) {
subject := delivery.Subject()
standing, err := unit.NotificationRights().InvitationNoticeStanding(ctx, delivery.RecipientUserID(), subject.ID(), subject.OrganizationID())
if err != nil {
return "", fmt.Errorf("invitationNoticeRights.Check - read standing: %w", err)
}
return delivery.CheckInvitationNotice(standing, at), nil
}
@@ -109,10 +109,13 @@ func (renderer TemplateRenderer) RenderPasswordReset(data mailtemplate.PasswordR
return content, nil
}
// NotificationRequest asks for one notification mail to one account.
// NotificationRequest asks for one notification mail to one account. Subject
// names the record the notice concerns, whose rights are checked before the
// send; the zero value names none.
type NotificationRequest struct {
RecipientUserID uuid.UUID
Notification mailtemplate.NotificationData
Subject domain.MailSubject
}
// MailRequester records mail requests in the caller's transaction.
@@ -154,6 +157,7 @@ func (requester *MailRequester) RequestNotification(ctx context.Context, unit ou
Body: request.Notification.Body,
LinkPath: request.Notification.LinkPath,
},
Subject: request.Subject,
CreatedAt: requester.clock(),
})
if err != nil {
@@ -0,0 +1,81 @@
package notification
import (
"context"
"errors"
"fmt"
"log/slog"
"time"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// ErrNoSubjectRights reports a notification whose subject kind has no rights
// checker in this build. Such a notice is neither sent nor cancelled: its
// basis cannot be checked, so it waits for a build that can check it.
var ErrNoSubjectRights = errors.New("no rights check is registered for the notification subject")
// SubjectRights is the rights check of one subject kind of product
// notifications. A notice names a subject, and its check runs in the claim
// transaction and again before the transport is called, under the delivery
// lock. A future notice that carries a candidate field or a contact adds its
// consent check here (C4 for a contact, C2 for a publication-dependent field)
// and never puts a contact into the mail: contacts are read on request, and
// every read re-checks its grant.
type SubjectRights interface {
// Subject is the subject kind this check decides.
Subject() domain.MailSubjectKind
// Check reads the current standing and returns the cancel reason, or an
// empty reason when the notice may be sent.
Check(ctx context.Context, unit outbound.UnitOfWork, delivery domain.Delivery, at time.Time) (domain.DeliveryCancelReason, error)
}
// subjectEligibility dispatches the rights check by the subject of the
// delivery. A notification that names no subject has no basis to check and is
// cancelled with source_closed.
type subjectEligibility struct {
rights map[domain.MailSubjectKind]SubjectRights
}
func (eligibility subjectEligibility) Check(ctx context.Context, unit outbound.UnitOfWork, delivery domain.Delivery, at time.Time) (domain.DeliveryCancelReason, error) {
subject := delivery.Subject()
if subject.IsZero() {
return domain.DeliveryCancelSourceClosed, nil
}
checker, ok := eligibility.rights[subject.Kind()]
if !ok {
return "", fmt.Errorf("subjectEligibility.Check - subject kind %q: %w", subject.Kind(), ErrNoSubjectRights)
}
return checker.Check(ctx, unit, delivery, at)
}
// NewNotificationSender builds the sender of the product notification lane. It
// claims only notifications and sends one only when the rights check of its
// subject kind passes. rights lists one check per subject kind; a kind listed
// twice is refused. gate must be built for settings.Account.
func NewNotificationSender(
transactor outbound.Transactor,
sender outbound.MailSender,
gate *QuotaGate,
settings DeliverySenderSettings,
clock func() time.Time,
logger *slog.Logger,
rights []SubjectRights,
) (*DeliverySender, error) {
byKind := make(map[domain.MailSubjectKind]SubjectRights, len(rights))
for _, check := range rights {
if check == nil {
return nil, errors.New("notification.NewNotificationSender - rights check must not be nil")
}
if _, dup := byKind[check.Subject()]; dup {
return nil, fmt.Errorf("notification.NewNotificationSender - subject kind %q has two rights checks", check.Subject())
}
byKind[check.Subject()] = check
}
return newDeliverySender(deliveryLane{
scope: outbound.ClaimScopeNotification,
kinds: domain.ProductMailKinds(),
eligibility: subjectEligibility{rights: byKind},
}, transactor, sender, gate, settings, clock, logger)
}
+32 -3
View File
@@ -51,8 +51,12 @@ var (
// Send returned an error, the delivery's next state). The reservation
// journal makes a repeated settlement harmless.
type QuotaGate struct {
account domain.MailProviderAccount
limits domain.MailQuotaLimits
account domain.MailProviderAccount
limits domain.MailQuotaLimits
// reserveDaily and reserveMonthly are the recipients per window that this
// gate leaves free for other mail; see WithReserve.
reserveDaily int64
reserveMonthly int64
idempotencyWindow time.Duration
clock func() time.Time
logger *slog.Logger
@@ -74,6 +78,27 @@ func NewQuotaGate(
return &QuotaGate{account: account, limits: limits, idempotencyWindow: idempotencyWindow, clock: clock, logger: logger}
}
// WithReserve returns a gate that admits a send only while the windows keep
// the given recipients free after it: daily and monthly recipients that other
// mail may use. The service lane keeps the full limits, so a reserve held for
// service mail is never spent by product notifications. The reserve shapes
// admission only; a window that the provider reports used up is still marked
// against the full limit, so the provider's answer is never understated.
func (gate *QuotaGate) WithReserve(daily, monthly int64) (*QuotaGate, error) {
if _, err := gate.limits.WithReserve(daily, monthly); err != nil {
return nil, fmt.Errorf("QuotaGate.WithReserve - reserve: %w", err)
}
next := *gate
next.reserveDaily, next.reserveMonthly = daily, monthly
return &next, nil
}
// admission returns the limits that a send is admitted against: the limits
// less the reserve. It is computed at each decision from the current limits.
func (gate *QuotaGate) admission() (domain.MailQuotaLimits, error) {
return gate.limits.WithReserve(gate.reserveDaily, gate.reserveMonthly)
}
// QuotaPermit admits one send of one delivery. It holds the reservation, so
// a settlement after midnight still releases the windows the send was
// counted in.
@@ -142,6 +167,10 @@ func (gate *QuotaGate) PrepareSend(ctx context.Context, unit outbound.UnitOfWork
return SendDecision{}, fmt.Errorf("%s - delivery is %s: %w", location, delivery.Status(), domain.ErrDeliveryTransition)
}
now := gate.clock()
admission, err := gate.admission()
if err != nil {
return SendDecision{}, fmt.Errorf("%s - admission limits: %w", location, err)
}
reservationID, err := uuid.NewV7()
if err != nil {
return SendDecision{}, fmt.Errorf("%s - generate reservation ID: %w", location, err)
@@ -155,7 +184,7 @@ func (gate *QuotaGate) PrepareSend(ctx context.Context, unit outbound.UnitOfWork
Recipients: recipientsPerDelivery,
ReservedAt: now,
},
Limits: gate.limits,
Limits: admission,
}
if gate.idempotencyWindow > 0 {
request.ReuseSince = now.Add(-gate.idempotencyWindow)
@@ -2,128 +2,38 @@ 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
)
// ServiceMailSenderSettings are the named limits of the service mail sender.
type ServiceMailSenderSettings = DeliverySenderSettings
// 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
// ServiceMailSender sends the service identity mail of the account flows
// (email verification and password reset) that ServiceMailer stored. It is a
// DeliverySender of the service lane: it claims only service mail and checks
// each delivery's token and account before the send.
type ServiceMailSender = DeliverySender
// 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")
// serviceEligibility applies the token and account rules of service mail.
// Publishing consent (C2) and the other product consents play no part: a
// service mail is part of the account flow, not a product notification.
type serviceEligibility struct{}
// 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")
func (serviceEligibility) Check(ctx context.Context, unit outbound.UnitOfWork, delivery domain.Delivery, at time.Time) (domain.DeliveryCancelReason, error) {
state, err := unit.Deliveries().ServiceMailState(ctx, delivery.ID())
if err != nil {
return "", fmt.Errorf("serviceEligibility.Check - read token and account: %w", err)
}
return nil
return delivery.CheckServiceMail(state, at), 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.
// NewServiceMailSender builds the sender of the service lane. gate must be
// built for settings.Account. clock is the application clock.
func NewServiceMailSender(
transactor outbound.Transactor,
sender outbound.MailSender,
@@ -132,748 +42,9 @@ func NewServiceMailSender(
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
firstSendStarted bool
sinceFirstSend time.Duration
manualRetryPending bool
manualRetryCycleStarted bool
sendStartUnsettled bool
requireDedupWindow bool
// 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 result, handled, err := sender.handleInvalidClaim(ctx, unit, claim, delivery, state, now); err != nil || handled {
if handled {
decided = &result
}
return err
}
started, err := unit.Deliveries().MarkSendStarted(ctx, delivery.ID(), sender.owner,
claim.requireDedupWindow, sender.safeRetryWindow())
if err != nil {
return fmt.Errorf("mark send started: %w", err)
}
if !started {
result, err := sender.handleUnmarkedSend(ctx, unit, claim, delivery, now)
if err != nil {
return err
}
decided = &result
}
return nil
})
if err != nil {
return nil, err
}
return decided, nil
}
func (sender *ServiceMailSender) handleInvalidClaim(
ctx context.Context,
unit outbound.UnitOfWork,
claim claimedSend,
delivery domain.Delivery,
state domain.ServiceMailState,
now time.Time,
) (inbound.MailPassResult, bool, error) {
reason := delivery.CheckServiceMail(state, now)
if reason == "" {
return inbound.MailPassResult{}, false, nil
}
if delivery.Status() == domain.DeliveryStatusUnknown {
if err := sender.releaseUnsentReservation(ctx, unit, claim); err != nil {
return inbound.MailPassResult{}, true, err
}
stopped, err := sender.stopAutomaticRetry(ctx, unit, delivery, now)
return stopped.result, true, err
}
if _, err := sender.gate.SettleSend(ctx, unit, claim.permit, outbound.SendResult{}, errNotSent); err != nil {
return inbound.MailPassResult{}, true, fmt.Errorf("give the reservation back: %w", err)
}
cancelled, err := sender.cancel(ctx, unit, delivery, now, reason)
return cancelled.result, true, err
}
func (sender *ServiceMailSender) handleUnmarkedSend(
ctx context.Context,
unit outbound.UnitOfWork,
claim claimedSend,
delivery domain.Delivery,
now time.Time,
) (inbound.MailPassResult, error) {
if delivery.Status() == domain.DeliveryStatusUnknown {
if err := sender.releaseUnsentReservation(ctx, unit, claim); err != nil {
return inbound.MailPassResult{}, err
}
stopped, err := sender.stopAutomaticRetry(ctx, unit, delivery, now)
return stopped.result, err
}
if claim.sendStartUnsettled {
inDoubt, err := sender.recordInDoubt(ctx, unit, delivery, now)
return inDoubt.result, err
}
if claim.requireDedupWindow && claim.firstSendStarted {
if err := sender.releaseUnsentReservation(ctx, unit, claim); err != nil {
return inbound.MailPassResult{}, err
}
stopped, err := sender.stopAutomaticRetry(ctx, unit, delivery, now)
return stopped.result, err
}
if claim.firstSendStarted {
inDoubt, err := sender.recordInDoubt(ctx, unit, delivery, now)
return inDoubt.result, err
}
return resultOf(inbound.MailPassLeaseLost, delivery), 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 claimed.ManualRetryCycleStarted && claimed.SendStartUnsettled {
// A manually authorized send started but its result was not recorded.
// Do not spend that authorization on another provider call.
return sender.recordInDoubt(ctx, unit, delivery, now)
}
if sender.retryBeyondDeduplication(claimed) {
if claimed.SendStartUnsettled {
return sender.recordInDoubt(ctx, unit, delivery, now)
}
return sender.stopAutomaticRetry(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 sender.waitForQuota(ctx, unit, delivery, decision, now)
}
return claimedSend{
delivery: decision.Delivery,
permit: decision.Permit,
firstSendStarted: claimed.FirstSendStarted,
sinceFirstSend: claimed.SinceFirstSend,
manualRetryPending: claimed.ManualRetryPending,
manualRetryCycleStarted: claimed.ManualRetryCycleStarted,
sendStartUnsettled: claimed.SendStartUnsettled,
requireDedupWindow: sender.requiresDedupWindow(claimed),
}, nil
}
func (sender *ServiceMailSender) waitForQuota(
ctx context.Context,
unit outbound.UnitOfWork,
delivery domain.Delivery,
decision SendDecision,
now time.Time,
) (claimedSend, error) {
if delivery.Status() != domain.DeliveryStatusUnknown || decision.ResetAt.IsZero() {
return claimedSend{decided: true, result: resultOf(inbound.MailPassWaitingQuota, decision.Delivery)}, nil
}
at := latest(now, delivery.UpdatedAt())
deferred, err := delivery.ScheduleUnknownRetry(at, latest(decision.ResetAt, at))
if err != nil {
return claimedSend{}, fmt.Errorf("schedule uncertain quota retry: %w", err)
}
if err := unit.Deliveries().ScheduleUnknownRetry(ctx, sender.owner, deferred); err != nil {
return claimedSend{}, fmt.Errorf("store uncertain quota retry: %w", err)
}
return claimedSend{decided: true, result: resultOf(inbound.MailPassUnknown, deferred)}, 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) requiresDedupWindow(claimed outbound.ClaimedDelivery) bool {
if claimed.SendStartUnsettled {
return true
}
if claimed.ManualRetryPending {
return false
}
if claimed.Delivery.Status() == domain.DeliveryStatusUnknown {
return true
}
return claimed.HasUncertainAttempt && !claimed.ManualRetryCycleStarted
}
func (sender *ServiceMailSender) retryBeyondDeduplication(claimed outbound.ClaimedDelivery) bool {
if !sender.requiresDedupWindow(claimed) {
return false
}
if !claimed.FirstSendStarted {
return true
}
return claimed.SinceFirstSend >= sender.safeRetryWindow()
}
func (sender *ServiceMailSender) safeRetryWindow() time.Duration {
return max(sender.gate.IdempotencyWindow()-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) stopAutomaticRetry(
ctx context.Context,
unit outbound.UnitOfWork,
delivery domain.Delivery,
now time.Time,
) (claimedSend, error) {
next, err := delivery.StopAutomaticRetry(latest(now, delivery.UpdatedAt()))
if err != nil {
return claimedSend{}, fmt.Errorf("stop automatic retry: %w", err)
}
if err := unit.Deliveries().StopUnknownRetry(ctx, sender.owner, next); err != nil {
return claimedSend{}, fmt.Errorf("store stopped retry: %w", err)
}
sender.logger.WarnContext(ctx, "automatic retries stopped before the provider deduplication cutoff; the delivery remains unknown for an operator decision",
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) releaseUnsentReservation(ctx context.Context, unit outbound.UnitOfWork, claim claimedSend) error {
if claim.permit.IsZero() || claim.permit.Reused() {
return nil
}
if _, err := sender.gate.SettleSend(ctx, unit, claim.permit, outbound.SendResult{}, errNotSent); err != nil {
return fmt.Errorf("release unused reservation: %w", err)
}
return 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())
manualRetry := claim.manualRetryPending || claim.manualRetryCycleStarted
next, attempt, err := delivery.RecordAttempt(sender.attemptInput(delivery, result, at, until, manualRetry))
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, manualRetry bool) 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)
case result.Outcome == outbound.MailOutcomeUnknown && !manualRetry && sender.gate.IdempotencyWindow() > 0:
input.NextAttemptAt = sender.settings.Retry.NextAttemptAt(at, delivery.AttemptCount()+1, result.RetryAfter)
}
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
}
return newDeliverySender(deliveryLane{
scope: outbound.ClaimScopeService,
kinds: domain.ServiceMailKinds(),
eligibility: serviceEligibility{},
}, transactor, sender, gate, settings, clock, logger)
}
+3
View File
@@ -220,6 +220,9 @@ services:
# resend and refuses to start smtp without stated limits.
EMAIL_QUOTA_DAILY: ${EMAIL_QUOTA_DAILY:-}
EMAIL_QUOTA_MONTHLY: ${EMAIL_QUOTA_MONTHLY:-}
# Empty means a fifth of the matching quota limit (see .env.example).
EMAIL_SERVICE_RESERVE_DAILY: ${EMAIL_SERVICE_RESERVE_DAILY:-}
EMAIL_SERVICE_RESERVE_MONTHLY: ${EMAIL_SERVICE_RESERVE_MONTHLY:-}
APP_PUBLIC_URL: ${APP_PUBLIC_URL:?Set APP_PUBLIC_URL in the root .env file}
RESEND_API_KEY: ${RESEND_API_KEY:-}
SMTP_HOST: ${SMTP_HOST:-}
+37 -15
View File
@@ -196,7 +196,7 @@ Metrics: `lincodex_scheduled_jobs_total{kind,outcome}` counts claimed jobs by `d
### Mail transport
Implemented: the outbound `MailSender` port (`backend/internal/port/outbound/mail.go`), the `disabled` transport (`adapter/secondary/mail/disabled/`), the Resend transport (`adapter/secondary/mail/resend/`, the primary provider for the working stand), and the transport selection in bootstrap. Usecases, templates, and domain events depend only on the port; `EMAIL_PROVIDER` selects exactly one transport (`resend`, `smtp`, or `disabled`), and bootstrap binds the port to it before migrations run. There is no fallback between transports: an unusable selection stops startup. Planned: an SMTP relay transport (`mail/smtp/`, outside the MVP); until it exists, `smtp` fails startup after its settings are validated. The only caller is the sending worker for service identity mail (see [Sending service mail](#sending-service-mail)); product notifications are stored as deliveries but not sent until product notification sending is implemented. Settings are described in [DEPLOY.md](DEPLOY.md#mail).
Implemented: the outbound `MailSender` port (`backend/internal/port/outbound/mail.go`), the `disabled` transport (`adapter/secondary/mail/disabled/`), the Resend transport (`adapter/secondary/mail/resend/`, the primary provider for the working stand), and the transport selection in bootstrap. Usecases, templates, and domain events depend only on the port; `EMAIL_PROVIDER` selects exactly one transport (`resend`, `smtp`, or `disabled`), and bootstrap binds the port to it before migrations run. There is no fallback between transports: an unusable selection stops startup. Planned: an SMTP relay transport (`mail/smtp/`, outside the MVP); until it exists, `smtp` fails startup after its settings are validated. The callers are the sending workers: the service worker for identity mail (see [Sending service mail](#sending-service-mail)) and the notification worker (see [Sending product notifications](#sending-product-notifications)). Settings are described in [DEPLOY.md](DEPLOY.md#mail).
`Send(ctx, OutgoingMail)` makes exactly one attempt. `OutgoingMail` carries the recipient, subject, text and HTML bodies, and an idempotency key that stays the same for one logical delivery across retries (1 to 256 printable ASCII characters, the Resend limit, without personal data); the sender comes from `EMAIL_FROM`. With a nil error the result is one of:
@@ -234,7 +234,7 @@ Every `rejected` or `unknown` answer with a known error name sets `ProviderCode`
### Mail deliveries
Implemented: the `domain.Delivery` aggregate, `domain.MailContent`, and `domain.MailRequest` (`backend/internal/domain/delivery.go`, `mail_content.go`, `mail_request.go`), the `outbound.DeliveryRepository` and `outbound.MailRequestRepository` ports (`port/outbound/delivery.go`) through `UnitOfWork.Deliveries()`, `UnitOfWork.MailRequests()`, and `postgres.DeliveryStore`, migration `00006_create_deliveries.sql` with the `mail_requests`, `deliveries`, and `delivery_attempts` tables, the queries in `backend/db/queries/delivery.sql`, and in `backend/internal/usecase/notification/` the request usecase `MailRequester` and the consumer `DeliveryHandler`. The quota gate that admits or defers a send is implemented; see [Mail quotas](#mail-quotas). Implemented: the service-mail worker, bounded retries, the unknown-outcome cutoff, and the audited local operator command, with migrations `00012_add_delivery_sending.sql` and `00017_retry_unknown_mail.sql`; see [Sending service mail](#sending-service-mail). Sending product notifications with the permission check before a send is not implemented. The delivery state gauges are implemented; see [Metrics, telemetry, and alerts](#metrics-telemetry-and-alerts). Product flows do not call `MailRequester` yet, so notification requests remain queued. Registration and resend create verification mail through `ServiceMailer`; password reset is not implemented.
Implemented: the `domain.Delivery` aggregate, `domain.MailContent`, and `domain.MailRequest` (`backend/internal/domain/delivery.go`, `mail_content.go`, `mail_request.go`), the `outbound.DeliveryRepository` and `outbound.MailRequestRepository` ports (`port/outbound/delivery.go`) through `UnitOfWork.Deliveries()`, `UnitOfWork.MailRequests()`, and `postgres.DeliveryStore`, migration `00006_create_deliveries.sql` with the `mail_requests`, `deliveries`, and `delivery_attempts` tables, the queries in `backend/db/queries/delivery.sql`, and in `backend/internal/usecase/notification/` the request usecase `MailRequester` and the consumer `DeliveryHandler`. The quota gate that admits or defers a send is implemented; see [Mail quotas](#mail-quotas). Implemented: the service-mail worker, bounded retries, the unknown-outcome cutoff, and the audited local operator command, with migrations `00012_add_delivery_sending.sql` and `00017_retry_unknown_mail.sql`; see [Sending service mail](#sending-service-mail). Sending product notifications, with the rights check before each send, is implemented; see [Sending product notifications](#sending-product-notifications). The delivery state gauges are implemented; see [Metrics, telemetry, and alerts](#metrics-telemetry-and-alerts). The invitation send is the first product caller of `MailRequester`. Registration and resend create verification mail through `ServiceMailer`; password reset is not implemented.
A delivery is the durable state of sending one message to one recipient. A `deliveries` row holds:
@@ -247,7 +247,7 @@ A delivery is the durable state of sending one message to one recipient. A `deli
Creation path:
1. A usecase calls `MailRequester.RequestNotification(ctx, unit, request)` inside its own transaction with the recipient account ID and the notification data. The usecase checks the data with the current template, so a bad request fails its own transaction instead of becoming a dead letter, and assigns a UUIDv7 request ID. In the caller's transaction it inserts a `mail_requests` row with that ID, the recipient, the kind, the raw subject, body, and link path, and the request time, and appends `notification.mail_requested` with schema version 1: aggregate type `mail_request`, aggregate ID equal to the request ID, aggregate version 1, and the payload `{"mail_request_id": <id>, "kind": "notification"}` and nothing else.
1. A usecase calls `MailRequester.RequestNotification(ctx, unit, request)` inside its own transaction with the recipient account ID and the notification data. The usecase checks the data with the current template, so a bad request fails its own transaction instead of becoming a dead letter, and assigns a UUIDv7 request ID. In the caller's transaction it inserts a `mail_requests` row with that ID, the recipient, the kind, the raw subject, body, and link path, the subject the notice concerns (for an invitation, the invitation and its organization), and the request time, and appends `notification.mail_requested` with schema version 1: aggregate type `mail_request`, aggregate ID equal to the request ID, aggregate version 1, and the payload `{"mail_request_id": <id>, "kind": "notification"}` and nothing else.
2. The relay publishes the event, and the consumer `notification_delivery` applies it in the transaction of its dedup marker. It checks the envelope and that `mail_request_id` equals the aggregate ID, refuses trailing data after the payload object, and locks the request row (`FOR UPDATE`). It reads the account, renders the notification once with the current template version, inserts the delivery under the request ID with `source_event_id` set, and deletes the request row, all in that transaction.
3. A redelivered event is a `duplicate` of the consumer marker. A replay under another consumer name, a replayed dead letter after success, or a concurrent second consumer finds the request row gone (the second consumer waits on its lock) and skips. When an insert finds a delivery under the request ID already, the handler accepts it only for the same recipient and kind, and rejects the event otherwise.
4. Skips: a request that no longer exists, because it was handled or its account was deleted, and a notification to an account whose address is not verified (`email_verified_at` NULL). The unverified case deletes the request; notifications go only to confirmed addresses. Skips are logged at info level with the delivery and event IDs only. An unknown schema version, a payload that breaks the contract, or text that the template refuses is rejected for good and becomes a `handler_rejected` dead letter; storage errors are retried. An account deleted after the handler read it makes the insert fail on the foreign key; the transaction is aborted, so the error is retried, and the retry finds the request deleted with the account and skips.
@@ -273,14 +273,14 @@ Statuses. The values follow the `MailSender` outcomes:
| `accepted` | The provider accepted the message and returned `provider_message_id`: "accepted by the provider". Not delivery to or reading by a person; no status claims that | None; terminal |
| `rejected` | A `permanent` or `invalid_request` rejection; the cause must be fixed | None; terminal |
| `unknown` | The attempt may have reached the provider (`delivery_uncertain`). Never "not sent": an eligible automatic or operator-approved retry uses the pinned key and stored body | Optional; none means operator review is required |
| `cancelled` | The message was deliberately not sent and never will be: the token or the account no longer matches, or the stored message is unsendable. `cancel_reason` says why; no attempt is recorded | None; terminal |
| `cancelled` | The message was deliberately not sent and never will be: the token or the account no longer matches, a notification's rights no longer hold, or the stored message is unsendable. `cancel_reason` says why; no attempt is recorded | None; terminal |
| `waiting_quota` | A provider quota or the local quota is used up | Optional: the expected reset (see [Mail quotas](#mail-quotas)); none when the reset is unknown, for example after a provider quota answer that names neither a window nor a wait, and an operator decides |
Transitions:
- `Delivery.RecordAttempt` takes the result of one transport attempt and appends an attempt row. `pending`, `waiting_quota`, and `unknown` accept an attempt: `accepted` gives `accepted`, a `permanent` or `invalid_request` rejection gives `rejected`, `temporary` or `rate_limited` gives `pending`, `quota_exhausted` gives `waiting_quota`, and `unknown` gives `unknown`. `accepted`, `rejected`, and `cancelled` refuse any further attempt with `domain.ErrDeliveryTransition`.
- `Delivery.WaitForQuota(at, until)` parks a `pending` or `waiting_quota` delivery in `waiting_quota` without an attempt, for the case where the local mail quota defers a send before the transport is called; a zero `until` means the reset is unknown. It refuses `unknown`, whose earlier attempt may have been accepted and whose retry belongs to the retry policy, and the terminal statuses. `DeliveryRepository.WaitForQuota` stores it.
- `Delivery.Cancel(at, reason)` ends a `pending` or `waiting_quota` delivery in `cancelled` without an attempt; the reason is one of `token_missing`, `token_purpose_mismatch`, `token_owner_mismatch`, `token_consumed`, `token_revoked`, `token_expired`, `account_not_current`, `recipient_mismatch`, `content_invalid`, or `processing_failed`. It refuses `unknown`, like `WaitForQuota`: an earlier attempt may have been accepted, so it is never reported as not sent. `DeliveryRepository.Cancel` stores it.
- `Delivery.Cancel(at, reason)` ends a `pending` or `waiting_quota` delivery in `cancelled` without an attempt; the reason is one of `token_missing`, `token_purpose_mismatch`, `token_owner_mismatch`, `token_consumed`, `token_revoked`, `token_expired`, `account_not_current`, `recipient_mismatch`, `content_invalid`, `processing_failed`, `rights_revoked`, `recipient_ineligible`, or `source_closed`. It refuses `unknown`, like `WaitForQuota`: an earlier attempt may have been accepted, so it is never reported as not sent. `DeliveryRepository.Cancel` stores it.
- `Delivery.Rebind(at, account)` moves a delivery that has no attempt yet to another provider account; see below. `DeliveryRepository.Rebind` stores it.
Every change advances `version`, and the store applies it only over the previous version. The next attempt time comes from the caller's retry policy and must fit the target status; the CHECK `deliveries_next_attempt_matches_status` repeats the rule, and `deliveries_provider_message_id_when_accepted` requires the provider ID exactly for `accepted`.
@@ -293,11 +293,11 @@ Provider account. Each delivery is pinned to the transport and account configure
Migration `00012_add_delivery_sending.sql` is additive; existing rows stay valid. It adds to `deliveries`: `email_token_id` (a nullable foreign key to `email_tokens.id` for token mail, immutable like the rest of the content, NULL for notifications), `cancel_reason` (set exactly when the status is `cancelled`, CHECK-limited to the reasons above), the lease columns `claim_owner` and `claimed_until` (both or neither; only a delivery the worker may still send holds one), `first_send_started_at` (when the first request started, by the database clock), `failure_count` (consecutive failures of the worker on the row), `body_redacted_at` (the bodies of a token mail were cleared), the status `cancelled` with its CHECKs, and two partial indexes: `deliveries_due_idx` on `(next_attempt_at, id)` whose predicate names the service kinds and the statuses that are picked up again, so notification rows never enter it and an idle poll does not scan them, and one on `email_token_id`. The trigger `deliveries_refuse_content_change` also allows exactly one change of the bodies: a terminal token mail may have both set to empty together with `body_redacted_at`, once. It adds the `password_reset` token purpose to `email_tokens`. The down migration turns cancelled deliveries into rejected ones and deletes reset tokens. Planned: a cancelled delivery for a revoked permission.
The store provides `Get`, `ListAttempts`, the version-checked `RecordAttempt`, `WaitForQuota`, `Cancel`, and `Rebind`, and for the sending worker `ClaimDue`, `ReleaseClaim`, and `ServiceMailState`. Migration `00017_retry_unknown_mail.sql` adds the manual-cycle markers, the append-only decision journal, and `unknown` to the due index predicate. It drops and recreates the partial due index, which takes a table lock while it rebuilds. Rolling this migration back drops the decision journal and its audit data; preserve an export first if rollback is required.
The store provides `Get`, `ListAttempts`, the version-checked `RecordAttempt`, `WaitForQuota`, `Cancel`, and `Rebind`, and for the sending workers `ClaimDue` (one statement per lane, selected by `ClaimScope`), `ReleaseClaim`, and `ServiceMailState`. The notification rights reader is `UnitOfWork.NotificationRights()`. Migrations `00044_add_notification_subject.sql` and `00045_send_product_notifications.sql` add the subject columns, the product due index `deliveries_product_due_idx`, and the cancel reasons of the rights checks. Migration `00017_retry_unknown_mail.sql` adds the manual-cycle markers, the append-only decision journal, and `unknown` to the due index predicate. It drops and recreates the partial due index, which takes a table lock while it rebuilds. Rolling this migration back drops the decision journal and its audit data; preserve an export first if rollback is required.
### Mail quotas
Implemented: quota windows and limits in `backend/internal/domain/mail_quota.go`; the `outbound.MailQuotaRepository` port (`port/outbound/mail_quota.go`), whose writes go through `UnitOfWork.MailQuotas()` and whose reads also go through `postgres.MailQuotaStore`; migration `00007_create_mail_quota_usage.sql` with the `mail_quota_usage` and `mail_quota_reservations` tables; the queries in `backend/db/queries/mail_quota.sql`; in `backend/internal/usecase/notification/`, `QuotaGate` with `PrepareSend` and `SettleSend` (`quota.go`), the startup report `ReportQuotaUsage`, and the user status reader `DeliveryStatusReader` (`delivery_status.go`); `SendResult.QuotaPeriod` in the mail port, filled by the Resend adapter; and the startup report in bootstrap (`bootstrap/mail_quota.go`). The sending worker calls the gate around `MailSender.Send` and `bootstrap/mail_sender.go` builds it from configuration with `resend.IdempotencyWindow` or zero for SMTP; see [Sending service mail](#sending-service-mail). Planned: the API or identity flow that shows the status reader's result. Only service identity mail counts against the quota until product notification sending is implemented.
Implemented: quota windows and limits in `backend/internal/domain/mail_quota.go`; the `outbound.MailQuotaRepository` port (`port/outbound/mail_quota.go`), whose writes go through `UnitOfWork.MailQuotas()` and whose reads also go through `postgres.MailQuotaStore`; migration `00007_create_mail_quota_usage.sql` with the `mail_quota_usage` and `mail_quota_reservations` tables; the queries in `backend/db/queries/mail_quota.sql`; in `backend/internal/usecase/notification/`, `QuotaGate` with `PrepareSend` and `SettleSend` (`quota.go`), the startup report `ReportQuotaUsage`, and the user status reader `DeliveryStatusReader` (`delivery_status.go`); `SendResult.QuotaPeriod` in the mail port, filled by the Resend adapter; and the startup report in bootstrap (`bootstrap/mail_quota.go`). The sending worker calls the gate around `MailSender.Send` and `bootstrap/mail_sender.go` builds it from configuration with `resend.IdempotencyWindow` or zero for SMTP; see [Sending service mail](#sending-service-mail). Planned: the API or identity flow that shows the status reader's result. Both lanes count against the quota: a product notification is admitted only while the windows keep the service reserve free (see [Sending product notifications](#sending-product-notifications)).
Limits. `EMAIL_QUOTA_DAILY` and `EMAIL_QUOTA_MONTHLY` limit the recipients sent through the configured provider account (`EMAIL_PROVIDER` and `EMAIL_ACCOUNT`) per UTC day, from 00:00 to 00:00 UTC, and per UTC calendar month. Every recipient counts, as Resend counts them; a delivery has one recipient. The defaults are the Resend Free limits checked on 2026-10-05, 100 and 3000; they apply to `resend` and to `disabled`, which sends nothing. `smtp` has no default and does not start without both values, because a relay's limits are not Resend's. Values range from 1 to 1000000000, and the daily limit must not exceed the monthly one. No value turns the quota off, so no provider runs without the gate. Limits are configuration, not domain constants, and are not stored: a changed limit applies from the next reservation, and a limit lowered below the current usage defers every new send until the window resets.
@@ -342,9 +342,9 @@ Operators read the same rows with the queries in [DEPLOY.md](DEPLOY.md#mail-quot
### Sending service mail
Implemented: the sending usecase `ServiceMailSender` (`backend/internal/usecase/notification/service_sender.go`), the enqueue usecase `ServiceMailer` (`service_mail.go`), the retry schedule `RetryPolicy` (`send_retry.go`), bounded retries of unknown Resend outcomes, audited operator decisions through `DeliveryRetryOperator`, and the local command `backend/cmd/mail-retry/`. `Delivery.CheckServiceMail` and `Delivery.Cancel` hold the cancel reasons (`backend/internal/domain/delivery.go`, `delivery_guard.go`), the loop is in `backend/internal/worker/mailsender/`, and the inbound port is `inbound.MailPass` (`port/inbound/mail_sender.go`). The repository and migrations `00012_add_delivery_sending.sql` and `00017_retry_unknown_mail.sql` store attempts, leases, retry cutoffs, and operator decisions. Registration queues a verification email, and `ConfirmEmail` consumes its link. Product notification sending and the password reset flow are not implemented.
Implemented: the sending usecase `ServiceMailSender` (`backend/internal/usecase/notification/service_sender.go`), the enqueue usecase `ServiceMailer` (`service_mail.go`), the retry schedule `RetryPolicy` (`send_retry.go`), bounded retries of unknown Resend outcomes, audited operator decisions through `DeliveryRetryOperator`, and the local command `backend/cmd/mail-retry/`. `Delivery.CheckServiceMail` and `Delivery.Cancel` hold the cancel reasons (`backend/internal/domain/delivery.go`, `delivery_guard.go`), the loop is in `backend/internal/worker/mailsender/`, and the inbound port is `inbound.MailPass` (`port/inbound/mail_sender.go`). The repository and migrations `00012_add_delivery_sending.sql` and `00017_retry_unknown_mail.sql` store attempts, leases, retry cutoffs, and operator decisions. Registration queues a verification email, and `ConfirmEmail` consumes its link. The password reset flow is not implemented.
Scope. The worker claims only the kinds `verification` and `password_reset`. A product notification is never claimed here, whatever its state. Service mail needs no consent record of any purpose: it is part of the account flow, so nothing reads the consent ledger, and C2 (publication of the candidate card) and the other product consents play no part. What stands between the account and the mail is the check below, not a consent.
Scope. The service worker claims only the kinds `verification` and `password_reset`. A product notification is never claimed here, whatever its state; the notification lane is described in [Sending product notifications](#sending-product-notifications). Service mail needs no consent record of any purpose: it is part of the account flow, so nothing reads the consent ledger, and C2 (publication of the candidate card) and the other product consents play no part. What stands between the account and the mail is the check below, not a consent.
Enqueue. `ServiceMailer.EnqueueVerification` and `EnqueuePasswordReset` run in the transaction that inserts the token, with the token record, the raw token, the recipient address, and the lifetime in hours. They check that the token purpose fits the message, render the message once with the current template version, and store a `pending` delivery bound to the token (`email_token_id`) under the token's ID as the delivery ID. A repeated call for the same token stores nothing new, and the stored body stays as it was.
@@ -408,7 +408,29 @@ Test fixture only. `resendfixture` and `resend.NewLoopbackSender` are never used
Tests. `integration_test/mail_sender_test.go` runs a local Resend fixture (`resendfixture`, an `httptest` server speaking the part of the API the transport uses, reached through `resend.NewLoopbackSender`, which accepts only a loopback endpoint) against PostgreSQL; see [TESTING.md](TESTING.md). It is a test fixture only; production binds the real Resend transport with its fixed endpoint.
Open points. Sending product notifications and the permission check they need are planned; until then notifications wait, and they are not counted in the overdue gauge, so a notification backlog does not fire `LincodexMailDeliveriesOverdue` (the gauge `lincodex_mail_delivery_oldest_due_pending_age_seconds` covers `domain.ServiceMailKinds`; its predicate is the one of `deliveries_due_idx`). Whether a password reset goes to unverified accounts is for the reset flow to decide. The poll runs every 5 seconds and the claim reads one indexed statement, which suits the current volume.
Open points. Notifications are not counted in the overdue gauge, so a notification backlog does not fire `LincodexMailDeliveriesOverdue` (the gauge `lincodex_mail_delivery_oldest_due_pending_age_seconds` covers `domain.ServiceMailKinds`; its predicate is the one of `deliveries_due_idx`); the notification lane has no overdue alert yet. Whether a password reset goes to unverified accounts is for the reset flow to decide. The poll runs every 5 seconds and the claim reads one indexed statement, which suits the current volume.
### Sending product notifications
Implemented: the notification lane of the sending loop. `usecase/notification.NewNotificationSender` (`notification_sender.go`) builds a `DeliverySender` (`delivery_sender.go`) for the notification kind. It claims with `ClaimDueProductDelivery` through the partial index `deliveries_product_due_idx` and uses the same transport, quota gate, and settlement as the service lane. A `SubjectRights` implementation decides, per subject kind, whether a notice may still go out. The invitation notice is `invitationNoticeRights` (`invitation_rights.go`), and its rule is `Delivery.CheckInvitationNotice` (`backend/internal/domain/invitation_notice.go`). `bootstrap/notification_sender.go` builds the loop with the service timing and `EMAIL_PROVIDER`.
Subject. A notification names the record whose rights it depends on: `domain.MailSubject`, stored with the request and copied to the delivery. The invitation send names the invitation and its organization. The subject is fixed with the delivery, and the content trigger refuses to change it (migration `00044_add_notification_subject.sql`).
Rights check. Before the transport is called, the lane's eligibility runs twice: once in the claim transaction, and again in the check transaction that holds the delivery lock, so a change after the claim is honored. The invitation rule checks, in this order: the recipient account exists and its address is verified; the address of the delivery is still the address of the account; the invitation exists in the organization of the subject; the invitation still awaits an answer (delivered or viewed) and its response deadline has not passed; the candidate has not hidden the organization; and the candidate's publication (C2) is current. The notice declares no allowed fields: its body is fixed text that names neither the organization nor the terms, and it carries no contact, so no field consent (C4) applies. The content was rendered once when the request was handled, so the check is the only work before the transport call. Like the check of service mail, the rights read is a snapshot taken in the sending transaction.
Contacts. Mail never carries a contact. Contact reads are pull-only, and each read re-checks the consent and the grant, so a contact copied into mail would outlive its grant. A future notice that carries a candidate field or a contact adds its consent check to `SubjectRights` before it can be sent.
Cancel reasons. A failed check cancels the delivery with no attempt, no provider call, and no change of the provider account, and clears its bodies (`deliveries_body_present` allows the clearing of a cancelled notification). `rights_revoked` covers a hidden organization, a withdrawn publication, and an invitation that was answered, expired, or passed its deadline. `recipient_ineligible` covers a missing account or an unverified address, and `recipient_mismatch` a changed address. `source_closed` covers a notice that names no subject, or an invitation that no longer exists. A subject kind that this build cannot check is neither sent nor cancelled: the claim returns `ErrNoSubjectRights` and the row waits for a build that can check it. None of these reasons counts as a broken cancellation for `LincodexMailCancelledBroken`.
Reserve. The notification lane's quota gate admits a send only while, after it, each window keeps at least `EMAIL_SERVICE_RESERVE_DAILY` and `EMAIL_SERVICE_RESERVE_MONTHLY` recipients free (`QuotaGate.WithReserve`). The defaults are a fifth of each quota limit: 20 a day and 600 a month on the Resend Free plan. The service lane keeps the full limits, so service mail always has its share of the same windows. A notification that the reserve refuses is parked in `waiting_quota` until the reset, and an idle pass does not claim it again, so the loop does not spin. A provider answer that its quota is used up marks the full window, not the reserve.
Retention. Every due notice is checked when it is claimed, including one whose invitation ended long ago, so no cancellable row stays due. A cancelled notice loses its bodies. An accepted notice keeps its neutral body, which is an open point.
Loop and disabled transport. The loop has its own gauge, `lincodex_notification_sender_running`, and its cancellations count in `lincodex_mail_sender_cancelled_total` by reason. With `EMAIL_PROVIDER=disabled` or without a database no loop starts, and a stored notice waits pinned to the transport it was created under, as service mail does. Once a transport runs, the loop rebinds the notice and sends it, if its rights still hold.
Privacy. Logs name a notice only by its delivery ID, kind, and closed values (the outcome and the cancel reason). The subject, the address, the candidate, and the body never appear in a log line, an error, or a metric label.
Open points. The invitation notice requires the candidate's publication, so a withdrawn publication cancels a pending notice; the product owner should confirm that choice. Accepted notices keep their neutral bodies, and no retention rule clears them yet. The notification lane has no overdue alert; the `lincodex_mail_deliveries{kind="notification",status="pending"}` gauge shows its backlog.
### Internal notifications
@@ -541,7 +563,7 @@ backend/
usecase/policy/ publication of policy versions and the demo policy seed
usecase/consent/ granting of consents C1-C3 and C5 and the scoped C4 with the current-text check
usecase/files/ shared private file layer: policies, opaque keys, stream limits, checksums
usecase/notification/ mail requests and the consumer that stores them as deliveries, the quota gate, the service mail enqueue (`ServiceMailer`), and the sender of service mail (`ServiceMailSender`)
usecase/notification/ mail requests and the consumer that stores them as deliveries, the quota gate, the service mail enqueue (`ServiceMailer`), the senders of service mail (`ServiceMailSender`) and of product notifications (`NewNotificationSender`), and their rights checks
usecase/notification/mailtemplate/ pure rendering of versioned service emails; the delivery consumer renders notifications with it
port/outbound/ readiness, cache, object storage, transaction, outbox, outbox relay, event publishing, event consumption, identity, consent ledger, organization and membership, policy, password hashing, and mail boundaries
adapter/primary/http/
@@ -566,7 +588,7 @@ backend/
worker/outboxrelay/ outbox relay loop: claim, publish, mark, backoff, and shutdown
worker/eventconsumer/ event consumer runtime: dedup transaction, retries, dead letters, offset commits, and shutdown
worker/jobrunner/ scheduled job runtime: claim under a lease, run with the completion, retries, release, and shutdown
worker/mailsender/ sending loop of service identity mail: repeats passes, waits when idle, backs off on failures, reports lincodex_mail_sender_running
worker/mailsender/ sending loop of the mail lanes (service identity mail and product notifications): repeats passes, waits when idle, backs off on failures, reports its running gauge
worker/retry/ backoff with jitter and a context-aware wait shared by the workers
worker/deliverymetrics/ periodic read of the delivery and mail quota aggregates into the metrics
bootstrap/ configuration, wiring, lifecycle, shutdown
@@ -579,7 +601,7 @@ Domain types live directly in `backend/internal/domain/`: `user.go`, `candidate.
Outside the implemented identity and consent flows, domain types and usecases for other product workflows are not implemented. SMTP and FSP adapters, and product worker jobs, remain planned. `main.go` starts bootstrap and handles process errors. The public generated transport uses ogen v1.24.0 and the contracts declare OpenAPI 3.2.0. Verify only the feature subset used by the repository, not every specification feature.
This is a compact map, not a claim that every planned product package exists. Current Go code includes health usecases and adapters, generated API clients, bootstrap with startup migrations, a PostgreSQL health query, the transactional outbox writer, the outbox relay that publishes committed events to Kafka through the franz-go adapter, the event consumer runtime with the `notification_delivery` and `notification_inbox` handlers, the internal notification inbox with its list and read-state operations, the scheduled job runtime (`worker/jobrunner`) with no registered product job kind, identity usecases for registration, resend, confirmation, and login, PostgreSQL sessions and a security boundary for every operation protected by the API contract, the consent usecase that records C1 during registration, the versioned policy store with its publisher and the demo policy seed at startup, the `PasswordHasher` port with the Argon2id adapter and checks used by registration, confirmation, and login, a Redis cache adapter, a SeaweedFS S3 adapter with the shared private file layer over it, the `MailSender` port with the `disabled` and Resend transports, the mail template renderer, and the identity mail worker used for registration and resend. Profiles, resumes, assessments, invitations, product job kinds, file workflows, sending product notifications, the SMTP transport, and FSP adapters remain planned. Do not create empty module directories before a real use case exists.
This is a compact map, not a claim that every planned product package exists. Current Go code includes health usecases and adapters, generated API clients, bootstrap with startup migrations, a PostgreSQL health query, the transactional outbox writer, the outbox relay that publishes committed events to Kafka through the franz-go adapter, the event consumer runtime with the `notification_delivery` and `notification_inbox` handlers, the internal notification inbox with its list and read-state operations, the scheduled job runtime (`worker/jobrunner`) with no registered product job kind, identity usecases for registration, resend, confirmation, and login, PostgreSQL sessions and a security boundary for every operation protected by the API contract, the consent usecase that records C1 during registration, the versioned policy store with its publisher and the demo policy seed at startup, the `PasswordHasher` port with the Argon2id adapter and checks used by registration, confirmation, and login, a Redis cache adapter, a SeaweedFS S3 adapter with the shared private file layer over it, the `MailSender` port with the `disabled` and Resend transports, the mail template renderer, and the identity mail worker used for registration and resend. Profiles, resumes, assessments, invitations, product job kinds, file workflows, the SMTP transport, and FSP adapters remain planned. Do not create empty module directories before a real use case exists.
`backend/pkg/` is reserved for small technical packages with a justified shared boundary, not product usecases or domain types. `pkg/testutil/` holds `FakeClock`, a concurrency-safe manual clock that the worker, integration, and future usecase tests inject wherever production code takes a `func() time.Time` clock, and `FindPersonalIdentifiers`, which the metrics tests use to find email-like and UUID-like values in an exposition. A `mailer` package remains a candidate. Mail templates live in `internal/usecase/notification/mailtemplate/`: they hold product copy and use domain types such as `SecretToken`. It is a pure rendering package without I/O or logging. The delivery consumer in `internal/usecase/notification/` renders notifications with it; `ServiceMailer` creates verification mail during registration and resend. Password reset mail belongs to the planned reset flow. Templates, versions, and link format are described in [DEPLOY.md](DEPLOY.md#mail-templates). Keep the S3 client in the SeaweedFS adapter. Keep service-specific behavior private under `internal/`.
@@ -1106,7 +1128,7 @@ The Go service exports standard Go/process metrics and the product metrics on an
- API: `lincodex_http_requests_total{method,route,status}`, `lincodex_http_request_duration_seconds{method,route,status_class}`, and `lincodex_http_problems_total{route,code}`. `route` is the chi route template of an operational route and, under `/api/v1`, the OpenAPI path template of the matched operation, such as `/api/v1/me/invitations/{invitation_id}`, which the router resolves with the generated server's `FindPath`; a path or method without an operation keeps the mount pattern `/api/v1/*` or `/api/*`, and a path outside every route is `unmatched`. `status_class` is `1xx` to `5xx`. `code` is the RFC 9457 problem code: `problem.New` records it from the closed catalogue through the request-scoped `observe` package (`adapter/primary/http/observe/`), the middleware counts it only for a 4xx or 5xx response, and the adapter counts a code outside its mirrored list as `other`. An error without a problem body, such as `/readyz` 503, is counted by status only. The request log (`middleware.RequestLog`, which replaces the go-httpkit logger) uses the same route template and logs the request ID, method, status and class, problem code, latency, response size, and the number of query parameters, never the raw path, a query key or value, a header, the client address, or the user agent; `/healthz` and `/readyz` are not logged.
- Outbox and events: the relay, consumer, and scheduled job metrics in [Outbox relay](#outbox-relay), [Event consumers](#event-consumers), and [Scheduled jobs](#scheduled-jobs). Outbox lag is `lincodex_outbox_relay_oldest_pending_age_seconds`.
- Mail: `lincodex_mail_deliveries{kind,status}` for every kind and the statuses `pending`, `waiting_quota`, `unknown`, `accepted`, `rejected`, and `cancelled`, zero included; `lincodex_mail_sender_running`, 1 while this process's mail sending loop runs and 0 otherwise (per process, so aggregate it with `max`; it stays 0 with `EMAIL_PROVIDER=disabled`, where no loop starts); `lincodex_mail_delivery_oldest_due_pending_age_seconds`, which counts only service mail (`domain.ServiceMailKinds`), so a notification backlog never looks overdue; `lincodex_mail_sender_cancelled_total{reason}`, deliveries the sending worker ended without sending, by the closed set of cancel reasons, zero included; and, for an active transport, `lincodex_mail_quota_used_recipients`, `lincodex_mail_quota_limit_recipients`, and `lincodex_mail_quota_provider_exhausted`, each with `provider` and `window` (`day` or `month`). The sampler in `backend/internal/worker/deliverymetrics/` reads them every 30 seconds on its own one-connection pool: `postgres.DeliveryStatisticsStore` aggregates `deliveries` by kind and status, and `MailQuotaUsageReader.Usage` reads the current windows of the configured account. The delivery aggregate is the sqlc query `GetDeliveryStatistics` in `db/queries/delivery.sql`. It scans the table, which suits the current volume; add an index or per-status counters before the table holds millions of rows. `EMAIL_ACCOUNT` is not a label: it is free operator text that can name a person, and each process reports only its own account. Every instance reports the same database-wide values; aggregate them with `max`. A failed read keeps the previous values and logs `delivery metrics could not be read; the gauges are stale`; `lincodex_mail_metrics_last_success_timestamp_seconds` shows the last read in which every aggregate was read (0 from the sampler start until the first one), and the age gauge exists only after the first successful read. There is no attempt outcome counter yet; the delivery states, the logs of the sending worker, and the `delivery_attempts` history show outcomes.
- Mail: `lincodex_mail_deliveries{kind,status}` for every kind and the statuses `pending`, `waiting_quota`, `unknown`, `accepted`, `rejected`, and `cancelled`, zero included; `lincodex_mail_sender_running`, 1 while this process's mail sending loop runs and 0 otherwise (per process, so aggregate it with `max`; it stays 0 with `EMAIL_PROVIDER=disabled`, where no loop starts); `lincodex_notification_sender_running` reports the same for the notification loop; `lincodex_mail_delivery_oldest_due_pending_age_seconds`, which counts only service mail (`domain.ServiceMailKinds`), so a notification backlog never looks overdue; `lincodex_mail_sender_cancelled_total{reason}`, deliveries the sending worker ended without sending, by the closed set of cancel reasons, zero included; and, for an active transport, `lincodex_mail_quota_used_recipients`, `lincodex_mail_quota_limit_recipients`, and `lincodex_mail_quota_provider_exhausted`, each with `provider` and `window` (`day` or `month`). The sampler in `backend/internal/worker/deliverymetrics/` reads them every 30 seconds on its own one-connection pool: `postgres.DeliveryStatisticsStore` aggregates `deliveries` by kind and status, and `MailQuotaUsageReader.Usage` reads the current windows of the configured account. The delivery aggregate is the sqlc query `GetDeliveryStatistics` in `db/queries/delivery.sql`. It scans the table, which suits the current volume; add an index or per-status counters before the table holds millions of rows. `EMAIL_ACCOUNT` is not a label: it is free operator text that can name a person, and each process reports only its own account. Every instance reports the same database-wide values; aggregate them with `max`. A failed read keeps the previous values and logs `delivery metrics could not be read; the gauges are stale`; `lincodex_mail_metrics_last_success_timestamp_seconds` shows the last read in which every aggregate was read (0 from the sampler start until the first one), and the age gauge exists only after the first successful read. There is no attempt outcome counter yet; the delivery states, the logs of the sending worker, and the `delivery_attempts` history show outcomes.
- Assessment answers: `lincodex_assessment_answer_saves_total{format,outcome}` with the outcomes `stored`, `unchanged`, `rejected`, and `failed`. PRD 6.6 asks to observe the saving of answers; this is read as the assessment answer command `SubmitMyAssessmentAnswer`. The command is not implemented, so only the hook `Metrics.ObserveAssessmentAnswerSave` exists, and no series appears until the usecase calls it once per command. A value outside the closed sets becomes `other`. The HTTP latency and errors of the command already appear under the route `/api/v1/me/assessment-attempts/{attempt_id}/answers`.
Do not use user, candidate, delivery, or request IDs, full URLs or query strings, addresses, or resume content as labels. Unit tests drive the real router and every metric hook with email and UUID fixtures and fail when the exposition contains an email-like or UUID-like value. Go runtime, PostgreSQL, Redis, SeaweedFS, Linux, and Lincodex product dashboard JSON files are maintained project sources, not imported dashboard IDs. Inference metrics are not implemented in the current scaffold.
@@ -1115,7 +1137,7 @@ Planned observability work includes bounded measurements for queued jobs, oldest
The planned browser path is Faro Web SDK -> same-origin `/telemetry` -> Alloy `faro.receiver` -> Loki. The React SDK is not connected yet. Collect cleaned Web Vitals, JavaScript errors, release, and normalized route; exclude console logs, form content, resume text, and session replay. Remove query strings, fragments, and identifiers from URLs. Limit receiver size, rate, and origin. Request/trace IDs remain log fields, not labels; complete span storage needs a separate backend such as Tempo and is not currently supported.
Alert rules in `observability/prometheus/rules/lincodex.yml` cover an unavailable backend target, a 5xx share above 5% with at least 15 requests in 5 minutes, outbox lag, dead letters and stalled consumers, dead and lagging scheduled jobs, deliveries with an unknown outcome, stale delivery and quota gauges, a used-up mail quota, and overdue deliveries; the last one also requires `lincodex_mail_sender_running` to be 1 on some instance, so it stays silent where no sending loop runs, for example with `EMAIL_PROVIDER=disabled`. It counts only service mail, the kinds the worker sends, so a due notification does not fire it. `LincodexMailCancelledBroken` fires on an increase of `lincodex_mail_sender_cancelled_total` with the reason `content_invalid` or `processing_failed`, the cancellations that mean a broken row or a defect rather than a user action. `promtool test rules` gives every alert a firing case and every guard a silent one. Prometheus evaluates them and shows their state on its /alerts page and in Grafana; no Alertmanager or notification channel is configured, so no alert reaches a person. Future alerts cover latency budget breaches, disk pressure, ML errors, and dropped logs. Low traffic needs a window and minimum event count to avoid unstable rates and percentiles. Configure `No Data` and datasource-error behavior explicitly. A monitoring stack cannot reliably report a host failure on that same host; that requires an independent external health check. Compose and dashboard smoke checks do not verify alert delivery. Document alert rules and notification channels as implemented only after they have been tested.
Alert rules in `observability/prometheus/rules/lincodex.yml` cover an unavailable backend target, a 5xx share above 5% with at least 15 requests in 5 minutes, outbox lag, dead letters and stalled consumers, dead and lagging scheduled jobs, deliveries with an unknown outcome, stale delivery and quota gauges, a used-up mail quota, and overdue deliveries; the last one also requires `lincodex_mail_sender_running` to be 1 on some instance, so it stays silent where no sending loop runs, for example with `EMAIL_PROVIDER=disabled`. It counts only service mail, the kinds the worker sends, so a due notification does not fire it. `LincodexMailCancelledBroken` fires on an increase of `lincodex_mail_sender_cancelled_total` with the reason `content_invalid` or `processing_failed`, the cancellations that mean a broken row or a defect rather than a user action; the rights reasons of notifications (`rights_revoked`, `recipient_ineligible`, `source_closed`) are normal and do not fire it. `promtool test rules` gives every alert a firing case and every guard a silent one. Prometheus evaluates them and shows their state on its /alerts page and in Grafana; no Alertmanager or notification channel is configured, so no alert reaches a person. Future alerts cover latency budget breaches, disk pressure, ML errors, and dropped logs. Low traffic needs a window and minimum event count to avoid unstable rates and percentiles. Configure `No Data` and datasource-error behavior explicitly. A monitoring stack cannot reliably report a host failure on that same host; that requires an independent external health check. Compose and dashboard smoke checks do not verify alert delivery. Document alert rules and notification channels as implemented only after they have been tested.
## Requirements coverage
+6 -4
View File
@@ -361,6 +361,8 @@ Release compatibility: `ConfirmEmail` requires both `token` and the password sel
| `EMAIL_TIMEOUT` | `10s` | Go duration from `1s` to `1m`; limits one transport attempt |
| `EMAIL_QUOTA_DAILY` | `100` for `resend` and `disabled`; none for `smtp`, where it is required | Recipients per UTC day through the configured provider account: an integer from 1 to 1000000000. Empty counts as unset. No value turns the quota off. |
| `EMAIL_QUOTA_MONTHLY` | `3000` for `resend` and `disabled`; none for `smtp`, where it is required | Recipients per UTC calendar month: an integer from 1 to 1000000000, not below `EMAIL_QUOTA_DAILY`. Empty counts as unset. |
| `EMAIL_SERVICE_RESERVE_DAILY` | A fifth of `EMAIL_QUOTA_DAILY`, for example 20 on the Resend Free plan | Recipients per UTC day that product notifications leave free for service mail: an integer from 0 to below `EMAIL_QUOTA_DAILY`. Empty counts as unset. A notification is admitted only while the day keeps this many recipients free after it. |
| `EMAIL_SERVICE_RESERVE_MONTHLY` | A fifth of `EMAIL_QUOTA_MONTHLY`, for example 600 on the Resend Free plan | The same for the UTC calendar month: an integer from 0 to below `EMAIL_QUOTA_MONTHLY`. Empty counts as unset. |
| `APP_PUBLIC_URL` | none, required | Public origin for mail links and exact Origin checks on unsafe public identity and protected operations: `https://host[:port]`, or `http` only for `localhost`, `127.0.0.1`, or `[::1]`. No credentials, path, query, or fragment; one trailing `/` is dropped. |
| `RESEND_API_KEY` | empty | Read only for `resend`, where it is required. Printable ASCII without whitespace. The `re_` prefix shown in Resend examples is not enforced. |
| `SMTP_HOST` | empty | Read only for `smtp`, where it is required. Hostname or IP address without a port. |
@@ -368,13 +370,13 @@ Release compatibility: `ConfirmEmail` requires both `token` and the password sel
| `SMTP_USERNAME`, `SMTP_PASSWORD` | empty | Required for `smtp`; an anonymous relay is not supported. |
| `SMTP_TLS_MODE` | empty | Required for `smtp`. `starttls` (upgrade with STARTTLS, usually port 587) or `tls` (TLS from the start, usually port 465). Plaintext SMTP is not supported. |
Compose passes these variables from the root `.env`; it passes an unset `EMAIL_QUOTA_DAILY` or `EMAIL_QUOTA_MONTHLY` as an empty value, which the backend reads as unset. `EMAIL_PROVIDER`, `EMAIL_FROM`, and `APP_PUBLIC_URL` are required, so Compose refuses to render the project without them; copy the mail block from `.env.example` into an existing `.env`. Keep `RESEND_API_KEY` and `SMTP_PASSWORD` in the server environment or a deployment secret store and never commit them. Configuration errors name the setting but never print its value, and the startup log names only the selected provider.
Compose passes these variables from the root `.env`; it passes an unset `EMAIL_QUOTA_DAILY` or `EMAIL_QUOTA_MONTHLY` as an empty value, which the backend reads as unset. The same holds for `EMAIL_SERVICE_RESERVE_DAILY` and `EMAIL_SERVICE_RESERVE_MONTHLY`. `EMAIL_PROVIDER`, `EMAIL_FROM`, and `APP_PUBLIC_URL` are required, so Compose refuses to render the project without them; copy the mail block from `.env.example` into an existing `.env`. Keep `RESEND_API_KEY` and `SMTP_PASSWORD` in the server environment or a deployment secret store and never commit them. Configuration errors name the setting but never print its value, and the startup log names only the selected provider.
### Mail deliveries
A notification request is a row in `mail_requests` until the consumer `notification_delivery` turns it into a row in `deliveries` and deletes it; the model is in [ARCHITECTURE.md](ARCHITECTURE.md#mail-deliveries). Migration 00006 creates `mail_requests`, `deliveries`, and `delivery_attempts` at startup; migration 00017 adds the unknown-outcome decision journal and rebuilds the due partial index under a table lock. Rolling 00017 back drops that journal and its audit history, so export the decisions before rollback. Neither migration needs a setting. Notification deliveries are only stored for now: the sending worker claims verification and password reset mail only, so a notification stays `pending` until product notification sending is implemented. Notifications are created only for accounts with a verified address; a request for an unverified address is dropped with a log line.
- Each delivery is pinned to `EMAIL_PROVIDER` and `EMAIL_ACCOUNT` at creation, and a later configuration change applies only to new deliveries. Change `EMAIL_ACCOUNT` together with `RESEND_API_KEY` whenever the key belongs to another Resend account, so deliveries that started under the old account are never sent through the new one. Service mail created while `EMAIL_PROVIDER=disabled` stays pinned to `disabled` until the backend runs with a transport: the sending worker then moves it with `Rebind` (allowed only before the first attempt) and sends it if its token and account still pass the check. Do not rebind by hand.
- Each delivery is pinned to `EMAIL_PROVIDER` and `EMAIL_ACCOUNT` at creation, and a later configuration change applies only to new deliveries. Change `EMAIL_ACCOUNT` together with `RESEND_API_KEY` whenever the key belongs to another Resend account, so deliveries that started under the old account are never sent through the new one. Service mail created while `EMAIL_PROVIDER=disabled` stays pinned to `disabled` until the backend runs with a transport: the sending worker then moves it with `Rebind` (allowed only before the first attempt) and sends it if its token and account still pass the check. Do not rebind by hand. Product notifications follow the same rule, and their loop rebinds them the same way.
- The rows hold the recipient address and the rendered bodies, and a waiting `mail_requests` row holds the raw notification text; verification and password reset bodies hold a live one-time token until it is used or expires. Treat read access to `deliveries` like access to those links, and keep database dumps and backups under the same protection. Retention of finished deliveries is not implemented yet.
- To inspect deliveries, select metadata only, for example `SELECT id, kind, template_version, status, attempt_count, next_attempt_at, last_attempt_at, provider, provider_account, created_at FROM deliveries ORDER BY created_at DESC LIMIT 50`, and `SELECT attempt_number, attempted_at, outcome, rejection, provider_code, status_after FROM delivery_attempts WHERE delivery_id = '<id>' ORDER BY attempt_number`. `SELECT count(*), min(created_at) FROM mail_requests` shows requests the consumer has not handled yet; a growing count means the consumer is stopped or its events are dead-lettered. Do not select `recipient_email`, `subject`, `text_body`, `html_body`, or the `mail_requests` text columns, and never paste them into tickets or chats.
- Without SQL, the internal /metrics endpoint shows `lincodex_mail_deliveries{kind,status}` for every kind and status, zero included, and `lincodex_mail_delivery_oldest_due_pending_age_seconds`, the time the earliest pending delivery has been due. The backend reads them every 30 seconds with one aggregate over `deliveries`; every instance reports the same values, so aggregate them with `max`. A read that fails keeps the previous values and logs `delivery metrics could not be read; the gauges are stale`. Notifications stay `pending` until product notification sending is implemented; they are not counted in the due age. The age series appears only after the first successful read, so a fresh start never claims that nothing is late; `lincodex_mail_metrics_last_success_timestamp_seconds` is the Unix time of the last read in which every aggregate was read (0 from the start until the first one), and `LincodexMailMetricsStale` fires when it is more than 5 minutes old for 5 minutes. The alert `LincodexMailDeliveryUnknownOutcome` fires while any delivery has an unknown outcome. `LincodexMailDeliveriesOverdue` (a pending delivery due for more than 15 minutes) also requires `lincodex_mail_sender_running` to be 1 on some instance: the sending worker exports it, 1 while its loop runs and 0 otherwise, so the alert stays silent with `EMAIL_PROVIDER=disabled` (no loop starts) and without traffic. The age counts only service mail (verification and password reset), so a backlog of notifications, which the worker does not send until product notification sending is implemented, does not fire it. The status `cancelled` is counted like the others, and `accepted` means accepted by the provider.
@@ -385,11 +387,11 @@ A notification request is a row in `mail_requests` until the consumer `notificat
Migration 00007 creates `mail_quota_usage` and the reservation journal `mail_quota_reservations` at startup; it needs no setting. The sending worker calls the quota gate around every send (see [Sending service mail](#sending-service-mail)), so service mail counts against the quota and notifications do not until product notification sending is implemented. The model is in [ARCHITECTURE.md](ARCHITECTURE.md#mail-quotas).
- Set `EMAIL_QUOTA_DAILY` and `EMAIL_QUOTA_MONTHLY` to the plan of the provider account named by `EMAIL_ACCOUNT`. The defaults are Resend Free: 100 recipients per UTC day and 3000 per month, as checked on 2026-10-05. Check the account's current quota in the Resend dashboard before the stand goes live and after any plan change. With `smtp`, set both to the relay's limits; startup fails without them. A changed value applies after a restart.
- Set `EMAIL_QUOTA_DAILY` and `EMAIL_QUOTA_MONTHLY` to the plan of the provider account named by `EMAIL_ACCOUNT`. The defaults are Resend Free: 100 recipients per UTC day and 3000 per month, as checked on 2026-10-05. Check the account's current quota in the Resend dashboard before the stand goes live and after any plan change. With `smtp`, set both to the relay's limits; startup fails without them. A changed value applies after a restart. The service reserve (`EMAIL_SERVICE_RESERVE_DAILY` and `EMAIL_SERVICE_RESERVE_MONTHLY`) keeps part of each window for service mail: product notifications are admitted only while the window keeps the reserve free after them, and they take a fifth of each limit by default.
- Change `EMAIL_ACCOUNT` only together with a real change of the provider account, that is, a key of another account. The local count is kept per account label, so renaming the label for the same account starts a new count from zero while the provider keeps the old one. At startup the backend logs `mail quota usage` with the provider, account, and the current day and month usage and limits, and warns when other labels of the same provider have usage this month.
- When a quota is used up, deliveries wait in `waiting_quota` until `next_attempt_at`: the next 00:00 UTC for the day, the first day of the next month at 00:00 UTC for the month. Nothing buys a plan, switches the account to a paid tier, or moves mail to another transport or account. The account itself can see that its mail waits and until when through the status reader described in [ARCHITECTURE.md](ARCHITECTURE.md#mail-quotas); no HTTP route shows it yet.
- To see the state, select only counters and metadata, for example `SELECT provider, provider_account, period_kind, period_start, used_recipients, provider_exhausted_at FROM mail_quota_usage ORDER BY period_start DESC, period_kind LIMIT 10`, `SELECT count(*), min(next_attempt_at) FROM deliveries WHERE status = 'waiting_quota'`, and, for sends that were counted but never settled, `SELECT count(*), min(reserved_at) FROM mail_quota_reservations WHERE settled_outcome IS NULL AND released_at IS NULL`. Logs show `mail quota is used up; the delivery waits for the reset` and, when the provider itself refused, `the mail provider reported its quota used up; local sending stops until the reset`.
- The internal /metrics endpoint shows the current windows of the configured account, read every 30 seconds: `lincodex_mail_quota_used_recipients`, `lincodex_mail_quota_limit_recipients`, and `lincodex_mail_quota_provider_exhausted` (1 after a quota refusal by the provider), each with the labels `provider` and `window` (`day` or `month`). `EMAIL_ACCOUNT` is not a label, because the operator chooses its text; with `EMAIL_PROVIDER=disabled` there are no quota series. The alert `LincodexMailQuotaUsedUp` (severity info) fires while a window is used up.
- The internal /metrics endpoint shows the current windows of the configured account, read every 30 seconds: `lincodex_mail_quota_used_recipients`, `lincodex_mail_quota_limit_recipients`, and `lincodex_mail_quota_provider_exhausted` (1 after a quota refusal by the provider), each with the labels `provider` and `window` (`day` or `month`). `EMAIL_ACCOUNT` is not a label, because the operator chooses its text; with `EMAIL_PROVIDER=disabled` there are no quota series. The alert `LincodexMailQuotaUsedUp` (severity info) fires while a window is used up. `lincodex_mail_sender_running` reports the service loop of the process, and `lincodex_notification_sender_running` the product notification loop; both are 0 with `EMAIL_PROVIDER=disabled`.
- Choices while mail waits: wait for the reset, which needs no action; or, after a deliberate plan change with the provider, raise the limits and restart the backend, so new sends are admitted again while parked deliveries keep their stored `next_attempt_at`; or deliberately switch the transport or account (see [Mail deliveries](#mail-deliveries) for what stays pinned). Do not lower `used_recipients` or edit the journal by hand to free sends: the provider keeps its own count, so the sends would only be refused.
- `provider_exhausted_at` on a row means that the provider refused with a quota answer while the local count still had room. Possible reasons: the account also sends from elsewhere; Resend counts received (inbound) mail against the same quota; or the configured limit is above the plan. Align the limits with the plan.
- Resend's monthly quota follows the account's billing cycle, while the gate's month is the UTC calendar month. After a monthly refusal the delivery retries at the next UTC month start; if the billing cycle resets later, that retry is refused again and waits another month. The local operator command is for terminal unknown outcomes, not quota-waiting deliveries.
+24 -1
View File
@@ -244,6 +244,8 @@ Unit tests (`make -C backend test`) cover:
`TestServiceMailSending` in `backend/integration_test/mail_sender_test.go` uses `bootstrap(t, postgresService)`, the real transactor, stores, quota gate, and sending usecase, the real Resend transport pointed at the local fixture, and a fake clock. Subtests share the database and start from empty tables:
- A service email for a synthetic account with no consent record of any purpose is enqueued with its token in one transaction and accepted by the fixture: one provider call with the key `delivery/<id>`, the address, and the link with the token in the fragment; the delivery is `accepted` with the provider message ID, one accepted attempt, one counted recipient, no lease left, the account's status is `accepted`, and a second pass does nothing. Logs hold neither the address nor the token.
- A password reset email for a synthetic account without C2 is accepted by the fixture: one call with the key `delivery/<id>`, the address, and the `/reset-password` link with the token in the fragment; the log holds no address and no token.
- A verification email goes out even if C2 is granted and revoked while the email waits for the worker: the check reads only the token and the account, and the fixture gets exactly one call.
- A worker that holds a delivery keeps another off it: the fixture answers slowly, the second worker's pass is idle while the first one's request is in flight, and the fixture gets exactly one call and the database one attempt.
- Four workers drain a queue of eight deliveries at once: eight provider calls under eight distinct keys, none replayed, eight accepted deliveries with one attempt each, eight counted recipients.
- A worker that stopped after sending (the database fails when it stores the answer) is replaced after its lease expires: two calls under the same key, the second a replay, one message at the provider, one attempt, and the open reservation reused, so the recipient counts once. Beyond the 24-hour window the replacement records an unknown attempt and does not call the provider.
@@ -256,9 +258,10 @@ Unit tests (`make -C backend test`) cover:
- A notification-only backlog does not make the earliest pending age appear; a service mail does.
- A token mail's bodies are cleared when it is accepted or cancelled and the token no longer appears in any row; a waiting mail cannot be cleared by hand; a cleared row cannot get a body back or lose its mark; the account still sees its status.
- A token revoked by a resend, a token already used, an expired token, an account registered again, an address already verified, a changed address, and a token of another purpose each end the delivery as `cancelled` with the matching reason, no attempt, no lease, no next attempt, no reservation, and no provider call; the account sees `cancelled`; a further pass is idle. A deleted account takes its delivery with it.
- A verification email revoked before its send is cancelled as `token_revoked` with no provider call and no attempt; the delivery keeps its provider account, its body is cleared, and the log holds no address, token, link, or account ID.
- Provider answers: a 503 `service_unavailable` leaves the delivery `pending` due one minute later, a pass before that is idle, the retry at the due time repeats the key and is accepted; a 500 is `unknown` with no next attempt and no retry a day later; a 403 `validation_error` is `rejected`.
- Quota: a local limit of one per day parks the second delivery in `waiting_quota` until midnight UTC without a provider call, the account sees the wait and its end, and the delivery is sent at the reset; the provider's `daily_quota_exceeded` answer parks the delivery until the next midnight.
- A product notification is never claimed.
- A product notification is never claimed by the service worker; the notification lane sends it instead (`TestProductNoticeIsSentOnceByItsOwnWorker`).
- `EMAIL_PROVIDER=disabled`: with the disabled transport the pass reports the channel unavailable, the delivery stays untouched at version 1, the lease and the reservation are released, nothing reaches the fixture, a loop run against it makes at most four passes in under a second, and the gauge is 1 while it runs and 0 after; with a transport the same mail is rebound to the configured account and accepted.
- The schema refuses a cancelled delivery without a reason, a reason on another status, a half lease, a lease on a terminal delivery, a notification bound to a token, a change of the token binding, and the deletion of a token that a delivery references; deleting the account removes both.
@@ -268,6 +271,26 @@ Unit tests (`make -C backend test`) cover:
No check calls the real Resend API: the fixture is the only provider, so these tests prove the protocol the transport speaks and the delivery rules, not Resend's behavior, deliverability, or the account's real quota.
## Product notification tests
Unit tests (`make -C backend test`) cover:
- `domain`: `Delivery.CheckInvitationNotice` decides in its documented order (a missing or unverified recipient, a changed address, a missing or foreign invitation, an invitation that was answered, expired, or past its deadline, a hidden organization, a withdrawn publication, and a notice without a subject), and the first failed rule decides, so an unverified address outranks a hidden organization; `MailSubject` accepts only known kinds with complete IDs and prints no identifier; only a notification names a subject; `MailQuotaLimits.WithReserve` keeps each window's share and refuses a reserve that leaves no room; the three rights reasons parse and exist at zero in the metrics set.
- `config`: the service reserve defaults to a fifth of each quota limit (20 and 600 on the Resend Free plan), a stated zero is kept, and a reserve that is negative or reaches its limit is refused with a message that names the setting.
- `adapter/secondary/prometheus`: `lincodex_notification_sender_running` exists at 0 and follows `SetNotificationSenderRunning` without moving the service gauge; the rights reasons exist at zero in `lincodex_mail_sender_cancelled_total`.
- `bootstrap`: no notification worker without a transport or a database, and the notification loop starts and stops with the application while its gauge follows.
- `observability/prometheus/tests`: `LincodexMailCancelledBroken` stays silent on `rights_revoked`, `recipient_ineligible`, and `source_closed` (`make -C observability check`).
`TestProductNotice*` in `backend/integration_test/product_notification_test.go` use `bootstrap(t, postgresService)`, an isolated database with the real invitation send and the real notifier, the consumer `DeliveryHandler` run on the stored request, the real notification sender with the Resend fixture as its transport, and a fake clock. Each top-level test uses its own isolated database, so quota counts never mix between them; the subtests of the rights test share one database:
- `TestProductNoticeIsSentOnceByItsOwnWorker`: the notice of a delivered invitation is sent once by the notification lane, with the neutral body, which names neither the organization nor the candidate and links to the inbox; the service worker takes nothing (idle, no provider call); a second pass is idle; the logs hold neither the address, the candidate ID, nor the card handle.
- `TestProductNoticeRightsAreCheckedBeforeEverySend`: a candidate who hides the organization between the send and the worker gets no mail, and the notice is cancelled as `rights_revoked` with no provider call, its bodies cleared, a further pass idle, and no address in the logs; an address that is no longer verified is cancelled as `recipient_ineligible`; a notice that names no subject is cancelled as `source_closed` with its body cleared; an invitation past its response deadline is cancelled as `rights_revoked`. The deadline subtest moves the clock, so it runs last.
- `TestProductNoticeReserveLeavesServiceQuotaToServiceMail`: with a daily limit of 10 and a reserve of 8, the notification lane sends two notices and parks the third in `waiting_quota` until the next UTC midnight, without a provider call and without a spin; a verification mail then goes out under the full limit, and the day counts three recipients.
- `TestProductNoticeQueueIsDrainedOnceByConcurrentWorkers`: four senders drain six notices at once; the provider sees six calls, and each notice is accepted after one attempt.
- `TestProductNoticeClaimReadsItsOwnDueIndex`: over 5000 service-mail rows the product claim plan uses `deliveries_product_due_idx` and no sequential scan (`EXPLAIN`).
These tests prove the rights rules and the lane mechanics against the local fixture. They do not decide the product questions listed under [Sending product notifications](ARCHITECTURE.md#sending-product-notifications), such as whether a withdrawn publication should cancel a pending notice.
## Scheduled job tests
Unit tests (`make -C backend test`) cover the job runtime with an in-memory store that applies the claim, lease guard, and release rules of the PostgreSQL store and a fake clock from `backend/pkg/testutil/` (`internal/worker/jobrunner/`): only due jobs of registered kinds run, in due order, and a job due in two days runs exactly when the clock reaches it; a failing job is retried after the backoff by the clock, is not claimed again before it, and is dead after the last attempt with an error log and metrics; `ErrJobRejected` and a panic end a job after one attempt without logging the panic value; a handler that outlives its lease fails as `timeout`; a job reclaimed by another worker before it starts is skipped without calling the handler; a job whose last started lease expired becomes dead without running; a slow first job of a batch neither spends the next job's single attempt nor lets it die, and another worker runs a job that a busy worker claimed but did not start, on the same attempt; a database failure outside the handler releases the job and the rest of the batch without counting attempts; failed claims back off instead of looping; at shutdown the job in progress finishes within the grace, a job that outlasts it is canceled and released without an effect or a counted attempt, and claimed jobs that did not start are released; a panic during shutdown still makes the job dead; and the backlog of all kinds is reported. Further unit tests cover the job rules (`internal/domain/`: kind, key, flat payload, size limit, UTC microsecond due time), the settings (`config/`), the counters and gauges (`internal/adapter/secondary/prometheus/`), `FakeClock` (`pkg/testutil/`), and in `internal/bootstrap/` the skip cases with their log lines, the empty kind registry, a duplicate kind, and an application that runs the worker against an unreachable database and still stops.
+35 -13
View File
@@ -196,7 +196,7 @@ Offsets и партиции. Каждый обработчик - один уча
### Почтовый транспорт
Реализовано: outbound порт `MailSender` (`backend/internal/port/outbound/mail.go`), транспорт `disabled` (`adapter/secondary/mail/disabled/`), транспорт Resend (`adapter/secondary/mail/resend/`, основной провайдер рабочего стенда) и выбор транспорта в bootstrap. Usecase, шаблоны и доменные события зависят только от порта; `EMAIL_PROVIDER` выбирает ровно один транспорт (`resend`, `smtp` или `disabled`), и bootstrap связывает с ним порт до запуска миграций. Переключения между транспортами нет: непригодный выбор останавливает запуск. Запланировано: транспорт SMTP relay (`mail/smtp/`, вне MVP); пока его нет, `smtp` после проверки своих настроек останавливает запуск. Единственный вызывающий - worker отправки служебной почты identity (см. [Отправка служебной почты](#отправка-служебной-почты)); продуктовые уведомления сохраняются как доставки, но не отправляются до реализации отправки продуктовых уведомлений. Настройки описаны в [DEPLOY.md](DEPLOY.md#почта).
Реализовано: outbound порт `MailSender` (`backend/internal/port/outbound/mail.go`), транспорт `disabled` (`adapter/secondary/mail/disabled/`), транспорт Resend (`adapter/secondary/mail/resend/`, основной провайдер рабочего стенда) и выбор транспорта в bootstrap. Usecase, шаблоны и доменные события зависят только от порта; `EMAIL_PROVIDER` выбирает ровно один транспорт (`resend`, `smtp` или `disabled`), и bootstrap связывает с ним порт до запуска миграций. Переключения между транспортами нет: непригодный выбор останавливает запуск. Запланировано: транспорт SMTP relay (`mail/smtp/`, вне MVP); пока его нет, `smtp` после проверки своих настроек останавливает запуск. Единственный вызывающий - worker отправки служебной почты identity (см. [Отправка служебной почты](#отправка-служебной-почты)); продуктовые уведомления отправляет отдельный worker уведомлений (см. [Отправка продуктовых уведомлений](#отправка-продуктовых-уведомлений)). Настройки описаны в [DEPLOY.md](DEPLOY.md#почта).
`Send(ctx, OutgoingMail)` делает ровно одну попытку. `OutgoingMail` содержит получателя, тему, текстовое и HTML тело и ключ идемпотентности, который не меняется для одной логической доставки между повторами (от 1 до 256 печатных ASCII символов, предел Resend, без персональных данных); отправитель берется из `EMAIL_FROM`. При nil ошибке результат один из:
@@ -234,7 +234,7 @@ Offsets и партиции. Каждый обработчик - один уча
### Доставки писем
Реализовано: агрегат `domain.Delivery`, `domain.MailContent` и `domain.MailRequest` (`backend/internal/domain/delivery.go`, `mail_content.go`, `mail_request.go`), порты `outbound.DeliveryRepository` и `outbound.MailRequestRepository` (`port/outbound/delivery.go`) через `UnitOfWork.Deliveries()`, `UnitOfWork.MailRequests()` и `postgres.DeliveryStore`, миграция `00006_create_deliveries.sql` с таблицами `mail_requests`, `deliveries` и `delivery_attempts`, запросы в `backend/db/queries/delivery.sql`, а в `backend/internal/usecase/notification/` usecase запроса `MailRequester` и обработчик `DeliveryHandler`. Шлюз квот, который допускает или откладывает отправку, реализован; см. [Квоты почты](#квоты-почты). Реализовано: worker, который берет к отправке служебные письма, проверяет их токен и аккаунт, пропускает через шлюз квот и вызывает `MailSender`, вместе с миграцией `00012_add_delivery_sending.sql`; см. [Отправка служебной почты](#отправка-служебной-почты). Реализованы повторы служебной почты и политика неизвестного исхода, включая локальную команду оператора. Отправка продуктовых уведомлений с проверкой разрешений перед отправкой не реализована. Gauges состояний доставки реализованы; см. [Метрики, телеметрия и alerts](#метрики-телеметрия-и-alerts). Продуктовые сценарии пока не вызывают `MailRequester`, поэтому запросы уведомлений ждут отправки. Регистрация и повторная отправка создают письма подтверждения через `ServiceMailer`; сброс пароля не реализован.
Реализовано: агрегат `domain.Delivery`, `domain.MailContent` и `domain.MailRequest` (`backend/internal/domain/delivery.go`, `mail_content.go`, `mail_request.go`), порты `outbound.DeliveryRepository` и `outbound.MailRequestRepository` (`port/outbound/delivery.go`) через `UnitOfWork.Deliveries()`, `UnitOfWork.MailRequests()` и `postgres.DeliveryStore`, миграция `00006_create_deliveries.sql` с таблицами `mail_requests`, `deliveries` и `delivery_attempts`, запросы в `backend/db/queries/delivery.sql`, а в `backend/internal/usecase/notification/` usecase запроса `MailRequester` и обработчик `DeliveryHandler`. Шлюз квот, который допускает или откладывает отправку, реализован; см. [Квоты почты](#квоты-почты). Реализовано: worker, который берет к отправке служебные письма, проверяет их токен и аккаунт, пропускает через шлюз квот и вызывает `MailSender`, вместе с миграцией `00012_add_delivery_sending.sql`; см. [Отправка служебной почты](#отправка-служебной-почты). Реализованы повторы служебной почты и политика неизвестного исхода, включая локальную команду оператора. Отправка продуктовых уведомлений с проверкой прав перед каждой отправкой реализована; см. [Отправка продуктовых уведомлений](#отправка-продуктовых-уведомлений). Gauges состояний доставки реализованы; см. [Метрики, телеметрия и alerts](#метрики-телеметрия-и-alerts). Первый продуктовый вызывающий `MailRequester` - отправка приглашения; его уведомления отправляет worker уведомлений. Регистрация и повторная отправка создают письма подтверждения через `ServiceMailer`; сброс пароля не реализован.
Доставка - устойчивое состояние отправки одного письма одному получателю. Строка `deliveries` содержит:
@@ -247,7 +247,7 @@ Offsets и партиции. Каждый обработчик - один уча
Путь создания:
1. Usecase вызывает `MailRequester.RequestNotification(ctx, unit, request)` внутри своей транзакции с ID аккаунта получателя и данными уведомления. Usecase проверяет данные текущим шаблоном, чтобы некорректный запрос провалил свою транзакцию, а не стал dead letter, и назначает UUIDv7 запроса. В транзакции вызывающего кода он вставляет строку `mail_requests` с этим ID, получателем, видом, исходными темой, текстом и путем ссылки и временем запроса и добавляет `notification.mail_requested` с версией схемы 1: тип агрегата `mail_request`, ID агрегата равен ID запроса, версия агрегата 1, payload `{"mail_request_id": <id>, "kind": "notification"}` и больше ничего.
1. Usecase вызывает `MailRequester.RequestNotification(ctx, unit, request)` внутри своей транзакции с ID аккаунта получателя, данными уведомления и субъектом (для приглашения - приглашение и его организация). Usecase проверяет данные текущим шаблоном, чтобы некорректный запрос провалил свою транзакцию, а не стал dead letter, и назначает UUIDv7 запроса. В транзакции вызывающего кода он вставляет строку `mail_requests` с этим ID, получателем, видом, исходными темой, текстом и путем ссылки, субъектом и временем запроса и добавляет `notification.mail_requested` с версией схемы 1: тип агрегата `mail_request`, ID агрегата равен ID запроса, версия агрегата 1, payload `{"mail_request_id": <id>, "kind": "notification"}` и больше ничего.
2. Relay публикует событие, а обработчик `notification_delivery` применяет его в транзакции своего dedup-маркера. Он проверяет конверт и равенство `mail_request_id` и ID агрегата, отклоняет данные после объекта payload и блокирует строку запроса (`FOR UPDATE`). Затем в этой же транзакции он читает аккаунт, один раз рендерит уведомление текущей версией шаблона, вставляет доставку под ID запроса с заполненным `source_event_id` и удаляет строку запроса.
3. Повторно доставленное событие становится `duplicate` по маркеру обработчика. Повтор под другим именем обработчика, повтор dead letter после успеха или параллельный второй обработчик находят строку запроса уже удаленной (второй обработчик ждет ее блокировку) и пропускают событие. Если вставка находит доставку под ID запроса, обработчик принимает ее только для того же получателя и вида, а иначе отклоняет событие.
4. Пропуски: запрос, которого уже нет, потому что его обработали или удалили аккаунт, и уведомление аккаунту с неподтвержденным адресом (`email_verified_at` равен NULL). Во втором случае запрос удаляется: уведомления уходят только на подтвержденные адреса. Пропуски пишутся в лог на уровне info только с ID доставки и события. Неизвестная версия схемы, payload, нарушающий контракт, или текст, который отклоняет шаблон, отклоняются окончательно и становятся dead letter класса `handler_rejected`; ошибки хранилища повторяются. Если аккаунт удалили после того, как обработчик его прочитал, вставка падает на внешнем ключе; транзакция прервана, поэтому ошибка повторяется, а повтор находит запрос удаленным вместе с аккаунтом и пропускает его.
@@ -280,7 +280,7 @@ Offsets и партиции. Каждый обработчик - один уча
- `Delivery.RecordAttempt` принимает результат одной попытки транспорта и добавляет строку попытки. `pending`, `waiting_quota` и `unknown` принимают попытку: `accepted` дает `accepted`, отказ `permanent` или `invalid_request` дает `rejected`, `temporary` или `rate_limited` - `pending`, `quota_exhausted` - `waiting_quota`, а `unknown` - `unknown`. `accepted`, `rejected` и `cancelled` отклоняют любую следующую попытку с `domain.ErrDeliveryTransition`.
- `Delivery.WaitForQuota(at, until)` переводит доставку из `pending` или `waiting_quota` в `waiting_quota` без попытки - для случая, когда локальная почтовая квота откладывает отправку до вызова транспорта; нулевой `until` значит, что момент сброса неизвестен. Переход отклоняет `unknown`, чья прошлая попытка могла быть принята и чей повтор решает политика повторов, и конечные статусы. Сохраняет его `DeliveryRepository.WaitForQuota`.
- `Delivery.Cancel(at, reason)` завершает доставку из `pending` или `waiting_quota` в `cancelled` без попытки; причина - одна из `token_missing`, `token_purpose_mismatch`, `token_owner_mismatch`, `token_consumed`, `token_revoked`, `token_expired`, `account_not_current`, `recipient_mismatch`, `content_invalid` или `processing_failed`. Переход отклоняет `unknown`, как `WaitForQuota`: прошлая попытка могла быть принята, поэтому письмо никогда не объявляется неотправленным. Сохраняет его `DeliveryRepository.Cancel`.
- `Delivery.Cancel(at, reason)` завершает доставку из `pending` или `waiting_quota` в `cancelled` без попытки; причина - одна из `token_missing`, `token_purpose_mismatch`, `token_owner_mismatch`, `token_consumed`, `token_revoked`, `token_expired`, `account_not_current`, `recipient_mismatch`, `content_invalid`, `processing_failed`, `rights_revoked`, `recipient_ineligible` или `source_closed`. Переход отклоняет `unknown`, как `WaitForQuota`: прошлая попытка могла быть принята, поэтому письмо никогда не объявляется неотправленным. Сохраняет его `DeliveryRepository.Cancel`.
- `Delivery.Rebind(at, account)` переносит доставку без единой попытки на другой аккаунт провайдера; см. ниже. Сохраняет его `DeliveryRepository.Rebind`.
Каждое изменение увеличивает `version`, и хранилище применяет его только поверх предыдущей версии. Время следующей попытки задает политика повторов вызывающего кода, и оно должно соответствовать целевому статусу; CHECK `deliveries_next_attempt_matches_status` повторяет это правило, а `deliveries_provider_message_id_when_accepted` требует ID провайдера ровно для `accepted`.
@@ -297,7 +297,7 @@ Offsets и партиции. Каждый обработчик - один уча
### Квоты почты
Реализовано: окна и лимиты квот в `backend/internal/domain/mail_quota.go`; порт `outbound.MailQuotaRepository` (`port/outbound/mail_quota.go`), запись через который идет через `UnitOfWork.MailQuotas()`, а чтение еще и через `postgres.MailQuotaStore`; миграция `00007_create_mail_quota_usage.sql` с таблицами `mail_quota_usage` и `mail_quota_reservations`; запросы в `backend/db/queries/mail_quota.sql`; в `backend/internal/usecase/notification/` - `QuotaGate` с `PrepareSend` и `SettleSend` (`quota.go`), отчет при запуске `ReportQuotaUsage` и чтение статуса для пользователя `DeliveryStatusReader` (`delivery_status.go`); `SendResult.QuotaPeriod` в почтовом порте, который заполняет адаптер Resend; отчет при запуске в bootstrap (`bootstrap/mail_quota.go`). Worker отправки вызывает шлюз вокруг `MailSender.Send`, а `bootstrap/mail_sender.go` собирает его из конфигурации с `resend.IdempotencyWindow` или нулем для SMTP; см. [Отправка служебной почты](#отправка-служебной-почты). Запланировано: API или сценарий identity, который показывает результат чтения статуса. Пока отправка продуктовых уведомлений не реализована, в квоту считается только служебная почта identity.
Реализовано: окна и лимиты квот в `backend/internal/domain/mail_quota.go`; порт `outbound.MailQuotaRepository` (`port/outbound/mail_quota.go`), запись через который идет через `UnitOfWork.MailQuotas()`, а чтение еще и через `postgres.MailQuotaStore`; миграция `00007_create_mail_quota_usage.sql` с таблицами `mail_quota_usage` и `mail_quota_reservations`; запросы в `backend/db/queries/mail_quota.sql`; в `backend/internal/usecase/notification/` - `QuotaGate` с `PrepareSend` и `SettleSend` (`quota.go`), отчет при запуске `ReportQuotaUsage` и чтение статуса для пользователя `DeliveryStatusReader` (`delivery_status.go`); `SendResult.QuotaPeriod` в почтовом порте, который заполняет адаптер Resend; отчет при запуске в bootstrap (`bootstrap/mail_quota.go`). Worker отправки вызывает шлюз вокруг `MailSender.Send`, а `bootstrap/mail_sender.go` собирает его из конфигурации с `resend.IdempotencyWindow` или нулем для SMTP; см. [Отправка служебной почты](#отправка-служебной-почты). Запланировано: API или сценарий identity, который показывает результат чтения статуса. В квоту считаются обе полосы: продуктовое уведомление допускается, только пока окна сохраняют резерв служебной почты (см. [Отправка продуктовых уведомлений](#отправка-продуктовых-уведомлений)).
Лимиты. `EMAIL_QUOTA_DAILY` и `EMAIL_QUOTA_MONTHLY` ограничивают число получателей, отправленных через настроенный аккаунт провайдера (`EMAIL_PROVIDER` и `EMAIL_ACCOUNT`), за UTC-сутки, с 00:00 до 00:00 UTC, и за календарный месяц UTC. Считается каждый получатель, как считает Resend; у доставки один получатель. Значения по умолчанию - лимиты Resend Free, проверенные 05.10.2026: 100 и 3000; они действуют для `resend` и для `disabled`, который ничего не отправляет. У `smtp` значений по умолчанию нет, и без обоих значений он не запускается: лимиты relay не совпадают с лимитами Resend. Допустимы значения от 1 до 1000000000, суточный лимит не больше месячного. Значения, которое отключает квоту, нет, поэтому ни один провайдер не работает без шлюза. Лимиты - это конфигурация, а не доменные константы, и они не хранятся: измененный лимит действует со следующего резервирования, а лимит, сниженный ниже текущего расхода, откладывает каждую новую отправку до сброса окна.
@@ -342,9 +342,9 @@ Offsets и партиции. Каждый обработчик - один уча
### Отправка служебной почты
Реализовано: usecase отправки `ServiceMailSender` (`backend/internal/usecase/notification/service_sender.go`), usecase постановки `ServiceMailer` (`service_mail.go`), минимальное расписание повторов `RetryPolicy` (`send_retry.go`), `Delivery.CheckServiceMail` и `Delivery.Cancel` с причинами отмены (`backend/internal/domain/delivery.go`, `delivery_guard.go`), цикл в `backend/internal/worker/mailsender/`, входящий порт `inbound.MailPass` (`port/inbound/mail_sender.go`), методы репозитория `ClaimDue`, `ReleaseClaim`, `Cancel` и `ServiceMailState`, миграция `00012_add_delivery_sending.sql`, gauge `lincodex_mail_sender_running` и подключение в `bootstrap/mail_sender.go`. Регистрация ставит письмо подтверждения в очередь, а `ConfirmEmail` погашает ссылку. Не реализованы: отправка продуктовых уведомлений и сценарий сброса пароля.
Реализовано: usecase отправки `ServiceMailSender` (`backend/internal/usecase/notification/service_sender.go`), usecase постановки `ServiceMailer` (`service_mail.go`), минимальное расписание повторов `RetryPolicy` (`send_retry.go`), `Delivery.CheckServiceMail` и `Delivery.Cancel` с причинами отмены (`backend/internal/domain/delivery.go`, `delivery_guard.go`), цикл в `backend/internal/worker/mailsender/`, входящий порт `inbound.MailPass` (`port/inbound/mail_sender.go`), методы репозитория `ClaimDue`, `ReleaseClaim`, `Cancel` и `ServiceMailState`, миграция `00012_add_delivery_sending.sql`, gauge `lincodex_mail_sender_running` и подключение в `bootstrap/mail_sender.go`. Регистрация ставит письмо подтверждения в очередь, а `ConfirmEmail` погашает ссылку. Не реализован сценарий сброса пароля.
Область. Worker берет только виды `verification` и `password_reset`. Продуктовое уведомление он не берет никогда, в каком бы состоянии оно ни было. Служебной почте не нужна запись согласия ни для какого назначения: она часть сценария аккаунта, поэтому ничто не читает журнал согласий, а C2 (публикация карточки кандидата) и остальные продуктовые согласия не участвуют. Между аккаунтом и письмом стоит проверка ниже, а не согласие.
Область. Worker берет только виды `verification` и `password_reset`. Продуктовое уведомление он не берет никогда, в каком бы состоянии оно ни было; см. [Отправка продуктовых уведомлений](#отправка-продуктовых-уведомлений). Служебной почте не нужна запись согласия ни для какого назначения: она часть сценария аккаунта, поэтому ничто не читает журнал согласий, а C2 (публикация карточки кандидата) и остальные продуктовые согласия не участвуют. Между аккаунтом и письмом стоит проверка ниже, а не согласие.
Постановка. `ServiceMailer.EnqueueVerification` и `EnqueuePasswordReset` выполняются в транзакции, которая вставляет токен, и получают запись токена, исходный токен, адрес получателя и срок действия в часах. Они проверяют, что назначение токена подходит письму, один раз рендерят письмо текущей версией шаблона и сохраняют доставку `pending`, привязанную к токену (`email_token_id`), с ID токена в роли ID доставки. Повторный вызов для того же токена ничего нового не сохраняет, а сохраненное тело остается прежним.
@@ -408,7 +408,29 @@ Offsets и партиции. Каждый обработчик - один уча
Тесты. `integration_test/mail_sender_test.go` запускает локальную имитацию Resend (`resendfixture`, сервер `httptest`, который говорит на части API, используемой транспортом, и доступен через `resend.NewLoopbackSender`, принимающий только loopback endpoint) против PostgreSQL; см. [TESTING.md](TESTING.md). Это только тестовая подмена; production использует настоящий транспорт Resend с фиксированным endpoint.
Открытые вопросы. Отправка продуктовых уведомлений и нужная ей проверка разрешений запланированы; до их реализации уведомления ждут и не учитываются в gauge просрочки, поэтому очередь уведомлений не включает `LincodexMailDeliveriesOverdue` (gauge `lincodex_mail_delivery_oldest_due_pending_age_seconds` охватывает `domain.ServiceMailKinds`; его предикат - предикат `deliveries_due_idx`). Идет ли сброс пароля на неподтвержденные аккаунты, решает сценарий сброса. Опрос выполняется каждые 5 секунд, захват читает один индексированный запрос, что подходит для текущего объема.
Открытые вопросы. Уведомления не учитываются в gauge просрочки, поэтому очередь уведомлений не включает `LincodexMailDeliveriesOverdue` и пока не имеет собственного alert просрочки (gauge `lincodex_mail_delivery_oldest_due_pending_age_seconds` охватывает `domain.ServiceMailKinds`; его предикат - предикат `deliveries_due_idx`). Идет ли сброс пароля на неподтвержденные аккаунты, решает сценарий сброса. Опрос выполняется каждые 5 секунд, захват читает один индексированный запрос, что подходит для текущего объема.
### Отправка продуктовых уведомлений
Реализовано: полоса уведомлений цикла отправки. `usecase/notification.NewNotificationSender` (`notification_sender.go`) строит `DeliverySender` (`delivery_sender.go`) для вида уведомлений; он берет строки через `ClaimDueProductDelivery` по частичному индексу `deliveries_product_due_idx` и использует тот же транспорт, шлюз квот и фиксацию результата, что служебная полоса. Реализация `SubjectRights` решает для каждого вида субъекта, можно ли еще отправить уведомление: уведомление о приглашении - это `invitationNoticeRights` (`invitation_rights.go`), а его правило - `Delivery.CheckInvitationNotice` (`backend/internal/domain/invitation_notice.go`). `bootstrap/notification_sender.go` собирает цикл с таймингами служебной почты и `EMAIL_PROVIDER`.
Субъект. Уведомление называет запись, от прав на которую оно зависит: `domain.MailSubject`, он хранится с запросом и копируется в доставку. Отправка приглашения называет приглашение и его организацию. Субъект фиксируется вместе с доставкой, а триггер содержимого не дает его изменить (миграция `00044_add_notification_subject.sql`).
Проверка прав. До вызова транспорта проверка полосы выполняется дважды: в транзакции захвата и повторно в транзакции проверки, которая держит блокировку доставки, поэтому изменение после захвата учитывается. Правило приглашения проверяет по порядку: аккаунт получателя существует и его адрес подтвержден; адрес доставки все еще адрес аккаунта; приглашение существует в организации субъекта; приглашение еще ждет ответа (delivered или viewed) и срок ответа не истек; кандидат не скрыл организацию; публикация кандидата (C2) действующая. Уведомление не объявляет разрешенных полей: его тело - фиксированный текст, который не называет ни организацию, ни условия, и в нем нет контактов, поэтому согласие на поля (C4) не применяется. Содержимое отрисовано один раз при обработке запроса, поэтому проверка - единственная работа перед вызовом транспорта. Как и проверка служебной почты, чтение прав - снимок в транзакции отправки.
Контакты. Письмо никогда не содержит контакт. Чтение контактов только по запросу, и каждое чтение заново проверяет согласие и грант, поэтому контакт, скопированный в письмо, пережил бы свой грант. Будущее уведомление с полем кандидата или контактом добавит проверку согласия в `SubjectRights` до того, как сможет уйти.
Причины отмены. Неуспешная проверка отменяет доставку без попытки, без вызова провайдера и без смены аккаунта провайдера, и очищает ее тела (`deliveries_body_present` допускает очистку отмененного уведомления). `rights_revoked` покрывает скрытую организацию, отозванную публикацию и приглашение, на которое ответили, которое истекло или которое прошло срок ответа. `recipient_ineligible` покрывает пропавший аккаунт или неподтвержденный адрес, `recipient_mismatch` - измененный адрес. `source_closed` покрывает уведомление без субъекта или приглашение, которого больше нет. Вид субъекта, который эта сборка не умеет проверить, не отправляется и не отменяется: захват возвращает `ErrNoSubjectRights`, и строка ждет сборки, которая умеет ее проверить. Ни одна из этих причин не считается сломанной отменой для `LincodexMailCancelledBroken`.
Резерв. Шлюз квот полосы уведомлений допускает отправку, только пока после нее каждое окно сохраняет не менее `EMAIL_SERVICE_RESERVE_DAILY` и `EMAIL_SERVICE_RESERVE_MONTHLY` получателей свободными (`QuotaGate.WithReserve`). По умолчанию резерв равен пятой части каждого лимита квоты: 20 в день и 600 в месяц на тарифе Resend Free. Служебная полоса сохраняет полные лимиты, поэтому служебная почта всегда получает свою долю тех же окон. Уведомление, которое резерв не пропустил, паркуется в `waiting_quota` до сброса, а пустой проход его снова не захватывает, поэтому цикл не крутится впустую. Ответ провайдера о том, что квота исчерпана, отмечает полное окно, а не резерв.
Хранение. Каждое due-уведомление проверяется при захвате, в том числе то, чье приглашение закончилось давно, поэтому ни одна отменяемая строка не остается due. Отмененное уведомление теряет тела. Принятое уведомление сохраняет свое нейтральное тело, это открытый вопрос.
Цикл и отключенный транспорт. Цикл имеет собственный gauge `lincodex_notification_sender_running`, а его отмены считаются в `lincodex_mail_sender_cancelled_total` по причинам. При `EMAIL_PROVIDER=disabled` или без базы данных цикл не запускается, а сохраненное уведомление ждет, закрепленное за транспортом, при котором создано, как и служебная почта. Когда транспорт работает, цикл переносит уведомление и отправляет его, если его права еще действуют.
Приватность. Логи называют уведомление только ID доставки, видом и закрытыми значениями (исходом и причиной отмены). Субъект, адрес, кандидат и тело никогда не попадают в строку лога, ошибку или метку метрики.
Открытые вопросы. Уведомление о приглашении требует публикации кандидата, поэтому отозванная публикация отменяет ожидающее уведомление; это выбор, который должен подтвердить владелец продукта. Принятые уведомления сохраняют нейтральные тела, и правило хранения пока их не очищает. У полосы уведомлений нет alert просрочки; показать очередь позволяет gauge `lincodex_mail_deliveries{kind="notification",status="pending"}`.
### Внутренние уведомления
@@ -541,7 +563,7 @@ backend/
usecase/policy/ публикация версий политики и начальное заполнение демонстрационной политики
usecase/consent/ выдача согласий C1-C3 и C5 и C4 со scope с проверкой актуального текста
usecase/files/ общий закрытый файловый слой: политики, непрозрачные ключи, лимиты потока, контрольные суммы
usecase/notification/ запросы писем и обработчик, который сохраняет их как доставки, шлюз квот, постановка служебной почты (`ServiceMailer`) и отправитель служебной почты (`ServiceMailSender`)
usecase/notification/ запросы писем и обработчик, который сохраняет их как доставки, шлюз квот, постановка служебной почты (`ServiceMailer`) и отправители служебной почты (`ServiceMailSender`) и продуктовых уведомлений (`NewNotificationSender`) с проверкой прав
usecase/notification/mailtemplate/ чистый рендеринг версионированных служебных писем; обработчик доставки рендерит им уведомления
port/outbound/ границы readiness, кеша, объектного хранилища, транзакции, outbox, relay outbox, публикации и потребления событий, identity, журнала согласий, организаций и членств, политики, хеширования паролей и почты
adapter/primary/http/
@@ -566,7 +588,7 @@ backend/
worker/outboxrelay/ цикл relay outbox: захват, публикация, отметка, backoff и остановка
worker/eventconsumer/ runtime обработчиков событий: транзакция дедупликации, повторы, dead letters, commit offsets и остановка
worker/jobrunner/ runtime заданий по сроку: захват под lease, выполнение вместе с завершением, повторы, освобождение и остановка
worker/mailsender/ цикл отправки служебной почты identity: повторяет проходы, ждет без работы, откатывается при сбоях, сообщает lincodex_mail_sender_running
worker/mailsender/ цикл отправки почтовых полос (служебной почты identity и продуктовых уведомлений): повторяет проходы, ждет без работы, откатывается при сбоях, сообщает свой gauge работы
worker/retry/ backoff с jitter и ожидание с учетом context, общие для workers
worker/deliverymetrics/ периодическое чтение агрегатов доставок и квот почты в метрики
bootstrap/ конфигурация, wiring, lifecycle, shutdown
@@ -579,7 +601,7 @@ backend/
За пределами реализованных потоков identity и согласий доменные типы и usecase других продуктовых сценариев пока не реализованы. Адаптеры SMTP и FSP, а также продуктовые задания worker остаются планом. `main.go` запускает bootstrap и обрабатывает ошибку процесса. Для публичного generated transport выбран ogen v1.24.0, контракты используют OpenAPI 3.2.0. Проверяется только применяемое подмножество, не вся спецификация.
Это компактная карта, а не обещание, что все запланированные продуктовые пакеты уже существуют. Сейчас Go-код включает health usecase/adapters, generated API clients, bootstrap с миграциями при старте, PostgreSQL health query, транзакционную запись outbox, relay outbox, который публикует зафиксированные события в Kafka через адаптер franz-go, runtime обработчиков событий с обработчиками `notification_delivery` и `notification_inbox`, внутренний inbox уведомлений с операциями списка и прочтения, runtime заданий по сроку (`worker/jobrunner`) без зарегистрированного продуктового вида задания, usecase регистрации, повторной отправки, подтверждения и входа identity, PostgreSQL сессии и security boundary для всех операций, защищенных API-контрактом, usecase согласий, который записывает C1 в потоке регистрации, версионированное хранилище политики с публикацией и начальным заполнением демонстрационной политики при старте, порт `PasswordHasher` с адаптером Argon2id и проверкой пароля в регистрации, подтверждении и входе, Redis cache adapter, S3-адаптер SeaweedFS с общим закрытым файловым слоем поверх него, порт `MailSender` с транспортами `disabled` и Resend, renderer шаблонов писем и worker отправки служебной почты identity для регистрации и повторной отправки. Профили, резюме, оценивание, приглашения, продуктовые виды заданий, файловые сценарии, отправка продуктовых уведомлений, транспорт SMTP и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей.
Это компактная карта, а не обещание, что все запланированные продуктовые пакеты уже существуют. Сейчас Go-код включает health usecase/adapters, generated API clients, bootstrap с миграциями при старте, PostgreSQL health query, транзакционную запись outbox, relay outbox, который публикует зафиксированные события в Kafka через адаптер franz-go, runtime обработчиков событий с обработчиками `notification_delivery` и `notification_inbox`, внутренний inbox уведомлений с операциями списка и прочтения, runtime заданий по сроку (`worker/jobrunner`) без зарегистрированного продуктового вида задания, usecase регистрации, повторной отправки, подтверждения и входа identity, PostgreSQL сессии и security boundary для всех операций, защищенных API-контрактом, usecase согласий, который записывает C1 в потоке регистрации, версионированное хранилище политики с публикацией и начальным заполнением демонстрационной политики при старте, порт `PasswordHasher` с адаптером Argon2id и проверкой пароля в регистрации, подтверждении и входе, Redis cache adapter, S3-адаптер SeaweedFS с общим закрытым файловым слоем поверх него, порт `MailSender` с транспортами `disabled` и Resend, renderer шаблонов писем и worker отправки служебной почты identity для регистрации и повторной отправки. Профили, резюме, оценивание, приглашения, продуктовые виды заданий, файловые сценарии, транспорт SMTP и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей.
`backend/pkg/` зарезервирован для небольших технических пакетов с оправданной общей границей, а не для продуктовых usecase или domain types. В `pkg/testutil/` находится `FakeClock` - потокобезопасные ручные часы, которые тесты worker, интеграционные тесты и будущие тесты usecase подставляют везде, где production-код принимает часы `func() time.Time`, и `FindPersonalIdentifiers`, которым тесты метрик ищут в выдаче значения, похожие на email и UUID. Пакет `mailer` остается кандидатом. Шаблоны писем находятся в `internal/usecase/notification/mailtemplate/`: они содержат продуктовые тексты и используют domain types, например `SecretToken`. Это чистый пакет рендеринга без I/O и логирования. Обработчик доставки в `internal/usecase/notification/` рендерит им уведомления; `ServiceMailer` создает письма подтверждения при регистрации и повторной отправке. Письма сброса пароля относятся к будущему потоку сброса. Шаблоны, версии и формат ссылок описаны в [DEPLOY.md](DEPLOY.md#шаблоны-писем). S3-клиент остается в адаптере SeaweedFS. Поведение, специфичное для этого сервиса, остается внутри `internal/`.
@@ -1106,7 +1128,7 @@ Go экспортирует стандартные Go/process метрики и
- API: `lincodex_http_requests_total{method,route,status}`, `lincodex_http_request_duration_seconds{method,route,status_class}` и `lincodex_http_problems_total{route,code}`. `route` - шаблон маршрута chi для операционных маршрутов, а под `/api/v1` - шаблон пути OpenAPI найденной операции, например `/api/v1/me/invitations/{invitation_id}`; router находит его через `FindPath` сгенерированного сервера. Путь или метод без операции сохраняет шаблон монтирования `/api/v1/*` или `/api/*`, а путь вне всех маршрутов получает `unmatched`. `status_class` - от `1xx` до `5xx`. `code` - код problem по RFC 9457: `problem.New` записывает его из закрытого каталога через пакет `observe` уровня запроса (`adapter/primary/http/observe/`), middleware учитывает его только для ответа 4xx или 5xx, а адаптер считает код вне своего зеркального списка как `other`. Ошибка без тела problem, например 503 от `/readyz`, учитывается только по статусу. Журнал запросов (`middleware.RequestLog`, заменяет logger из go-httpkit) использует тот же шаблон маршрута и пишет request ID, метод, статус и класс, код problem, задержку, размер ответа и число параметров query, но никогда не пишет исходный путь, ключ или значение query, заголовок, адрес клиента и user agent; `/healthz` и `/readyz` не журналируются.
- Outbox и события: метрики relay, обработчиков и заданий по сроку описаны в разделах [Relay outbox](#relay-outbox), [Обработчики событий](#обработчики-событий) и [Задания по сроку](#задания-по-сроку). Отставание outbox показывает `lincodex_outbox_relay_oldest_pending_age_seconds`.
- Почта: `lincodex_mail_deliveries{kind,status}` для каждого вида и статусов `pending`, `waiting_quota`, `unknown`, `accepted`, `rejected` и `cancelled`, включая нулевые; `lincodex_mail_sender_running` - 1, пока цикл отправки почты этого процесса работает, и 0 иначе (по процессу, поэтому агрегируйте через `max`; при `EMAIL_PROVIDER=disabled` остается 0, цикл не запускается); `lincodex_mail_delivery_oldest_due_pending_age_seconds`, который считает только служебную почту (`domain.ServiceMailKinds`), поэтому очередь уведомлений никогда не выглядит просроченной; `lincodex_mail_sender_cancelled_total{reason}` - доставки, которые worker отправки завершил без отправки, по закрытому набору причин отмены, включая нулевые; для активного транспорта - `lincodex_mail_quota_used_recipients`, `lincodex_mail_quota_limit_recipients` и `lincodex_mail_quota_provider_exhausted` с `provider` и `window` (`day` или `month`). Sampler в `backend/internal/worker/deliverymetrics/` читает их каждые 30 секунд через собственный pool на одно соединение: `postgres.DeliveryStatisticsStore` агрегирует `deliveries` по виду и статусу, а `MailQuotaUsageReader.Usage` читает текущие окна настроенного аккаунта. Агрегат доставок - запрос sqlc `GetDeliveryStatistics` в `db/queries/delivery.sql`. Запрос сканирует таблицу, что подходит для текущего объема; до миллионов строк нужен индекс или счетчики по статусам. `EMAIL_ACCOUNT` не становится label: это свободный текст оператора, который может назвать человека, а каждый процесс сообщает только свой аккаунт. Все экземпляры сообщают одинаковые значения по всей базе; агрегируйте их через `max`. Неудачное чтение сохраняет прежние значения и пишет в журнал `delivery metrics could not be read; the gauges are stale`; `lincodex_mail_metrics_last_success_timestamp_seconds` показывает последнее чтение, в котором прочитаны все агрегаты (0 от запуска sampler до первого такого чтения), а gauge просрочки появляется только после первого успешного чтения. Счетчика исходов попыток пока нет; исходы показывают состояния доставок, журнал worker отправки и история `delivery_attempts`.
- Почта: `lincodex_mail_deliveries{kind,status}` для каждого вида и статусов `pending`, `waiting_quota`, `unknown`, `accepted`, `rejected` и `cancelled`, включая нулевые; `lincodex_mail_sender_running` - 1, пока цикл отправки почты этого процесса работает, и 0 иначе (по процессу, поэтому агрегируйте через `max`; при `EMAIL_PROVIDER=disabled` остается 0, цикл не запускается); `lincodex_notification_sender_running` - то же для цикла уведомлений; `lincodex_mail_delivery_oldest_due_pending_age_seconds`, который считает только служебную почту (`domain.ServiceMailKinds`), поэтому очередь уведомлений никогда не выглядит просроченной; `lincodex_mail_sender_cancelled_total{reason}` - доставки, которые worker отправки завершил без отправки, по закрытому набору причин отмены, включая нулевые; для активного транспорта - `lincodex_mail_quota_used_recipients`, `lincodex_mail_quota_limit_recipients` и `lincodex_mail_quota_provider_exhausted` с `provider` и `window` (`day` или `month`). Sampler в `backend/internal/worker/deliverymetrics/` читает их каждые 30 секунд через собственный pool на одно соединение: `postgres.DeliveryStatisticsStore` агрегирует `deliveries` по виду и статусу, а `MailQuotaUsageReader.Usage` читает текущие окна настроенного аккаунта. Агрегат доставок - запрос sqlc `GetDeliveryStatistics` в `db/queries/delivery.sql`. Запрос сканирует таблицу, что подходит для текущего объема; до миллионов строк нужен индекс или счетчики по статусам. `EMAIL_ACCOUNT` не становится label: это свободный текст оператора, который может назвать человека, а каждый процесс сообщает только свой аккаунт. Все экземпляры сообщают одинаковые значения по всей базе; агрегируйте их через `max`. Неудачное чтение сохраняет прежние значения и пишет в журнал `delivery metrics could not be read; the gauges are stale`; `lincodex_mail_metrics_last_success_timestamp_seconds` показывает последнее чтение, в котором прочитаны все агрегаты (0 от запуска sampler до первого такого чтения), а gauge просрочки появляется только после первого успешного чтения. Счетчика исходов попыток пока нет; исходы показывают состояния доставок, журнал worker отправки и история `delivery_attempts`.
- Ответы теста: `lincodex_assessment_answer_saves_total{format,outcome}` с исходами `stored`, `unchanged`, `rejected` и `failed`. PRD 6.6 требует наблюдать сохранение ответов; это понимается как команда ответа теста `SubmitMyAssessmentAnswer`. Команда не реализована, поэтому есть только hook `Metrics.ObserveAssessmentAnswerSave`, и серии не появятся, пока usecase не начнет вызывать его один раз на команду. Значение вне закрытых наборов превращается в `other`. Задержка и ошибки HTTP этой команды уже видны под маршрутом `/api/v1/me/assessment-attempts/{attempt_id}/answers`.
В labels нельзя помещать ID пользователя, кандидата, доставки или запроса, полный URL или query string, адреса и содержимое резюме. Unit-тесты прогоняют настоящий router и каждый hook метрик с fixture email и UUID и падают, если в выдаче есть значение, похожее на email или UUID. JSON dashboards Go runtime, PostgreSQL, Redis, SeaweedFS, Linux и продуктовый Lincodex поддерживаются в проекте; это не импортированные Grafana dashboard IDs. Метрики inference пока не реализованы.
@@ -1115,7 +1137,7 @@ Go экспортирует стандартные Go/process метрики и
План браузерного пути: Faro Web SDK -> same-origin `/telemetry` -> Alloy `faro.receiver` -> Loki. React SDK пока не подключен. Собирать очищенные Web Vitals, JS errors, release и нормализованный маршрут; исключить console logs, формы, текст резюме и session replay. Удалять query string, fragment и ID из URL. Ограничить размер, частоту и origin приемника. Request/trace IDs остаются полями логов, не labels; хранение spans требует отдельного backend, например Tempo, и пока не поддерживается.
Правила alerts в `observability/prometheus/rules/lincodex.yml` покрывают недоступный target backend, долю 5xx выше 5% при не менее чем 15 запросах за 5 минут, отставание outbox, dead letters и застрявшие обработчики, мертвые и опаздывающие задания по сроку, доставки с неизвестным исходом, устаревшие gauges доставок и квот, исчерпанную квоту почты и просроченные доставки; последнее правило требует еще, чтобы `lincodex_mail_sender_running` был 1 хотя бы на одном экземпляре, поэтому там, где цикл отправки не работает, например при `EMAIL_PROVIDER=disabled`, оно молчит. Оно считает только служебную почту, виды, которые отправляет worker, поэтому просроченное уведомление его не включает. `LincodexMailCancelledBroken` срабатывает при росте `lincodex_mail_sender_cancelled_total` с причиной `content_invalid` или `processing_failed`, то есть для отмен, означающих испорченную строку или дефект, а не действие пользователя. `promtool test rules` дает каждому alert случай срабатывания, а каждому ограничению - случай молчания. Prometheus вычисляет их и показывает состояние на странице /alerts и в Grafana; Alertmanager и канал уведомлений не настроены, поэтому alert никому не приходит. Планируемые alerts: превышение latency budget, заполнение диска, ошибки ML и отброшенные логи. При низком трафике нужны окно и минимальное число событий, иначе процентили нестабильны. Настроить поведение `No Data` и ошибки datasource. Стек на том же хосте не может надежно сообщить о его остановке; для этого нужен внешний health check. Compose и dashboard smoke не проверяют доставку alerts. Правила и канал уведомления следует описывать как внедренные только после отдельной проверки.
Правила alerts в `observability/prometheus/rules/lincodex.yml` покрывают недоступный target backend, долю 5xx выше 5% при не менее чем 15 запросах за 5 минут, отставание outbox, dead letters и застрявшие обработчики, мертвые и опаздывающие задания по сроку, доставки с неизвестным исходом, устаревшие gauges доставок и квот, исчерпанную квоту почты и просроченные доставки; последнее правило требует еще, чтобы `lincodex_mail_sender_running` был 1 хотя бы на одном экземпляре, поэтому там, где цикл отправки не работает, например при `EMAIL_PROVIDER=disabled`, оно молчит. Оно считает только служебную почту, виды, которые отправляет worker, поэтому просроченное уведомление его не включает. Причины прав уведомлений (`rights_revoked`, `recipient_ineligible`, `source_closed`) - ожидаемые отмены, и alert на них не срабатывает. `LincodexMailCancelledBroken` срабатывает при росте `lincodex_mail_sender_cancelled_total` с причиной `content_invalid` или `processing_failed`, то есть для отмен, означающих испорченную строку или дефект, а не действие пользователя. `promtool test rules` дает каждому alert случай срабатывания, а каждому ограничению - случай молчания. Prometheus вычисляет их и показывает состояние на странице /alerts и в Grafana; Alertmanager и канал уведомлений не настроены, поэтому alert никому не приходит. Планируемые alerts: превышение latency budget, заполнение диска, ошибки ML и отброшенные логи. При низком трафике нужны окно и минимальное число событий, иначе процентили нестабильны. Настроить поведение `No Data` и ошибки datasource. Стек на том же хосте не может надежно сообщить о его остановке; для этого нужен внешний health check. Compose и dashboard smoke не проверяют доставку alerts. Правила и канал уведомления следует описывать как внедренные только после отдельной проверки.
## Покрытие требований ТЗ
+6 -4
View File
@@ -363,6 +363,8 @@ Backend отправляет почту через порт `MailSender`. `EMAIL
| `EMAIL_TIMEOUT` | `10s` | Go duration от `1s` до `1m`; ограничивает одну попытку транспорта |
| `EMAIL_QUOTA_DAILY` | `100` для `resend` и `disabled`; для `smtp` значения по умолчанию нет, и там переменная обязательна | Получатели за UTC-сутки через настроенный аккаунт провайдера: целое от 1 до 1000000000. Пустое значение считается незаданным. Значения, которое отключает квоту, нет. |
| `EMAIL_QUOTA_MONTHLY` | `3000` для `resend` и `disabled`; для `smtp` значения по умолчанию нет, и там переменная обязательна | Получатели за календарный месяц UTC: целое от 1 до 1000000000, не меньше `EMAIL_QUOTA_DAILY`. Пустое значение считается незаданным. |
| `EMAIL_SERVICE_RESERVE_DAILY` | Пятая часть `EMAIL_QUOTA_DAILY`, например 20 на тарифе Resend Free | Получатели за UTC-сутки, которые продуктовые уведомления оставляют свободными для служебной почты: целое от 0 до значения ниже `EMAIL_QUOTA_DAILY`. Пустое значение считается незаданным. Уведомление допускается, только если после него сутки сохраняют столько свободных получателей. |
| `EMAIL_SERVICE_RESERVE_MONTHLY` | Пятая часть `EMAIL_QUOTA_MONTHLY`, например 600 на тарифе Resend Free | То же для календарного месяца UTC: целое от 0 до значения ниже `EMAIL_QUOTA_MONTHLY`. Пустое значение считается незаданным. |
| `APP_PUBLIC_URL` | нет, обязательна | Публичный origin для ссылок в письмах и точной проверки Origin у небезопасных публичных identity-операций и защищенных операций: `https://host[:port]`, а `http` только для `localhost`, `127.0.0.1` или `[::1]`. Без учетных данных, пути, query и fragment; один завершающий `/` отбрасывается. |
| `RESEND_API_KEY` | пусто | Читается только для `resend` и там обязательна. Печатные ASCII символы без пробелов. Префикс `re_` из примеров Resend не проверяется. |
| `SMTP_HOST` | пусто | Читается только для `smtp` и там обязательна. Имя хоста или IP адрес без порта. |
@@ -370,13 +372,13 @@ Backend отправляет почту через порт `MailSender`. `EMAIL
| `SMTP_USERNAME`, `SMTP_PASSWORD` | пусто | Обязательны для `smtp`; анонимный relay не поддерживается. |
| `SMTP_TLS_MODE` | пусто | Обязательна для `smtp`. `starttls` (переход на TLS через STARTTLS, обычно порт 587) или `tls` (TLS с начала соединения, обычно порт 465). SMTP без шифрования не поддерживается. |
Compose передает эти переменные из корневого `.env`; незаданные `EMAIL_QUOTA_DAILY` или `EMAIL_QUOTA_MONTHLY` он передает пустыми, и backend читает их как незаданные. `EMAIL_PROVIDER`, `EMAIL_FROM` и `APP_PUBLIC_URL` обязательны, поэтому без них Compose не соберет конфигурацию проекта; перенесите блок почты из `.env.example` в существующий `.env`. Храните `RESEND_API_KEY` и `SMTP_PASSWORD` в окружении сервера или в хранилище секретов деплоя и никогда не коммитьте их. Ошибки конфигурации называют настройку, но не печатают ее значение, а лог запуска называет только выбранного провайдера.
Compose передает эти переменные из корневого `.env`; незаданные `EMAIL_QUOTA_DAILY` или `EMAIL_QUOTA_MONTHLY` он передает пустыми, и backend читает их как незаданные. То же относится к `EMAIL_SERVICE_RESERVE_DAILY` и `EMAIL_SERVICE_RESERVE_MONTHLY`. `EMAIL_PROVIDER`, `EMAIL_FROM` и `APP_PUBLIC_URL` обязательны, поэтому без них Compose не соберет конфигурацию проекта; перенесите блок почты из `.env.example` в существующий `.env`. Храните `RESEND_API_KEY` и `SMTP_PASSWORD` в окружении сервера или в хранилище секретов деплоя и никогда не коммитьте их. Ошибки конфигурации называют настройку, но не печатают ее значение, а лог запуска называет только выбранного провайдера.
### Доставки писем
Запрос уведомления - строка `mail_requests`, пока обработчик `notification_delivery` не превратит его в строку `deliveries` и не удалит; модель описана в [ARCHITECTURE.md](ARCHITECTURE.md#доставки-писем). Миграция 00006 создает `mail_requests`, `deliveries` и `delivery_attempts` при запуске; настройки для этого не нужны. Доставки уведомлений пока только сохраняются: worker отправки берет только письма подтверждения и сброса пароля, поэтому уведомление остается в `pending`, пока не реализована отправка продуктовых уведомлений. Уведомления создаются только для аккаунтов с подтвержденным адресом; запрос на неподтвержденный адрес отбрасывается со строкой в логе.
- Каждая доставка закрепляется за `EMAIL_PROVIDER` и `EMAIL_ACCOUNT` в момент создания, а последующее изменение конфигурации применяется только к новым доставкам. Меняйте `EMAIL_ACCOUNT` вместе с `RESEND_API_KEY` каждый раз, когда ключ принадлежит другому аккаунту Resend, чтобы доставки, начатые под старым аккаунтом, никогда не отправлялись через новый. Служебная почта, созданная при `EMAIL_PROVIDER=disabled`, остается закрепленной за `disabled`, пока backend не запущен с транспортом: тогда worker отправки переносит ее через `Rebind` (разрешено только до первой попытки) и отправляет, если ее токен и аккаунт все еще проходят проверку. Не переносите вручную.
- Каждая доставка закрепляется за `EMAIL_PROVIDER` и `EMAIL_ACCOUNT` в момент создания, а последующее изменение конфигурации применяется только к новым доставкам. Меняйте `EMAIL_ACCOUNT` вместе с `RESEND_API_KEY` каждый раз, когда ключ принадлежит другому аккаунту Resend, чтобы доставки, начатые под старым аккаунтом, никогда не отправлялись через новый. Служебная почта, созданная при `EMAIL_PROVIDER=disabled`, остается закрепленной за `disabled`, пока backend не запущен с транспортом: тогда worker отправки переносит ее через `Rebind` (разрешено только до первой попытки) и отправляет, если ее токен и аккаунт все еще проходят проверку. Не переносите вручную. Продуктовые уведомления подчиняются тому же правилу, а их цикл переносит их так же.
- Строки содержат адрес получателя и сформированные тела писем, а ожидающая строка `mail_requests` - исходный текст уведомления; тела писем подтверждения почты и сброса пароля содержат действующий одноразовый токен, пока его не использовали или пока не истек срок. Относитесь к доступу на чтение к `deliveries` как к доступу к этим ссылкам и защищайте дампы и резервные копии базы так же. Срок хранения завершенных доставок пока не реализован.
- Для просмотра доставок выбирайте только метаданные, например `SELECT id, kind, template_version, status, attempt_count, next_attempt_at, last_attempt_at, provider, provider_account, created_at FROM deliveries ORDER BY created_at DESC LIMIT 50` и `SELECT attempt_number, attempted_at, outcome, rejection, provider_code, status_after FROM delivery_attempts WHERE delivery_id = '<id>' ORDER BY attempt_number`. `SELECT count(*), min(created_at) FROM mail_requests` показывает запросы, которые обработчик еще не обработал; растущее число значит, что обработчик остановлен или его события уходят в dead letters. Не выбирайте `recipient_email`, `subject`, `text_body`, `html_body` и текстовые столбцы `mail_requests` и никогда не вставляйте их в задачи и чаты.
- Без SQL внутренний endpoint /metrics показывает `lincodex_mail_deliveries{kind,status}` для каждого вида и статуса, включая нулевые, и `lincodex_mail_delivery_oldest_due_pending_age_seconds` - сколько времени самая ранняя доставка в `pending` уже ждет своего срока. Backend читает их каждые 30 секунд одним агрегатом по `deliveries`; все экземпляры сообщают одинаковые значения, поэтому агрегируйте их через `max`. Неудачное чтение сохраняет прежние значения и пишет в журнал `delivery metrics could not be read; the gauges are stale`. Уведомления остаются в `pending` до реализации отправки продуктовых уведомлений; в просрочку они не считаются. Серия просрочки появляется только после первого успешного чтения, поэтому свежий запуск не заявляет, что ничего не просрочено; `lincodex_mail_metrics_last_success_timestamp_seconds` - Unix-время последнего чтения, в котором прочитаны все агрегаты (0 от запуска до первого такого чтения), а `LincodexMailMetricsStale` срабатывает, когда оно старше 5 минут в течение 5 минут. Alert `LincodexMailDeliveryUnknownOutcome` срабатывает, пока у какой-либо доставки неизвестный исход. `LincodexMailDeliveriesOverdue` (доставка в `pending` просрочена больше чем на 15 минут) требует еще, чтобы `lincodex_mail_sender_running` был 1 хотя бы на одном экземпляре: его экспортирует worker отправки, 1 пока цикл работает и 0 иначе, поэтому alert молчит при `EMAIL_PROVIDER=disabled` (цикл не запускается) и без трафика. Просрочка считает только служебную почту (подтверждение и сброс пароля), поэтому очередь уведомлений, которые worker не отправляет до реализации отправки продуктовых уведомлений, его не включает. Статус `cancelled` считается наравне с остальными, а `accepted` означает принято провайдером.
@@ -387,11 +389,11 @@ Compose передает эти переменные из корневого `.e
Миграция 00007 создает `mail_quota_usage` и журнал резервирований `mail_quota_reservations` при запуске; настройка не нужна. Worker отправки вызывает шлюз квот при каждой отправке (см. [Отправка служебной почты](#отправка-служебной-почты)), поэтому служебная почта считается в квоту, а уведомления - нет до реализации отправки продуктовых уведомлений. Модель описана в [ARCHITECTURE.md](ARCHITECTURE.md#квоты-почты).
- Задайте `EMAIL_QUOTA_DAILY` и `EMAIL_QUOTA_MONTHLY` по тарифу аккаунта провайдера, который назван в `EMAIL_ACCOUNT`. Значения по умолчанию соответствуют Resend Free: 100 получателей за UTC-сутки и 3000 за месяц по проверке 05.10.2026. Сверьте текущую квоту аккаунта в панели Resend до запуска стенда и после любой смены тарифа. Для `smtp` задайте оба значения по лимитам relay; без них запуск завершается ошибкой. Измененное значение действует после перезапуска.
- Задайте `EMAIL_QUOTA_DAILY` и `EMAIL_QUOTA_MONTHLY` по тарифу аккаунта провайдера, который назван в `EMAIL_ACCOUNT`. Значения по умолчанию соответствуют Resend Free: 100 получателей за UTC-сутки и 3000 за месяц по проверке 05.10.2026. Сверьте текущую квоту аккаунта в панели Resend до запуска стенда и после любой смены тарифа. Для `smtp` задайте оба значения по лимитам relay; без них запуск завершается ошибкой. Измененное значение действует после перезапуска. Резерв служебной почты (`EMAIL_SERVICE_RESERVE_DAILY` и `EMAIL_SERVICE_RESERVE_MONTHLY`) оставляет часть каждого окна служебной почте: продуктовые уведомления допускаются, только пока после них окно сохраняет резерв свободным, а по умолчанию резерв равен пятой части каждого лимита.
- Меняйте `EMAIL_ACCOUNT` только вместе с настоящей сменой аккаунта провайдера, то есть с ключом другого аккаунта. Локальный счет ведется по метке аккаунта, поэтому переименование метки для того же аккаунта начинает счет с нуля, а у провайдера остается прежний. При запуске backend пишет в журнал `mail quota usage` с провайдером, аккаунтом, текущим расходом и лимитами суток и месяца и предупреждает, если у других меток того же провайдера есть расход в этом месяце.
- Когда квота исчерпана, доставки ждут в `waiting_quota` до `next_attempt_at`: ближайших 00:00 UTC для суток и первого числа следующего месяца в 00:00 UTC для месяца. Ничто не покупает тариф, не переводит аккаунт на платный план и не переносит почту на другой транспорт или аккаунт. Сам аккаунт может узнать, что его письмо ждет и до какого времени, через чтение статуса, описанное в [ARCHITECTURE.md](ARCHITECTURE.md#квоты-почты); HTTP-маршрута для этого пока нет.
- Чтобы увидеть состояние, выбирайте только счетчики и метаданные, например `SELECT provider, provider_account, period_kind, period_start, used_recipients, provider_exhausted_at FROM mail_quota_usage ORDER BY period_start DESC, period_kind LIMIT 10`, `SELECT count(*), min(next_attempt_at) FROM deliveries WHERE status = 'waiting_quota'` и для отправок, которые посчитаны, но так и не рассчитаны, `SELECT count(*), min(reserved_at) FROM mail_quota_reservations WHERE settled_outcome IS NULL AND released_at IS NULL`. В журнале видны `mail quota is used up; the delivery waits for the reset` и, если отказал сам провайдер, `the mail provider reported its quota used up; local sending stops until the reset`.
- Внутренний endpoint /metrics показывает текущие окна настроенного аккаунта, которые читаются каждые 30 секунд: `lincodex_mail_quota_used_recipients`, `lincodex_mail_quota_limit_recipients` и `lincodex_mail_quota_provider_exhausted` (1 после отказа провайдера по квоте), каждая с labels `provider` и `window` (`day` или `month`). `EMAIL_ACCOUNT` не становится label, потому что его текст выбирает оператор; при `EMAIL_PROVIDER=disabled` серий квот нет. Alert `LincodexMailQuotaUsedUp` (severity info) срабатывает, пока окно исчерпано.
- Внутренний endpoint /metrics показывает текущие окна настроенного аккаунта, которые читаются каждые 30 секунд: `lincodex_mail_quota_used_recipients`, `lincodex_mail_quota_limit_recipients` и `lincodex_mail_quota_provider_exhausted` (1 после отказа провайдера по квоте), каждая с labels `provider` и `window` (`day` или `month`). `EMAIL_ACCOUNT` не становится label, потому что его текст выбирает оператор; при `EMAIL_PROVIDER=disabled` серий квот нет. Alert `LincodexMailQuotaUsedUp` (severity info) срабатывает, пока окно исчерпано. `lincodex_mail_sender_running` показывает цикл служебной почты процесса, а `lincodex_notification_sender_running` - цикл продуктовых уведомлений; оба равны 0 при `EMAIL_PROVIDER=disabled`.
- Варианты, пока письма ждут: дождаться сброса, для этого ничего делать не нужно; или после осознанной смены тарифа у провайдера поднять лимиты и перезапустить backend, тогда новые отправки снова допускаются, а отложенные доставки сохраняют свой `next_attempt_at`; или осознанно сменить транспорт или аккаунт (что остается закрепленным, описано в [Доставки писем](#доставки-писем)). Не уменьшайте `used_recipients` и не правьте журнал вручную, чтобы освободить отправки: у провайдера свой счет, и такие отправки он только отклонит.
- `provider_exhausted_at` в строке значит, что провайдер ответил отказом по квоте, хотя по локальному счету место было. Возможные причины: аккаунт отправляет письма еще откуда-то; Resend учитывает в той же квоте полученные (входящие) письма; или настроенный лимит выше тарифа. Приведите лимиты в соответствие с тарифом.
- Месячная квота Resend следует платежному циклу аккаунта, а месяц шлюза - календарный месяц UTC. После месячного отказа доставка повторяется в начале следующего месяца UTC; если платежный цикл сбрасывается позже, этот повтор снова получит отказ и будет ждать еще месяц. Локальная команда оператора предназначена для терминального `unknown`, а не для доставок, ожидающих сброса квоты.
+24 -1
View File
@@ -244,6 +244,8 @@ Unit-тесты (`make -C backend test`) проверяют правила кв
`TestServiceMailSending` в `backend/integration_test/mail_sender_test.go` использует `bootstrap(t, postgresService)`, настоящие транзакционный слой, хранилища, шлюз квот и usecase отправки, настоящий транспорт Resend, направленный на локальную имитацию, и фиктивные часы. Подтесты делят базу и начинают с пустых таблиц:
- Служебное письмо для синтетического аккаунта без записи согласия любого назначения ставится вместе с токеном в одной транзакции и принимается имитацией: один вызов провайдера с ключом `delivery/<id>`, адресом и ссылкой с токеном во fragment; доставка `accepted` с ID сообщения провайдера, одной принятой попыткой, одним посчитанным получателем и без оставшегося lease, аккаунт видит статус `accepted`, а второй проход ничего не делает. Журнал не содержит ни адреса, ни токена.
- Письмо сброса пароля для синтетического аккаунта без C2 принимается имитацией: один вызов с ключом `delivery/<id>`, адресом и ссылкой `/reset-password` с токеном во fragment; журнал не содержит адреса и токена.
- Письмо подтверждения уходит, даже если C2 выдан и отозван, пока письмо ждет worker: проверка читает только токен и аккаунт, а имитация получает ровно один вызов.
- Worker, который держит доставку, не пускает к ней другого: имитация отвечает медленно, проход второго worker холостой, пока запрос первого в пути, и имитация получает ровно один вызов, а база - одну попытку.
- Четыре worker одновременно разбирают очередь из восьми доставок: восемь вызовов провайдера под восемью разными ключами, ни один не повторен, восемь принятых доставок по одной попытке, восемь посчитанных получателей.
- Worker, остановившийся после отправки (база отказывает при сохранении ответа), заменяется после истечения его lease: два вызова под одним ключом, второй - повтор, одно сообщение у провайдера, одна попытка, открытое резервирование использовано повторно, поэтому получатель считается один раз. За пределами 24-часового окна замена записывает попытку unknown и не вызывает провайдера.
@@ -256,9 +258,10 @@ Unit-тесты (`make -C backend test`) проверяют правила кв
- Очередь из одних уведомлений не создает возраст самой ранней ожидающей доставки; служебное письмо создает.
- Тела письма с токеном очищаются, когда оно принято или отменено, и токен больше не встречается ни в одной строке; ожидающее письмо вручную очистить нельзя; очищенная строка не может получить тело обратно или потерять метку; аккаунт по-прежнему видит свой статус.
- Токен, отозванный повторной отправкой, уже использованный токен, истекший токен, повторно зарегистрированный аккаунт, уже подтвержденный адрес, измененный адрес и токен другого назначения завершают доставку как `cancelled` с соответствующей причиной, без попытки, без lease, без следующей попытки, без резервирования и без вызова провайдера; аккаунт видит `cancelled`; следующий проход холостой. Удаленный аккаунт уносит свою доставку.
- Письмо подтверждения, отозванное до отправки, отменяется как `token_revoked` без вызова провайдера и без попытки; аккаунт провайдера доставки не меняется, тело очищается, а журнал не содержит адреса, токена, ссылки и ID аккаунта.
- Ответы провайдера: 503 `service_unavailable` оставляет доставку в `pending` со сроком через минуту, проход до срока холостой, повтор в срок использует тот же ключ и принимается; 500 дает `unknown` без следующей попытки и без повтора через сутки; 403 `validation_error` дает `rejected`.
- Квота: локальный лимит один в сутки переводит вторую доставку в `waiting_quota` до полуночи UTC без вызова провайдера, аккаунт видит ожидание и его конец, а доставка отправляется при сбросе; ответ провайдера `daily_quota_exceeded` откладывает доставку до следующей полуночи.
- Продуктовое уведомление не берется никогда.
- Служебный worker никогда не берет продуктовое уведомление; его отправляет полоса уведомлений (`TestProductNoticeIsSentOnceByItsOwnWorker`).
- `EMAIL_PROVIDER=disabled`: с транспортом disabled проход сообщает, что канал недоступен, доставка остается нетронутой на версии 1, lease и резервирование освобождены, до имитации ничего не доходит, цикл с ним делает не больше четырех проходов меньше чем за секунду, а gauge равен 1, пока он работает, и 0 после; с транспортом то же письмо переносится на настроенный аккаунт и принимается.
- Схема отклоняет отмененную доставку без причины, причину у другого статуса, половину lease, lease у конечной доставки, уведомление, привязанное к токену, смену привязки токена и удаление токена, на который ссылается доставка; удаление аккаунта убирает оба.
@@ -268,6 +271,26 @@ Unit-тесты (`make -C backend test`) проверяют правила кв
Ни одна проверка не вызывает настоящий API Resend: единственный провайдер - имитация, поэтому эти тесты доказывают протокол, на котором говорит транспорт, и правила доставки, но не поведение Resend, доставляемость и реальную квоту аккаунта.
## Тесты продуктовых уведомлений
Unit-тесты (`make -C backend test`) покрывают:
- `domain`: `Delivery.CheckInvitationNotice` решает в описанном порядке (нет получателя или адрес не подтвержден, адрес изменился, приглашение отсутствует или принадлежит другой организации, на приглашение ответили, оно истекло или прошло срок ответа, организация скрыта, публикация отозвана, уведомление без субъекта), и решает первое нарушенное правило, поэтому неподтвержденный адрес важнее скрытой организации; `MailSubject` принимает только известные виды с полными ID и не печатает идентификаторов; субъект может быть только у уведомления; `MailQuotaLimits.WithReserve` сохраняет долю каждого окна и отказывает в резерве, который не оставляет места; три причины прав разбираются и есть в наборе метрик с нулем.
- `config`: резерв служебной почты по умолчанию равен пятой части каждого лимита квоты (20 и 600 на тарифе Resend Free), явный ноль сохраняется, а резерв отрицательный или достигающий своего лимита отклоняется с сообщением, которое называет настройку.
- `adapter/secondary/prometheus`: `lincodex_notification_sender_running` есть со значением 0, следует за `SetNotificationSenderRunning` и не сдвигает gauge служебного цикла; причины прав есть со значением 0 в `lincodex_mail_sender_cancelled_total`.
- `bootstrap`: нет worker уведомлений без транспорта или базы данных, а цикл уведомлений запускается и останавливается вместе с приложением, и его gauge следует за ним.
- `observability/prometheus/tests`: `LincodexMailCancelledBroken` молчит на `rights_revoked`, `recipient_ineligible` и `source_closed` (`make -C observability check`).
`TestProductNotice*` в `backend/integration_test/product_notification_test.go` используют `bootstrap(t, postgresService)`, изолированную базу с настоящей отправкой приглашения и настоящим notifier, обработчик `DeliveryHandler`, запущенный над сохраненным запросом, настоящий отправитель уведомлений с фикстурой Resend в качестве транспорта и фальшивые часы. Каждая верхнеуровневая функция работает в своей изолированной базе, поэтому счетчики квоты не смешиваются; подтесты правил прав делят одну базу:
- `TestProductNoticeIsSentOnceByItsOwnWorker`: уведомление о доставленном приглашении отправляет полоса уведомлений один раз, с нейтральным текстом, который не называет ни организацию, ни кандидата и ведет во входящие; служебный worker ничего не берет (пустой проход, без вызова провайдера); второй проход пуст; в логах нет ни адреса, ни ID кандидата, ни handle карточки.
- `TestProductNoticeRightsAreCheckedBeforeEverySend`: кандидат, который скрыл организацию между отправкой и worker, письма не получает, уведомление отменяется как `rights_revoked` без вызова провайдера, тела очищаются, следующий проход пуст, адреса в логах нет; адрес, который больше не подтвержден, отменяется как `recipient_ineligible`; уведомление без субъекта отменяется как `source_closed` с очищенным телом; приглашение, прошедшее срок ответа, отменяется как `rights_revoked`. Подтест со сроком сдвигает часы, поэтому идет последним.
- `TestProductNoticeReserveLeavesServiceQuotaToServiceMail`: при дневном лимите 10 и резерве 8 полоса уведомлений отправляет два уведомления и паркует третье в `waiting_quota` до следующей полуночи UTC, без вызова провайдера и без цикла впустую; затем письмо подтверждения уходит под полным лимитом, и за день учтены три получателя.
- `TestProductNoticeQueueIsDrainedOnceByConcurrentWorkers`: четыре отправителя одновременно разбирают шесть уведомлений; провайдер получает шесть вызовов, и каждое уведомление принято после одной попытки.
- `TestProductNoticeClaimReadsItsOwnDueIndex`: при 5000 строках служебной почты план захвата уведомлений использует `deliveries_product_due_idx` и не делает последовательного чтения (`EXPLAIN`).
Эти тесты доказывают правила прав и механику полосы на локальной фикстуре. Они не решают продуктовые вопросы из раздела [Отправка продуктовых уведомлений](ARCHITECTURE.md#отправка-продуктовых-уведомлений), например, должна ли отозванная публикация отменять ожидающее уведомление.
## Тесты заданий по сроку
Unit-тесты (`make -C backend test`) проверяют runtime заданий с хранилищем в памяти, которое повторяет правила захвата, проверки lease и освобождения хранилища PostgreSQL, и с fake clock из `backend/pkg/testutil/` (`internal/worker/jobrunner/`): выполняются только наступившие задания зарегистрированных видов в порядке срока, а задание со сроком через два дня выполняется ровно тогда, когда часы его достигают; неудачное задание повторяется после backoff по часам, не захватывается раньше и после последней попытки становится dead с записью в журнал уровня error и метриками; `ErrJobRejected` и panic завершают задание после одной попытки, а значение panic не попадает в журнал; обработчик, переживший свой lease, падает как `timeout`; задание, которое другой worker захватил до начала, пропускается без вызова обработчика; задание с истекшим lease последней начатой попытки становится dead без выполнения; медленное первое задание пачки не тратит единственную попытку следующего и не убивает его, а другой worker выполняет задание, которое занятый worker захватил, но не начал, на той же попытке; сбой базы данных вне обработчика освобождает задание и остаток пачки без учета попыток; неудачные захваты ждут backoff, а не крутятся в цикле; при остановке задание в работе завершается внутри grace, задание, которое его переживает, отменяется и освобождается без эффекта и без учтенной попытки, а захваченные, но не начатые задания освобождаются; panic во время остановки все равно делает задание dead; backlog всех видов попадает в метрики. Остальные unit-тесты покрывают правила задания (`internal/domain/`: вид, ключ, плоский payload, лимит размера, срок в UTC с точностью до микросекунд), настройки (`config/`), счетчики и gauges (`internal/adapter/secondary/prometheus/`), `FakeClock` (`pkg/testutil/`), а в `internal/bootstrap/` - случаи без запуска с их строками журнала, пустой реестр видов, повторный вид и приложение, которое запускает worker против недоступной базы и все равно останавливается.
+4 -3
View File
@@ -98,8 +98,9 @@ groups:
# loop starts. The rule fires only while at least one backend instance
# reports 1, so a stand without a transport stays silent. The age gauge
# counts only service mail (verification and password reset), the kinds
# the worker sends: a due notification awaits product notification sending and is not
# counted, so a notification backlog never fires this alert.
# the service worker sends. Product notifications have their own loop,
# lincodex_notification_sender_running, and are not counted here, so a
# notification backlog never fires this alert.
- alert: LincodexMailDeliveriesOverdue
expr: |
max(lincodex_mail_delivery_oldest_due_pending_age_seconds{job="backend"}) > 900
@@ -118,7 +119,7 @@ groups:
severity: warning
annotations:
summary: The mail sending worker cancelled a delivery because of a broken row or a repeated internal failure.
description: Reason content_invalid (the stored content does not match its hash, or the message is unsendable) or processing_failed (the worker failed on the row several times) is a defect or a manual edit, not a user action. Select id, kind, and cancel_reason from deliveries where status is cancelled and read the worker logs for the delivery_id. Cancellations that follow a user action (token_revoked, token_consumed, token_expired, account_not_current) are normal and do not fire this alert.
description: Reason content_invalid (the stored content does not match its hash, or the message is unsendable) or processing_failed (the worker failed on the row several times) is a defect or a manual edit, not a user action. Select id, kind, and cancel_reason from deliveries where status is cancelled and read the worker logs for the delivery_id. Cancellations that follow a user action or a rights change (token_revoked, token_consumed, token_expired, account_not_current, rights_revoked, recipient_ineligible, source_closed) are normal and do not fire this alert.
- alert: LincodexMailMetricsStale
expr: time() - max(lincodex_mail_metrics_last_success_timestamp_seconds{job="backend"}) > 300
@@ -279,17 +279,24 @@ tests:
severity: warning
exp_annotations:
summary: The mail sending worker cancelled a delivery because of a broken row or a repeated internal failure.
description: Reason content_invalid (the stored content does not match its hash, or the message is unsendable) or processing_failed (the worker failed on the row several times) is a defect or a manual edit, not a user action. Select id, kind, and cancel_reason from deliveries where status is cancelled and read the worker logs for the delivery_id. Cancellations that follow a user action (token_revoked, token_consumed, token_expired, account_not_current) are normal and do not fire this alert.
description: Reason content_invalid (the stored content does not match its hash, or the message is unsendable) or processing_failed (the worker failed on the row several times) is a defect or a manual edit, not a user action. Select id, kind, and cancel_reason from deliveries where status is cancelled and read the worker logs for the delivery_id. Cancellations that follow a user action or a rights change (token_revoked, token_consumed, token_expired, account_not_current, rights_revoked, recipient_ineligible, source_closed) are normal and do not fire this alert.
- eval_time: 35m
alertname: LincodexMailCancelledBroken
exp_alerts: []
- interval: 1m
# Reasons that follow a user action never fire it, however many there are.
# Reasons that follow a user action or a rights change never fire it, however
# many there are.
input_series:
- series: lincodex_mail_sender_cancelled_total{job="backend",instance="a",reason="token_revoked"}
values: 0+5x40
- series: lincodex_mail_sender_cancelled_total{job="backend",instance="a",reason="token_expired"}
values: 0+3x40
- series: lincodex_mail_sender_cancelled_total{job="backend",instance="a",reason="rights_revoked"}
values: 0+4x40
- series: lincodex_mail_sender_cancelled_total{job="backend",instance="a",reason="recipient_ineligible"}
values: 0+2x40
- series: lincodex_mail_sender_cancelled_total{job="backend",instance="a",reason="source_closed"}
values: 0+2x40
alert_rule_test:
- eval_time: 30m
alertname: LincodexMailCancelledBroken
@@ -306,7 +313,7 @@ tests:
severity: warning
exp_annotations:
summary: The mail sending worker cancelled a delivery because of a broken row or a repeated internal failure.
description: Reason content_invalid (the stored content does not match its hash, or the message is unsendable) or processing_failed (the worker failed on the row several times) is a defect or a manual edit, not a user action. Select id, kind, and cancel_reason from deliveries where status is cancelled and read the worker logs for the delivery_id. Cancellations that follow a user action (token_revoked, token_consumed, token_expired, account_not_current) are normal and do not fire this alert.
description: Reason content_invalid (the stored content does not match its hash, or the message is unsendable) or processing_failed (the worker failed on the row several times) is a defect or a manual edit, not a user action. Select id, kind, and cancel_reason from deliveries where status is cancelled and read the worker logs for the delivery_id. Cancellations that follow a user action or a rights change (token_revoked, token_consumed, token_expired, account_not_current, rights_revoked, recipient_ineligible, source_closed) are normal and do not fire this alert.
- interval: 1m
input_series:
- series: lincodex_mail_metrics_last_success_timestamp_seconds{job="backend",instance="a"}