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

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

No files matched your search

@@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"slices"
"strings"
"time"
@@ -104,28 +105,31 @@ func (repository deliveryRepository) Create(ctx context.Context, delivery domain
content := delivery.Content()
hash := content.Hash()
inserted, err := repository.queries.InsertDelivery(ctx, sqlc.InsertDeliveryParams{
ID: pgUUID(delivery.ID()),
SourceEventID: pgOptionalUUID(delivery.SourceEventID()),
RecipientUserID: pgUUID(delivery.RecipientUserID()),
RecipientEmail: delivery.Recipient().Address(),
Kind: string(content.Kind()),
TemplateVersion: content.TemplateVersion(),
Subject: content.Subject(),
TextBody: content.Text(),
HtmlBody: content.HTML(),
ContentSha256: hash[:],
Provider: delivery.ProviderAccount().Provider(),
ProviderAccount: delivery.ProviderAccount().Account(),
IdempotencyKey: delivery.IdempotencyKey(),
Status: string(delivery.Status()),
AttemptCount: delivery.AttemptCount(),
NextAttemptAt: pgZeroableTime(delivery.NextAttemptAt()),
LastAttemptAt: pgZeroableTime(delivery.LastAttemptAt()),
ProviderMessageID: pgOptionalText(delivery.ProviderMessageID()),
EmailTokenID: pgOptionalUUID(delivery.EmailTokenID()),
Version: delivery.Version(),
CreatedAt: pgTime(delivery.CreatedAt()),
UpdatedAt: pgTime(delivery.UpdatedAt()),
ID: pgUUID(delivery.ID()),
SourceEventID: pgOptionalUUID(delivery.SourceEventID()),
RecipientUserID: pgUUID(delivery.RecipientUserID()),
RecipientEmail: delivery.Recipient().Address(),
Kind: string(content.Kind()),
TemplateVersion: content.TemplateVersion(),
Subject: content.Subject(),
TextBody: content.Text(),
HtmlBody: content.HTML(),
ContentSha256: hash[:],
Provider: delivery.ProviderAccount().Provider(),
ProviderAccount: delivery.ProviderAccount().Account(),
IdempotencyKey: delivery.IdempotencyKey(),
Status: string(delivery.Status()),
AttemptCount: delivery.AttemptCount(),
NextAttemptAt: pgZeroableTime(delivery.NextAttemptAt()),
LastAttemptAt: pgZeroableTime(delivery.LastAttemptAt()),
ProviderMessageID: pgOptionalText(delivery.ProviderMessageID()),
EmailTokenID: pgOptionalUUID(delivery.EmailTokenID()),
SubjectKind: pgOptionalText(string(delivery.Subject().Kind())),
SubjectID: pgOptionalUUID(delivery.Subject().ID()),
SubjectOrganizationID: pgOptionalUUID(delivery.Subject().OrganizationID()),
Version: delivery.Version(),
CreatedAt: pgTime(delivery.CreatedAt()),
UpdatedAt: pgTime(delivery.UpdatedAt()),
})
if err != nil {
return false, fmt.Errorf("deliveryRepository.Create - insert delivery: %w", mapDeliveryError(err))
@@ -142,34 +146,37 @@ func (repository deliveryRepository) Get(ctx context.Context, id uuid.UUID) (dom
return domain.Delivery{}, fmt.Errorf("deliveryRepository.Get - select delivery: %w", mapDeliveryError(err))
}
return deliveryFromRow(sqlc.Delivery{
ID: row.ID,
SourceEventID: row.SourceEventID,
RecipientUserID: row.RecipientUserID,
RecipientEmail: row.RecipientEmail,
Kind: row.Kind,
TemplateVersion: row.TemplateVersion,
Subject: row.Subject,
TextBody: row.TextBody,
HtmlBody: row.HtmlBody,
ContentSha256: row.ContentSha256,
Provider: row.Provider,
ProviderAccount: row.ProviderAccount,
IdempotencyKey: row.IdempotencyKey,
Status: row.Status,
AttemptCount: row.AttemptCount,
NextAttemptAt: row.NextAttemptAt,
LastAttemptAt: row.LastAttemptAt,
ProviderMessageID: row.ProviderMessageID,
Version: row.Version,
CreatedAt: row.CreatedAt,
UpdatedAt: row.UpdatedAt,
EmailTokenID: row.EmailTokenID,
CancelReason: row.CancelReason,
ClaimOwner: row.ClaimOwner,
ClaimedUntil: row.ClaimedUntil,
FirstSendStartedAt: row.FirstSendStartedAt,
FailureCount: row.FailureCount,
BodyRedactedAt: row.BodyRedactedAt,
ID: row.ID,
SourceEventID: row.SourceEventID,
RecipientUserID: row.RecipientUserID,
RecipientEmail: row.RecipientEmail,
Kind: row.Kind,
TemplateVersion: row.TemplateVersion,
Subject: row.Subject,
TextBody: row.TextBody,
HtmlBody: row.HtmlBody,
ContentSha256: row.ContentSha256,
Provider: row.Provider,
ProviderAccount: row.ProviderAccount,
IdempotencyKey: row.IdempotencyKey,
Status: row.Status,
AttemptCount: row.AttemptCount,
NextAttemptAt: row.NextAttemptAt,
LastAttemptAt: row.LastAttemptAt,
ProviderMessageID: row.ProviderMessageID,
Version: row.Version,
CreatedAt: row.CreatedAt,
UpdatedAt: row.UpdatedAt,
EmailTokenID: row.EmailTokenID,
CancelReason: row.CancelReason,
ClaimOwner: row.ClaimOwner,
ClaimedUntil: row.ClaimedUntil,
FirstSendStartedAt: row.FirstSendStartedAt,
FailureCount: row.FailureCount,
BodyRedactedAt: row.BodyRedactedAt,
SubjectKind: row.SubjectKind,
SubjectID: row.SubjectID,
SubjectOrganizationID: row.SubjectOrganizationID,
})
}
@@ -406,6 +413,52 @@ func (repository deliveryRepository) updateState(ctx context.Context, location s
return nil
}
// claimKindsBelongToScope reports that every kind is one the lane's claim
// statement reads: the product statement has a literal notification predicate,
// so it must not be asked for service mail, and the reverse.
func claimKindsBelongToScope(scope outbound.ClaimScope, kinds []domain.MailKind) bool {
allowed := domain.ServiceMailKinds()
if scope == outbound.ClaimScopeNotification {
allowed = domain.ProductMailKinds()
}
for _, kind := range kinds {
if !slices.Contains(allowed, kind) {
return false
}
}
return true
}
// claimRow runs the claim statement of the claim's lane. The product statement
// returns the same columns in the same order, so its row converts to the row of
// the service statement; the conversion does not compile if the columns drift.
func (repository deliveryRepository) claimRow(ctx context.Context, claim outbound.DeliveryClaim, kinds []string) (sqlc.ClaimDueDeliveryRow, error) {
switch claim.Scope {
case outbound.ClaimScopeService:
return repository.queries.ClaimDueDelivery(ctx, sqlc.ClaimDueDeliveryParams{
LeaseOwner: pgUUID(claim.Owner),
LeaseSeconds: claim.Lease.Seconds(),
Kinds: kinds,
Now: pgTime(claim.Now),
Provider: claim.Account.Provider(),
ProviderAccount: claim.Account.Account(),
RebindProvider: claim.RebindProvider,
})
case outbound.ClaimScopeNotification:
product, err := repository.queries.ClaimDueProductDelivery(ctx, sqlc.ClaimDueProductDeliveryParams{
LeaseOwner: pgUUID(claim.Owner),
LeaseSeconds: claim.Lease.Seconds(),
Now: pgTime(claim.Now),
Provider: claim.Account.Provider(),
ProviderAccount: claim.Account.Account(),
RebindProvider: claim.RebindProvider,
})
return sqlc.ClaimDueDeliveryRow(product), err
default:
return sqlc.ClaimDueDeliveryRow{}, fmt.Errorf("deliveryRepository.claimRow - unknown claim scope %d: %w", claim.Scope, domain.ErrInvalidDelivery)
}
}
func (repository deliveryRepository) ClaimDue(ctx context.Context, claim outbound.DeliveryClaim) (outbound.ClaimedDelivery, error) {
const location = "deliveryRepository.ClaimDue"
if claim.Owner == uuid.Nil || claim.Account.IsZero() || len(claim.Kinds) == 0 || claim.Now.IsZero() || claim.Lease <= 0 {
@@ -418,15 +471,10 @@ func (repository deliveryRepository) ClaimDue(ctx context.Context, claim outboun
}
kinds = append(kinds, string(kind))
}
row, err := repository.queries.ClaimDueDelivery(ctx, sqlc.ClaimDueDeliveryParams{
LeaseOwner: pgUUID(claim.Owner),
LeaseSeconds: claim.Lease.Seconds(),
Kinds: kinds,
Now: pgTime(claim.Now),
Provider: claim.Account.Provider(),
ProviderAccount: claim.Account.Account(),
RebindProvider: claim.RebindProvider,
})
if !claimKindsBelongToScope(claim.Scope, claim.Kinds) {
return outbound.ClaimedDelivery{}, fmt.Errorf("%s - kinds do not belong to the claim scope: %w", location, domain.ErrInvalidDelivery)
}
row, err := repository.claimRow(ctx, claim, kinds)
if errors.Is(err, pgx.ErrNoRows) {
return outbound.ClaimedDelivery{}, outbound.ErrNoDeliveryDue
}
@@ -434,30 +482,33 @@ func (repository deliveryRepository) ClaimDue(ctx context.Context, claim outboun
return outbound.ClaimedDelivery{}, fmt.Errorf("%s - claim due delivery: %w", location, mapDeliveryError(err))
}
delivery, err := deliveryFromRow(sqlc.Delivery{
ID: row.ID,
SourceEventID: row.SourceEventID,
RecipientUserID: row.RecipientUserID,
RecipientEmail: row.RecipientEmail,
Kind: row.Kind,
TemplateVersion: row.TemplateVersion,
Subject: row.Subject,
TextBody: row.TextBody,
HtmlBody: row.HtmlBody,
ContentSha256: row.ContentSha256,
Provider: row.Provider,
ProviderAccount: row.ProviderAccount,
IdempotencyKey: row.IdempotencyKey,
Status: row.Status,
AttemptCount: row.AttemptCount,
NextAttemptAt: row.NextAttemptAt,
LastAttemptAt: row.LastAttemptAt,
ProviderMessageID: row.ProviderMessageID,
EmailTokenID: row.EmailTokenID,
CancelReason: row.CancelReason,
BodyRedactedAt: row.BodyRedactedAt,
Version: row.Version,
CreatedAt: row.CreatedAt,
UpdatedAt: row.UpdatedAt,
ID: row.ID,
SourceEventID: row.SourceEventID,
RecipientUserID: row.RecipientUserID,
RecipientEmail: row.RecipientEmail,
Kind: row.Kind,
TemplateVersion: row.TemplateVersion,
Subject: row.Subject,
TextBody: row.TextBody,
HtmlBody: row.HtmlBody,
ContentSha256: row.ContentSha256,
Provider: row.Provider,
ProviderAccount: row.ProviderAccount,
IdempotencyKey: row.IdempotencyKey,
Status: row.Status,
AttemptCount: row.AttemptCount,
NextAttemptAt: row.NextAttemptAt,
LastAttemptAt: row.LastAttemptAt,
ProviderMessageID: row.ProviderMessageID,
EmailTokenID: row.EmailTokenID,
CancelReason: row.CancelReason,
BodyRedactedAt: row.BodyRedactedAt,
Version: row.Version,
CreatedAt: row.CreatedAt,
UpdatedAt: row.UpdatedAt,
SubjectKind: row.SubjectKind,
SubjectID: row.SubjectID,
SubjectOrganizationID: row.SubjectOrganizationID,
})
if err != nil {
unreadable := &outbound.UnreadableDeliveryError{DeliveryID: uuid.UUID(row.ID.Bytes), FailureCount: row.FailureCount, Err: err}
@@ -575,9 +626,12 @@ func deliveryFromRow(row sqlc.Delivery) (domain.Delivery, error) {
return domain.Delivery{}, fmt.Errorf("postgres.deliveryFromRow - decode kind: %w", err)
}
var content domain.MailContent
if row.BodyRedactedAt.Valid {
switch {
case row.BodyRedactedAt.Valid && kind == domain.MailKindNotification:
content, err = domain.RestoreRedactedNotificationContent(row.TemplateVersion, row.Subject, row.ContentSha256)
case row.BodyRedactedAt.Valid:
content, err = domain.RestoreRedactedMailContent(kind, row.TemplateVersion, row.Subject, row.ContentSha256)
} else {
default:
content, err = domain.RestoreMailContent(kind, row.TemplateVersion, row.Subject, row.TextBody, row.HtmlBody, row.ContentSha256)
}
if err != nil {
@@ -587,12 +641,17 @@ func deliveryFromRow(row sqlc.Delivery) (domain.Delivery, error) {
if err != nil {
return domain.Delivery{}, fmt.Errorf("postgres.deliveryFromRow - decode provider account: %w", err)
}
subject, err := domain.RestoreMailSubject(row.SubjectKind.String, optionalUUID(row.SubjectID), optionalUUID(row.SubjectOrganizationID))
if err != nil {
return domain.Delivery{}, fmt.Errorf("postgres.deliveryFromRow - decode subject: %w", err)
}
delivery, err := domain.RestoreDelivery(domain.DeliverySnapshot{
ID: uuid.UUID(row.ID.Bytes),
SourceEventID: optionalUUID(row.SourceEventID),
RecipientUserID: uuid.UUID(row.RecipientUserID.Bytes),
RecipientAddress: row.RecipientEmail,
Content: content,
Subject: subject,
ProviderAccount: providerAccount,
IdempotencyKey: row.IdempotencyKey,
Status: domain.DeliveryStatus(row.Status),
@@ -654,13 +713,16 @@ func (repository mailRequestRepository) Create(ctx context.Context, request doma
return fmt.Errorf("mailRequestRepository.Create - validate request: %w", err)
}
err := repository.queries.InsertMailRequest(ctx, sqlc.InsertMailRequestParams{
ID: pgUUID(request.ID),
RecipientUserID: pgUUID(request.RecipientUserID),
Kind: string(request.Kind),
Subject: request.Notification.Subject,
Body: request.Notification.Body,
LinkPath: request.Notification.LinkPath,
CreatedAt: pgTime(request.CreatedAt),
ID: pgUUID(request.ID),
RecipientUserID: pgUUID(request.RecipientUserID),
Kind: string(request.Kind),
Subject: request.Notification.Subject,
Body: request.Notification.Body,
LinkPath: request.Notification.LinkPath,
SubjectKind: pgOptionalText(string(request.Subject.Kind())),
SubjectID: pgOptionalUUID(request.Subject.ID()),
SubjectOrganizationID: pgOptionalUUID(request.Subject.OrganizationID()),
CreatedAt: pgTime(request.CreatedAt),
})
if err != nil {
return fmt.Errorf("mailRequestRepository.Create - insert mail request: %w", mapDeliveryError(err))
@@ -680,11 +742,16 @@ func (repository mailRequestRepository) Lock(ctx context.Context, id uuid.UUID)
if err != nil {
return domain.MailRequest{}, fmt.Errorf("mailRequestRepository.Lock - decode kind: %w", err)
}
subject, err := domain.RestoreMailSubject(row.SubjectKind.String, optionalUUID(row.SubjectID), optionalUUID(row.SubjectOrganizationID))
if err != nil {
return domain.MailRequest{}, fmt.Errorf("mailRequestRepository.Lock - decode subject: %w", err)
}
request, err := domain.NewMailRequest(domain.MailRequest{
ID: uuid.UUID(row.ID.Bytes),
RecipientUserID: uuid.UUID(row.RecipientUserID.Bytes),
Kind: kind,
Notification: domain.NotificationText{Subject: row.Subject, Body: row.Body, LinkPath: row.LinkPath},
Subject: subject,
CreatedAt: row.CreatedAt.Time,
})
if err != nil {
@@ -0,0 +1,49 @@
package postgres
import (
"context"
"fmt"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// NotificationRights is available only inside a transaction: the rights check
// reads the standing in the transaction that holds the delivery lock.
func (unit *UnitOfWork) NotificationRights() outbound.NotificationRightsReader {
return notificationRightsReader{queries: unit.queries}
}
type notificationRightsReader struct {
queries *sqlc.Queries
}
var _ outbound.NotificationRightsReader = notificationRightsReader{}
func (reader notificationRightsReader) InvitationNoticeStanding(
ctx context.Context,
recipientUserID, invitationID, organizationID uuid.UUID,
) (domain.InvitationNoticeStanding, error) {
row, err := reader.queries.GetInvitationNoticeStanding(ctx, sqlc.GetInvitationNoticeStandingParams{
RecipientUserID: pgUUID(recipientUserID),
InvitationID: pgUUID(invitationID),
OrganizationID: pgUUID(organizationID),
})
if err != nil {
return domain.InvitationNoticeStanding{}, fmt.Errorf("notificationRightsReader.InvitationNoticeStanding - read standing: %w", mapDeliveryError(err))
}
return domain.InvitationNoticeStanding{
RecipientFound: row.RecipientFound,
RecipientEmailVerified: row.RecipientEmailVerified,
RecipientEmailKey: row.RecipientEmailKey,
InvitationFound: row.InvitationFound,
InvitationOrganizationID: optionalUUID(row.InvitationOrganizationID),
InvitationState: domain.InvitationState(row.InvitationState),
ResponseDeadlineAt: zeroableTime(row.InvitationResponseDeadlineAt),
OrganizationHidden: row.OrganizationHidden,
PublicationPublished: row.PublicationPublished,
}, nil
}
@@ -162,14 +162,14 @@ SET
claim_owner = NULL,
claimed_until = NULL,
text_body = CASE
WHEN deliveries.kind IN ('verification', 'password_reset') THEN '' ELSE deliveries.text_body
WHEN deliveries.kind IN ('verification', 'password_reset', 'notification') THEN '' ELSE deliveries.text_body
END,
html_body = CASE
WHEN deliveries.kind IN ('verification', 'password_reset') THEN '' ELSE deliveries.html_body
WHEN deliveries.kind IN ('verification', 'password_reset', 'notification') THEN '' ELSE deliveries.html_body
END,
body_redacted_at = CASE
WHEN
deliveries.kind IN ('verification', 'password_reset')
deliveries.kind IN ('verification', 'password_reset', 'notification')
THEN greatest(deliveries.updated_at, $1::timestamptz)
ELSE deliveries.body_redacted_at
END,
@@ -279,6 +279,9 @@ RETURNING
claimed.version,
claimed.created_at,
claimed.updated_at,
claimed.subject_kind,
claimed.subject_id,
claimed.subject_organization_id,
candidate.previous_claimed_until,
candidate.since_first_send_seconds,
candidate.manual_retry_pending,
@@ -323,6 +326,9 @@ type ClaimDueDeliveryRow struct {
Version int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
SubjectKind pgtype.Text
SubjectID pgtype.UUID
SubjectOrganizationID pgtype.UUID
PreviousClaimedUntil pgtype.Timestamptz
SinceFirstSendSeconds float64
ManualRetryPending pgtype.Bool
@@ -392,6 +398,203 @@ func (q *Queries) ClaimDueDelivery(ctx context.Context, arg ClaimDueDeliveryPara
&i.Version,
&i.CreatedAt,
&i.UpdatedAt,
&i.SubjectKind,
&i.SubjectID,
&i.SubjectOrganizationID,
&i.PreviousClaimedUntil,
&i.SinceFirstSendSeconds,
&i.ManualRetryPending,
&i.ManualRetryCycleStarted,
&i.SendStartUnsettled,
&i.HasUncertainAttempt,
)
return i, err
}
const claimDueProductDelivery = `-- name: ClaimDueProductDelivery :one
WITH candidate AS (
SELECT
due.id,
due.claimed_until AS previous_claimed_until,
coalesce(
extract(EPOCH FROM clock_timestamp() - due.first_send_started_at),
-1
)::float8 AS since_first_send_seconds,
(due.manual_retry_authorized_at IS NOT NULL AND due.manual_retry_started_at IS NULL)
AS manual_retry_pending,
(due.manual_retry_started_at IS NOT NULL)::boolean AS manual_retry_cycle_started,
(
due.send_started_attempt_count IS NOT NULL
AND due.send_started_attempt_count = due.attempt_count
)::boolean AS send_start_unsettled,
EXISTS (
SELECT 1
FROM delivery_attempts AS prior_attempt
WHERE prior_attempt.delivery_id = due.id
AND prior_attempt.outcome = 'unknown'
)::boolean AS has_uncertain_attempt
FROM deliveries AS due
WHERE
due.kind = 'notification'
AND due.status IN ('pending', 'waiting_quota', 'unknown')
AND due.next_attempt_at IS NOT NULL
AND due.next_attempt_at <= $3::timestamptz
AND (
(
due.provider = $4
AND due.provider_account = $5
)
OR (
due.provider = $6::text
AND due.attempt_count = 0
)
)
AND (
due.claim_owner IS NULL
OR due.claimed_until <= clock_timestamp()
)
ORDER BY due.next_attempt_at, due.id
LIMIT 1
FOR UPDATE SKIP LOCKED
)
UPDATE deliveries AS claimed
SET
claim_owner = $1::uuid,
claimed_until = clock_timestamp()
+ make_interval(secs => $2::float8)
FROM candidate
WHERE claimed.id = candidate.id
RETURNING
claimed.id,
claimed.source_event_id,
claimed.recipient_user_id,
claimed.recipient_email,
claimed.kind,
claimed.template_version,
claimed.subject,
claimed.text_body,
claimed.html_body,
claimed.content_sha256,
claimed.provider,
claimed.provider_account,
claimed.idempotency_key,
claimed.status,
claimed.attempt_count,
claimed.next_attempt_at,
claimed.last_attempt_at,
claimed.provider_message_id,
claimed.email_token_id,
claimed.cancel_reason,
claimed.body_redacted_at,
claimed.failure_count,
claimed.version,
claimed.created_at,
claimed.updated_at,
claimed.subject_kind,
claimed.subject_id,
claimed.subject_organization_id,
candidate.previous_claimed_until,
candidate.since_first_send_seconds,
candidate.manual_retry_pending,
candidate.manual_retry_cycle_started,
candidate.send_start_unsettled,
candidate.has_uncertain_attempt
`
type ClaimDueProductDeliveryParams struct {
LeaseOwner pgtype.UUID
LeaseSeconds float64
Now pgtype.Timestamptz
Provider string
ProviderAccount string
RebindProvider string
}
type ClaimDueProductDeliveryRow struct {
ID pgtype.UUID
SourceEventID pgtype.UUID
RecipientUserID pgtype.UUID
RecipientEmail string
Kind string
TemplateVersion string
Subject string
TextBody string
HtmlBody string
ContentSha256 []byte
Provider string
ProviderAccount string
IdempotencyKey string
Status string
AttemptCount int32
NextAttemptAt pgtype.Timestamptz
LastAttemptAt pgtype.Timestamptz
ProviderMessageID pgtype.Text
EmailTokenID pgtype.UUID
CancelReason pgtype.Text
BodyRedactedAt pgtype.Timestamptz
FailureCount int32
Version int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
SubjectKind pgtype.Text
SubjectID pgtype.UUID
SubjectOrganizationID pgtype.UUID
PreviousClaimedUntil pgtype.Timestamptz
SinceFirstSendSeconds float64
ManualRetryPending pgtype.Bool
ManualRetryCycleStarted bool
SendStartUnsettled bool
HasUncertainAttempt bool
}
// Claims the most overdue product notification, under the same rules as
// ClaimDueDelivery: a lease in the database clock, the configured provider
// account or a rebind of a delivery before its first attempt, and no live
// lease. It reads deliveries_product_due_idx, whose predicate repeats the
// literal kind below, so the backlog of service mail never enters the scan.
// A notification is claimed here whatever its subject; the sending worker
// checks the subject's rights after the claim and cancels a notice whose
// basis no longer holds.
func (q *Queries) ClaimDueProductDelivery(ctx context.Context, arg ClaimDueProductDeliveryParams) (ClaimDueProductDeliveryRow, error) {
row := q.db.QueryRow(ctx, claimDueProductDelivery,
arg.LeaseOwner,
arg.LeaseSeconds,
arg.Now,
arg.Provider,
arg.ProviderAccount,
arg.RebindProvider,
)
var i ClaimDueProductDeliveryRow
err := row.Scan(
&i.ID,
&i.SourceEventID,
&i.RecipientUserID,
&i.RecipientEmail,
&i.Kind,
&i.TemplateVersion,
&i.Subject,
&i.TextBody,
&i.HtmlBody,
&i.ContentSha256,
&i.Provider,
&i.ProviderAccount,
&i.IdempotencyKey,
&i.Status,
&i.AttemptCount,
&i.NextAttemptAt,
&i.LastAttemptAt,
&i.ProviderMessageID,
&i.EmailTokenID,
&i.CancelReason,
&i.BodyRedactedAt,
&i.FailureCount,
&i.Version,
&i.CreatedAt,
&i.UpdatedAt,
&i.SubjectKind,
&i.SubjectID,
&i.SubjectOrganizationID,
&i.PreviousClaimedUntil,
&i.SinceFirstSendSeconds,
&i.ManualRetryPending,
@@ -444,40 +647,46 @@ SELECT
claimed_until,
first_send_started_at,
failure_count,
body_redacted_at
body_redacted_at,
subject_kind,
subject_id,
subject_organization_id
FROM deliveries
WHERE id = $1
`
type GetDeliveryByIDRow struct {
ID pgtype.UUID
SourceEventID pgtype.UUID
RecipientUserID pgtype.UUID
RecipientEmail string
Kind string
TemplateVersion string
Subject string
TextBody string
HtmlBody string
ContentSha256 []byte
Provider string
ProviderAccount string
IdempotencyKey string
Status string
AttemptCount int32
NextAttemptAt pgtype.Timestamptz
LastAttemptAt pgtype.Timestamptz
ProviderMessageID pgtype.Text
Version int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
EmailTokenID pgtype.UUID
CancelReason pgtype.Text
ClaimOwner pgtype.UUID
ClaimedUntil pgtype.Timestamptz
FirstSendStartedAt pgtype.Timestamptz
FailureCount int32
BodyRedactedAt pgtype.Timestamptz
ID pgtype.UUID
SourceEventID pgtype.UUID
RecipientUserID pgtype.UUID
RecipientEmail string
Kind string
TemplateVersion string
Subject string
TextBody string
HtmlBody string
ContentSha256 []byte
Provider string
ProviderAccount string
IdempotencyKey string
Status string
AttemptCount int32
NextAttemptAt pgtype.Timestamptz
LastAttemptAt pgtype.Timestamptz
ProviderMessageID pgtype.Text
Version int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
EmailTokenID pgtype.UUID
CancelReason pgtype.Text
ClaimOwner pgtype.UUID
ClaimedUntil pgtype.Timestamptz
FirstSendStartedAt pgtype.Timestamptz
FailureCount int32
BodyRedactedAt pgtype.Timestamptz
SubjectKind pgtype.Text
SubjectID pgtype.UUID
SubjectOrganizationID pgtype.UUID
}
func (q *Queries) GetDeliveryByID(ctx context.Context, id pgtype.UUID) (GetDeliveryByIDRow, error) {
@@ -512,6 +721,9 @@ func (q *Queries) GetDeliveryByID(ctx context.Context, id pgtype.UUID) (GetDeliv
&i.FirstSendStartedAt,
&i.FailureCount,
&i.BodyRedactedAt,
&i.SubjectKind,
&i.SubjectID,
&i.SubjectOrganizationID,
)
return i, err
}
@@ -730,6 +942,9 @@ INSERT INTO deliveries (
last_attempt_at,
provider_message_id,
email_token_id,
subject_kind,
subject_id,
subject_organization_id,
version,
created_at,
updated_at
@@ -755,34 +970,40 @@ INSERT INTO deliveries (
$19,
$20,
$21,
$22
$22,
$23,
$24,
$25
)
ON CONFLICT (id) DO NOTHING
`
type InsertDeliveryParams struct {
ID pgtype.UUID
SourceEventID pgtype.UUID
RecipientUserID pgtype.UUID
RecipientEmail string
Kind string
TemplateVersion string
Subject string
TextBody string
HtmlBody string
ContentSha256 []byte
Provider string
ProviderAccount string
IdempotencyKey string
Status string
AttemptCount int32
NextAttemptAt pgtype.Timestamptz
LastAttemptAt pgtype.Timestamptz
ProviderMessageID pgtype.Text
EmailTokenID pgtype.UUID
Version int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
ID pgtype.UUID
SourceEventID pgtype.UUID
RecipientUserID pgtype.UUID
RecipientEmail string
Kind string
TemplateVersion string
Subject string
TextBody string
HtmlBody string
ContentSha256 []byte
Provider string
ProviderAccount string
IdempotencyKey string
Status string
AttemptCount int32
NextAttemptAt pgtype.Timestamptz
LastAttemptAt pgtype.Timestamptz
ProviderMessageID pgtype.Text
EmailTokenID pgtype.UUID
SubjectKind pgtype.Text
SubjectID pgtype.UUID
SubjectOrganizationID pgtype.UUID
Version int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
// Stores a new delivery. A delivery with the same ID already exists when the
@@ -811,6 +1032,9 @@ func (q *Queries) InsertDelivery(ctx context.Context, arg InsertDeliveryParams)
arg.LastAttemptAt,
arg.ProviderMessageID,
arg.EmailTokenID,
arg.SubjectKind,
arg.SubjectID,
arg.SubjectOrganizationID,
arg.Version,
arg.CreatedAt,
arg.UpdatedAt,
@@ -829,6 +1053,9 @@ INSERT INTO mail_requests (
subject,
body,
link_path,
subject_kind,
subject_id,
subject_organization_id,
created_at
) VALUES (
$1,
@@ -837,18 +1064,24 @@ INSERT INTO mail_requests (
$4,
$5,
$6,
$7
$7,
$8,
$9,
$10
)
`
type InsertMailRequestParams struct {
ID pgtype.UUID
RecipientUserID pgtype.UUID
Kind string
Subject string
Body string
LinkPath string
CreatedAt pgtype.Timestamptz
ID pgtype.UUID
RecipientUserID pgtype.UUID
Kind string
Subject string
Body string
LinkPath string
SubjectKind pgtype.Text
SubjectID pgtype.UUID
SubjectOrganizationID pgtype.UUID
CreatedAt pgtype.Timestamptz
}
func (q *Queries) InsertMailRequest(ctx context.Context, arg InsertMailRequestParams) error {
@@ -859,6 +1092,9 @@ func (q *Queries) InsertMailRequest(ctx context.Context, arg InsertMailRequestPa
arg.Subject,
arg.Body,
arg.LinkPath,
arg.SubjectKind,
arg.SubjectID,
arg.SubjectOrganizationID,
arg.CreatedAt,
)
return err
@@ -945,20 +1181,36 @@ SELECT
subject,
body,
link_path,
subject_kind,
subject_id,
subject_organization_id,
created_at
FROM mail_requests
WHERE id = $1
FOR UPDATE
`
type LockMailRequestRow struct {
ID pgtype.UUID
RecipientUserID pgtype.UUID
Kind string
Subject string
Body string
LinkPath string
SubjectKind pgtype.Text
SubjectID pgtype.UUID
SubjectOrganizationID pgtype.UUID
CreatedAt pgtype.Timestamptz
}
// Locks a request for the consumer transaction that turns it into a
// delivery. A concurrent consumer of the same request waits here and then
// finds the row deleted. The account cleanup and the cascade from users take
// the same row lock, so a request is never converted for an account whose
// deletion is in progress without one of the two transactions waiting.
func (q *Queries) LockMailRequest(ctx context.Context, id pgtype.UUID) (MailRequest, error) {
func (q *Queries) LockMailRequest(ctx context.Context, id pgtype.UUID) (LockMailRequestRow, error) {
row := q.db.QueryRow(ctx, lockMailRequest, id)
var i MailRequest
var i LockMailRequestRow
err := row.Scan(
&i.ID,
&i.RecipientUserID,
@@ -966,6 +1218,9 @@ func (q *Queries) LockMailRequest(ctx context.Context, id pgtype.UUID) (MailRequ
&i.Subject,
&i.Body,
&i.LinkPath,
&i.SubjectKind,
&i.SubjectID,
&i.SubjectOrganizationID,
&i.CreatedAt,
)
return i, err
@@ -1181,7 +1436,7 @@ SET
WHEN
$1::boolean
AND deliveries.failure_count + 1 >= $2::integer
AND deliveries.kind IN ('verification', 'password_reset')
AND deliveries.kind IN ('verification', 'password_reset', 'notification')
THEN ''
ELSE deliveries.text_body
END,
@@ -1189,7 +1444,7 @@ SET
WHEN
$1::boolean
AND deliveries.failure_count + 1 >= $2::integer
AND deliveries.kind IN ('verification', 'password_reset')
AND deliveries.kind IN ('verification', 'password_reset', 'notification')
THEN ''
ELSE deliveries.html_body
END,
@@ -1197,7 +1452,7 @@ SET
WHEN
$1::boolean
AND deliveries.failure_count + 1 >= $2::integer
AND deliveries.kind IN ('verification', 'password_reset')
AND deliveries.kind IN ('verification', 'password_reset', 'notification')
THEN greatest(deliveries.updated_at, $4::timestamptz)
ELSE deliveries.body_redacted_at
END,
@@ -1328,21 +1583,21 @@ SET
text_body = CASE
WHEN
$1::text = 'cancelled'
AND deliveries.kind IN ('verification', 'password_reset')
AND deliveries.kind IN ('verification', 'password_reset', 'notification')
THEN ''
ELSE deliveries.text_body
END,
html_body = CASE
WHEN
$1::text = 'cancelled'
AND deliveries.kind IN ('verification', 'password_reset')
AND deliveries.kind IN ('verification', 'password_reset', 'notification')
THEN ''
ELSE deliveries.html_body
END,
body_redacted_at = CASE
WHEN
$1::text = 'cancelled'
AND deliveries.kind IN ('verification', 'password_reset')
AND deliveries.kind IN ('verification', 'password_reset', 'notification')
THEN $7
ELSE deliveries.body_redacted_at
END,
@@ -532,6 +532,12 @@ type Delivery struct {
ManualRetryStartedAt pgtype.Timestamptz
// Attempt count when the latest provider call started. Equality with attempt_count means its result was not recorded; a greater attempt_count means a provider result was stored after that send-start.
SendStartedAttemptCount pgtype.Int4
// The kind of record a notification is about; set only for a notification, NULL when it names none. The product sending worker re-checks its rights before the send.
SubjectKind pgtype.Text
// The record a notification is about; an opaque ID, never an address or a contact.
SubjectID pgtype.UUID
// The organization the subject record belongs to.
SubjectOrganizationID pgtype.UUID
}
type DeliveryAttempt struct {
@@ -702,6 +708,12 @@ type MailRequest struct {
Body string
LinkPath string
CreatedAt pgtype.Timestamptz
// The kind of record the notification is about, NULL when it names none; the sending worker checks the rights of that kind.
SubjectKind pgtype.Text
// The record the notification is about, for example the invitation; an opaque ID, never an address or a contact.
SubjectID pgtype.UUID
// The organization the subject record belongs to, for example the organization that sent the invitation.
SubjectOrganizationID pgtype.UUID
}
type Membership struct {
@@ -0,0 +1,86 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: notification_rights.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const getInvitationNoticeStanding = `-- name: GetInvitationNoticeStanding :one
SELECT
(recipient.id IS NOT NULL)::boolean AS recipient_found,
coalesce(recipient.email_verified_at IS NOT NULL, false)::boolean AS recipient_email_verified,
coalesce(recipient.email_normalized, '')::text AS recipient_email_key,
(invitation.id IS NOT NULL)::boolean AS invitation_found,
invitation.organization_id AS invitation_organization_id,
coalesce(invitation.state, '')::text AS invitation_state,
invitation.response_deadline_at AS invitation_response_deadline_at,
EXISTS (
SELECT 1
FROM candidate_hidden_organizations AS hidden
WHERE
hidden.user_id = $1
AND hidden.organization_id = $2
)::boolean AS organization_hidden,
EXISTS (
SELECT 1
FROM candidate_effective_publications AS publication
WHERE publication.user_id = $1
)::boolean AS publication_published
FROM (SELECT $1::uuid AS user_id) AS target
LEFT JOIN users AS recipient
ON recipient.id = target.user_id
LEFT JOIN invitations AS invitation
ON invitation.id = $3
AND invitation.candidate_id = target.user_id
AND invitation.organization_id = $2
`
type GetInvitationNoticeStandingParams struct {
RecipientUserID pgtype.UUID
OrganizationID pgtype.UUID
InvitationID pgtype.UUID
}
type GetInvitationNoticeStandingRow struct {
RecipientFound bool
RecipientEmailVerified bool
RecipientEmailKey string
InvitationFound bool
InvitationOrganizationID pgtype.UUID
InvitationState string
InvitationResponseDeadlineAt pgtype.Timestamptz
OrganizationHidden bool
PublicationPublished bool
}
// Reads the standing of an invitation notice in one statement, for the rights
// check before the send. The recipient is matched by ID; the invitation must
// be addressed to that recipient and belong to the organization of the
// subject, otherwise it is not found. It reads no address and no contact:
// the recipient address is returned only as its comparison key. The hiding
// is the candidate's own current state. The publication is read through the
// effective view, so a publication whose C2 consent was revoked does not count
// as current. A missing account or invitation gives false flags and NULL
// columns.
func (q *Queries) GetInvitationNoticeStanding(ctx context.Context, arg GetInvitationNoticeStandingParams) (GetInvitationNoticeStandingRow, error) {
row := q.db.QueryRow(ctx, getInvitationNoticeStanding, arg.RecipientUserID, arg.OrganizationID, arg.InvitationID)
var i GetInvitationNoticeStandingRow
err := row.Scan(
&i.RecipientFound,
&i.RecipientEmailVerified,
&i.RecipientEmailKey,
&i.InvitationFound,
&i.InvitationOrganizationID,
&i.InvitationState,
&i.InvitationResponseDeadlineAt,
&i.OrganizationHidden,
&i.PublicationPublished,
)
return i, err
}
@@ -99,6 +99,15 @@ type Querier interface {
// now is the application clock. Unknown deliveries without a scheduled retry
// and quota waits with an unknown reset wait for an operator.
ClaimDueDelivery(ctx context.Context, arg ClaimDueDeliveryParams) (ClaimDueDeliveryRow, error)
// Claims the most overdue product notification, under the same rules as
// ClaimDueDelivery: a lease in the database clock, the configured provider
// account or a rebind of a delivery before its first attempt, and no live
// lease. It reads deliveries_product_due_idx, whose predicate repeats the
// literal kind below, so the backlog of service mail never enters the scan.
// A notification is claimed here whatever its subject; the sending worker
// checks the subject's rights after the claim and cancels a notice whose
// basis no longer holds.
ClaimDueProductDelivery(ctx context.Context, arg ClaimDueProductDeliveryParams) (ClaimDueProductDeliveryRow, error)
// Claims up to batch_limit jobs of the listed kinds in one statement: jobs
// whose available_at has passed, and running jobs whose lease expired
// because their worker stopped without finishing them. Rows that another
@@ -343,6 +352,16 @@ type Querier interface {
GetInvitationAcceptResult(ctx context.Context, scopeHash []byte) (GetInvitationAcceptResultRow, error)
GetInvitationCreationResult(ctx context.Context, scopeHash []byte) (string, error)
GetInvitationDeclineResult(ctx context.Context, scopeHash []byte) (GetInvitationDeclineResultRow, error)
// Reads the standing of an invitation notice in one statement, for the rights
// check before the send. The recipient is matched by ID; the invitation must
// be addressed to that recipient and belong to the organization of the
// subject, otherwise it is not found. It reads no address and no contact:
// the recipient address is returned only as its comparison key. The hiding
// is the candidate's own current state. The publication is read through the
// effective view, so a publication whose C2 consent was revoked does not count
// as current. A missing account or invitation gives false flags and NULL
// columns.
GetInvitationNoticeStanding(ctx context.Context, arg GetInvitationNoticeStandingParams) (GetInvitationNoticeStandingRow, error)
GetInvitationSendResult(ctx context.Context, scopeHash []byte) (GetInvitationSendResultRow, error)
// The caller holds the attempt row lock, so the last mark is stable.
GetLastAssessmentOriginMark(ctx context.Context, attemptID pgtype.UUID) (AssessmentAttemptOriginMark, error)
@@ -864,7 +883,7 @@ type Querier interface {
// finds the row deleted. The account cleanup and the cascade from users take
// the same row lock, so a request is never converted for an account whose
// deletion is in progress without one of the two transactions waiting.
LockMailRequest(ctx context.Context, id pgtype.UUID) (MailRequest, error)
LockMailRequest(ctx context.Context, id pgtype.UUID) (LockMailRequestRow, error)
// Locks the next relay batch. For each aggregate only its earliest unpublished
// event (lowest aggregate_version, then position) qualifies, so a relay never
// holds a later version while an earlier one is still pending, whether that
@@ -36,6 +36,10 @@ type mailMetrics struct {
// per process, not database-wide, so dashboards and alerts aggregate it
// with max across instances.
senderRunning client.Gauge
// notificationSenderRunning is 1 while this process's product notification
// loop runs. It is separate from senderRunning, so the service loop's alert
// keeps its meaning.
notificationSenderRunning client.Gauge
// senderCancelled counts deliveries that the sending worker ended without
// sending, by cancel reason, a closed set from the domain.
senderCancelled *client.CounterVec
@@ -100,6 +104,10 @@ func newMailMetrics() mailMetrics {
Name: "lincodex_mail_sender_running",
Help: "1 while the mail sending loop of this process runs, 0 while it does not, for example with EMAIL_PROVIDER=disabled or after shutdown began.",
}),
notificationSenderRunning: client.NewGauge(client.GaugeOpts{
Name: "lincodex_notification_sender_running",
Help: "1 while the product notification sending loop of this process runs, 0 while it does not, for example with EMAIL_PROVIDER=disabled or after shutdown began.",
}),
}
// Every reason exists at zero, so an alert on an increase sees the first
// cancellation instead of a new series.
@@ -132,7 +140,7 @@ func (mail mailMetrics) collectors() []client.Collector {
return []client.Collector{
mail.deliveries, mail.oldestDuePendingAge, mail.lastSuccess,
mail.quotaUsed, mail.quotaLimit, mail.quotaProviderExhausted,
mail.senderRunning, mail.senderCancelled, mail.identityRateLimited,
mail.senderRunning, mail.notificationSenderRunning, mail.senderCancelled, mail.identityRateLimited,
}
}
@@ -182,6 +190,16 @@ func (metrics *Metrics) SetMailSenderRunning(running bool) {
metrics.mail.senderRunning.Set(value)
}
// SetNotificationSenderRunning reports whether this process's product
// notification loop runs: 1 from its start until its stop, 0 otherwise.
func (metrics *Metrics) SetNotificationSenderRunning(running bool) {
value := 0.0
if running {
value = 1
}
metrics.mail.notificationSenderRunning.Set(value)
}
// PrepareMailMetricsReads exposes the last success time at 0 when the
// sampler starts, so an alert sees a sampler that never reads successfully.
func (metrics *Metrics) PrepareMailMetricsReads() {
@@ -18,6 +18,19 @@ func TestMetricsHandlerExposesWhetherTheMailSenderRuns(t *testing.T) {
requireSeries(t, scrape(t, metrics), "lincodex_mail_sender_running 0")
}
func TestMetricsHandlerExposesWhetherTheNotificationSenderRuns(t *testing.T) {
metrics := New()
// The product loop has its own series, so the service loop's gauge keeps
// its meaning when only the product loop runs.
requireSeries(t, scrape(t, metrics), "lincodex_notification_sender_running 0")
metrics.SetNotificationSenderRunning(true)
requireSeries(t, scrape(t, metrics), "lincodex_notification_sender_running 1", "lincodex_mail_sender_running 0")
metrics.SetNotificationSenderRunning(false)
requireSeries(t, scrape(t, metrics), "lincodex_notification_sender_running 0")
}
func TestMetricsHandlerCountsCancelledMailByABoundedReason(t *testing.T) {
metrics := New()
// Every reason exists at zero before the first cancellation.
@@ -26,6 +39,9 @@ func TestMetricsHandlerCountsCancelledMailByABoundedReason(t *testing.T) {
`lincodex_mail_sender_cancelled_total{reason="content_invalid"} 0`,
`lincodex_mail_sender_cancelled_total{reason="processing_failed"} 0`,
`lincodex_mail_sender_cancelled_total{reason="token_revoked"} 0`,
`lincodex_mail_sender_cancelled_total{reason="rights_revoked"} 0`,
`lincodex_mail_sender_cancelled_total{reason="recipient_ineligible"} 0`,
`lincodex_mail_sender_cancelled_total{reason="source_closed"} 0`,
)
metrics.ObserveMailCancelled("content_invalid")
metrics.ObserveMailCancelled("content_invalid")
+19 -10
View File
@@ -51,6 +51,10 @@ type Application struct {
// the servers run. It is nil with EMAIL_PROVIDER=disabled or when the
// database is not configured.
mailSending *mailsender.Worker
// notificationSending sends the stored product notifications while the
// servers run, after their rights checks. It is nil under the same
// conditions as mailSending.
notificationSending *notificationSendingWorker
// deliveryMetrics reads the delivery and quota gauges while the servers
// run. It is nil when the database is not configured.
deliveryMetrics *deliverymetrics.Sampler
@@ -66,19 +70,21 @@ func NewApplication(
consumers eventConsumers,
jobs *jobrunner.Worker,
mailSending *mailsender.Worker,
notificationSending *notificationSendingWorker,
deliveryMetrics *deliverymetrics.Sampler,
) *Application {
return &Application{
config: config,
apiHandler: apiHandler,
metrics: metrics,
logger: logger,
mailSender: mailSender,
relay: relay,
consumers: consumers,
jobs: jobs,
mailSending: mailSending,
deliveryMetrics: deliveryMetrics,
config: config,
apiHandler: apiHandler,
metrics: metrics,
logger: logger,
mailSender: mailSender,
relay: relay,
consumers: consumers,
jobs: jobs,
mailSending: mailSending,
notificationSending: notificationSending,
deliveryMetrics: deliveryMetrics,
}
}
@@ -224,6 +230,9 @@ func (application *Application) startWorkers(ctx context.Context) <-chan struct{
if application.mailSending != nil {
workers.Go(func() { application.mailSending.Run(ctx) })
}
if application.notificationSending != nil {
workers.Go(func() { application.notificationSending.Run(ctx) })
}
if application.deliveryMetrics != nil {
workers.Go(func() { application.deliveryMetrics.Run(ctx) })
}
+1 -1
View File
@@ -207,7 +207,7 @@ func TestApplicationRunsConsumersWhileServingAndWaitsForThem(t *testing.T) {
HTTPAddr: "127.0.0.1:0",
MetricsAddr: "127.0.0.1:0",
ShutdownTimeout: time.Second,
}, http.NotFoundHandler(), metrics, logger, nil, nil, eventConsumers{consumer}, nil, nil, nil)
}, http.NotFoundHandler(), metrics, logger, nil, nil, eventConsumers{consumer}, nil, nil, nil, nil)
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
@@ -63,7 +63,7 @@ func TestApplicationRunsAndStopsTheDeliveryMetricsSampler(t *testing.T) {
if sampler == nil {
t.Fatal("newDeliveryMetrics() built no sampler with DATABASE_URL set")
}
application := NewApplication(settings, http.NotFoundHandler(), metrics, logger, nil, nil, nil, nil, nil, sampler)
application := NewApplication(settings, http.NotFoundHandler(), metrics, logger, nil, nil, nil, nil, nil, nil, sampler)
ctx, cancel := context.WithCancel(t.Context())
finished := make(chan error, 1)
+1 -1
View File
@@ -93,7 +93,7 @@ func TestApplicationRunsAndStopsTheJobWorker(t *testing.T) {
if worker == nil {
t.Fatal("buildJobWorker() built no worker for a registered kind")
}
application := NewApplication(settings, http.NotFoundHandler(), metrics, logger, nil, nil, nil, worker, nil, nil)
application := NewApplication(settings, http.NotFoundHandler(), metrics, logger, nil, nil, nil, worker, nil, nil, nil)
ctx, cancel := context.WithCancel(t.Context())
finished := make(chan error, 1)
+27 -15
View File
@@ -105,16 +105,7 @@ func newMailSenderWorker(
postgres.NewTransactor(pool),
mailSender,
gate,
notification.ServiceMailSenderSettings{
Account: account,
RebindProvider: string(config.EmailProviderDisabled),
Lease: settings.EmailTimeout + mailSenderLeaseMargin,
StoreTimeout: mailSenderStoreTimeout,
SettleBudget: mailSenderSettleBudget,
ShutdownSettleBudget: shutdownSettleBudget(settings.ShutdownTimeout),
MaxFailures: mailSenderMaxFailures,
Retry: notification.RetryPolicy{Initial: mailSenderRetryInitial, Max: mailSenderRetryMax, Jitter: notification.RandomJitter},
},
deliverySenderSettings(settings, account),
time.Now,
workerLogger,
)
@@ -122,11 +113,7 @@ func newMailSenderWorker(
pool.Close()
return nil, nil, fmt.Errorf("bootstrap.newMailSenderWorker - create sender: %w", err)
}
worker, err := mailsender.New(sender, metrics, workerLogger, mailsender.Settings{
PollInterval: mailSenderPollInterval,
Backoff: retry.Backoff{Initial: mailSenderBackoffInitial, Max: mailSenderBackoffMax},
ShutdownGrace: mailSenderShutdownGrace,
})
worker, err := mailsender.New(sender, metrics, workerLogger, mailSenderLoopSettings())
if err != nil {
pool.Close()
return nil, nil, fmt.Errorf("bootstrap.newMailSenderWorker - create worker: %w", err)
@@ -136,6 +123,31 @@ func newMailSenderWorker(
return worker, pool.Close, nil
}
// deliverySenderSettings are the limits of a sending worker of any lane. The
// disabled transport is the only one whose unsent deliveries may be rebound to
// the configured account, so every lane rebinds from it.
func deliverySenderSettings(settings config.Config, account domain.MailProviderAccount) notification.DeliverySenderSettings {
return notification.DeliverySenderSettings{
Account: account,
RebindProvider: string(config.EmailProviderDisabled),
Lease: settings.EmailTimeout + mailSenderLeaseMargin,
StoreTimeout: mailSenderStoreTimeout,
SettleBudget: mailSenderSettleBudget,
ShutdownSettleBudget: shutdownSettleBudget(settings.ShutdownTimeout),
MaxFailures: mailSenderMaxFailures,
Retry: notification.RetryPolicy{Initial: mailSenderRetryInitial, Max: mailSenderRetryMax, Jitter: notification.RandomJitter},
}
}
// mailSenderLoopSettings are the pacing limits of a sending loop of any lane.
func mailSenderLoopSettings() mailsender.Settings {
return mailsender.Settings{
PollInterval: mailSenderPollInterval,
Backoff: retry.Backoff{Initial: mailSenderBackoffInitial, Max: mailSenderBackoffMax},
ShutdownGrace: mailSenderShutdownGrace,
}
}
// shutdownSettleBudget is the time to store the answer of a send once shutdown
// began: what SHUTDOWN_TIMEOUT leaves after the shutdown grace, at most
// mailSenderMaxShutdownSettle and at least one second.
@@ -93,7 +93,7 @@ func TestApplicationRunsAndStopsTheMailSenderWorker(t *testing.T) {
if worker == nil {
t.Fatal("newMailSenderWorker() built no worker for an active transport")
}
application := NewApplication(settings, http.NotFoundHandler(), metrics, logger, nil, nil, nil, nil, worker, nil)
application := NewApplication(settings, http.NotFoundHandler(), metrics, logger, nil, nil, nil, nil, worker, nil, nil)
ctx, cancel := context.WithCancel(t.Context())
finished := make(chan error, 1)
@@ -0,0 +1,107 @@
package bootstrap
import (
"context"
"fmt"
"log/slog"
"time"
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/notification"
"lincodex/backend/internal/worker/mailsender"
)
// notificationSendingWorker is the sending loop of product notifications. Its
// own type keeps it apart from the service mail loop in the dependency graph.
type notificationSendingWorker struct {
*mailsender.Worker
}
var _ mailsender.Metrics = notificationSenderMetrics{}
// notificationSenderMetrics reports the product loop to the process metrics:
// its running state to its own gauge, and its cancellations to the counter the
// service loop also uses, by reason.
type notificationSenderMetrics struct {
metrics *prometheus.Metrics
}
func (metrics notificationSenderMetrics) SetMailSenderRunning(running bool) {
metrics.metrics.SetNotificationSenderRunning(running)
}
func (metrics notificationSenderMetrics) ObserveMailCancelled(reason string) {
metrics.metrics.ObserveMailCancelled(reason)
}
// newNotificationSenderWorker builds the sending loop of product notifications
// and the PostgreSQL pool it owns. It shares the transport, the provider
// account, and the timing of the service loop, but its quota gate keeps the
// service reserve free: a notification is admitted only while each window stays
// above EMAIL_SERVICE_RESERVE_DAILY and EMAIL_SERVICE_RESERVE_MONTHLY after it.
//
// Like the service loop, it returns no worker when EMAIL_PROVIDER=disabled or
// DATABASE_URL is unset, so a notification waits, pinned to the transport it
// was created under, until a transport runs. Nothing connects here.
func newNotificationSenderWorker(
ctx context.Context,
settings config.Config,
logger *slog.Logger,
metrics *prometheus.Metrics,
mailSender outbound.MailSender,
) (*notificationSendingWorker, func(), error) {
switch {
case settings.EmailProvider == config.EmailProviderDisabled:
logger.Info("notification sender worker is not started because EMAIL_PROVIDER is disabled; stored notifications wait")
return nil, func() {}, nil
case settings.DatabaseURL == "":
logger.Warn("notification sender worker skipped because DATABASE_URL is not set")
return nil, func() {}, nil
}
account, err := domain.NewMailProviderAccount(string(settings.EmailProvider), settings.EmailAccount)
if err != nil {
return nil, nil, fmt.Errorf("bootstrap.newNotificationSenderWorker - provider account: %w", err)
}
limits, err := domain.NewMailQuotaLimits(int64(settings.EmailQuotaDaily), int64(settings.EmailQuotaMonthly))
if err != nil {
return nil, nil, fmt.Errorf("bootstrap.newNotificationSenderWorker - quota limits: %w", err)
}
workerLogger := logger.With(slog.String("component", "notification_sender"))
gate, err := notification.NewQuotaGate(account, limits, mailIdempotencyWindow(settings), time.Now, workerLogger).
WithReserve(int64(settings.EmailServiceReserveDaily), int64(settings.EmailServiceReserveMonthly))
if err != nil {
return nil, nil, fmt.Errorf("bootstrap.newNotificationSenderWorker - service reserve: %w", err)
}
pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, mailSenderPoolMaxConns)
if err != nil {
return nil, nil, fmt.Errorf("bootstrap.newNotificationSenderWorker - create pool: %w", err)
}
sender, err := notification.NewNotificationSender(
postgres.NewTransactor(pool),
mailSender,
gate,
deliverySenderSettings(settings, account),
time.Now,
workerLogger,
// Every subject kind a notification may name needs its check here. A
// kind without one is refused by the sender, so it never goes out
// unchecked.
[]notification.SubjectRights{notification.NewInvitationNoticeRights()},
)
if err != nil {
pool.Close()
return nil, nil, fmt.Errorf("bootstrap.newNotificationSenderWorker - create sender: %w", err)
}
worker, err := mailsender.New(sender, notificationSenderMetrics{metrics: metrics}, workerLogger, mailSenderLoopSettings())
if err != nil {
pool.Close()
return nil, nil, fmt.Errorf("bootstrap.newNotificationSenderWorker - create worker: %w", err)
}
// The application stops the worker before this cleanup runs, so no send
// uses the pool while it closes.
return &notificationSendingWorker{Worker: worker}, pool.Close, nil
}
@@ -0,0 +1,93 @@
package bootstrap
import (
"context"
"log/slog"
"net/http"
"strings"
"testing"
"time"
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/mail/disabled"
"lincodex/backend/internal/adapter/secondary/prometheus"
)
func TestNewNotificationSenderWorkerSkipsWithoutWork(t *testing.T) {
noDatabase := resendSenderConfig(t)
noDatabase.DatabaseURL = ""
tests := []struct {
name string
settings config.Config
log string
}{
// consumerTestConfig selects the disabled transport.
{name: "transport disabled", settings: consumerTestConfig(t), log: "EMAIL_PROVIDER is disabled"},
{name: "database not configured", settings: noDatabase, log: "DATABASE_URL is not set"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
var logs strings.Builder
logger := slog.New(slog.NewTextHandler(&logs, nil))
metrics := prometheus.New()
worker, cleanup, err := newNotificationSenderWorker(t.Context(), test.settings, logger, metrics, disabled.NewSender())
if err != nil {
t.Fatalf("newNotificationSenderWorker() error = %v", err)
}
cleanup()
if worker != nil {
t.Fatal("newNotificationSenderWorker() built a worker without work to do")
}
if !strings.Contains(logs.String(), test.log) {
t.Fatalf("logs = %q, want %q", logs.String(), test.log)
}
// The product loop has its own gauge: without it the gauge reads 0,
// and the service loop's gauge is untouched.
body := scrape(metrics)
if !strings.Contains(body, "lincodex_notification_sender_running 0\n") {
t.Fatalf("metrics lack lincodex_notification_sender_running 0:\n%s", body)
}
})
}
}
func TestApplicationRunsAndStopsTheNotificationSenderWorker(t *testing.T) {
settings := resendSenderConfig(t)
settings.HTTPAddr = "127.0.0.1:0"
settings.MetricsAddr = "127.0.0.1:0"
settings.ShutdownTimeout = time.Second
metrics := prometheus.New()
logger := slog.New(slog.DiscardHandler)
worker, cleanup, err := newNotificationSenderWorker(t.Context(), settings, logger, metrics, disabled.NewSender())
if err != nil {
t.Fatalf("newNotificationSenderWorker() error = %v", err)
}
defer cleanup()
if worker == nil {
t.Fatal("newNotificationSenderWorker() built no worker for an active transport")
}
application := NewApplication(settings, http.NotFoundHandler(), metrics, logger, nil, nil, nil, nil, nil, worker, nil)
ctx, cancel := context.WithCancel(t.Context())
finished := make(chan error, 1)
go func() { finished <- application.run(ctx) }()
deadline := time.Now().Add(relayLifecycleTimeout)
for !strings.Contains(scrape(metrics), "lincodex_notification_sender_running 1\n") {
if time.Now().After(deadline) {
t.Fatal("the product loop never reported that it runs")
}
time.Sleep(10 * time.Millisecond)
}
cancel()
select {
case err := <-finished:
if err != nil {
t.Fatalf("run() error = %v", err)
}
case <-time.After(relayLifecycleTimeout):
t.Fatal("run() did not return after cancellation")
}
if body := scrape(metrics); !strings.Contains(body, "lincodex_notification_sender_running 0\n") {
t.Fatalf("the gauge did not return to 0 after the loop stopped:\n%s", body)
}
}
+1 -1
View File
@@ -76,7 +76,7 @@ func TestApplicationRunsTheRelayWhileServing(t *testing.T) {
HTTPAddr: "127.0.0.1:0",
MetricsAddr: "127.0.0.1:0",
ShutdownTimeout: time.Second,
}, http.NotFoundHandler(), metrics, logger, nil, relay, nil, nil, nil, nil)
}, http.NotFoundHandler(), metrics, logger, nil, relay, nil, nil, nil, nil, nil)
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
+1
View File
@@ -67,6 +67,7 @@ func initialize(
newEventConsumers,
newJobWorker,
newMailSenderWorker,
newNotificationSenderWorker,
newDeliveryMetrics,
NewApplication,
),
+30 -2
View File
@@ -381,7 +381,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
sampler, cleanup23, err := newDeliveryMetrics(ctx, config2, logger, metrics)
bootstrapNotificationSendingWorker, cleanup23, err := newNotificationSenderWorker(ctx, config2, logger, metrics, mailSender)
if err != nil {
cleanup22()
cleanup21()
@@ -407,8 +407,36 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
application := NewApplication(config2, httpHandler, metrics, logger, mailSender, relay, bootstrapEventConsumers, worker, mailsenderWorker, sampler)
sampler, cleanup24, err := newDeliveryMetrics(ctx, config2, logger, metrics)
if err != nil {
cleanup23()
cleanup22()
cleanup21()
cleanup20()
cleanup19()
cleanup18()
cleanup17()
cleanup16()
cleanup15()
cleanup14()
cleanup13()
cleanup12()
cleanup11()
cleanup10()
cleanup9()
cleanup8()
cleanup7()
cleanup6()
cleanup5()
cleanup4()
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
application := NewApplication(config2, httpHandler, metrics, logger, mailSender, relay, bootstrapEventConsumers, worker, mailsenderWorker, bootstrapNotificationSendingWorker, sampler)
return application, func() {
cleanup24()
cleanup23()
cleanup22()
cleanup21()
+37 -6
View File
@@ -170,6 +170,19 @@ const (
// again and again for a reason of its own, so it stopped trying and left
// the row to an operator.
DeliveryCancelProcessingFailed DeliveryCancelReason = "processing_failed"
// DeliveryCancelRightsRevoked: a notification's basis no longer holds
// when it is about to be sent. The organization is hidden from the
// candidate, the candidate withdrew publication (C2), or the invitation
// was answered, expired, or passed its deadline (see
// Delivery.CheckInvitationNotice).
DeliveryCancelRightsRevoked DeliveryCancelReason = "rights_revoked"
// DeliveryCancelRecipientIneligible: the recipient account is gone or its
// address is not verified, so a notification may not go to it.
DeliveryCancelRecipientIneligible DeliveryCancelReason = "recipient_ineligible"
// DeliveryCancelSourceClosed: the record a notification is about does not
// exist, belongs to another organization, or the notification names no
// record at all, so there is no right to check.
DeliveryCancelSourceClosed DeliveryCancelReason = "source_closed"
)
// DeliveryCancelReasons lists every cancel reason, for metrics that expose
@@ -179,7 +192,8 @@ func DeliveryCancelReasons() []DeliveryCancelReason {
DeliveryCancelTokenMissing, DeliveryCancelTokenPurposeMismatch, DeliveryCancelTokenOwnerMismatch,
DeliveryCancelTokenConsumed, DeliveryCancelTokenRevoked, DeliveryCancelTokenExpired,
DeliveryCancelAccountNotCurrent, DeliveryCancelRecipientMismatch, DeliveryCancelContentInvalid,
DeliveryCancelProcessingFailed,
DeliveryCancelProcessingFailed, DeliveryCancelRightsRevoked, DeliveryCancelRecipientIneligible,
DeliveryCancelSourceClosed,
}
}
@@ -189,7 +203,8 @@ func ParseDeliveryCancelReason(value string) (DeliveryCancelReason, error) {
case DeliveryCancelTokenMissing, DeliveryCancelTokenPurposeMismatch, DeliveryCancelTokenOwnerMismatch,
DeliveryCancelTokenConsumed, DeliveryCancelTokenRevoked, DeliveryCancelTokenExpired,
DeliveryCancelAccountNotCurrent, DeliveryCancelRecipientMismatch, DeliveryCancelContentInvalid,
DeliveryCancelProcessingFailed:
DeliveryCancelProcessingFailed, DeliveryCancelRightsRevoked, DeliveryCancelRecipientIneligible,
DeliveryCancelSourceClosed:
return reason, nil
default:
return "", invalidDelivery("domain.ParseDeliveryCancelReason", "unknown cancel reason")
@@ -239,6 +254,7 @@ type Delivery struct {
recipientUserID uuid.UUID
recipient EmailAddress
content MailContent
subject MailSubject
providerAccount MailProviderAccount
idempotencyKey string
status DeliveryStatus
@@ -271,7 +287,11 @@ type NewDeliveryInput struct {
// the worker with the reason token_missing. It must be uuid.Nil for a
// notification.
EmailTokenID uuid.UUID
CreatedAt time.Time
// Subject names the record a notification is about; the sending worker
// checks its rights before the send. Only a notification may name one, and
// the zero value names none.
Subject MailSubject
CreatedAt time.Time
}
// NewDelivery validates input and returns a pending delivery that is due at
@@ -293,6 +313,8 @@ func NewDelivery(input NewDeliveryInput) (Delivery, error) {
return Delivery{}, invalidDelivery(location, "creation time must be set")
case input.EmailTokenID != uuid.Nil && !input.Content.Kind().CarriesBearerToken():
return Delivery{}, invalidDelivery(location, "only a delivery of a token kind is bound to a token")
case !input.Subject.IsZero() && input.Content.Kind() != MailKindNotification:
return Delivery{}, invalidDelivery(location, "only a notification names a subject")
}
return Delivery{
id: input.ID,
@@ -300,6 +322,7 @@ func NewDelivery(input NewDeliveryInput) (Delivery, error) {
recipientUserID: input.RecipientUserID,
recipient: input.Recipient,
content: input.Content,
subject: input.Subject,
providerAccount: input.ProviderAccount,
emailTokenID: input.EmailTokenID,
idempotencyKey: deliveryIdempotencyKeyPrefix + input.ID.String(),
@@ -329,9 +352,11 @@ type DeliverySnapshot struct {
EmailTokenID uuid.UUID
// CancelReason is set exactly for a cancelled delivery.
CancelReason DeliveryCancelReason
Version int64
CreatedAt time.Time
UpdatedAt time.Time
// Subject is the zero value for a delivery without a subject.
Subject MailSubject
Version int64
CreatedAt time.Time
UpdatedAt time.Time
}
// RestoreDelivery rebuilds a stored delivery and checks the invariants that
@@ -362,6 +387,7 @@ func RestoreDelivery(snapshot DeliverySnapshot) (Delivery, error) {
recipientUserID: snapshot.RecipientUserID,
recipient: recipient,
content: snapshot.Content,
subject: snapshot.Subject,
providerAccount: snapshot.ProviderAccount,
idempotencyKey: snapshot.IdempotencyKey,
status: snapshot.Status,
@@ -408,6 +434,8 @@ func checkCancellationAndBinding(location string, snapshot DeliverySnapshot) err
return invalidDelivery(location, "cancel reason must be set exactly for a cancelled delivery")
case snapshot.EmailTokenID != uuid.Nil && !snapshot.Content.Kind().CarriesBearerToken():
return invalidDelivery(location, "only a delivery of a token kind is bound to a token")
case !snapshot.Subject.IsZero() && snapshot.Content.Kind() != MailKindNotification:
return invalidDelivery(location, "only a notification names a subject")
}
if snapshot.CancelReason != "" {
if _, err := ParseDeliveryCancelReason(string(snapshot.CancelReason)); err != nil {
@@ -440,6 +468,9 @@ func (delivery Delivery) RecipientUserID() uuid.UUID { return delivery.recipient
// only to send the message; never log it.
func (delivery Delivery) Recipient() EmailAddress { return delivery.recipient }
// Subject is the record a notification is about; zero for other deliveries.
func (delivery Delivery) Subject() MailSubject { return delivery.subject }
func (delivery Delivery) Kind() MailKind { return delivery.content.Kind() }
func (delivery Delivery) Content() MailContent { return delivery.content }
@@ -0,0 +1,74 @@
package domain
import (
"time"
"github.com/google/uuid"
)
// InvitationNoticeStanding is what the rights check of an invitation notice
// reads about its recipient and its source at the time of the send. It holds
// no address and no contact: the recipient address enters only as the
// normalized key that the delivery is compared with.
type InvitationNoticeStanding struct {
RecipientFound bool
RecipientEmailVerified bool
// RecipientEmailKey is the normalized address of the account now.
RecipientEmailKey string
InvitationFound bool
InvitationOrganizationID uuid.UUID
InvitationState InvitationState
// ResponseDeadlineAt is zero when the invitation was never delivered.
ResponseDeadlineAt time.Time
// OrganizationHidden reports that the recipient hid the sending
// organization.
OrganizationHidden bool
// PublicationPublished reports that the recipient's publication (C2) is
// current, which is the state an invitation was sent under.
PublicationPublished bool
}
// CheckInvitationNotice decides whether the notice about an invitation may still
// be sent at the given time, and returns the cancel reason when it may not. An
// empty reason means that the notice is sendable. The checks run in this order
// and the first failure decides:
//
// 1. the delivery names an invitation subject;
// 2. the recipient account exists and its address is verified;
// 3. the address of the delivery is still the address of the account;
// 4. the invitation exists and belongs to the organization of the subject;
// 5. the invitation still awaits an answer (delivered or viewed) and its
// response deadline has not passed;
// 6. the recipient has not hidden the sending organization, and the
// recipient's publication (C2) is current.
//
// The notice declares no allowed fields. Its body is fixed text that names
// neither the organization nor the terms, and it carries no contact, so no
// field consent (C4) applies. A future notice that carries any candidate field
// or contact must add that field's consent check here, and must not put a
// contact into the mail at all: contacts are read on request, and every read
// re-checks the grant.
//
// The check is a snapshot taken in the sending transaction. A change after it
// and before the provider call still lets the notice go, which is the same
// rule as for service mail.
func (delivery Delivery) CheckInvitationNotice(standing InvitationNoticeStanding, at time.Time) DeliveryCancelReason {
subject := delivery.Subject()
awaitsAnswer := standing.InvitationState == InvitationDelivered || standing.InvitationState == InvitationViewed
switch {
case subject.Kind() != MailSubjectInvitation:
return DeliveryCancelSourceClosed
case !standing.RecipientFound || !standing.RecipientEmailVerified:
return DeliveryCancelRecipientIneligible
case standing.RecipientEmailKey != delivery.Recipient().Normalized():
return DeliveryCancelRecipientMismatch
case !standing.InvitationFound || standing.InvitationOrganizationID != subject.OrganizationID():
return DeliveryCancelSourceClosed
case !awaitsAnswer || !at.Before(standing.ResponseDeadlineAt):
return DeliveryCancelRightsRevoked
case standing.OrganizationHidden || !standing.PublicationPublished:
return DeliveryCancelRightsRevoked
default:
return ""
}
}
@@ -0,0 +1,173 @@
package domain
import (
"errors"
"testing"
"github.com/google/uuid"
)
var (
testInvitationID = uuid.MustParse("01926f3a-7c00-7000-8000-0000000000c1")
testSenderOrganizationID = uuid.MustParse("01926f3a-7c00-7000-8000-0000000000c3")
)
// newInvitationNotice is a notification to the test recipient that names an
// invitation of the test organization.
func newInvitationNotice(t *testing.T) Delivery {
t.Helper()
content, err := NewMailContent(MailKindNotification, "notification.v1", "Новое приглашение от работодателя", "Работодатель отправил вам приглашение\n", "")
if err != nil {
t.Fatalf("NewMailContent() error = %v", err)
}
subject, err := NewInvitationMailSubject(testInvitationID, testSenderOrganizationID)
if err != nil {
t.Fatalf("NewInvitationMailSubject() error = %v", err)
}
input := testDeliveryInput(t)
input.Content = content
input.Subject = subject
delivery, err := NewDelivery(input)
if err != nil {
t.Fatalf("NewDelivery() error = %v", err)
}
return delivery
}
// currentInvitationStanding is the standing of a notice that may be sent: the
// address is verified and unchanged, the invitation awaits an answer before its
// deadline, and the candidate neither hid the organization nor withdrew
// publication.
func currentInvitationStanding(delivery Delivery) InvitationNoticeStanding {
return InvitationNoticeStanding{
RecipientFound: true,
RecipientEmailVerified: true,
RecipientEmailKey: delivery.Recipient().Normalized(),
InvitationFound: true,
InvitationOrganizationID: testSenderOrganizationID,
InvitationState: InvitationDelivered,
ResponseDeadlineAt: after(7 * 24 * 60),
PublicationPublished: true,
}
}
func TestCheckInvitationNoticeAllowsAnInvitationThatStillAwaitsAnswer(t *testing.T) {
delivery := newInvitationNotice(t)
for _, state := range []InvitationState{InvitationDelivered, InvitationViewed} {
standing := currentInvitationStanding(delivery)
standing.InvitationState = state
if reason := delivery.CheckInvitationNotice(standing, after(1)); reason != "" {
t.Fatalf("CheckInvitationNotice(%s) = %q for an open invitation, want it sendable", state, reason)
}
}
}
// The first failed rule decides, so each row changes one fact from the current
// standing and names the reason that fact must give.
func TestCheckInvitationNoticeNamesTheReasonOfTheFirstFailedRule(t *testing.T) {
delivery := newInvitationNotice(t)
deadline := currentInvitationStanding(delivery).ResponseDeadlineAt
for _, test := range []struct {
name string
change func(*InvitationNoticeStanding)
at int
want DeliveryCancelReason
}{
{"the account is gone", func(s *InvitationNoticeStanding) { s.RecipientFound = false }, 1, DeliveryCancelRecipientIneligible},
{"the address is not verified", func(s *InvitationNoticeStanding) { s.RecipientEmailVerified = false }, 1, DeliveryCancelRecipientIneligible},
{"the address changed", func(s *InvitationNoticeStanding) { s.RecipientEmailKey = "other@example.com" }, 1, DeliveryCancelRecipientMismatch},
{"the invitation is gone", func(s *InvitationNoticeStanding) { s.InvitationFound = false }, 1, DeliveryCancelSourceClosed},
{"the invitation belongs to another organization", func(s *InvitationNoticeStanding) {
s.InvitationOrganizationID = uuid.MustParse("01926f3a-7c00-7000-8000-0000000000c9")
}, 1, DeliveryCancelSourceClosed},
{"the candidate declined", func(s *InvitationNoticeStanding) { s.InvitationState = InvitationDeclined }, 1, DeliveryCancelRightsRevoked},
{"the candidate accepted", func(s *InvitationNoticeStanding) { s.InvitationState = InvitationAccepted }, 1, DeliveryCancelRightsRevoked},
{"the invitation expired", func(s *InvitationNoticeStanding) { s.InvitationState = InvitationExpired }, 1, DeliveryCancelRightsRevoked},
{"the deadline has passed", func(*InvitationNoticeStanding) {}, 7*24*60 + 1, DeliveryCancelRightsRevoked},
{"the deadline is reached", func(*InvitationNoticeStanding) {}, 7 * 24 * 60, DeliveryCancelRightsRevoked},
{"the invitation was never delivered", func(s *InvitationNoticeStanding) {
s.ResponseDeadlineAt = deadline
s.InvitationState = InvitationDraft
}, 1, DeliveryCancelRightsRevoked},
{"the candidate hid the organization", func(s *InvitationNoticeStanding) { s.OrganizationHidden = true }, 1, DeliveryCancelRightsRevoked},
{"the candidate withdrew publication", func(s *InvitationNoticeStanding) { s.PublicationPublished = false }, 1, DeliveryCancelRightsRevoked},
{"an unverified address outranks a hidden organization", func(s *InvitationNoticeStanding) {
s.RecipientEmailVerified = false
s.OrganizationHidden = true
}, 1, DeliveryCancelRecipientIneligible},
} {
t.Run(test.name, func(t *testing.T) {
standing := currentInvitationStanding(delivery)
test.change(&standing)
if got := delivery.CheckInvitationNotice(standing, after(test.at)); got != test.want {
t.Fatalf("CheckInvitationNotice() = %q, want %q", got, test.want)
}
})
}
}
func TestCheckInvitationNoticeRefusesAMailThatNamesNoInvitation(t *testing.T) {
content, err := NewMailContent(MailKindNotification, "notification.v1", "Уведомление", "Текст\n", "")
if err != nil {
t.Fatalf("NewMailContent() error = %v", err)
}
input := testDeliveryInput(t)
input.Content = content
delivery, err := NewDelivery(input)
if err != nil {
t.Fatalf("NewDelivery() error = %v", err)
}
if reason := delivery.CheckInvitationNotice(currentInvitationStanding(delivery), after(1)); reason != DeliveryCancelSourceClosed {
t.Fatalf("CheckInvitationNotice() = %q for a notice without a subject, want source_closed", reason)
}
}
func TestNewMailSubjectNamesOnlyKnownRecords(t *testing.T) {
if _, err := NewInvitationMailSubject(uuid.Nil, testSenderOrganizationID); !errors.Is(err, ErrInvalidMailSubject) {
t.Fatalf("NewInvitationMailSubject(nil invitation) error = %v, want ErrInvalidMailSubject", err)
}
if _, err := NewInvitationMailSubject(testInvitationID, uuid.Nil); !errors.Is(err, ErrInvalidMailSubject) {
t.Fatalf("NewInvitationMailSubject(nil organization) error = %v, want ErrInvalidMailSubject", err)
}
if subject, err := RestoreMailSubject("", uuid.Nil, uuid.Nil); err != nil || !subject.IsZero() {
t.Fatalf("RestoreMailSubject(empty) = %v, %v; want the zero subject", subject, err)
}
if _, err := RestoreMailSubject("contract", testInvitationID, testSenderOrganizationID); !errors.Is(err, ErrInvalidMailSubject) {
t.Fatalf("RestoreMailSubject(unknown kind) error = %v, want ErrInvalidMailSubject", err)
}
subject, err := NewInvitationMailSubject(testInvitationID, testSenderOrganizationID)
if err != nil {
t.Fatalf("NewInvitationMailSubject() error = %v", err)
}
if text := subject.String(); text != "[mail subject invitation]" {
t.Fatalf("String() = %q; the identifiers must stay out of printed values", text)
}
}
func TestOnlyANotificationNamesASubject(t *testing.T) {
subject, err := NewInvitationMailSubject(testInvitationID, testSenderOrganizationID)
if err != nil {
t.Fatalf("NewInvitationMailSubject() error = %v", err)
}
input := testDeliveryInput(t)
input.Subject = subject
if _, err := NewDelivery(input); !errors.Is(err, ErrInvalidDelivery) {
t.Fatalf("NewDelivery(verification with subject) error = %v, want ErrInvalidDelivery", err)
}
}
func TestRightsCancelReasonsAreKnownAndExposed(t *testing.T) {
for _, value := range []string{"rights_revoked", "recipient_ineligible", "source_closed"} {
reason, err := ParseDeliveryCancelReason(value)
if err != nil {
t.Fatalf("ParseDeliveryCancelReason(%q) error = %v", value, err)
}
listed := false
for _, known := range DeliveryCancelReasons() {
listed = listed || known == reason
}
if !listed {
t.Fatalf("%q is parsed but missing from DeliveryCancelReasons, so its metric series would not exist at zero", value)
}
}
}
+21 -4
View File
@@ -58,14 +58,20 @@ func ParseMailKind(value string) (MailKind, error) {
}
// ServiceMailKinds lists the kinds of service identity mail, the kinds the
// sending worker claims and sends. Notifications are not among them until
// their sending is connected. The delivery metrics of due mail,
// the sending worker, and the due index of the deliveries table follow this
// list; changing it changes the predicate of deliveries_due_idx too.
// service sending worker claims and sends. The delivery metrics of due mail
// and the due index of the deliveries table follow this list; changing it
// changes the predicate of deliveries_due_idx too.
func ServiceMailKinds() []MailKind {
return []MailKind{MailKindVerification, MailKindPasswordReset}
}
// ProductMailKinds lists the kinds of product notifications, the kinds the
// notification sending worker claims. Its claim has its own partial index,
// deliveries_product_due_idx, which follows this list.
func ProductMailKinds() []MailKind {
return []MailKind{MailKindNotification}
}
// IsServiceMail reports a kind of service identity mail.
func (kind MailKind) IsServiceMail() bool { return kind.CarriesBearerToken() }
@@ -173,6 +179,17 @@ func RestoreRedactedMailContent(kind MailKind, templateVersion, subject string,
if _, err := ParseMailKind(string(kind)); err != nil || !kind.CarriesBearerToken() {
return MailContent{}, invalidMailContent("only a token mail has redacted content")
}
return restoreRedactedContent(location, kind, templateVersion, subject, hash)
}
// RestoreRedactedNotificationContent rebuilds the content of a notification
// whose bodies were cleared when it was cancelled. Like a redacted token mail,
// it keeps the subject and the hash and can never be sent.
func RestoreRedactedNotificationContent(templateVersion, subject string, hash []byte) (MailContent, error) {
return restoreRedactedContent("domain.RestoreRedactedNotificationContent", MailKindNotification, templateVersion, subject, hash)
}
func restoreRedactedContent(location string, kind MailKind, templateVersion, subject string, hash []byte) (MailContent, error) {
if !mailTemplateVersionPattern.MatchString(templateVersion) || !strings.HasPrefix(templateVersion, string(kind)+".v") ||
strings.TrimSpace(subject) == "" || utf8.RuneCountInString(subject) > maxMailSubjectRunes {
return MailContent{}, fmt.Errorf("%s - stored version or subject is invalid: %w", location, ErrInvalidMailContent)
+16
View File
@@ -44,6 +44,22 @@ func NewMailQuotaLimits(daily, monthly int64) (MailQuotaLimits, error) {
func (limits MailQuotaLimits) IsZero() bool { return limits.daily == 0 }
// WithReserve returns the limits that a sender may use when daily and monthly
// recipients stay free for other mail. Each window keeps its own reserve, so
// the result is checked window by window; it may not keep the rule that the
// daily limit does not exceed the monthly one, which the configuration keeps.
// A reserve must be zero or more and leave at least one recipient per window.
func (limits MailQuotaLimits) WithReserve(daily, monthly int64) (MailQuotaLimits, error) {
const location = "domain.MailQuotaLimits.WithReserve"
switch {
case daily < 0 || monthly < 0:
return MailQuotaLimits{}, fmt.Errorf("%s - reserves must not be negative: %w", location, ErrInvalidMailQuota)
case daily >= limits.daily || monthly >= limits.monthly:
return MailQuotaLimits{}, fmt.Errorf("%s - a reserve must leave room in its window: %w", location, ErrInvalidMailQuota)
}
return MailQuotaLimits{daily: limits.daily - daily, monthly: limits.monthly - monthly}, nil
}
func (limits MailQuotaLimits) Daily() int64 { return limits.daily }
func (limits MailQuotaLimits) Monthly() int64 { return limits.monthly }
@@ -118,3 +118,36 @@ func TestNewMailQuotaLimits(t *testing.T) {
})
}
}
func TestWithReserveLeavesEachWindowItsOwnShare(t *testing.T) {
limits, err := NewMailQuotaLimits(100, 3000)
if err != nil {
t.Fatalf("NewMailQuotaLimits() error = %v", err)
}
admission, err := limits.WithReserve(20, 600)
if err != nil {
t.Fatalf("WithReserve(20, 600) error = %v", err)
}
if admission.Daily() != 80 || admission.Monthly() != 2400 {
t.Fatalf("admission = %d a day and %d a month, want 80 and 2400", admission.Daily(), admission.Monthly())
}
if unchanged, err := limits.WithReserve(0, 0); err != nil || unchanged.Daily() != 100 || unchanged.Monthly() != 3000 {
t.Fatalf("WithReserve(0, 0) = %+v, %v; want the limits unchanged", unchanged, err)
}
}
func TestWithReserveRefusesAReserveThatLeavesNoRoom(t *testing.T) {
limits, err := NewMailQuotaLimits(100, 3000)
if err != nil {
t.Fatalf("NewMailQuotaLimits() error = %v", err)
}
for name, reserve := range map[string][2]int64{
"a daily reserve equal to the limit": {100, 0},
"a monthly reserve above the limit": {0, 3001},
"a negative reserve": {-1, 0},
} {
if _, err := limits.WithReserve(reserve[0], reserve[1]); !errors.Is(err, ErrInvalidMailQuota) {
t.Fatalf("%s: WithReserve() error = %v, want ErrInvalidMailQuota", name, err)
}
}
}
+22 -6
View File
@@ -60,7 +60,11 @@ type MailRequest struct {
RecipientUserID uuid.UUID
Kind MailKind
Notification NotificationText
CreatedAt time.Time
// Subject names the record the notification is about. It is copied to the
// delivery, whose sending worker checks its rights; the zero value names
// none.
Subject MailSubject
CreatedAt time.Time
}
// NewMailRequest checks the storage rules of a request. Only notification
@@ -68,7 +72,6 @@ type MailRequest struct {
// transaction that issues the token. Whether the text renders is checked by
// the template, not here.
func NewMailRequest(request MailRequest) (MailRequest, error) {
text := request.Notification
switch {
case request.ID == uuid.Nil || request.RecipientUserID == uuid.Nil:
return MailRequest{}, invalidMailRequest("request and recipient user IDs must not be nil")
@@ -76,17 +79,30 @@ func NewMailRequest(request MailRequest) (MailRequest, error) {
return MailRequest{}, invalidMailRequest("only notification mail can be requested")
case request.CreatedAt.IsZero():
return MailRequest{}, invalidMailRequest("creation time must be set")
case !request.Subject.IsZero() && request.Subject.Kind() != MailSubjectInvitation:
return MailRequest{}, invalidMailRequest("the subject kind is unknown")
}
if err := checkMailRequestText(request.Notification); err != nil {
return MailRequest{}, err
}
return request, nil
}
// checkMailRequestText bounds and checks the raw text of a request, before the
// template normalizes it.
func checkMailRequestText(text NotificationText) error {
switch {
case !utf8.ValidString(text.Subject) || !utf8.ValidString(text.Body) || !utf8.ValidString(text.LinkPath):
return MailRequest{}, invalidMailRequest("text must be valid UTF-8")
return invalidMailRequest("text must be valid UTF-8")
// PostgreSQL text cannot store NUL.
case strings.ContainsRune(text.Subject, 0) || strings.ContainsRune(text.Body, 0) || strings.ContainsRune(text.LinkPath, 0):
return MailRequest{}, invalidMailRequest("text must not contain NUL characters")
return invalidMailRequest("text must not contain NUL characters")
case utf8.RuneCountInString(text.Subject) > maxMailRequestSubjectRunes ||
utf8.RuneCountInString(text.Body) > maxMailRequestBodyRunes ||
len(text.LinkPath) > maxMailRequestLinkPathSize:
return MailRequest{}, invalidMailRequest("subject, body, or link path is too long")
return invalidMailRequest("subject, body, or link path is too long")
}
return request, nil
return nil
}
// LogValue carries the IDs and kind only.
+83
View File
@@ -0,0 +1,83 @@
package domain
import (
"errors"
"fmt"
"log/slog"
"github.com/google/uuid"
)
// ErrInvalidMailSubject reports a subject that names no record or breaks the
// rule of its kind. Errors name the rule, never an identifier.
var ErrInvalidMailSubject = errors.New("invalid mail subject")
// MailSubjectKind names the kind of record a notification is about. The
// values are stored, and each one has a rights checker in the sending usecase.
type MailSubjectKind string
const (
// MailSubjectInvitation is an invitation addressed to the recipient. The
// subject ID is the invitation and the organization is its sender.
MailSubjectInvitation MailSubjectKind = "invitation"
)
// MailSubject links a notification to the record whose rights must still hold
// when the mail is sent. The sending worker re-checks those rights before the
// transport is called, so a notification that outlives its basis is cancelled
// instead of sent. The zero value names no subject; the worker then has no
// rights to check and cancels the notification with source_closed.
type MailSubject struct {
kind MailSubjectKind
id uuid.UUID
organizationID uuid.UUID
}
// NewInvitationMailSubject names an invitation and the organization that sent
// it. Both IDs must be set.
func NewInvitationMailSubject(invitationID, organizationID uuid.UUID) (MailSubject, error) {
if invitationID == uuid.Nil || organizationID == uuid.Nil {
return MailSubject{}, fmt.Errorf("domain.NewInvitationMailSubject - invitation and organization IDs must be set: %w", ErrInvalidMailSubject)
}
return MailSubject{kind: MailSubjectInvitation, id: invitationID, organizationID: organizationID}, nil
}
// RestoreMailSubject rebuilds a stored subject. A kind of "" with nil IDs is
// the zero subject; any other combination must be a complete known subject.
func RestoreMailSubject(kind string, id, organizationID uuid.UUID) (MailSubject, error) {
if kind == "" && id == uuid.Nil && organizationID == uuid.Nil {
return MailSubject{}, nil
}
switch MailSubjectKind(kind) {
case MailSubjectInvitation:
return NewInvitationMailSubject(id, organizationID)
default:
return MailSubject{}, fmt.Errorf("domain.RestoreMailSubject - unknown subject kind: %w", ErrInvalidMailSubject)
}
}
// IsZero reports a subject that names nothing.
func (subject MailSubject) IsZero() bool { return subject.kind == "" }
func (subject MailSubject) Kind() MailSubjectKind { return subject.kind }
// ID is the identifier of the subject record.
func (subject MailSubject) ID() uuid.UUID { return subject.id }
// OrganizationID is the organization the subject record belongs to.
func (subject MailSubject) OrganizationID() uuid.UUID { return subject.organizationID }
// String shows the kind only; the identifiers stay out of printed values.
func (subject MailSubject) String() string {
if subject.IsZero() {
return "[empty mail subject]"
}
return fmt.Sprintf("[mail subject %s]", subject.kind)
}
func (subject MailSubject) GoString() string { return subject.String() }
// LogValue carries the kind only.
func (subject MailSubject) LogValue() slog.Value {
return slog.StringValue(string(subject.kind))
}
@@ -193,8 +193,26 @@ type DeliveryRetrySnapshot struct {
ManualRetryStartedAt time.Time
}
// ClaimScope names the lane a claim serves. Each lane has its own claim
// statement and partial due index, so an idle poll of one lane never reads
// the backlog of the other.
type ClaimScope int
const (
// ClaimScopeService claims service identity mail: verification and
// password reset, through deliveries_due_idx. It is the zero value, so a
// claim that names no lane is a service claim.
ClaimScopeService ClaimScope = iota
// ClaimScopeNotification claims product notifications, through
// deliveries_product_due_idx.
ClaimScopeNotification
)
// DeliveryClaim selects and leases the next delivery for a sending worker.
type DeliveryClaim struct {
// Scope selects the lane and its claim statement. Kinds must be the kinds
// of that lane.
Scope ClaimScope
// Owner identifies the worker; a lease belongs to it.
Owner uuid.UUID
// Account is the configured provider account. Only deliveries pinned to
@@ -0,0 +1,23 @@
package outbound
import (
"context"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
// NotificationRightsReader reads the standing that the rights checks of
// product notifications need. It runs inside the caller's transaction, in
// the same transaction that holds the delivery lock, and it locks nothing
// itself. It returns the facts of one record only, never an address, a
// contact, or the content of a notification.
type NotificationRightsReader interface {
// InvitationNoticeStanding reads the standing of an invitation notice: the
// recipient account, the invitation the recipient is addressed by, the
// hiding of the sending organization, and the current publication. A
// missing account or invitation is reported as not found, not as an
// error.
InvitationNoticeStanding(ctx context.Context, recipientUserID, invitationID, organizationID uuid.UUID) (domain.InvitationNoticeStanding, error)
}
@@ -79,6 +79,7 @@ type UnitOfWork interface {
Deliveries() DeliveryRepository
MailRequests() MailRequestRepository
MailQuotas() MailQuotaRepository
NotificationRights() NotificationRightsReader
Outbox() OutboxWriter
ScheduledJobs() JobScheduler
}
@@ -120,6 +120,7 @@ func (handler *DeliveryHandler) Handle(ctx context.Context, unit outbound.UnitOf
Recipient: recipient.Email,
Content: content,
ProviderAccount: handler.providerAccount,
Subject: request.Subject,
CreatedAt: handler.clock(),
})
if err != nil {
@@ -0,0 +1,900 @@
package notification
import (
"context"
"errors"
"fmt"
"log/slog"
"sync/atomic"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/port/outbound"
)
const (
// settleAttempts bounds how often the transaction that stores a send
// result is repeated after a database failure. The provider answer lives
// only in memory until it is stored, so one failure should not lose it.
settleAttempts = 3
// settleRetryDelay separates two attempts to store a send result.
settleRetryDelay = 200 * time.Millisecond
)
// dedupSafetyMargin is taken off the provider's idempotency window before it
// is compared with the age of the first request: clocks of the provider and the
// database differ a little, and a key about to expire is as good as expired.
const dedupSafetyMargin = time.Hour
// errLeaseLost reports a result that another worker recorded first: the
// settlement transaction is rolled back and nothing of this attempt is kept.
var errLeaseLost = errors.New("delivery was recorded by another worker")
// DeliverySenderSettings are the named limits of a sending worker.
type DeliverySenderSettings struct {
// Account is the configured provider account. The sender claims only
// deliveries pinned to it, and moves deliveries stored while no
// transport ran onto it.
Account domain.MailProviderAccount
// RebindProvider is the provider name whose deliveries, before their
// first attempt, are moved onto Account: the disabled transport. Empty
// for none.
RebindProvider string
// Lease is how long a claimed delivery belongs to this sender, measured by
// the database clock. Claim, the call, and the settlement all fit inside
// it: the call is bounded by what is left of the lease after the claim and
// the settlement budget.
Lease time.Duration
// StoreTimeout bounds the claim transaction, the check before the send,
// and each try to store a result.
StoreTimeout time.Duration
// SettleBudget bounds the whole of storing a send result, retries
// included; it is reserved inside the lease.
SettleBudget time.Duration
// ShutdownSettleBudget replaces SettleBudget when shutdown has begun, so
// the process stops within its shutdown timeout.
ShutdownSettleBudget time.Duration
// MaxFailures is how many consecutive failures of the worker itself on one
// delivery are retried before the delivery is cancelled with the reason
// processing_failed.
MaxFailures int32
Retry RetryPolicy
}
func (settings DeliverySenderSettings) validate() error {
switch {
case settings.Account.IsZero():
return errors.New("notification.NewDeliverySender - provider account must be set")
case settings.Lease <= 0 || settings.StoreTimeout <= 0 || settings.SettleBudget <= 0 || settings.ShutdownSettleBudget <= 0 || settings.MaxFailures < 1:
return errors.New("notification.NewDeliverySender - lease, timeouts, and settle budgets must be positive and the failure limit at least 1")
case settings.SettleBudget >= settings.Lease:
return errors.New("notification.NewDeliverySender - the settle budget must be shorter than the lease")
case settings.Retry.Initial <= 0 || settings.Retry.Max < settings.Retry.Initial:
return errors.New("notification.NewDeliverySender - retry delays must be positive and the maximum not below the initial delay")
}
return nil
}
// DeliverySender sends the deliveries of one lane: service identity mail
// (ServiceMailSender) or product notifications (NotificationSender). Several
// senders may run against one database, in one process or many.
//
// One pass takes one delivery through three steps:
//
// 1. Claim transaction: ClaimDue leases the most overdue due delivery of the
// lane with FOR UPDATE SKIP LOCKED, so no two senders hold the same one.
// The lane's Eligibility decides whether the mail may still go out; one
// that may not is cancelled with a reason. Otherwise QuotaGate.PrepareSend
// reserves the quota, or parks the delivery in waiting_quota. The
// transaction commits before the transport is called, so a slow provider
// never holds a row lock.
// 2. Check right before the send, in a second short transaction that takes the
// delivery lock again and runs the Eligibility a second time, so a
// revocation after the claim is honored; then one call to MailSender.Send
// with the stored content and the stable idempotency key. The sender never
// retries: a failed attempt becomes the delivery's next state and due time.
// 3. Settlement transaction: QuotaGate.SettleSend and
// DeliveryRepository.RecordAttempt in one transaction. The attempt is
// recorded over the delivery's version, so of two senders that both
// reached this step only the first is kept.
//
// A sender that stops after the claim leaves its lease to expire; another
// sender then claims the delivery and calls the provider with the same
// idempotency key, which the provider answers with the original result
// instead of sending twice, and the quota gate reuses the open reservation.
// Past the provider's idempotency window the earlier attempt is in doubt,
// so the delivery is recorded as unknown instead of being sent again.
//
// Logs and results name a delivery only by its ID, never by address or
// content.
type DeliverySender struct {
owner uuid.UUID
// countingPaused stops counting failures of single rows; see
// PauseFailureCounting.
countingPaused atomic.Bool
transactor outbound.Transactor
sender outbound.MailSender
gate *QuotaGate
lane deliveryLane
settings DeliverySenderSettings
clock func() time.Time
logger *slog.Logger
}
// deliveryLane is what one sender serves: the claim scope and kinds it leases,
// and the rule that decides before each send.
type deliveryLane struct {
scope outbound.ClaimScope
kinds []domain.MailKind
eligibility Eligibility
}
// Eligibility decides whether a claimed delivery may still be sent. It runs in
// the caller's transaction, after the delivery is locked for the lease holder,
// and returns the cancel reason, or an empty reason when the mail may go out.
// It reads the current standing of the recipient and of the record the mail
// concerns; it never reads an address or a contact into its result.
type Eligibility interface {
Check(ctx context.Context, unit outbound.UnitOfWork, delivery domain.Delivery, at time.Time) (domain.DeliveryCancelReason, error)
}
// newDeliverySender builds a sender of one lane with a random lease owner ID.
// gate must be built for settings.Account. clock is the application clock: due,
// lease, and quota decisions use it, so tests move time with a fake one.
func newDeliverySender(
lane deliveryLane,
transactor outbound.Transactor,
sender outbound.MailSender,
gate *QuotaGate,
settings DeliverySenderSettings,
clock func() time.Time,
logger *slog.Logger,
) (*DeliverySender, error) {
if err := settings.validate(); err != nil {
return nil, err
}
owner := uuid.New()
return &DeliverySender{
owner: owner,
transactor: transactor,
sender: sender,
gate: gate,
lane: lane,
settings: settings,
clock: clock,
logger: logger.With(slog.String("lease_owner", owner.String())),
}, nil
}
// claimedSend is a delivery that passed the claim transaction and is ready to
// be sent, or the final result of a delivery the transaction already decided.
type claimedSend struct {
delivery domain.Delivery
permit QuotaPermit
firstSendStarted bool
sinceFirstSend time.Duration
manualRetryPending bool
manualRetryCycleStarted bool
sendStartUnsettled bool
requireDedupWindow bool
// decided is set when the claim transaction ended the pass: the result
// is final and nothing is sent.
decided bool
result inbound.MailPassResult
// failureCount is the number of consecutive failures of the worker on the
// delivery before this pass.
failureCount int32
}
var _ inbound.MailPass = (*DeliverySender)(nil)
// PauseFailureCounting implements inbound.MailPass.
func (sender *DeliverySender) PauseFailureCounting(paused bool) {
sender.countingPaused.Store(paused)
}
// isRowFault reports an error that the delivery itself causes and that
// repeating cannot cure: it breaks a domain rule, cannot be restored, or is
// refused by a data or integrity constraint. Every other error (a context that
// ended, a timeout, a deadlock, a lost connection, a missing quota
// configuration) says nothing about the row, so it is never counted against
// it.
func isRowFault(err error) bool {
var unreadable *outbound.UnreadableDeliveryError
return errors.As(err, &unreadable) ||
errors.Is(err, domain.ErrInvalidDelivery) ||
errors.Is(err, domain.ErrDeliveryTransition) ||
errors.Is(err, domain.ErrInvalidMailContent) ||
errors.Is(err, domain.ErrMailContentIntegrity) ||
errors.Is(err, domain.ErrInvalidEmailAddress) ||
errors.Is(err, outbound.ErrRowFault)
}
// ProcessNext runs one pass. ctx ends the claim of new work; workCtx bounds
// the transport call and should outlive ctx by a shutdown grace, so a send in
// progress is not cut off at the first sign of shutdown. An error reports a
// database failure; the delivery it concerned is left under its lease, which
// expires, or was never claimed.
func (sender *DeliverySender) ProcessNext(ctx, workCtx context.Context) (inbound.MailPassResult, error) {
// The lease runs by the database clock from the claim, which is later
// than this reading, so the budget below errs on the short side.
started := time.Now()
claim, err := sender.claim(ctx)
if err != nil {
return inbound.MailPassResult{}, fmt.Errorf("DeliverySender.ProcessNext - claim delivery: %w", err)
}
if claim.decided {
return claim.result, nil
}
if decided, err := sender.beforeSend(workCtx, claim); err != nil || decided != nil {
if err != nil {
return inbound.MailPassResult{}, fmt.Errorf("DeliverySender.ProcessNext - check before sending: %w", err)
}
return *decided, nil
}
delivery := claim.delivery
content := delivery.Content()
// What is left of the lease after the claim and the reserve for storing
// the answer is the most the call may take.
callBudget := sender.settings.Lease - time.Since(started) - sender.settings.SettleBudget
if callBudget <= 0 {
return sender.releaseUnsent(ctx, claim)
}
sendCtx, cancel := context.WithTimeout(workCtx, callBudget)
result, sendErr := sender.sender.Send(sendCtx, outbound.OutgoingMail{
To: delivery.Recipient(),
Subject: content.Subject(),
TextBody: content.Text(),
HTMLBody: content.HTML(),
IdempotencyKey: delivery.IdempotencyKey(),
})
cancel()
return sender.settle(ctx, claim, result, sendErr)
}
// failingRow names a claimed delivery on which the claim transaction failed,
// so a failure can be recorded for it outside that transaction.
type failingRow struct {
id uuid.UUID
count int32
}
func (sender *DeliverySender) claim(ctx context.Context) (claimedSend, error) {
var claim claimedSend
var failing *failingRow
claimCtx, cancel := context.WithTimeout(ctx, sender.settings.StoreTimeout)
defer cancel()
err := sender.transactor.WithinTransaction(claimCtx, func(ctx context.Context, unit outbound.UnitOfWork) error {
now := sender.clock()
claimed, err := unit.Deliveries().ClaimDue(ctx, outbound.DeliveryClaim{
Scope: sender.lane.scope,
Owner: sender.owner,
Account: sender.settings.Account,
RebindProvider: sender.settings.RebindProvider,
Kinds: sender.lane.kinds,
Now: now,
Lease: sender.settings.Lease,
})
if errors.Is(err, outbound.ErrNoDeliveryDue) {
claim = claimedSend{decided: true, result: inbound.MailPassResult{Outcome: inbound.MailPassIdle}}
return nil
}
var unreadable *outbound.UnreadableDeliveryError
if errors.As(err, &unreadable) {
if unreadable.Cancelled {
// The store cancelled the broken row; committing keeps it
// from blocking the queue. Its content is left as it is for
// an operator.
sender.logger.ErrorContext(ctx, "a due delivery does not match its content hash and was cancelled; an operator should inspect it",
slog.String("delivery_id", unreadable.DeliveryID.String()),
slog.String("reason", string(domain.DeliveryCancelContentInvalid)))
claim = claimedSend{decided: true, result: inbound.MailPassResult{
Outcome: inbound.MailPassCancelled,
DeliveryID: unreadable.DeliveryID,
CancelReason: domain.DeliveryCancelContentInvalid,
}}
return nil
}
failing = &failingRow{id: unreadable.DeliveryID, count: unreadable.FailureCount}
return fmt.Errorf("claim due delivery: %w", err)
}
if err != nil {
return fmt.Errorf("claim due delivery: %w", err)
}
failing = &failingRow{id: claimed.Delivery.ID(), count: claimed.FailureCount}
claim, err = sender.prepare(ctx, unit, claimed, now)
if err != nil {
return err
}
failing = nil
claim.failureCount = claimed.FailureCount
return nil
})
if err != nil {
// The transaction rolled back, and with it the lease: the same row
// would be claimed again and fail again, and every delivery behind
// it would wait. Record the failure in a transaction of its own so
// the row moves back in the queue.
if failing != nil && ctx.Err() == nil && isRowFault(err) {
if result, recordErr := sender.recordRowFailure(ctx, *failing, err); recordErr == nil {
return claimedSend{decided: true, result: result}, nil
}
}
return claimedSend{}, err
}
return claim, nil
}
// recordRowFailure counts a failure of the worker on a delivery in a short
// transaction of its own and makes the row due later by the retry schedule;
// after MaxFailures it cancels the row with processing_failed.
func (sender *DeliverySender) recordRowFailure(ctx context.Context, failing failingRow, cause error) (inbound.MailPassResult, error) {
var cancelled bool
recordCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), sender.settings.StoreTimeout)
defer cancel()
err := sender.transactor.WithinTransaction(recordCtx, func(ctx context.Context, unit outbound.UnitOfWork) error {
now := sender.clock()
var err error
cancelled, err = unit.Deliveries().RecordFailure(ctx, failing.id, sender.owner, now,
sender.settings.Retry.NextAttemptAt(now, failing.count+1, 0), sender.settings.MaxFailures, !sender.countingPaused.Load())
return err
})
if err != nil {
return inbound.MailPassResult{}, fmt.Errorf("record failure: %w", err)
}
// The cause is a wrapped chain of rules and sentinels; it never quotes
// the row.
sender.logger.ErrorContext(ctx, "the sending worker failed on a delivery; it is retried later and cancelled after repeated failures",
slog.String("delivery_id", failing.id.String()),
slog.Int("consecutive_failures", int(failing.count)+1),
slog.Bool("cancelled", cancelled),
slog.Any("error", cause))
if cancelled {
return inbound.MailPassResult{Outcome: inbound.MailPassCancelled, DeliveryID: failing.id, CancelReason: domain.DeliveryCancelProcessingFailed}, nil
}
return inbound.MailPassResult{Outcome: inbound.MailPassRowFailed, DeliveryID: failing.id}, nil
}
// beforeSend runs right before the transport is called: it takes the delivery
// lock and runs the lane's eligibility again, so a revocation after the claim
// committed is honored, and notes the start of the first request. A mail that
// is no longer valid is cancelled and its reservation given back.
func (sender *DeliverySender) beforeSend(ctx context.Context, claim claimedSend) (*inbound.MailPassResult, error) {
var decided *inbound.MailPassResult
checkCtx, cancel := context.WithTimeout(ctx, sender.settings.StoreTimeout)
defer cancel()
err := sender.transactor.WithinTransaction(checkCtx, func(ctx context.Context, unit outbound.UnitOfWork) error {
delivery := claim.delivery
held, err := unit.Deliveries().LockClaimed(ctx, delivery.ID(), sender.owner)
if err != nil {
return fmt.Errorf("lock delivery: %w", err)
}
if !held {
result := resultOf(inbound.MailPassLeaseLost, delivery)
decided = &result
return nil
}
now := sender.clock()
if result, handled, err := sender.handleInvalidClaim(ctx, unit, claim, delivery, now); err != nil || handled {
if handled {
decided = &result
}
return err
}
started, err := unit.Deliveries().MarkSendStarted(ctx, delivery.ID(), sender.owner,
claim.requireDedupWindow, sender.safeRetryWindow())
if err != nil {
return fmt.Errorf("mark send started: %w", err)
}
if !started {
result, err := sender.handleUnmarkedSend(ctx, unit, claim, delivery, now)
if err != nil {
return err
}
decided = &result
}
return nil
})
if err != nil {
return nil, err
}
return decided, nil
}
func (sender *DeliverySender) handleInvalidClaim(
ctx context.Context,
unit outbound.UnitOfWork,
claim claimedSend,
delivery domain.Delivery,
now time.Time,
) (inbound.MailPassResult, bool, error) {
reason, err := sender.lane.eligibility.Check(ctx, unit, delivery, now)
if err != nil {
return inbound.MailPassResult{}, true, fmt.Errorf("check eligibility: %w", err)
}
if reason == "" {
return inbound.MailPassResult{}, false, nil
}
if delivery.Status() == domain.DeliveryStatusUnknown {
if err := sender.releaseUnsentReservation(ctx, unit, claim); err != nil {
return inbound.MailPassResult{}, true, err
}
stopped, err := sender.stopAutomaticRetry(ctx, unit, delivery, now)
return stopped.result, true, err
}
if _, err := sender.gate.SettleSend(ctx, unit, claim.permit, outbound.SendResult{}, errNotSent); err != nil {
return inbound.MailPassResult{}, true, fmt.Errorf("give the reservation back: %w", err)
}
cancelled, err := sender.cancel(ctx, unit, delivery, now, reason)
return cancelled.result, true, err
}
func (sender *DeliverySender) handleUnmarkedSend(
ctx context.Context,
unit outbound.UnitOfWork,
claim claimedSend,
delivery domain.Delivery,
now time.Time,
) (inbound.MailPassResult, error) {
if delivery.Status() == domain.DeliveryStatusUnknown {
if err := sender.releaseUnsentReservation(ctx, unit, claim); err != nil {
return inbound.MailPassResult{}, err
}
stopped, err := sender.stopAutomaticRetry(ctx, unit, delivery, now)
return stopped.result, err
}
if claim.sendStartUnsettled {
inDoubt, err := sender.recordInDoubt(ctx, unit, delivery, now)
return inDoubt.result, err
}
if claim.requireDedupWindow && claim.firstSendStarted {
if err := sender.releaseUnsentReservation(ctx, unit, claim); err != nil {
return inbound.MailPassResult{}, err
}
stopped, err := sender.stopAutomaticRetry(ctx, unit, delivery, now)
return stopped.result, err
}
if claim.firstSendStarted {
inDoubt, err := sender.recordInDoubt(ctx, unit, delivery, now)
return inDoubt.result, err
}
return resultOf(inbound.MailPassLeaseLost, delivery), nil
}
// errNotSent stands for "the message did not leave the process" when a
// reservation is given back before the transport was called.
var errNotSent = errors.New("message was not sent")
// releaseUnsent gives a claimed delivery back when no time is left to call
// the transport, and the reservation with it.
func (sender *DeliverySender) releaseUnsent(ctx context.Context, claim claimedSend) (inbound.MailPassResult, error) {
return sender.settle(ctx, claim, outbound.SendResult{}, context.DeadlineExceeded)
}
// prepare decides what a claimed delivery needs before the transport is
// called, in the claim transaction.
func (sender *DeliverySender) prepare(ctx context.Context, unit outbound.UnitOfWork, claimed outbound.ClaimedDelivery, now time.Time) (claimedSend, error) {
delivery := claimed.Delivery
if delivery.ProviderAccount() != sender.settings.Account {
// Mail stored while no transport ran has no attempt, so no provider
// holds its idempotency key and the account may change.
rebound, err := delivery.Rebind(latest(now, delivery.UpdatedAt()), sender.settings.Account)
if err != nil {
return claimedSend{}, fmt.Errorf("rebind delivery: %w", err)
}
if err := unit.Deliveries().Rebind(ctx, rebound); err != nil {
return claimedSend{}, fmt.Errorf("store rebound delivery: %w", err)
}
delivery = rebound
}
if claimed.ManualRetryCycleStarted && claimed.SendStartUnsettled {
// A manually authorized send started but its result was not recorded.
// Do not spend that authorization on another provider call.
return sender.recordInDoubt(ctx, unit, delivery, now)
}
if sender.retryBeyondDeduplication(claimed) {
if claimed.SendStartUnsettled {
return sender.recordInDoubt(ctx, unit, delivery, now)
}
return sender.stopAutomaticRetry(ctx, unit, delivery, now)
}
reason, err := sender.lane.eligibility.Check(ctx, unit, delivery, now)
if err != nil {
return claimedSend{}, fmt.Errorf("check eligibility: %w", err)
}
if reason != "" {
return sender.cancel(ctx, unit, delivery, now, reason)
}
decision, err := sender.gate.PrepareSend(ctx, unit, delivery)
if err != nil {
return claimedSend{}, fmt.Errorf("prepare send: %w", err)
}
if !decision.Proceed() {
return sender.waitForQuota(ctx, unit, delivery, decision, now)
}
return claimedSend{
delivery: decision.Delivery,
permit: decision.Permit,
firstSendStarted: claimed.FirstSendStarted,
sinceFirstSend: claimed.SinceFirstSend,
manualRetryPending: claimed.ManualRetryPending,
manualRetryCycleStarted: claimed.ManualRetryCycleStarted,
sendStartUnsettled: claimed.SendStartUnsettled,
requireDedupWindow: sender.requiresDedupWindow(claimed),
}, nil
}
func (sender *DeliverySender) waitForQuota(
ctx context.Context,
unit outbound.UnitOfWork,
delivery domain.Delivery,
decision SendDecision,
now time.Time,
) (claimedSend, error) {
if delivery.Status() != domain.DeliveryStatusUnknown || decision.ResetAt.IsZero() {
return claimedSend{decided: true, result: resultOf(inbound.MailPassWaitingQuota, decision.Delivery)}, nil
}
at := latest(now, delivery.UpdatedAt())
deferred, err := delivery.ScheduleUnknownRetry(at, latest(decision.ResetAt, at))
if err != nil {
return claimedSend{}, fmt.Errorf("schedule uncertain quota retry: %w", err)
}
if err := unit.Deliveries().ScheduleUnknownRetry(ctx, sender.owner, deferred); err != nil {
return claimedSend{}, fmt.Errorf("store uncertain quota retry: %w", err)
}
return claimedSend{decided: true, result: resultOf(inbound.MailPassUnknown, deferred)}, nil
}
// abandonedBeyondDeduplication reports a delivery whose earlier sender let its
// lease expire after it had started the first request, and so long ago that
// the provider may have forgotten the idempotency key: repeating the request
// could send the mail twice. The provider keeps the key for its window from
// the first request, so the age is counted from there, by the database clock,
// however often the delivery was claimed since and whatever the lease is,
// less a safety margin. A transport without provider-side deduplication
// (window zero) never repeats a request that may have been sent. A lease
// that never reached the request leaves nothing in doubt.
func (sender *DeliverySender) requiresDedupWindow(claimed outbound.ClaimedDelivery) bool {
if claimed.SendStartUnsettled {
return true
}
if claimed.ManualRetryPending {
return false
}
if claimed.Delivery.Status() == domain.DeliveryStatusUnknown {
return true
}
return claimed.HasUncertainAttempt && !claimed.ManualRetryCycleStarted
}
func (sender *DeliverySender) retryBeyondDeduplication(claimed outbound.ClaimedDelivery) bool {
if !sender.requiresDedupWindow(claimed) {
return false
}
if !claimed.FirstSendStarted {
return true
}
return claimed.SinceFirstSend >= sender.safeRetryWindow()
}
func (sender *DeliverySender) safeRetryWindow() time.Duration {
return max(sender.gate.IdempotencyWindow()-dedupSafetyMargin, 0)
}
// recordInDoubt records the lost attempt as unknown, without a next attempt,
// so an operator decides; it is never treated as not sent.
func (sender *DeliverySender) recordInDoubt(ctx context.Context, unit outbound.UnitOfWork, delivery domain.Delivery, now time.Time) (claimedSend, error) {
next, attempt, err := delivery.RecordAttempt(domain.DeliveryAttemptInput{
At: latest(now, delivery.UpdatedAt()),
Outcome: domain.DeliveryOutcomeUnknown,
})
if err != nil {
return claimedSend{}, fmt.Errorf("record lost attempt: %w", err)
}
if err := unit.Deliveries().RecordClaimedAttempt(ctx, sender.owner, next, attempt); err != nil {
return claimedSend{}, fmt.Errorf("store lost attempt: %w", err)
}
sender.logger.WarnContext(ctx, "an earlier attempt of the delivery stopped without a result beyond the provider's idempotency window; the delivery is unknown and needs an operator",
slog.String("delivery_id", delivery.ID().String()),
slog.String("kind", string(delivery.Kind())))
return claimedSend{decided: true, result: resultOf(inbound.MailPassUnknown, next)}, nil
}
func (sender *DeliverySender) stopAutomaticRetry(
ctx context.Context,
unit outbound.UnitOfWork,
delivery domain.Delivery,
now time.Time,
) (claimedSend, error) {
next, err := delivery.StopAutomaticRetry(latest(now, delivery.UpdatedAt()))
if err != nil {
return claimedSend{}, fmt.Errorf("stop automatic retry: %w", err)
}
if err := unit.Deliveries().StopUnknownRetry(ctx, sender.owner, next); err != nil {
return claimedSend{}, fmt.Errorf("store stopped retry: %w", err)
}
sender.logger.WarnContext(ctx, "automatic retries stopped before the provider deduplication cutoff; the delivery remains unknown for an operator decision",
slog.String("delivery_id", delivery.ID().String()),
slog.String("kind", string(delivery.Kind())))
return claimedSend{decided: true, result: resultOf(inbound.MailPassUnknown, next)}, nil
}
func (sender *DeliverySender) releaseUnsentReservation(ctx context.Context, unit outbound.UnitOfWork, claim claimedSend) error {
if claim.permit.IsZero() || claim.permit.Reused() {
return nil
}
if _, err := sender.gate.SettleSend(ctx, unit, claim.permit, outbound.SendResult{}, errNotSent); err != nil {
return fmt.Errorf("release unused reservation: %w", err)
}
return nil
}
func (sender *DeliverySender) cancel(
ctx context.Context,
unit outbound.UnitOfWork,
delivery domain.Delivery,
now time.Time,
reason domain.DeliveryCancelReason,
) (claimedSend, error) {
cancelled, err := delivery.Cancel(latest(now, delivery.UpdatedAt()), reason)
if err != nil {
return claimedSend{}, fmt.Errorf("cancel delivery: %w", err)
}
if err := unit.Deliveries().Cancel(ctx, cancelled); err != nil {
return claimedSend{}, fmt.Errorf("store cancelled delivery: %w", err)
}
sender.logger.InfoContext(ctx, "mail was not sent because it is no longer valid",
slog.String("delivery_id", delivery.ID().String()),
slog.String("kind", string(delivery.Kind())),
slog.String("reason", string(reason)))
return claimedSend{decided: true, result: resultOf(inbound.MailPassCancelled, cancelled)}, nil
}
// settle stores the result of the transport call, repeating the transaction
// after a database failure: the answer lives only here until it is stored.
// When every try fails, the delivery stays under its lease; once it expires,
// another claim repeats the request under the same idempotency key.
func (sender *DeliverySender) settle(ctx context.Context, claim claimedSend, result outbound.SendResult, sendErr error) (inbound.MailPassResult, error) {
const location = "DeliverySender.settle"
result, sendErr = sender.checkedSendResult(ctx, claim.delivery, result, sendErr)
// The result is stored even when ctx ended: shutdown must not lose it. The
// whole of storing is bounded by the budget reserved inside the lease, and
// by the shorter shutdown budget once shutdown has begun, so the process
// stops within its shutdown timeout.
budget := sender.settings.SettleBudget
if ctx.Err() != nil {
budget = min(budget, sender.settings.ShutdownSettleBudget)
}
storeCtx, cancelStore := context.WithTimeout(context.WithoutCancel(ctx), budget)
defer cancelStore()
var lastErr error
for attempt := 1; attempt <= settleAttempts; attempt++ {
var final inbound.MailPassResult
tryCtx, cancel := context.WithTimeout(storeCtx, sender.settings.StoreTimeout)
lastErr = sender.transactor.WithinTransaction(tryCtx, func(ctx context.Context, unit outbound.UnitOfWork) error {
var err error
final, err = sender.applyResult(ctx, unit, claim, result, sendErr)
return err
})
cancel()
switch {
case lastErr == nil:
sender.logFinished(storeCtx, final)
return final, nil
case errors.Is(lastErr, errLeaseLost):
sender.logger.InfoContext(storeCtx, "mail was recorded by another worker first; this attempt is dropped",
slog.String("delivery_id", claim.delivery.ID().String()))
return resultOf(inbound.MailPassLeaseLost, claim.delivery), nil
}
if attempt < settleAttempts && !waitFor(storeCtx, settleRetryDelay) {
break
}
}
sender.logger.ErrorContext(storeCtx, "the result of a mail send could not be stored; the delivery stays under its lease and is claimed again after it expires, with the same idempotency key",
slog.String("delivery_id", claim.delivery.ID().String()),
slog.String("kind", string(claim.delivery.Kind())))
return inbound.MailPassResult{}, fmt.Errorf("%s - store result: %w", location, lastErr)
}
// checkedSendResult guards the stored state against a transport that breaks
// the MailSender contract: a nil error with no outcome may mean that the
// message left, so it counts as unknown, never as not sent.
func (sender *DeliverySender) checkedSendResult(ctx context.Context, delivery domain.Delivery, result outbound.SendResult, sendErr error) (outbound.SendResult, error) {
if sendErr != nil {
return outbound.SendResult{}, sendErr
}
switch result.Outcome {
case outbound.MailOutcomeAccepted, outbound.MailOutcomeRejected, outbound.MailOutcomeUnknown:
return result, nil
default:
sender.logger.ErrorContext(ctx, "the mail transport returned no outcome; the attempt is recorded as unknown",
slog.String("delivery_id", delivery.ID().String()))
return outbound.SendResult{Outcome: outbound.MailOutcomeUnknown}, nil
}
}
// applyResult runs in the settlement transaction: the quota settlement and
// the delivery's next state commit together.
func (sender *DeliverySender) applyResult(
ctx context.Context,
unit outbound.UnitOfWork,
claim claimedSend,
result outbound.SendResult,
sendErr error,
) (inbound.MailPassResult, error) {
delivery := claim.delivery
// The delivery row is locked before the quota rows, the order of the claim,
// and only while this worker still holds the lease.
held, err := unit.Deliveries().LockClaimed(ctx, delivery.ID(), sender.owner)
if err != nil {
return inbound.MailPassResult{}, fmt.Errorf("lock delivery: %w", err)
}
if !held {
return inbound.MailPassResult{}, errLeaseLost
}
until, err := sender.gate.SettleSend(ctx, unit, claim.permit, result, sendErr)
if err != nil {
return inbound.MailPassResult{}, fmt.Errorf("settle quota: %w", err)
}
now := sender.clock()
if sendErr != nil {
return sender.applyNotSent(ctx, unit, claim, now, sendErr)
}
at := latest(now, delivery.UpdatedAt())
manualRetry := claim.manualRetryPending || claim.manualRetryCycleStarted
next, attempt, err := delivery.RecordAttempt(sender.attemptInput(delivery, result, at, until, manualRetry))
if err != nil {
return inbound.MailPassResult{}, fmt.Errorf("record attempt: %w", err)
}
if err := unit.Deliveries().RecordClaimedAttempt(ctx, sender.owner, next, attempt); err != nil {
if errors.Is(err, outbound.ErrDeliveryVersionConflict) {
return inbound.MailPassResult{}, errLeaseLost
}
return inbound.MailPassResult{}, fmt.Errorf("store attempt: %w", err)
}
return resultOf(outcomeOfStatus(next.Status()), next), nil
}
// attemptInput maps a transport answer to the attempt the delivery records.
// until is the quota reset that SettleSend returned for a provider quota
// refusal.
func (sender *DeliverySender) attemptInput(delivery domain.Delivery, result outbound.SendResult, at, until time.Time, manualRetry bool) domain.DeliveryAttemptInput {
input := domain.DeliveryAttemptInput{
At: at,
Outcome: domain.DeliveryAttemptOutcome(result.Outcome),
Rejection: domain.DeliveryRejection(result.Rejection),
ProviderCode: string(result.ProviderCode),
ProviderMessageID: result.ProviderMessageID,
RetryAfter: result.RetryAfter,
}
switch {
case result.Outcome == outbound.MailOutcomeAccepted:
// An accepted attempt carries no code or wait hint.
input.ProviderCode = ""
input.RetryAfter = 0
case result.Outcome == outbound.MailOutcomeRejected && (result.Rejection == outbound.MailRejectionTemporary || result.Rejection == outbound.MailRejectionRateLimited):
input.NextAttemptAt = sender.settings.Retry.NextAttemptAt(at, delivery.AttemptCount()+1, result.RetryAfter)
case result.Outcome == outbound.MailOutcomeRejected && result.Rejection == outbound.MailRejectionQuotaExhausted && !until.IsZero():
// Zero means that the reset is unknown, and the delivery waits for an
// operator.
input.NextAttemptAt = latest(until, at)
case result.Outcome == outbound.MailOutcomeUnknown && !manualRetry && sender.gate.IdempotencyWindow() > 0:
input.NextAttemptAt = sender.settings.Retry.NextAttemptAt(at, delivery.AttemptCount()+1, result.RetryAfter)
}
return input
}
// applyNotSent handles a Send error: nothing left the process, and SettleSend
// gave the reservation back.
//
// - An invalid stored message ends the delivery (content_invalid).
// - No transport, or a context that ended (shutdown, an exhausted call
// budget) is nobody's fault: the lease ends and the delivery stays due.
// - Any other error is a fault on this delivery or in the transport that a
// plain retry may repeat forever, with the row at the head of the queue.
// It is counted as a failure of the row: the delivery is due later by the
// retry schedule, and after MaxFailures it is cancelled with
// processing_failed for an operator.
func (sender *DeliverySender) applyNotSent(
ctx context.Context,
unit outbound.UnitOfWork,
claim claimedSend,
now time.Time,
sendErr error,
) (inbound.MailPassResult, error) {
delivery := claim.delivery
switch {
case errors.Is(sendErr, outbound.ErrInvalidOutgoingMail):
cancelled, err := delivery.Cancel(latest(now, delivery.UpdatedAt()), domain.DeliveryCancelContentInvalid)
if err != nil {
return inbound.MailPassResult{}, fmt.Errorf("cancel delivery: %w", err)
}
if err := unit.Deliveries().Cancel(ctx, cancelled); err != nil {
return inbound.MailPassResult{}, fmt.Errorf("store cancelled delivery: %w", err)
}
return resultOf(inbound.MailPassCancelled, cancelled), nil
case errors.Is(sendErr, outbound.ErrMailChannelUnavailable), errors.Is(sendErr, context.Canceled), errors.Is(sendErr, context.DeadlineExceeded):
if _, err := unit.Deliveries().ReleaseClaim(ctx, delivery.ID(), sender.owner); err != nil {
return inbound.MailPassResult{}, fmt.Errorf("release claim: %w", err)
}
outcome := inbound.MailPassInterrupted
if errors.Is(sendErr, outbound.ErrMailChannelUnavailable) {
outcome = inbound.MailPassChannelUnavailable
}
return resultOf(outcome, delivery), nil
default:
// An error without an answer that is neither a cancellation nor the
// missing transport says nothing certain about this row, so it is not
// counted against it; the row only moves back by the retry schedule,
// so it does not stay at the head of the queue, and the worker backs
// off as for any pass that could not send.
at := latest(now, delivery.UpdatedAt())
if _, err := unit.Deliveries().RecordFailure(ctx, delivery.ID(), sender.owner, at,
sender.settings.Retry.NextAttemptAt(at, claim.failureCount+1, 0), sender.settings.MaxFailures, false); err != nil {
return inbound.MailPassResult{}, fmt.Errorf("record failure: %w", err)
}
sender.logger.ErrorContext(ctx, "the mail transport failed without an answer; the delivery is retried later",
slog.String("delivery_id", delivery.ID().String()))
return resultOf(inbound.MailPassInterrupted, delivery), nil
}
}
func (sender *DeliverySender) logFinished(ctx context.Context, result inbound.MailPassResult) {
attributes := []any{
slog.String("delivery_id", result.DeliveryID.String()),
slog.String("kind", string(result.Kind)),
slog.String("outcome", string(result.Outcome)),
}
switch result.Outcome {
case inbound.MailPassRejected, inbound.MailPassUnknown:
sender.logger.WarnContext(ctx, "mail was not accepted by the provider", attributes...)
case inbound.MailPassCancelled:
sender.logger.InfoContext(ctx, "mail was not sent because it is invalid", append(attributes, slog.String("reason", string(result.CancelReason)))...)
case inbound.MailPassIdle, inbound.MailPassAccepted, inbound.MailPassRetry, inbound.MailPassWaitingQuota,
inbound.MailPassChannelUnavailable, inbound.MailPassInterrupted, inbound.MailPassLeaseLost, inbound.MailPassRowFailed:
sender.logger.InfoContext(ctx, "mail pass finished", attributes...)
}
}
func outcomeOfStatus(status domain.DeliveryStatus) inbound.MailPassOutcome {
switch status {
case domain.DeliveryStatusAccepted:
return inbound.MailPassAccepted
case domain.DeliveryStatusRejected:
return inbound.MailPassRejected
case domain.DeliveryStatusPending:
return inbound.MailPassRetry
case domain.DeliveryStatusWaitingQuota:
return inbound.MailPassWaitingQuota
case domain.DeliveryStatusCancelled:
return inbound.MailPassCancelled
case domain.DeliveryStatusUnknown:
return inbound.MailPassUnknown
default:
return inbound.MailPassUnknown
}
}
func resultOf(outcome inbound.MailPassOutcome, delivery domain.Delivery) inbound.MailPassResult {
return inbound.MailPassResult{
Outcome: outcome,
DeliveryID: delivery.ID(),
Kind: delivery.Kind(),
CancelReason: delivery.CancelReason(),
}
}
// waitFor sleeps for delay and reports false when ctx ends first.
func waitFor(ctx context.Context, delay time.Duration) bool {
timer := time.NewTimer(delay)
defer timer.Stop()
select {
case <-ctx.Done():
return false
case <-timer.C:
return true
}
}
@@ -76,11 +76,16 @@ func (notifier *InvitationNotifier) InvitationDelivered(ctx context.Context, uni
if err := unit.Outbox().Append(ctx, event); err != nil {
return fmt.Errorf("%s - append event: %w", location, err)
}
subject, err := domain.NewInvitationMailSubject(invitation.ID(), invitation.OrganizationID())
if err != nil {
return fmt.Errorf("%s - name invitation: %w", location, err)
}
if _, err := notifier.mail.RequestNotification(ctx, unit, NotificationRequest{
RecipientUserID: invitation.CandidateID(),
Notification: mailtemplate.NotificationData{
Subject: invitationMailSubject, Body: invitationMailBody, LinkPath: candidateInvitationsPath,
},
Subject: subject,
}); err != nil {
return fmt.Errorf("%s - request email: %w", location, err)
}
@@ -0,0 +1,31 @@
package notification
import (
"context"
"fmt"
"time"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// invitationNoticeRights checks the notice that tells a candidate about a
// delivered invitation: the standing it reads is the one the rule in
// domain.Delivery.CheckInvitationNotice decides on.
type invitationNoticeRights struct{}
// NewInvitationNoticeRights returns the rights check of invitation notices.
func NewInvitationNoticeRights() SubjectRights { return invitationNoticeRights{} }
func (invitationNoticeRights) Subject() domain.MailSubjectKind {
return domain.MailSubjectInvitation
}
func (invitationNoticeRights) Check(ctx context.Context, unit outbound.UnitOfWork, delivery domain.Delivery, at time.Time) (domain.DeliveryCancelReason, error) {
subject := delivery.Subject()
standing, err := unit.NotificationRights().InvitationNoticeStanding(ctx, delivery.RecipientUserID(), subject.ID(), subject.OrganizationID())
if err != nil {
return "", fmt.Errorf("invitationNoticeRights.Check - read standing: %w", err)
}
return delivery.CheckInvitationNotice(standing, at), nil
}
@@ -109,10 +109,13 @@ func (renderer TemplateRenderer) RenderPasswordReset(data mailtemplate.PasswordR
return content, nil
}
// NotificationRequest asks for one notification mail to one account.
// NotificationRequest asks for one notification mail to one account. Subject
// names the record the notice concerns, whose rights are checked before the
// send; the zero value names none.
type NotificationRequest struct {
RecipientUserID uuid.UUID
Notification mailtemplate.NotificationData
Subject domain.MailSubject
}
// MailRequester records mail requests in the caller's transaction.
@@ -154,6 +157,7 @@ func (requester *MailRequester) RequestNotification(ctx context.Context, unit ou
Body: request.Notification.Body,
LinkPath: request.Notification.LinkPath,
},
Subject: request.Subject,
CreatedAt: requester.clock(),
})
if err != nil {
@@ -0,0 +1,81 @@
package notification
import (
"context"
"errors"
"fmt"
"log/slog"
"time"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// ErrNoSubjectRights reports a notification whose subject kind has no rights
// checker in this build. Such a notice is neither sent nor cancelled: its
// basis cannot be checked, so it waits for a build that can check it.
var ErrNoSubjectRights = errors.New("no rights check is registered for the notification subject")
// SubjectRights is the rights check of one subject kind of product
// notifications. A notice names a subject, and its check runs in the claim
// transaction and again before the transport is called, under the delivery
// lock. A future notice that carries a candidate field or a contact adds its
// consent check here (C4 for a contact, C2 for a publication-dependent field)
// and never puts a contact into the mail: contacts are read on request, and
// every read re-checks its grant.
type SubjectRights interface {
// Subject is the subject kind this check decides.
Subject() domain.MailSubjectKind
// Check reads the current standing and returns the cancel reason, or an
// empty reason when the notice may be sent.
Check(ctx context.Context, unit outbound.UnitOfWork, delivery domain.Delivery, at time.Time) (domain.DeliveryCancelReason, error)
}
// subjectEligibility dispatches the rights check by the subject of the
// delivery. A notification that names no subject has no basis to check and is
// cancelled with source_closed.
type subjectEligibility struct {
rights map[domain.MailSubjectKind]SubjectRights
}
func (eligibility subjectEligibility) Check(ctx context.Context, unit outbound.UnitOfWork, delivery domain.Delivery, at time.Time) (domain.DeliveryCancelReason, error) {
subject := delivery.Subject()
if subject.IsZero() {
return domain.DeliveryCancelSourceClosed, nil
}
checker, ok := eligibility.rights[subject.Kind()]
if !ok {
return "", fmt.Errorf("subjectEligibility.Check - subject kind %q: %w", subject.Kind(), ErrNoSubjectRights)
}
return checker.Check(ctx, unit, delivery, at)
}
// NewNotificationSender builds the sender of the product notification lane. It
// claims only notifications and sends one only when the rights check of its
// subject kind passes. rights lists one check per subject kind; a kind listed
// twice is refused. gate must be built for settings.Account.
func NewNotificationSender(
transactor outbound.Transactor,
sender outbound.MailSender,
gate *QuotaGate,
settings DeliverySenderSettings,
clock func() time.Time,
logger *slog.Logger,
rights []SubjectRights,
) (*DeliverySender, error) {
byKind := make(map[domain.MailSubjectKind]SubjectRights, len(rights))
for _, check := range rights {
if check == nil {
return nil, errors.New("notification.NewNotificationSender - rights check must not be nil")
}
if _, dup := byKind[check.Subject()]; dup {
return nil, fmt.Errorf("notification.NewNotificationSender - subject kind %q has two rights checks", check.Subject())
}
byKind[check.Subject()] = check
}
return newDeliverySender(deliveryLane{
scope: outbound.ClaimScopeNotification,
kinds: domain.ProductMailKinds(),
eligibility: subjectEligibility{rights: byKind},
}, transactor, sender, gate, settings, clock, logger)
}
+32 -3
View File
@@ -51,8 +51,12 @@ var (
// Send returned an error, the delivery's next state). The reservation
// journal makes a repeated settlement harmless.
type QuotaGate struct {
account domain.MailProviderAccount
limits domain.MailQuotaLimits
account domain.MailProviderAccount
limits domain.MailQuotaLimits
// reserveDaily and reserveMonthly are the recipients per window that this
// gate leaves free for other mail; see WithReserve.
reserveDaily int64
reserveMonthly int64
idempotencyWindow time.Duration
clock func() time.Time
logger *slog.Logger
@@ -74,6 +78,27 @@ func NewQuotaGate(
return &QuotaGate{account: account, limits: limits, idempotencyWindow: idempotencyWindow, clock: clock, logger: logger}
}
// WithReserve returns a gate that admits a send only while the windows keep
// the given recipients free after it: daily and monthly recipients that other
// mail may use. The service lane keeps the full limits, so a reserve held for
// service mail is never spent by product notifications. The reserve shapes
// admission only; a window that the provider reports used up is still marked
// against the full limit, so the provider's answer is never understated.
func (gate *QuotaGate) WithReserve(daily, monthly int64) (*QuotaGate, error) {
if _, err := gate.limits.WithReserve(daily, monthly); err != nil {
return nil, fmt.Errorf("QuotaGate.WithReserve - reserve: %w", err)
}
next := *gate
next.reserveDaily, next.reserveMonthly = daily, monthly
return &next, nil
}
// admission returns the limits that a send is admitted against: the limits
// less the reserve. It is computed at each decision from the current limits.
func (gate *QuotaGate) admission() (domain.MailQuotaLimits, error) {
return gate.limits.WithReserve(gate.reserveDaily, gate.reserveMonthly)
}
// QuotaPermit admits one send of one delivery. It holds the reservation, so
// a settlement after midnight still releases the windows the send was
// counted in.
@@ -142,6 +167,10 @@ func (gate *QuotaGate) PrepareSend(ctx context.Context, unit outbound.UnitOfWork
return SendDecision{}, fmt.Errorf("%s - delivery is %s: %w", location, delivery.Status(), domain.ErrDeliveryTransition)
}
now := gate.clock()
admission, err := gate.admission()
if err != nil {
return SendDecision{}, fmt.Errorf("%s - admission limits: %w", location, err)
}
reservationID, err := uuid.NewV7()
if err != nil {
return SendDecision{}, fmt.Errorf("%s - generate reservation ID: %w", location, err)
@@ -155,7 +184,7 @@ func (gate *QuotaGate) PrepareSend(ctx context.Context, unit outbound.UnitOfWork
Recipients: recipientsPerDelivery,
ReservedAt: now,
},
Limits: gate.limits,
Limits: admission,
}
if gate.idempotencyWindow > 0 {
request.ReuseSince = now.Add(-gate.idempotencyWindow)
@@ -2,128 +2,38 @@ package notification
import (
"context"
"errors"
"fmt"
"log/slog"
"sync/atomic"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/port/outbound"
)
const (
// settleAttempts bounds how often the transaction that stores a send
// result is repeated after a database failure. The provider answer lives
// only in memory until it is stored, so one failure should not lose it.
settleAttempts = 3
// settleRetryDelay separates two attempts to store a send result.
settleRetryDelay = 200 * time.Millisecond
)
// ServiceMailSenderSettings are the named limits of the service mail sender.
type ServiceMailSenderSettings = DeliverySenderSettings
// dedupSafetyMargin is taken off the provider's idempotency window before it
// is compared with the age of the first request: clocks of the provider and the
// database differ a little, and a key about to expire is as good as expired.
const dedupSafetyMargin = time.Hour
// ServiceMailSender sends the service identity mail of the account flows
// (email verification and password reset) that ServiceMailer stored. It is a
// DeliverySender of the service lane: it claims only service mail and checks
// each delivery's token and account before the send.
type ServiceMailSender = DeliverySender
// errLeaseLost reports a result that another worker recorded first: the
// settlement transaction is rolled back and nothing of this attempt is kept.
var errLeaseLost = errors.New("delivery was recorded by another worker")
// serviceEligibility applies the token and account rules of service mail.
// Publishing consent (C2) and the other product consents play no part: a
// service mail is part of the account flow, not a product notification.
type serviceEligibility struct{}
// ServiceMailSenderSettings are the named limits of the sending worker.
type ServiceMailSenderSettings struct {
// Account is the configured provider account. The sender claims only
// deliveries pinned to it, and moves deliveries stored while no
// transport ran onto it.
Account domain.MailProviderAccount
// RebindProvider is the provider name whose deliveries, before their
// first attempt, are moved onto Account: the disabled transport. Empty
// for none.
RebindProvider string
// Lease is how long a claimed delivery belongs to this sender, measured by
// the database clock. Claim, the call, and the settlement all fit inside
// it: the call is bounded by what is left of the lease after the claim and
// the settlement budget.
Lease time.Duration
// StoreTimeout bounds the claim transaction, the check before the send,
// and each try to store a result.
StoreTimeout time.Duration
// SettleBudget bounds the whole of storing a send result, retries
// included; it is reserved inside the lease.
SettleBudget time.Duration
// ShutdownSettleBudget replaces SettleBudget when shutdown has begun, so
// the process stops within its shutdown timeout.
ShutdownSettleBudget time.Duration
// MaxFailures is how many consecutive failures of the worker itself on one
// delivery are retried before the delivery is cancelled with the reason
// processing_failed.
MaxFailures int32
Retry RetryPolicy
}
func (settings ServiceMailSenderSettings) validate() error {
switch {
case settings.Account.IsZero():
return errors.New("notification.NewServiceMailSender - provider account must be set")
case settings.Lease <= 0 || settings.StoreTimeout <= 0 || settings.SettleBudget <= 0 || settings.ShutdownSettleBudget <= 0 || settings.MaxFailures < 1:
return errors.New("notification.NewServiceMailSender - lease, timeouts, and settle budgets must be positive and the failure limit at least 1")
case settings.SettleBudget >= settings.Lease:
return errors.New("notification.NewServiceMailSender - the settle budget must be shorter than the lease")
case settings.Retry.Initial <= 0 || settings.Retry.Max < settings.Retry.Initial:
return errors.New("notification.NewServiceMailSender - retry delays must be positive and the maximum not below the initial delay")
func (serviceEligibility) Check(ctx context.Context, unit outbound.UnitOfWork, delivery domain.Delivery, at time.Time) (domain.DeliveryCancelReason, error) {
state, err := unit.Deliveries().ServiceMailState(ctx, delivery.ID())
if err != nil {
return "", fmt.Errorf("serviceEligibility.Check - read token and account: %w", err)
}
return nil
return delivery.CheckServiceMail(state, at), nil
}
// ServiceMailSender sends the service mail of the account flows (email
// verification and password reset) that ServiceMailer stored. Several
// senders may run against one database, in one process or many.
//
// One pass takes one delivery through three steps:
//
// 1. Claim transaction: ClaimDue leases the most overdue due delivery with
// FOR UPDATE SKIP LOCKED, so no two senders hold the same one. The
// token and the account are checked (domain.Delivery.CheckServiceMail);
// a mail that must not go out is cancelled with a reason. Otherwise
// QuotaGate.PrepareSend reserves the quota, or parks the delivery in
// waiting_quota. The transaction commits before the transport is called,
// so a slow provider never holds a row lock.
// 2. One call to MailSender.Send with the stored content and the stable
// idempotency key. The sender never retries: a failed attempt becomes the
// delivery's next state and due time.
// 3. Settlement transaction: QuotaGate.SettleSend and
// DeliveryRepository.RecordAttempt in one transaction. The attempt is
// recorded over the delivery's version, so of two senders that both
// reached this step only the first is kept.
//
// A sender that stops after the claim leaves its lease to expire; another
// sender then claims the delivery and calls the provider with the same
// idempotency key, which the provider answers with the original result
// instead of sending twice, and the quota gate reuses the open reservation.
// Past the provider's idempotency window the earlier attempt is in doubt,
// so the delivery is recorded as unknown instead of being sent again.
//
// Logs and results name a delivery only by its ID, never by address or
// content.
type ServiceMailSender struct {
owner uuid.UUID
// countingPaused stops counting failures of single rows; see
// PauseFailureCounting.
countingPaused atomic.Bool
transactor outbound.Transactor
sender outbound.MailSender
gate *QuotaGate
settings ServiceMailSenderSettings
clock func() time.Time
logger *slog.Logger
}
// NewServiceMailSender builds a sender with a random lease owner ID. gate
// must be built for settings.Account. clock is the application clock: due,
// lease, and quota decisions use it, so tests move time with a fake one.
// NewServiceMailSender builds the sender of the service lane. gate must be
// built for settings.Account. clock is the application clock.
func NewServiceMailSender(
transactor outbound.Transactor,
sender outbound.MailSender,
@@ -132,748 +42,9 @@ func NewServiceMailSender(
clock func() time.Time,
logger *slog.Logger,
) (*ServiceMailSender, error) {
if err := settings.validate(); err != nil {
return nil, err
}
owner := uuid.New()
return &ServiceMailSender{
owner: owner,
transactor: transactor,
sender: sender,
gate: gate,
settings: settings,
clock: clock,
logger: logger.With(slog.String("lease_owner", owner.String())),
}, nil
}
// claimedSend is a delivery that passed the claim transaction and is ready to
// be sent, or the final result of a delivery the transaction already decided.
type claimedSend struct {
delivery domain.Delivery
permit QuotaPermit
firstSendStarted bool
sinceFirstSend time.Duration
manualRetryPending bool
manualRetryCycleStarted bool
sendStartUnsettled bool
requireDedupWindow bool
// decided is set when the claim transaction ended the pass: the result
// is final and nothing is sent.
decided bool
result inbound.MailPassResult
// failureCount is the number of consecutive failures of the worker on the
// delivery before this pass.
failureCount int32
}
var _ inbound.MailPass = (*ServiceMailSender)(nil)
// PauseFailureCounting implements inbound.MailPass.
func (sender *ServiceMailSender) PauseFailureCounting(paused bool) {
sender.countingPaused.Store(paused)
}
// isRowFault reports an error that the delivery itself causes and that
// repeating cannot cure: it breaks a domain rule, cannot be restored, or is
// refused by a data or integrity constraint. Every other error (a context that
// ended, a timeout, a deadlock, a lost connection, a missing quota
// configuration) says nothing about the row, so it is never counted against
// it.
func isRowFault(err error) bool {
var unreadable *outbound.UnreadableDeliveryError
return errors.As(err, &unreadable) ||
errors.Is(err, domain.ErrInvalidDelivery) ||
errors.Is(err, domain.ErrDeliveryTransition) ||
errors.Is(err, domain.ErrInvalidMailContent) ||
errors.Is(err, domain.ErrMailContentIntegrity) ||
errors.Is(err, domain.ErrInvalidEmailAddress) ||
errors.Is(err, outbound.ErrRowFault)
}
// ProcessNext runs one pass. ctx ends the claim of new work; workCtx bounds
// the transport call and should outlive ctx by a shutdown grace, so a send in
// progress is not cut off at the first sign of shutdown. An error reports a
// database failure; the delivery it concerned is left under its lease, which
// expires, or was never claimed.
func (sender *ServiceMailSender) ProcessNext(ctx, workCtx context.Context) (inbound.MailPassResult, error) {
// The lease runs by the database clock from the claim, which is later
// than this reading, so the budget below errs on the short side.
started := time.Now()
claim, err := sender.claim(ctx)
if err != nil {
return inbound.MailPassResult{}, fmt.Errorf("ServiceMailSender.ProcessNext - claim delivery: %w", err)
}
if claim.decided {
return claim.result, nil
}
if decided, err := sender.beforeSend(workCtx, claim); err != nil || decided != nil {
if err != nil {
return inbound.MailPassResult{}, fmt.Errorf("ServiceMailSender.ProcessNext - check before sending: %w", err)
}
return *decided, nil
}
delivery := claim.delivery
content := delivery.Content()
// What is left of the lease after the claim and the reserve for storing
// the answer is the most the call may take.
callBudget := sender.settings.Lease - time.Since(started) - sender.settings.SettleBudget
if callBudget <= 0 {
return sender.releaseUnsent(ctx, claim)
}
sendCtx, cancel := context.WithTimeout(workCtx, callBudget)
result, sendErr := sender.sender.Send(sendCtx, outbound.OutgoingMail{
To: delivery.Recipient(),
Subject: content.Subject(),
TextBody: content.Text(),
HTMLBody: content.HTML(),
IdempotencyKey: delivery.IdempotencyKey(),
})
cancel()
return sender.settle(ctx, claim, result, sendErr)
}
// failingRow names a claimed delivery on which the claim transaction failed,
// so a failure can be recorded for it outside that transaction.
type failingRow struct {
id uuid.UUID
count int32
}
func (sender *ServiceMailSender) claim(ctx context.Context) (claimedSend, error) {
var claim claimedSend
var failing *failingRow
claimCtx, cancel := context.WithTimeout(ctx, sender.settings.StoreTimeout)
defer cancel()
err := sender.transactor.WithinTransaction(claimCtx, func(ctx context.Context, unit outbound.UnitOfWork) error {
now := sender.clock()
claimed, err := unit.Deliveries().ClaimDue(ctx, outbound.DeliveryClaim{
Owner: sender.owner,
Account: sender.settings.Account,
RebindProvider: sender.settings.RebindProvider,
Kinds: domain.ServiceMailKinds(),
Now: now,
Lease: sender.settings.Lease,
})
if errors.Is(err, outbound.ErrNoDeliveryDue) {
claim = claimedSend{decided: true, result: inbound.MailPassResult{Outcome: inbound.MailPassIdle}}
return nil
}
var unreadable *outbound.UnreadableDeliveryError
if errors.As(err, &unreadable) {
if unreadable.Cancelled {
// The store cancelled the broken row; committing keeps it
// from blocking the queue. Its content is left as it is for
// an operator.
sender.logger.ErrorContext(ctx, "a due delivery does not match its content hash and was cancelled; an operator should inspect it",
slog.String("delivery_id", unreadable.DeliveryID.String()),
slog.String("reason", string(domain.DeliveryCancelContentInvalid)))
claim = claimedSend{decided: true, result: inbound.MailPassResult{
Outcome: inbound.MailPassCancelled,
DeliveryID: unreadable.DeliveryID,
CancelReason: domain.DeliveryCancelContentInvalid,
}}
return nil
}
failing = &failingRow{id: unreadable.DeliveryID, count: unreadable.FailureCount}
return fmt.Errorf("claim due delivery: %w", err)
}
if err != nil {
return fmt.Errorf("claim due delivery: %w", err)
}
failing = &failingRow{id: claimed.Delivery.ID(), count: claimed.FailureCount}
claim, err = sender.prepare(ctx, unit, claimed, now)
if err != nil {
return err
}
failing = nil
claim.failureCount = claimed.FailureCount
return nil
})
if err != nil {
// The transaction rolled back, and with it the lease: the same row
// would be claimed again and fail again, and every delivery behind
// it would wait. Record the failure in a transaction of its own so
// the row moves back in the queue.
if failing != nil && ctx.Err() == nil && isRowFault(err) {
if result, recordErr := sender.recordRowFailure(ctx, *failing, err); recordErr == nil {
return claimedSend{decided: true, result: result}, nil
}
}
return claimedSend{}, err
}
return claim, nil
}
// recordRowFailure counts a failure of the worker on a delivery in a short
// transaction of its own and makes the row due later by the retry schedule;
// after MaxFailures it cancels the row with processing_failed.
func (sender *ServiceMailSender) recordRowFailure(ctx context.Context, failing failingRow, cause error) (inbound.MailPassResult, error) {
var cancelled bool
recordCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), sender.settings.StoreTimeout)
defer cancel()
err := sender.transactor.WithinTransaction(recordCtx, func(ctx context.Context, unit outbound.UnitOfWork) error {
now := sender.clock()
var err error
cancelled, err = unit.Deliveries().RecordFailure(ctx, failing.id, sender.owner, now,
sender.settings.Retry.NextAttemptAt(now, failing.count+1, 0), sender.settings.MaxFailures, !sender.countingPaused.Load())
return err
})
if err != nil {
return inbound.MailPassResult{}, fmt.Errorf("record failure: %w", err)
}
// The cause is a wrapped chain of rules and sentinels; it never quotes
// the row.
sender.logger.ErrorContext(ctx, "the sending worker failed on a delivery; it is retried later and cancelled after repeated failures",
slog.String("delivery_id", failing.id.String()),
slog.Int("consecutive_failures", int(failing.count)+1),
slog.Bool("cancelled", cancelled),
slog.Any("error", cause))
if cancelled {
return inbound.MailPassResult{Outcome: inbound.MailPassCancelled, DeliveryID: failing.id, CancelReason: domain.DeliveryCancelProcessingFailed}, nil
}
return inbound.MailPassResult{Outcome: inbound.MailPassRowFailed, DeliveryID: failing.id}, nil
}
// beforeSend runs right before the transport is called: it takes the delivery
// lock, reads the token and the account again, so a revocation after the claim
// committed is honored, and notes the start of the first request. A mail that
// is no longer valid is cancelled and its reservation given back.
func (sender *ServiceMailSender) beforeSend(ctx context.Context, claim claimedSend) (*inbound.MailPassResult, error) {
var decided *inbound.MailPassResult
checkCtx, cancel := context.WithTimeout(ctx, sender.settings.StoreTimeout)
defer cancel()
err := sender.transactor.WithinTransaction(checkCtx, func(ctx context.Context, unit outbound.UnitOfWork) error {
delivery := claim.delivery
held, err := unit.Deliveries().LockClaimed(ctx, delivery.ID(), sender.owner)
if err != nil {
return fmt.Errorf("lock delivery: %w", err)
}
if !held {
result := resultOf(inbound.MailPassLeaseLost, delivery)
decided = &result
return nil
}
state, err := unit.Deliveries().ServiceMailState(ctx, delivery.ID())
if err != nil {
return fmt.Errorf("read token and account: %w", err)
}
now := sender.clock()
if result, handled, err := sender.handleInvalidClaim(ctx, unit, claim, delivery, state, now); err != nil || handled {
if handled {
decided = &result
}
return err
}
started, err := unit.Deliveries().MarkSendStarted(ctx, delivery.ID(), sender.owner,
claim.requireDedupWindow, sender.safeRetryWindow())
if err != nil {
return fmt.Errorf("mark send started: %w", err)
}
if !started {
result, err := sender.handleUnmarkedSend(ctx, unit, claim, delivery, now)
if err != nil {
return err
}
decided = &result
}
return nil
})
if err != nil {
return nil, err
}
return decided, nil
}
func (sender *ServiceMailSender) handleInvalidClaim(
ctx context.Context,
unit outbound.UnitOfWork,
claim claimedSend,
delivery domain.Delivery,
state domain.ServiceMailState,
now time.Time,
) (inbound.MailPassResult, bool, error) {
reason := delivery.CheckServiceMail(state, now)
if reason == "" {
return inbound.MailPassResult{}, false, nil
}
if delivery.Status() == domain.DeliveryStatusUnknown {
if err := sender.releaseUnsentReservation(ctx, unit, claim); err != nil {
return inbound.MailPassResult{}, true, err
}
stopped, err := sender.stopAutomaticRetry(ctx, unit, delivery, now)
return stopped.result, true, err
}
if _, err := sender.gate.SettleSend(ctx, unit, claim.permit, outbound.SendResult{}, errNotSent); err != nil {
return inbound.MailPassResult{}, true, fmt.Errorf("give the reservation back: %w", err)
}
cancelled, err := sender.cancel(ctx, unit, delivery, now, reason)
return cancelled.result, true, err
}
func (sender *ServiceMailSender) handleUnmarkedSend(
ctx context.Context,
unit outbound.UnitOfWork,
claim claimedSend,
delivery domain.Delivery,
now time.Time,
) (inbound.MailPassResult, error) {
if delivery.Status() == domain.DeliveryStatusUnknown {
if err := sender.releaseUnsentReservation(ctx, unit, claim); err != nil {
return inbound.MailPassResult{}, err
}
stopped, err := sender.stopAutomaticRetry(ctx, unit, delivery, now)
return stopped.result, err
}
if claim.sendStartUnsettled {
inDoubt, err := sender.recordInDoubt(ctx, unit, delivery, now)
return inDoubt.result, err
}
if claim.requireDedupWindow && claim.firstSendStarted {
if err := sender.releaseUnsentReservation(ctx, unit, claim); err != nil {
return inbound.MailPassResult{}, err
}
stopped, err := sender.stopAutomaticRetry(ctx, unit, delivery, now)
return stopped.result, err
}
if claim.firstSendStarted {
inDoubt, err := sender.recordInDoubt(ctx, unit, delivery, now)
return inDoubt.result, err
}
return resultOf(inbound.MailPassLeaseLost, delivery), nil
}
// errNotSent stands for "the message did not leave the process" when a
// reservation is given back before the transport was called.
var errNotSent = errors.New("message was not sent")
// releaseUnsent gives a claimed delivery back when no time is left to call
// the transport, and the reservation with it.
func (sender *ServiceMailSender) releaseUnsent(ctx context.Context, claim claimedSend) (inbound.MailPassResult, error) {
return sender.settle(ctx, claim, outbound.SendResult{}, context.DeadlineExceeded)
}
// prepare decides what a claimed delivery needs before the transport is
// called, in the claim transaction.
func (sender *ServiceMailSender) prepare(ctx context.Context, unit outbound.UnitOfWork, claimed outbound.ClaimedDelivery, now time.Time) (claimedSend, error) {
delivery := claimed.Delivery
if delivery.ProviderAccount() != sender.settings.Account {
// Mail stored while no transport ran has no attempt, so no provider
// holds its idempotency key and the account may change.
rebound, err := delivery.Rebind(latest(now, delivery.UpdatedAt()), sender.settings.Account)
if err != nil {
return claimedSend{}, fmt.Errorf("rebind delivery: %w", err)
}
if err := unit.Deliveries().Rebind(ctx, rebound); err != nil {
return claimedSend{}, fmt.Errorf("store rebound delivery: %w", err)
}
delivery = rebound
}
if claimed.ManualRetryCycleStarted && claimed.SendStartUnsettled {
// A manually authorized send started but its result was not recorded.
// Do not spend that authorization on another provider call.
return sender.recordInDoubt(ctx, unit, delivery, now)
}
if sender.retryBeyondDeduplication(claimed) {
if claimed.SendStartUnsettled {
return sender.recordInDoubt(ctx, unit, delivery, now)
}
return sender.stopAutomaticRetry(ctx, unit, delivery, now)
}
state, err := unit.Deliveries().ServiceMailState(ctx, delivery.ID())
if err != nil {
return claimedSend{}, fmt.Errorf("read token and account: %w", err)
}
if reason := delivery.CheckServiceMail(state, now); reason != "" {
return sender.cancel(ctx, unit, delivery, now, reason)
}
decision, err := sender.gate.PrepareSend(ctx, unit, delivery)
if err != nil {
return claimedSend{}, fmt.Errorf("prepare send: %w", err)
}
if !decision.Proceed() {
return sender.waitForQuota(ctx, unit, delivery, decision, now)
}
return claimedSend{
delivery: decision.Delivery,
permit: decision.Permit,
firstSendStarted: claimed.FirstSendStarted,
sinceFirstSend: claimed.SinceFirstSend,
manualRetryPending: claimed.ManualRetryPending,
manualRetryCycleStarted: claimed.ManualRetryCycleStarted,
sendStartUnsettled: claimed.SendStartUnsettled,
requireDedupWindow: sender.requiresDedupWindow(claimed),
}, nil
}
func (sender *ServiceMailSender) waitForQuota(
ctx context.Context,
unit outbound.UnitOfWork,
delivery domain.Delivery,
decision SendDecision,
now time.Time,
) (claimedSend, error) {
if delivery.Status() != domain.DeliveryStatusUnknown || decision.ResetAt.IsZero() {
return claimedSend{decided: true, result: resultOf(inbound.MailPassWaitingQuota, decision.Delivery)}, nil
}
at := latest(now, delivery.UpdatedAt())
deferred, err := delivery.ScheduleUnknownRetry(at, latest(decision.ResetAt, at))
if err != nil {
return claimedSend{}, fmt.Errorf("schedule uncertain quota retry: %w", err)
}
if err := unit.Deliveries().ScheduleUnknownRetry(ctx, sender.owner, deferred); err != nil {
return claimedSend{}, fmt.Errorf("store uncertain quota retry: %w", err)
}
return claimedSend{decided: true, result: resultOf(inbound.MailPassUnknown, deferred)}, nil
}
// abandonedBeyondDeduplication reports a delivery whose earlier sender let its
// lease expire after it had started the first request, and so long ago that
// the provider may have forgotten the idempotency key: repeating the request
// could send the mail twice. The provider keeps the key for its window from
// the first request, so the age is counted from there, by the database clock,
// however often the delivery was claimed since and whatever the lease is,
// less a safety margin. A transport without provider-side deduplication
// (window zero) never repeats a request that may have been sent. A lease
// that never reached the request leaves nothing in doubt.
func (sender *ServiceMailSender) requiresDedupWindow(claimed outbound.ClaimedDelivery) bool {
if claimed.SendStartUnsettled {
return true
}
if claimed.ManualRetryPending {
return false
}
if claimed.Delivery.Status() == domain.DeliveryStatusUnknown {
return true
}
return claimed.HasUncertainAttempt && !claimed.ManualRetryCycleStarted
}
func (sender *ServiceMailSender) retryBeyondDeduplication(claimed outbound.ClaimedDelivery) bool {
if !sender.requiresDedupWindow(claimed) {
return false
}
if !claimed.FirstSendStarted {
return true
}
return claimed.SinceFirstSend >= sender.safeRetryWindow()
}
func (sender *ServiceMailSender) safeRetryWindow() time.Duration {
return max(sender.gate.IdempotencyWindow()-dedupSafetyMargin, 0)
}
// recordInDoubt records the lost attempt as unknown, without a next attempt,
// so an operator decides; it is never treated as not sent.
func (sender *ServiceMailSender) recordInDoubt(ctx context.Context, unit outbound.UnitOfWork, delivery domain.Delivery, now time.Time) (claimedSend, error) {
next, attempt, err := delivery.RecordAttempt(domain.DeliveryAttemptInput{
At: latest(now, delivery.UpdatedAt()),
Outcome: domain.DeliveryOutcomeUnknown,
})
if err != nil {
return claimedSend{}, fmt.Errorf("record lost attempt: %w", err)
}
if err := unit.Deliveries().RecordClaimedAttempt(ctx, sender.owner, next, attempt); err != nil {
return claimedSend{}, fmt.Errorf("store lost attempt: %w", err)
}
sender.logger.WarnContext(ctx, "an earlier attempt of the delivery stopped without a result beyond the provider's idempotency window; the delivery is unknown and needs an operator",
slog.String("delivery_id", delivery.ID().String()),
slog.String("kind", string(delivery.Kind())))
return claimedSend{decided: true, result: resultOf(inbound.MailPassUnknown, next)}, nil
}
func (sender *ServiceMailSender) stopAutomaticRetry(
ctx context.Context,
unit outbound.UnitOfWork,
delivery domain.Delivery,
now time.Time,
) (claimedSend, error) {
next, err := delivery.StopAutomaticRetry(latest(now, delivery.UpdatedAt()))
if err != nil {
return claimedSend{}, fmt.Errorf("stop automatic retry: %w", err)
}
if err := unit.Deliveries().StopUnknownRetry(ctx, sender.owner, next); err != nil {
return claimedSend{}, fmt.Errorf("store stopped retry: %w", err)
}
sender.logger.WarnContext(ctx, "automatic retries stopped before the provider deduplication cutoff; the delivery remains unknown for an operator decision",
slog.String("delivery_id", delivery.ID().String()),
slog.String("kind", string(delivery.Kind())))
return claimedSend{decided: true, result: resultOf(inbound.MailPassUnknown, next)}, nil
}
func (sender *ServiceMailSender) releaseUnsentReservation(ctx context.Context, unit outbound.UnitOfWork, claim claimedSend) error {
if claim.permit.IsZero() || claim.permit.Reused() {
return nil
}
if _, err := sender.gate.SettleSend(ctx, unit, claim.permit, outbound.SendResult{}, errNotSent); err != nil {
return fmt.Errorf("release unused reservation: %w", err)
}
return nil
}
func (sender *ServiceMailSender) cancel(
ctx context.Context,
unit outbound.UnitOfWork,
delivery domain.Delivery,
now time.Time,
reason domain.DeliveryCancelReason,
) (claimedSend, error) {
cancelled, err := delivery.Cancel(latest(now, delivery.UpdatedAt()), reason)
if err != nil {
return claimedSend{}, fmt.Errorf("cancel delivery: %w", err)
}
if err := unit.Deliveries().Cancel(ctx, cancelled); err != nil {
return claimedSend{}, fmt.Errorf("store cancelled delivery: %w", err)
}
sender.logger.InfoContext(ctx, "service mail was not sent because it is no longer valid",
slog.String("delivery_id", delivery.ID().String()),
slog.String("kind", string(delivery.Kind())),
slog.String("reason", string(reason)))
return claimedSend{decided: true, result: resultOf(inbound.MailPassCancelled, cancelled)}, nil
}
// settle stores the result of the transport call, repeating the transaction
// after a database failure: the answer lives only here until it is stored.
// When every try fails, the delivery stays under its lease; once it expires,
// another claim repeats the request under the same idempotency key.
func (sender *ServiceMailSender) settle(ctx context.Context, claim claimedSend, result outbound.SendResult, sendErr error) (inbound.MailPassResult, error) {
const location = "ServiceMailSender.settle"
result, sendErr = sender.checkedSendResult(ctx, claim.delivery, result, sendErr)
// The result is stored even when ctx ended: shutdown must not lose it. The
// whole of storing is bounded by the budget reserved inside the lease, and
// by the shorter shutdown budget once shutdown has begun, so the process
// stops within its shutdown timeout.
budget := sender.settings.SettleBudget
if ctx.Err() != nil {
budget = min(budget, sender.settings.ShutdownSettleBudget)
}
storeCtx, cancelStore := context.WithTimeout(context.WithoutCancel(ctx), budget)
defer cancelStore()
var lastErr error
for attempt := 1; attempt <= settleAttempts; attempt++ {
var final inbound.MailPassResult
tryCtx, cancel := context.WithTimeout(storeCtx, sender.settings.StoreTimeout)
lastErr = sender.transactor.WithinTransaction(tryCtx, func(ctx context.Context, unit outbound.UnitOfWork) error {
var err error
final, err = sender.applyResult(ctx, unit, claim, result, sendErr)
return err
})
cancel()
switch {
case lastErr == nil:
sender.logFinished(storeCtx, final)
return final, nil
case errors.Is(lastErr, errLeaseLost):
sender.logger.InfoContext(storeCtx, "service mail was recorded by another worker first; this attempt is dropped",
slog.String("delivery_id", claim.delivery.ID().String()))
return resultOf(inbound.MailPassLeaseLost, claim.delivery), nil
}
if attempt < settleAttempts && !waitFor(storeCtx, settleRetryDelay) {
break
}
}
sender.logger.ErrorContext(storeCtx, "the result of a mail send could not be stored; the delivery stays under its lease and is claimed again after it expires, with the same idempotency key",
slog.String("delivery_id", claim.delivery.ID().String()),
slog.String("kind", string(claim.delivery.Kind())))
return inbound.MailPassResult{}, fmt.Errorf("%s - store result: %w", location, lastErr)
}
// checkedSendResult guards the stored state against a transport that breaks
// the MailSender contract: a nil error with no outcome may mean that the
// message left, so it counts as unknown, never as not sent.
func (sender *ServiceMailSender) checkedSendResult(ctx context.Context, delivery domain.Delivery, result outbound.SendResult, sendErr error) (outbound.SendResult, error) {
if sendErr != nil {
return outbound.SendResult{}, sendErr
}
switch result.Outcome {
case outbound.MailOutcomeAccepted, outbound.MailOutcomeRejected, outbound.MailOutcomeUnknown:
return result, nil
default:
sender.logger.ErrorContext(ctx, "the mail transport returned no outcome; the attempt is recorded as unknown",
slog.String("delivery_id", delivery.ID().String()))
return outbound.SendResult{Outcome: outbound.MailOutcomeUnknown}, nil
}
}
// applyResult runs in the settlement transaction: the quota settlement and
// the delivery's next state commit together.
func (sender *ServiceMailSender) applyResult(
ctx context.Context,
unit outbound.UnitOfWork,
claim claimedSend,
result outbound.SendResult,
sendErr error,
) (inbound.MailPassResult, error) {
delivery := claim.delivery
// The delivery row is locked before the quota rows, the order of the claim,
// and only while this worker still holds the lease.
held, err := unit.Deliveries().LockClaimed(ctx, delivery.ID(), sender.owner)
if err != nil {
return inbound.MailPassResult{}, fmt.Errorf("lock delivery: %w", err)
}
if !held {
return inbound.MailPassResult{}, errLeaseLost
}
until, err := sender.gate.SettleSend(ctx, unit, claim.permit, result, sendErr)
if err != nil {
return inbound.MailPassResult{}, fmt.Errorf("settle quota: %w", err)
}
now := sender.clock()
if sendErr != nil {
return sender.applyNotSent(ctx, unit, claim, now, sendErr)
}
at := latest(now, delivery.UpdatedAt())
manualRetry := claim.manualRetryPending || claim.manualRetryCycleStarted
next, attempt, err := delivery.RecordAttempt(sender.attemptInput(delivery, result, at, until, manualRetry))
if err != nil {
return inbound.MailPassResult{}, fmt.Errorf("record attempt: %w", err)
}
if err := unit.Deliveries().RecordClaimedAttempt(ctx, sender.owner, next, attempt); err != nil {
if errors.Is(err, outbound.ErrDeliveryVersionConflict) {
return inbound.MailPassResult{}, errLeaseLost
}
return inbound.MailPassResult{}, fmt.Errorf("store attempt: %w", err)
}
return resultOf(outcomeOfStatus(next.Status()), next), nil
}
// attemptInput maps a transport answer to the attempt the delivery records.
// until is the quota reset that SettleSend returned for a provider quota
// refusal.
func (sender *ServiceMailSender) attemptInput(delivery domain.Delivery, result outbound.SendResult, at, until time.Time, manualRetry bool) domain.DeliveryAttemptInput {
input := domain.DeliveryAttemptInput{
At: at,
Outcome: domain.DeliveryAttemptOutcome(result.Outcome),
Rejection: domain.DeliveryRejection(result.Rejection),
ProviderCode: string(result.ProviderCode),
ProviderMessageID: result.ProviderMessageID,
RetryAfter: result.RetryAfter,
}
switch {
case result.Outcome == outbound.MailOutcomeAccepted:
// An accepted attempt carries no code or wait hint.
input.ProviderCode = ""
input.RetryAfter = 0
case result.Outcome == outbound.MailOutcomeRejected && (result.Rejection == outbound.MailRejectionTemporary || result.Rejection == outbound.MailRejectionRateLimited):
input.NextAttemptAt = sender.settings.Retry.NextAttemptAt(at, delivery.AttemptCount()+1, result.RetryAfter)
case result.Outcome == outbound.MailOutcomeRejected && result.Rejection == outbound.MailRejectionQuotaExhausted && !until.IsZero():
// Zero means that the reset is unknown, and the delivery waits for an
// operator.
input.NextAttemptAt = latest(until, at)
case result.Outcome == outbound.MailOutcomeUnknown && !manualRetry && sender.gate.IdempotencyWindow() > 0:
input.NextAttemptAt = sender.settings.Retry.NextAttemptAt(at, delivery.AttemptCount()+1, result.RetryAfter)
}
return input
}
// applyNotSent handles a Send error: nothing left the process, and SettleSend
// gave the reservation back.
//
// - An invalid stored message ends the delivery (content_invalid).
// - No transport, or a context that ended (shutdown, an exhausted call
// budget) is nobody's fault: the lease ends and the delivery stays due.
// - Any other error is a fault on this delivery or in the transport that a
// plain retry may repeat forever, with the row at the head of the queue.
// It is counted as a failure of the row: the delivery is due later by the
// retry schedule, and after MaxFailures it is cancelled with
// processing_failed for an operator.
func (sender *ServiceMailSender) applyNotSent(
ctx context.Context,
unit outbound.UnitOfWork,
claim claimedSend,
now time.Time,
sendErr error,
) (inbound.MailPassResult, error) {
delivery := claim.delivery
switch {
case errors.Is(sendErr, outbound.ErrInvalidOutgoingMail):
cancelled, err := delivery.Cancel(latest(now, delivery.UpdatedAt()), domain.DeliveryCancelContentInvalid)
if err != nil {
return inbound.MailPassResult{}, fmt.Errorf("cancel delivery: %w", err)
}
if err := unit.Deliveries().Cancel(ctx, cancelled); err != nil {
return inbound.MailPassResult{}, fmt.Errorf("store cancelled delivery: %w", err)
}
return resultOf(inbound.MailPassCancelled, cancelled), nil
case errors.Is(sendErr, outbound.ErrMailChannelUnavailable), errors.Is(sendErr, context.Canceled), errors.Is(sendErr, context.DeadlineExceeded):
if _, err := unit.Deliveries().ReleaseClaim(ctx, delivery.ID(), sender.owner); err != nil {
return inbound.MailPassResult{}, fmt.Errorf("release claim: %w", err)
}
outcome := inbound.MailPassInterrupted
if errors.Is(sendErr, outbound.ErrMailChannelUnavailable) {
outcome = inbound.MailPassChannelUnavailable
}
return resultOf(outcome, delivery), nil
default:
// An error without an answer that is neither a cancellation nor the
// missing transport says nothing certain about this row, so it is not
// counted against it; the row only moves back by the retry schedule,
// so it does not stay at the head of the queue, and the worker backs
// off as for any pass that could not send.
at := latest(now, delivery.UpdatedAt())
if _, err := unit.Deliveries().RecordFailure(ctx, delivery.ID(), sender.owner, at,
sender.settings.Retry.NextAttemptAt(at, claim.failureCount+1, 0), sender.settings.MaxFailures, false); err != nil {
return inbound.MailPassResult{}, fmt.Errorf("record failure: %w", err)
}
sender.logger.ErrorContext(ctx, "the mail transport failed without an answer; the delivery is retried later",
slog.String("delivery_id", delivery.ID().String()))
return resultOf(inbound.MailPassInterrupted, delivery), nil
}
}
func (sender *ServiceMailSender) logFinished(ctx context.Context, result inbound.MailPassResult) {
attributes := []any{
slog.String("delivery_id", result.DeliveryID.String()),
slog.String("kind", string(result.Kind)),
slog.String("outcome", string(result.Outcome)),
}
switch result.Outcome {
case inbound.MailPassRejected, inbound.MailPassUnknown:
sender.logger.WarnContext(ctx, "service mail was not accepted by the provider", attributes...)
case inbound.MailPassCancelled:
sender.logger.InfoContext(ctx, "service mail was not sent because it is invalid", append(attributes, slog.String("reason", string(result.CancelReason)))...)
case inbound.MailPassIdle, inbound.MailPassAccepted, inbound.MailPassRetry, inbound.MailPassWaitingQuota,
inbound.MailPassChannelUnavailable, inbound.MailPassInterrupted, inbound.MailPassLeaseLost, inbound.MailPassRowFailed:
sender.logger.InfoContext(ctx, "service mail pass finished", attributes...)
}
}
func outcomeOfStatus(status domain.DeliveryStatus) inbound.MailPassOutcome {
switch status {
case domain.DeliveryStatusAccepted:
return inbound.MailPassAccepted
case domain.DeliveryStatusRejected:
return inbound.MailPassRejected
case domain.DeliveryStatusPending:
return inbound.MailPassRetry
case domain.DeliveryStatusWaitingQuota:
return inbound.MailPassWaitingQuota
case domain.DeliveryStatusCancelled:
return inbound.MailPassCancelled
case domain.DeliveryStatusUnknown:
return inbound.MailPassUnknown
default:
return inbound.MailPassUnknown
}
}
func resultOf(outcome inbound.MailPassOutcome, delivery domain.Delivery) inbound.MailPassResult {
return inbound.MailPassResult{
Outcome: outcome,
DeliveryID: delivery.ID(),
Kind: delivery.Kind(),
CancelReason: delivery.CancelReason(),
}
}
// waitFor sleeps for delay and reports false when ctx ends first.
func waitFor(ctx context.Context, delay time.Duration) bool {
timer := time.NewTimer(delay)
defer timer.Stop()
select {
case <-ctx.Done():
return false
case <-timer.C:
return true
}
return newDeliverySender(deliveryLane{
scope: outbound.ClaimScopeService,
kinds: domain.ServiceMailKinds(),
eligibility: serviceEligibility{},
}, transactor, sender, gate, settings, clock, logger)
}