feat(notifications): send product notifications with a rights check right before each send
This commit is contained in:
1 parent
a856066316
commit
623d41b969
59 files changed
+4125
-1126
No files matched your search
@@ -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
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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
@@ -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")
|
||||
}
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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) })
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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 ¬ificationSendingWorker{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)
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
|
||||
@@ -67,6 +67,7 @@ func initialize(
|
||||
newEventConsumers,
|
||||
newJobWorker,
|
||||
newMailSenderWorker,
|
||||
newNotificationSenderWorker,
|
||||
newDeliveryMetrics,
|
||||
NewApplication,
|
||||
),
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
Reference in new issue
Block a user