feat(notification): add durable mail delivery state

This commit is contained in:
shira committed 2026-10-06 10:52:47 +03:00
1 parent 391c8a6cec
commit 2db585fbff
41 files changed
+4903 -108

No files matched your search

@@ -0,0 +1,345 @@
package postgres
import (
"context"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// deliveryConstraintErrors maps the delivery constraints and triggers whose
// violation is a caller-visible outcome to port sentinels, by SQLSTATE and
// constraint name, never by text.
var deliveryConstraintErrors = map[constraintViolation]error{
{foreignKeyViolationCode, "deliveries_recipient_user_id_fkey"}: outbound.ErrUserNotFound,
{foreignKeyViolationCode, "delivery_attempts_delivery_id_fkey"}: outbound.ErrDeliveryNotFound,
{integrityConstraintViolationCode, "deliveries_content_immutable"}: outbound.ErrDeliveryContentImmutable,
{integrityConstraintViolationCode, "delivery_attempts_immutable"}: outbound.ErrDeliveryContentImmutable,
{integrityConstraintViolationCode, "deliveries_provider_pinned"}: outbound.ErrDeliveryProviderPinned,
{foreignKeyViolationCode, "mail_requests_recipient_user_id_fkey"}: outbound.ErrUserNotFound,
// A backstop: the version check already stops a second writer of the
// same attempt number.
{uniqueViolationCode, "delivery_attempts_pkey"}: outbound.ErrDeliveryVersionConflict,
}
// mapDeliveryError turns a known delivery or mail request constraint
// violation into its sentinel and replaces any other PostgreSQL error with
// its SQLSTATE and constraint name, because the message and detail can quote
// the recipient address, request text, or a body that holds a token. Deadlocks and serialization failures
// also match ErrTransactionConflict.
func mapDeliveryError(err error) error {
var pgError *pgconn.PgError
if !errors.As(err, &pgError) {
return sanitizeConnectError(err)
}
if sentinel, ok := deliveryConstraintErrors[constraintViolation{code: pgError.Code, constraint: pgError.ConstraintName}]; ok {
return fmt.Errorf("postgres.mapDeliveryError - violate constraint %s: %w", pgError.ConstraintName, sentinel)
}
return markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName})
}
// DeliveryStore provides the delivery repository outside a transaction. Every
// call runs as its own statement on a pool connection; RecordAttempt is one
// statement, so it stays atomic. Called with a context that belongs to a
// Transactor callback, it fails with outbound.ErrNestedTransaction; use
// UnitOfWork.Deliveries there.
type DeliveryStore struct {
queries *sqlc.Queries
}
func NewDeliveryStore(pool *pgxpool.Pool) *DeliveryStore {
return &DeliveryStore{queries: sqlc.New(standaloneDB{pool: pool})}
}
func (store *DeliveryStore) Deliveries() outbound.DeliveryRepository {
return deliveryRepository{queries: store.queries}
}
func (unit *UnitOfWork) Deliveries() outbound.DeliveryRepository {
return deliveryRepository{queries: unit.queries}
}
// MailRequests is available only inside a transaction: a request is written
// with the outbox event that announces it and consumed under a row lock.
func (unit *UnitOfWork) MailRequests() outbound.MailRequestRepository {
return mailRequestRepository{queries: unit.queries}
}
type deliveryRepository struct {
queries *sqlc.Queries
}
var _ outbound.DeliveryRepository = deliveryRepository{}
func (repository deliveryRepository) Create(ctx context.Context, delivery domain.Delivery) (bool, error) {
if delivery.IsZero() || delivery.Content().IsZero() {
return false, fmt.Errorf("deliveryRepository.Create - delivery was not built by domain.NewDelivery: %w", domain.ErrInvalidDelivery)
}
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()),
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))
}
return inserted == 1, nil
}
func (repository deliveryRepository) Get(ctx context.Context, id uuid.UUID) (domain.Delivery, error) {
row, err := repository.queries.GetDeliveryByID(ctx, pgUUID(id))
if errors.Is(err, pgx.ErrNoRows) {
return domain.Delivery{}, fmt.Errorf("deliveryRepository.Get - select delivery: %w", outbound.ErrDeliveryNotFound)
}
if err != nil {
return domain.Delivery{}, fmt.Errorf("deliveryRepository.Get - select delivery: %w", mapDeliveryError(err))
}
return deliveryFromRow(row)
}
func (repository deliveryRepository) ListAttempts(ctx context.Context, id uuid.UUID) ([]domain.DeliveryAttempt, error) {
rows, err := repository.queries.ListDeliveryAttempts(ctx, pgUUID(id))
if err != nil {
return nil, fmt.Errorf("deliveryRepository.ListAttempts - select attempts: %w", mapDeliveryError(err))
}
attempts := make([]domain.DeliveryAttempt, 0, len(rows))
for _, row := range rows {
attempt, err := domain.RestoreDeliveryAttempt(domain.DeliveryAttempt{
DeliveryID: uuid.UUID(row.DeliveryID.Bytes),
Number: row.AttemptNumber,
At: row.AttemptedAt.Time,
Outcome: domain.DeliveryAttemptOutcome(row.Outcome),
Rejection: domain.DeliveryRejection(row.Rejection.String),
ProviderCode: row.ProviderCode.String,
ProviderMessageID: row.ProviderMessageID.String,
RetryAfter: time.Duration(row.RetryAfterNs),
StatusAfter: domain.DeliveryStatus(row.StatusAfter),
NextAttemptAt: zeroableTime(row.NextAttemptAt),
})
if err != nil {
return nil, fmt.Errorf("deliveryRepository.ListAttempts - decode attempt %d: %w", row.AttemptNumber, err)
}
attempts = append(attempts, attempt)
}
return attempts, nil
}
func (repository deliveryRepository) RecordAttempt(ctx context.Context, next domain.Delivery, attempt domain.DeliveryAttempt) error {
const location = "deliveryRepository.RecordAttempt"
if next.IsZero() || attempt.DeliveryID != next.ID() || attempt.Number != next.AttemptCount() || next.Version() <= 1 {
return fmt.Errorf("%s - state and attempt were not built by domain.Delivery.RecordAttempt: %w", location, domain.ErrInvalidDelivery)
}
recorded, err := repository.queries.RecordDeliveryAttempt(ctx, sqlc.RecordDeliveryAttemptParams{
AttemptNumber: attempt.Number,
AttemptedAt: pgTime(attempt.At),
Outcome: string(attempt.Outcome),
Rejection: pgOptionalText(string(attempt.Rejection)),
ProviderCode: pgOptionalText(attempt.ProviderCode),
ProviderMessageID: pgOptionalText(attempt.ProviderMessageID),
RetryAfterNs: int64(attempt.RetryAfter),
Status: string(next.Status()),
NextAttemptAt: pgZeroableTime(next.NextAttemptAt()),
UpdatedAt: pgTime(next.UpdatedAt()),
DeliveryID: pgUUID(next.ID()),
ExpectedVersion: next.Version() - 1,
})
if err != nil {
return fmt.Errorf("%s - update delivery and insert attempt: %w", location, mapDeliveryError(err))
}
if recorded == 0 {
return fmt.Errorf("%s - expected version %d: %w", location, next.Version()-1, outbound.ErrDeliveryVersionConflict)
}
return nil
}
func (repository deliveryRepository) WaitForQuota(ctx context.Context, next domain.Delivery) error {
if next.Status() != domain.DeliveryStatusWaitingQuota {
return fmt.Errorf("deliveryRepository.WaitForQuota - state was not built by domain.Delivery.WaitForQuota: %w", domain.ErrInvalidDelivery)
}
return repository.updateState(ctx, "deliveryRepository.WaitForQuota", next)
}
func (repository deliveryRepository) Rebind(ctx context.Context, next domain.Delivery) error {
if next.AttemptCount() != 0 {
return fmt.Errorf("deliveryRepository.Rebind - state was not built by domain.Delivery.Rebind: %w", domain.ErrInvalidDelivery)
}
return repository.updateState(ctx, "deliveryRepository.Rebind", next)
}
// updateState stores a state change without an attempt over the version
// before it.
func (repository deliveryRepository) updateState(ctx context.Context, location string, next domain.Delivery) error {
if next.IsZero() || next.Version() <= 1 {
return fmt.Errorf("%s - state was not built by a domain.Delivery transition: %w", location, domain.ErrInvalidDelivery)
}
updated, err := repository.queries.UpdateDeliveryState(ctx, sqlc.UpdateDeliveryStateParams{
Status: string(next.Status()),
NextAttemptAt: pgZeroableTime(next.NextAttemptAt()),
Provider: next.ProviderAccount().Provider(),
ProviderAccount: next.ProviderAccount().Account(),
UpdatedAt: pgTime(next.UpdatedAt()),
ID: pgUUID(next.ID()),
ExpectedVersion: next.Version() - 1,
})
if err != nil {
return fmt.Errorf("%s - update delivery: %w", location, mapDeliveryError(err))
}
if updated == 0 {
return fmt.Errorf("%s - expected version %d: %w", location, next.Version()-1, outbound.ErrDeliveryVersionConflict)
}
return nil
}
func deliveryFromRow(row sqlc.Delivery) (domain.Delivery, error) {
kind, err := domain.ParseMailKind(row.Kind)
if err != nil {
return domain.Delivery{}, fmt.Errorf("postgres.deliveryFromRow - decode kind: %w", err)
}
content, err := domain.RestoreMailContent(kind, row.TemplateVersion, row.Subject, row.TextBody, row.HtmlBody, row.ContentSha256)
if err != nil {
return domain.Delivery{}, fmt.Errorf("postgres.deliveryFromRow - decode content: %w", err)
}
providerAccount, err := domain.NewMailProviderAccount(row.Provider, row.ProviderAccount)
if err != nil {
return domain.Delivery{}, fmt.Errorf("postgres.deliveryFromRow - decode provider account: %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,
ProviderAccount: providerAccount,
IdempotencyKey: row.IdempotencyKey,
Status: domain.DeliveryStatus(row.Status),
AttemptCount: row.AttemptCount,
NextAttemptAt: zeroableTime(row.NextAttemptAt),
LastAttemptAt: zeroableTime(row.LastAttemptAt),
ProviderMessageID: row.ProviderMessageID.String,
Version: row.Version,
CreatedAt: row.CreatedAt.Time,
UpdatedAt: row.UpdatedAt.Time,
})
if err != nil {
return domain.Delivery{}, fmt.Errorf("postgres.deliveryFromRow - decode delivery: %w", err)
}
return delivery, nil
}
// pgZeroableTime stores the zero time, which the domain uses for "not set",
// as NULL.
func pgZeroableTime(value time.Time) pgtype.Timestamptz {
if value.IsZero() {
return pgtype.Timestamptz{}
}
return pgTime(value)
}
func zeroableTime(value pgtype.Timestamptz) time.Time {
if !value.Valid {
return time.Time{}
}
return value.Time
}
func pgOptionalText(value string) pgtype.Text {
return pgtype.Text{String: value, Valid: value != ""}
}
func pgOptionalUUID(id uuid.UUID) pgtype.UUID {
return pgtype.UUID{Bytes: id, Valid: id != uuid.Nil}
}
func optionalUUID(value pgtype.UUID) uuid.UUID {
if !value.Valid {
return uuid.Nil
}
return uuid.UUID(value.Bytes)
}
type mailRequestRepository struct {
queries *sqlc.Queries
}
var _ outbound.MailRequestRepository = mailRequestRepository{}
func (repository mailRequestRepository) Create(ctx context.Context, request domain.MailRequest) error {
if _, err := domain.NewMailRequest(request); err != nil {
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),
})
if err != nil {
return fmt.Errorf("mailRequestRepository.Create - insert mail request: %w", mapDeliveryError(err))
}
return nil
}
func (repository mailRequestRepository) Lock(ctx context.Context, id uuid.UUID) (domain.MailRequest, error) {
row, err := repository.queries.LockMailRequest(ctx, pgUUID(id))
if errors.Is(err, pgx.ErrNoRows) {
return domain.MailRequest{}, fmt.Errorf("mailRequestRepository.Lock - select mail request: %w", outbound.ErrMailRequestNotFound)
}
if err != nil {
return domain.MailRequest{}, fmt.Errorf("mailRequestRepository.Lock - select mail request: %w", mapDeliveryError(err))
}
kind, err := domain.ParseMailKind(row.Kind)
if err != nil {
return domain.MailRequest{}, fmt.Errorf("mailRequestRepository.Lock - decode kind: %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},
CreatedAt: row.CreatedAt.Time,
})
if err != nil {
return domain.MailRequest{}, fmt.Errorf("mailRequestRepository.Lock - decode mail request: %w", err)
}
return request, nil
}
func (repository mailRequestRepository) Delete(ctx context.Context, id uuid.UUID) error {
if _, err := repository.queries.DeleteMailRequest(ctx, pgUUID(id)); err != nil {
return fmt.Errorf("mailRequestRepository.Delete - delete mail request: %w", mapDeliveryError(err))
}
return nil
}
@@ -0,0 +1,63 @@
package postgres
import (
"errors"
"strings"
"testing"
"github.com/jackc/pgx/v5/pgconn"
"lincodex/backend/internal/port/outbound"
)
const privateRowValue = "Private.Recipient@Example.com"
func TestMapDeliveryErrorRecognizesDeliveryConstraints(t *testing.T) {
tests := []struct {
code, constraint string
want error
}{
{integrityConstraintViolationCode, "deliveries_content_immutable", outbound.ErrDeliveryContentImmutable},
{integrityConstraintViolationCode, "delivery_attempts_immutable", outbound.ErrDeliveryContentImmutable},
{integrityConstraintViolationCode, "deliveries_provider_pinned", outbound.ErrDeliveryProviderPinned},
{foreignKeyViolationCode, "deliveries_recipient_user_id_fkey", outbound.ErrUserNotFound},
{foreignKeyViolationCode, "mail_requests_recipient_user_id_fkey", outbound.ErrUserNotFound},
{foreignKeyViolationCode, "delivery_attempts_delivery_id_fkey", outbound.ErrDeliveryNotFound},
{uniqueViolationCode, "delivery_attempts_pkey", outbound.ErrDeliveryVersionConflict},
}
for _, test := range tests {
t.Run(test.constraint, func(t *testing.T) {
err := mapDeliveryError(&pgconn.PgError{
Code: test.code,
ConstraintName: test.constraint,
Message: "row " + privateRowValue,
Detail: "Key (recipient_email)=(" + privateRowValue + ")",
})
if !errors.Is(err, test.want) {
t.Fatalf("mapDeliveryError() = %v, want %v", err, test.want)
}
if strings.Contains(err.Error(), privateRowValue) {
t.Fatalf("mapped error quotes a row value: %v", err)
}
})
}
}
func TestMapDeliveryErrorDropsTheTextOfOtherPostgreSQLErrors(t *testing.T) {
err := mapDeliveryError(&pgconn.PgError{
Code: checkViolationCode,
ConstraintName: "deliveries_subject_length",
Message: "new row violates check constraint with " + privateRowValue,
Detail: "Failing row contains (" + privateRowValue + ")",
})
var state sqlStateError
if !errors.As(err, &state) || state.SQLState() != checkViolationCode {
t.Fatalf("mapDeliveryError() = %v, want SQLSTATE %s", err, checkViolationCode)
}
if strings.Contains(err.Error(), privateRowValue) || strings.Contains(err.Error(), "violates") {
t.Fatalf("mapped error keeps the PostgreSQL text: %v", err)
}
if !strings.Contains(err.Error(), "deliveries_subject_length") {
t.Fatalf("mapped error lost the constraint name: %v", err)
}
}
@@ -0,0 +1,446 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: delivery.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const deleteMailRequest = `-- name: DeleteMailRequest :execrows
DELETE FROM mail_requests
WHERE id = $1
`
func (q *Queries) DeleteMailRequest(ctx context.Context, id pgtype.UUID) (int64, error) {
result, err := q.db.Exec(ctx, deleteMailRequest, id)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const getDeliveryByID = `-- name: GetDeliveryByID :one
SELECT
id,
source_event_id,
recipient_user_id,
recipient_email,
kind,
template_version,
subject,
text_body,
html_body,
content_sha256,
provider,
provider_account,
idempotency_key,
status,
attempt_count,
next_attempt_at,
last_attempt_at,
provider_message_id,
version,
created_at,
updated_at
FROM deliveries
WHERE id = $1
`
func (q *Queries) GetDeliveryByID(ctx context.Context, id pgtype.UUID) (Delivery, error) {
row := q.db.QueryRow(ctx, getDeliveryByID, id)
var i Delivery
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.Version,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const insertDelivery = `-- name: InsertDelivery :execrows
INSERT INTO deliveries (
id,
source_event_id,
recipient_user_id,
recipient_email,
kind,
template_version,
subject,
text_body,
html_body,
content_sha256,
provider,
provider_account,
idempotency_key,
status,
attempt_count,
next_attempt_at,
last_attempt_at,
provider_message_id,
version,
created_at,
updated_at
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7,
$8,
$9,
$10,
$11,
$12,
$13,
$14,
$15,
$16,
$17,
$18,
$19,
$20,
$21
)
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
Version int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
// Stores a new delivery. A delivery with the same ID already exists when the
// same request is handled again; the statement then inserts nothing and
// returns 0 rows, and the stored content stays as it was. While another
// transaction holds an uncommitted row with the same ID, the insert waits
// for it.
func (q *Queries) InsertDelivery(ctx context.Context, arg InsertDeliveryParams) (int64, error) {
result, err := q.db.Exec(ctx, insertDelivery,
arg.ID,
arg.SourceEventID,
arg.RecipientUserID,
arg.RecipientEmail,
arg.Kind,
arg.TemplateVersion,
arg.Subject,
arg.TextBody,
arg.HtmlBody,
arg.ContentSha256,
arg.Provider,
arg.ProviderAccount,
arg.IdempotencyKey,
arg.Status,
arg.AttemptCount,
arg.NextAttemptAt,
arg.LastAttemptAt,
arg.ProviderMessageID,
arg.Version,
arg.CreatedAt,
arg.UpdatedAt,
)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const insertMailRequest = `-- name: InsertMailRequest :exec
INSERT INTO mail_requests (
id,
recipient_user_id,
kind,
subject,
body,
link_path,
created_at
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7
)
`
type InsertMailRequestParams struct {
ID pgtype.UUID
RecipientUserID pgtype.UUID
Kind string
Subject string
Body string
LinkPath string
CreatedAt pgtype.Timestamptz
}
func (q *Queries) InsertMailRequest(ctx context.Context, arg InsertMailRequestParams) error {
_, err := q.db.Exec(ctx, insertMailRequest,
arg.ID,
arg.RecipientUserID,
arg.Kind,
arg.Subject,
arg.Body,
arg.LinkPath,
arg.CreatedAt,
)
return err
}
const listDeliveryAttempts = `-- name: ListDeliveryAttempts :many
SELECT
delivery_id,
attempt_number,
attempted_at,
outcome,
rejection,
provider_code,
provider_message_id,
retry_after_ns,
status_after,
next_attempt_at
FROM delivery_attempts
WHERE delivery_id = $1
ORDER BY attempt_number
`
func (q *Queries) ListDeliveryAttempts(ctx context.Context, deliveryID pgtype.UUID) ([]DeliveryAttempt, error) {
rows, err := q.db.Query(ctx, listDeliveryAttempts, deliveryID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []DeliveryAttempt
for rows.Next() {
var i DeliveryAttempt
if err := rows.Scan(
&i.DeliveryID,
&i.AttemptNumber,
&i.AttemptedAt,
&i.Outcome,
&i.Rejection,
&i.ProviderCode,
&i.ProviderMessageID,
&i.RetryAfterNs,
&i.StatusAfter,
&i.NextAttemptAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const lockMailRequest = `-- name: LockMailRequest :one
SELECT
id,
recipient_user_id,
kind,
subject,
body,
link_path,
created_at
FROM mail_requests
WHERE id = $1
FOR UPDATE
`
// 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) {
row := q.db.QueryRow(ctx, lockMailRequest, id)
var i MailRequest
err := row.Scan(
&i.ID,
&i.RecipientUserID,
&i.Kind,
&i.Subject,
&i.Body,
&i.LinkPath,
&i.CreatedAt,
)
return i, err
}
const recordDeliveryAttempt = `-- name: RecordDeliveryAttempt :execrows
WITH advanced AS (
UPDATE deliveries
SET
status = $8,
attempt_count = $1,
next_attempt_at = $9,
last_attempt_at = $2,
provider_message_id = coalesce(
$6, deliveries.provider_message_id
),
version = deliveries.version + 1,
updated_at = $10
WHERE
deliveries.id = $11
AND deliveries.version = $12
RETURNING deliveries.id
)
INSERT INTO delivery_attempts (
delivery_id,
attempt_number,
attempted_at,
outcome,
rejection,
provider_code,
provider_message_id,
retry_after_ns,
status_after,
next_attempt_at
)
SELECT
advanced.id,
$1,
$2,
$3,
$4,
$5,
$6,
$7,
$8,
$9
FROM advanced
`
type RecordDeliveryAttemptParams struct {
AttemptNumber int32
AttemptedAt pgtype.Timestamptz
Outcome string
Rejection pgtype.Text
ProviderCode pgtype.Text
ProviderMessageID pgtype.Text
RetryAfterNs int64
Status string
NextAttemptAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
DeliveryID pgtype.UUID
ExpectedVersion int64
}
// Advances a delivery past one attempt and appends the attempt in one
// statement, so both happen or neither does, inside or outside a
// transaction. The update applies only while the stored version still
// equals expected_version; otherwise nothing is written and the statement
// returns 0 rows. Two workers that record the same attempt number therefore
// cannot both succeed. Content columns are not touched; a trigger refuses
// any change to them.
func (q *Queries) RecordDeliveryAttempt(ctx context.Context, arg RecordDeliveryAttemptParams) (int64, error) {
result, err := q.db.Exec(ctx, recordDeliveryAttempt,
arg.AttemptNumber,
arg.AttemptedAt,
arg.Outcome,
arg.Rejection,
arg.ProviderCode,
arg.ProviderMessageID,
arg.RetryAfterNs,
arg.Status,
arg.NextAttemptAt,
arg.UpdatedAt,
arg.DeliveryID,
arg.ExpectedVersion,
)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const updateDeliveryState = `-- name: UpdateDeliveryState :execrows
UPDATE deliveries
SET
status = $1,
next_attempt_at = $2,
provider = $3,
provider_account = $4,
version = deliveries.version + 1,
updated_at = $5
WHERE
deliveries.id = $6
AND deliveries.version = $7
`
type UpdateDeliveryStateParams struct {
Status string
NextAttemptAt pgtype.Timestamptz
Provider string
ProviderAccount string
UpdatedAt pgtype.Timestamptz
ID pgtype.UUID
ExpectedVersion int64
}
// Stores a change of the delivery state that is not an attempt: a quota wait
// or a new provider account before the first attempt. It applies only while
// the stored version still equals expected_version and returns 0 rows
// otherwise. The trigger refuses a provider change after an attempt.
func (q *Queries) UpdateDeliveryState(ctx context.Context, arg UpdateDeliveryStateParams) (int64, error) {
result, err := q.db.Exec(ctx, updateDeliveryState,
arg.Status,
arg.NextAttemptAt,
arg.Provider,
arg.ProviderAccount,
arg.UpdatedAt,
arg.ID,
arg.ExpectedVersion,
)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
@@ -93,6 +93,20 @@ locked_session AS (
FOR UPDATE SKIP LOCKED
),
locked_mail_request AS (
SELECT request.recipient_user_id
FROM mail_requests AS request
WHERE request.recipient_user_id IN (SELECT candidate.id FROM candidate)
FOR UPDATE SKIP LOCKED
),
locked_delivery AS (
SELECT delivery.recipient_user_id
FROM deliveries AS delivery
WHERE delivery.recipient_user_id IN (SELECT candidate.id FROM candidate)
FOR UPDATE SKIP LOCKED
),
deletable AS (
SELECT candidate.id
FROM candidate
@@ -111,6 +125,20 @@ deletable AS (
SELECT count(*) FROM locked_session
WHERE locked_session.user_id = candidate.id
)
AND (
SELECT count(*) FROM mail_requests AS request
WHERE request.recipient_user_id = candidate.id
) = (
SELECT count(*) FROM locked_mail_request
WHERE locked_mail_request.recipient_user_id = candidate.id
)
AND (
SELECT count(*) FROM deliveries AS delivery
WHERE delivery.recipient_user_id = candidate.id
) = (
SELECT count(*) FROM locked_delivery
WHERE locked_delivery.recipient_user_id = candidate.id
)
)
DELETE FROM users
@@ -124,15 +152,18 @@ type DeleteUnverifiedUsersRegisteredBeforeParams struct {
}
// Deletes one batch of accounts that stayed unverified since before cutoff,
// oldest first, with their tokens and sessions. Every lock is taken with SKIP
// LOCKED, so the statement never waits: an account whose row is locked, for
// example by a re-registration or a token insert, is skipped, and so is an
// account with any token or session row locked, for example by a
// confirmation that consumed a token. Skipped accounts stay for the next run.
// oldest first, with their tokens, sessions, mail requests, and mail
// deliveries (and through the deliveries their attempts). Every lock is taken
// with SKIP LOCKED, so the statement never waits: an account whose row is
// locked, for example by a re-registration, a token insert, or a delivery
// insert, is skipped, and so is an account with any token, session, mail
// request, or delivery row locked, for example by a confirmation that
// consumed a token, the delivery consumer, or a worker recording an attempt.
// Skipped accounts stay for the next run.
// Taking the account lock before the token locks is the reverse of the
// documented order, which is safe only because no lock here waits.
// An account qualifies only when every token and session row visible to the
// statement was locked above.
// An account qualifies only when every token, session, mail request, and
// delivery row visible to the statement was locked above.
func (q *Queries) DeleteUnverifiedUsersRegisteredBefore(ctx context.Context, arg DeleteUnverifiedUsersRegisteredBeforeParams) (int64, error) {
result, err := q.db.Exec(ctx, deleteUnverifiedUsersRegisteredBefore, arg.Cutoff, arg.BatchLimit)
if err != nil {
@@ -30,6 +30,43 @@ type ConsumerProcessedEvent struct {
ProcessedAt pgtype.Timestamptz
}
type Delivery 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
}
type DeliveryAttempt struct {
DeliveryID pgtype.UUID
AttemptNumber int32
AttemptedAt pgtype.Timestamptz
Outcome string
Rejection pgtype.Text
ProviderCode pgtype.Text
ProviderMessageID pgtype.Text
RetryAfterNs int64
StatusAfter string
NextAttemptAt pgtype.Timestamptz
}
type EmailToken struct {
ID pgtype.UUID
UserID pgtype.UUID
@@ -42,6 +79,16 @@ type EmailToken struct {
InvalidatedAt pgtype.Timestamptz
}
type MailRequest struct {
ID pgtype.UUID
RecipientUserID pgtype.UUID
Kind string
Subject string
Body string
LinkPath string
CreatedAt pgtype.Timestamptz
}
type OutboxEvent struct {
Position pgtype.Int8
EventID pgtype.UUID
@@ -21,18 +21,23 @@ type Querier interface {
// returned registration version in the same transaction, rolled back when it
// matches no row.
ConsumeEmailToken(ctx context.Context, arg ConsumeEmailTokenParams) (EmailToken, error)
DeleteMailRequest(ctx context.Context, id pgtype.UUID) (int64, error)
// Deletes one batch of accounts that stayed unverified since before cutoff,
// oldest first, with their tokens and sessions. Every lock is taken with SKIP
// LOCKED, so the statement never waits: an account whose row is locked, for
// example by a re-registration or a token insert, is skipped, and so is an
// account with any token or session row locked, for example by a
// confirmation that consumed a token. Skipped accounts stay for the next run.
// oldest first, with their tokens, sessions, mail requests, and mail
// deliveries (and through the deliveries their attempts). Every lock is taken
// with SKIP LOCKED, so the statement never waits: an account whose row is
// locked, for example by a re-registration, a token insert, or a delivery
// insert, is skipped, and so is an account with any token, session, mail
// request, or delivery row locked, for example by a confirmation that
// consumed a token, the delivery consumer, or a worker recording an attempt.
// Skipped accounts stay for the next run.
// Taking the account lock before the token locks is the reverse of the
// documented order, which is safe only because no lock here waits.
// An account qualifies only when every token and session row visible to the
// statement was locked above.
// An account qualifies only when every token, session, mail request, and
// delivery row visible to the statement was locked above.
DeleteUnverifiedUsersRegisteredBefore(ctx context.Context, arg DeleteUnverifiedUsersRegisteredBeforeParams) (int64, error)
GetActiveSessionByTokenHash(ctx context.Context, arg GetActiveSessionByTokenHashParams) (Session, error)
GetDeliveryByID(ctx context.Context, id pgtype.UUID) (Delivery, error)
// Among the versions of a family already effective at a time, the newest
// publication wins. A version scheduled for later therefore never undoes a
// version published after it. The unique (policy_key, version) index serves
@@ -54,7 +59,14 @@ type Querier interface {
// after a rewind the handler may fail differently. A different value at a
// reused position, after the topic was recreated, gets its own row.
InsertConsumerDeadLetter(ctx context.Context, arg InsertConsumerDeadLetterParams) error
// Stores a new delivery. A delivery with the same ID already exists when the
// same request is handled again; the statement then inserts nothing and
// returns 0 rows, and the stored content stays as it was. While another
// transaction holds an uncommitted row with the same ID, the insert waits
// for it.
InsertDelivery(ctx context.Context, arg InsertDeliveryParams) (int64, error)
InsertEmailToken(ctx context.Context, arg InsertEmailTokenParams) error
InsertMailRequest(ctx context.Context, arg InsertMailRequestParams) error
InsertOutboxEvent(ctx context.Context, arg InsertOutboxEventParams) error
// Stores a version and returns the stored row with the publication time and
// effective time set by the stamp trigger. A taken ID or version number
@@ -71,6 +83,13 @@ type Querier interface {
InsertSession(ctx context.Context, arg InsertSessionParams) error
InsertUser(ctx context.Context, arg InsertUserParams) error
InvalidateActiveEmailTokens(ctx context.Context, arg InvalidateActiveEmailTokensParams) (int64, error)
ListDeliveryAttempts(ctx context.Context, deliveryID pgtype.UUID) ([]DeliveryAttempt, error)
// 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.
LockMailRequest(ctx context.Context, id pgtype.UUID) (MailRequest, 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
@@ -91,6 +110,14 @@ type Querier interface {
// Reports whether a family has any version without reading a document, so a
// caller that only needs presence never depends on decoding.
PolicyVersionExists(ctx context.Context, policyKey string) (bool, error)
// Advances a delivery past one attempt and appends the attempt in one
// statement, so both happen or neither does, inside or outside a
// transaction. The update applies only while the stored version still
// equals expected_version; otherwise nothing is written and the statement
// returns 0 rows. Two workers that record the same attempt number therefore
// cannot both succeed. Content columns are not touched; a trigger refuses
// any change to them.
RecordDeliveryAttempt(ctx context.Context, arg RecordDeliveryAttemptParams) (int64, error)
RevokeSession(ctx context.Context, arg RevokeSessionParams) (int64, error)
RevokeUserSessions(ctx context.Context, arg RevokeUserSessionsParams) (int64, error)
// Bounds a consumer transaction on the server, local to the transaction.
@@ -112,6 +139,11 @@ type Querier interface {
// revoked, expired, or idle session is not revived; the update re-checks
// those conditions against a concurrent change.
TouchSession(ctx context.Context, arg TouchSessionParams) (TouchSessionRow, error)
// Stores a change of the delivery state that is not an attempt: a quota wait
// or a new provider account before the first attempt. It applies only while
// the stored version still equals expected_version and returns 0 rows
// otherwise. The trigger refuses a provider change after an attempt.
UpdateDeliveryState(ctx context.Context, arg UpdateDeliveryStateParams) (int64, error)
// Replaces the registration of an unverified account and advances the
// registration version in the same statement, so no caller can choose it.
// The version check rejects a writer that read an older row; a verified
+30 -6
View File
@@ -6,12 +6,16 @@ import (
"log/slog"
"math"
"sync"
"time"
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/kafka"
"lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/usecase/notification"
"lincodex/backend/internal/usecase/notification/mailtemplate"
"lincodex/backend/internal/worker/eventconsumer"
"lincodex/backend/internal/worker/retry"
)
@@ -24,11 +28,27 @@ type eventConsumers []*eventconsumer.Consumer
var _ eventconsumer.Metrics = (*prometheus.Metrics)(nil)
// eventHandlers lists the handlers that get a consumer. It is empty because
// no product module consumes domain events yet; a module adds its handler
// here, and its consumer then starts with the next deployment.
func eventHandlers() []inbound.EventHandler {
return nil
// eventHandlers lists the handlers that get a consumer. A product module
// adds its handler here, and its consumer then starts with the next
// deployment.
func eventHandlers(settings config.Config, logger *slog.Logger) ([]inbound.EventHandler, error) {
renderer, err := mailtemplate.NewRenderer(settings.AppPublicURL)
if err != nil {
return nil, fmt.Errorf("bootstrap.eventHandlers - create mail renderer: %w", err)
}
// New deliveries are pinned to the transport and account configured now;
// a later configuration change applies to new deliveries only.
providerAccount, err := domain.NewMailProviderAccount(string(settings.EmailProvider), settings.EmailAccount)
if err != nil {
return nil, fmt.Errorf("bootstrap.eventHandlers - mail provider account: %w", err)
}
deliveries := notification.NewDeliveryHandler(
notification.NewTemplateRenderer(renderer),
providerAccount,
time.Now,
logger.With(slog.String("component", "notification_delivery")),
)
return []inbound.EventHandler{deliveries}, nil
}
func newEventConsumers(
@@ -37,7 +57,11 @@ func newEventConsumers(
logger *slog.Logger,
metrics *prometheus.Metrics,
) (eventConsumers, func(), error) {
return buildEventConsumers(ctx, settings, logger, metrics, eventHandlers())
handlers, err := eventHandlers(settings, logger)
if err != nil {
return nil, nil, err
}
return buildEventConsumers(ctx, settings, logger, metrics, handlers)
}
// buildEventConsumers builds one consumer per handler and the resources they
+19 -3
View File
@@ -16,6 +16,7 @@ import (
"lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/notification"
"lincodex/backend/internal/worker/eventconsumer"
)
@@ -75,9 +76,24 @@ func TestBuildEventConsumersSkipsWithoutWork(t *testing.T) {
}
}
func TestBootstrapRegistersNoEventHandlerYet(t *testing.T) {
if handlers := eventHandlers(); len(handlers) != 0 {
t.Fatalf("eventHandlers() = %d handlers; update the documentation when the first consumer is registered", len(handlers))
func TestBootstrapRegistersTheDeliveryHandler(t *testing.T) {
handlers, err := eventHandlers(consumerTestConfig(t), slog.New(slog.DiscardHandler))
if err != nil {
t.Fatalf("eventHandlers() error = %v", err)
}
if len(handlers) != 1 || handlers[0].ConsumerName() != notification.DeliveryConsumerName {
t.Fatalf("eventHandlers() = %v; update the documentation when the registered consumers change", handlers)
}
if !handlers[0].Handles(notification.MailRequestedEventType) {
t.Fatalf("the delivery handler does not handle %s", notification.MailRequestedEventType)
}
}
func TestBootstrapRefusesAnInvalidMailAccountForDeliveries(t *testing.T) {
settings := consumerTestConfig(t)
settings.EmailAccount = "Not A Label"
if _, err := eventHandlers(settings, slog.New(slog.DiscardHandler)); err == nil {
t.Fatal("eventHandlers() accepted an invalid provider account label")
}
}
+600
View File
@@ -0,0 +1,600 @@
package domain
import (
"errors"
"fmt"
"log/slog"
"math"
"regexp"
"time"
"github.com/google/uuid"
)
// deliveryIdempotencyKeyPrefix and the delivery ID form the key sent to the
// provider: stable for every attempt of one delivery, unique per delivery,
// and free of personal data.
const deliveryIdempotencyKeyPrefix = "delivery/"
var (
// ErrInvalidDelivery reports a delivery, a stored delivery row, or an
// attempt result that breaks a delivery rule. Errors name the rule, never
// the recipient or the content.
ErrInvalidDelivery = errors.New("invalid delivery")
// ErrDeliveryTransition reports a change that the delivery's state does
// not allow: an attempt on an accepted or rejected delivery, a quota wait
// outside pending or waiting_quota, or a new provider account after the
// first attempt.
ErrDeliveryTransition = errors.New("delivery status does not allow the transition")
// Provider names follow config.EmailProvider values; the account is an
// operator label for the provider account, never a credential.
mailProviderPattern = regexp.MustCompile(`^[a-z][a-z0-9_]{0,31}$`)
mailProviderAccountPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]{0,63}$`)
// A provider code is a documented snake_case error name; see
// outbound.MailProviderCode.
mailProviderCodePattern = regexp.MustCompile(`^[a-z][a-z0-9_]{0,63}$`)
// A provider message ID is printable ASCII without spaces, at most 128
// characters, as the Resend transport accepts it.
providerMessageIDPattern = regexp.MustCompile(`^[!-~]{1,128}$`)
idempotencyKeyPattern = regexp.MustCompile(`^[!-~]{1,256}$`)
)
// DeliveryStatus is the state of one delivery. The values follow the
// outcomes of the MailSender port.
//
// Transitions:
//
// pending, waiting_quota, unknown --RecordAttempt--> accepted | rejected | pending | waiting_quota | unknown
// accepted, rejected --RecordAttempt--> refused (ErrDeliveryTransition)
// pending, waiting_quota --WaitForQuota---> waiting_quota (no attempt is recorded)
//
// The attempt outcome decides the target: accepted gives accepted; a
// permanent or invalid_request rejection gives rejected; a temporary or
// rate_limited rejection gives pending again with a scheduled next attempt; a
// quota_exhausted rejection gives waiting_quota until the expected reset, or
// without a time when the reset is unknown; unknown gives unknown.
type DeliveryStatus string
const (
// DeliveryStatusPending waits for its first or next attempt at
// NextAttemptAt.
DeliveryStatusPending DeliveryStatus = "pending"
// DeliveryStatusAccepted means the provider accepted the message and
// returned its ID. It is not delivery to or reading by the recipient.
DeliveryStatusAccepted DeliveryStatus = "accepted"
// DeliveryStatusRejected means the provider refused the message for good;
// the cause must be fixed before mail of this kind can succeed.
DeliveryStatusRejected DeliveryStatus = "rejected"
// DeliveryStatusUnknown means the last attempt may have reached the
// provider without a conclusive answer (delivery_uncertain). A retry must
// reuse the idempotency key and the stored content; it is never treated
// as not sent.
DeliveryStatusUnknown DeliveryStatus = "unknown"
// DeliveryStatusWaitingQuota means the provider or local quota is used
// up. The next attempt waits for the reset at NextAttemptAt; without a
// time the reset is unknown (for example a monthly provider quota) and an
// operator or the quota rule decides.
DeliveryStatusWaitingQuota DeliveryStatus = "waiting_quota"
)
// ParseDeliveryStatus accepts a known status.
func ParseDeliveryStatus(value string) (DeliveryStatus, error) {
switch status := DeliveryStatus(value); status {
case DeliveryStatusPending, DeliveryStatusAccepted, DeliveryStatusRejected, DeliveryStatusUnknown, DeliveryStatusWaitingQuota:
return status, nil
default:
return "", invalidDelivery("domain.ParseDeliveryStatus", "unknown delivery status")
}
}
// IsTerminal reports a status that accepts no further attempt.
func (status DeliveryStatus) IsTerminal() bool {
return status == DeliveryStatusAccepted || status == DeliveryStatusRejected
}
// requiresNextAttempt reports a status that the sending worker picks up again
// by itself, so it must say when.
func (status DeliveryStatus) requiresNextAttempt() bool {
return status == DeliveryStatusPending
}
// DeliveryAttemptOutcome is what one attempt established; the values equal
// outbound.MailOutcome.
type DeliveryAttemptOutcome string
const (
DeliveryOutcomeAccepted DeliveryAttemptOutcome = "accepted"
DeliveryOutcomeRejected DeliveryAttemptOutcome = "rejected"
DeliveryOutcomeUnknown DeliveryAttemptOutcome = "unknown"
)
// DeliveryRejection is the reason of a rejected attempt; the values equal
// outbound.MailRejection.
type DeliveryRejection string
const (
DeliveryRejectionPermanent DeliveryRejection = "permanent"
DeliveryRejectionInvalidRequest DeliveryRejection = "invalid_request"
DeliveryRejectionRateLimited DeliveryRejection = "rate_limited"
DeliveryRejectionQuotaExhausted DeliveryRejection = "quota_exhausted"
DeliveryRejectionTemporary DeliveryRejection = "temporary"
)
// MailProviderAccount names the transport and the provider account that a
// delivery is pinned to, for example resend and "main". It is configuration
// identity, never a credential. A delivery keeps it for its whole life: a
// configuration change applies to new deliveries only, because providers and
// accounts share no idempotency keys.
type MailProviderAccount struct {
provider string
account string
}
// NewMailProviderAccount validates a provider name (lowercase snake_case of
// at most 32 characters) and an account label (lowercase letters, digits,
// ".", "_", or "-", at most 64 characters).
func NewMailProviderAccount(provider, account string) (MailProviderAccount, error) {
if !mailProviderPattern.MatchString(provider) {
return MailProviderAccount{}, invalidDelivery("domain.NewMailProviderAccount", "provider must be a lowercase snake_case name of at most 32 characters")
}
if !mailProviderAccountPattern.MatchString(account) {
return MailProviderAccount{}, invalidDelivery("domain.NewMailProviderAccount", "account must be a lowercase label of at most 64 characters")
}
return MailProviderAccount{provider: provider, account: account}, nil
}
func (identity MailProviderAccount) Provider() string { return identity.provider }
func (identity MailProviderAccount) Account() string { return identity.account }
func (identity MailProviderAccount) IsZero() bool { return identity.provider == "" }
// Delivery is the durable state of sending one message to one recipient: the
// recipient, the immutable rendered content, the provider account it is
// pinned to, the idempotency key, and the attempt state. The content is fixed
// at creation, so a later template version never changes what a retry sends.
//
// Delivery is a value: RecordAttempt returns the next state and leaves the
// receiver unchanged. String, GoString, Format, and LogValue show the ID,
// kind, status, and provider, never the recipient or the content.
type Delivery struct {
id uuid.UUID
sourceEventID uuid.UUID
recipientUserID uuid.UUID
recipient EmailAddress
content MailContent
providerAccount MailProviderAccount
idempotencyKey string
status DeliveryStatus
attemptCount int32
nextAttemptAt time.Time
lastAttemptAt time.Time
providerMessageID string
version int64
createdAt time.Time
updatedAt time.Time
}
// NewDeliveryInput describes a new delivery. ID must be stable for the
// logical request, so a repeated request maps to the same delivery: the
// mail request ID, or another ID the caller derives from its source record.
type NewDeliveryInput struct {
ID uuid.UUID
// SourceEventID is the domain event the delivery was created from;
// uuid.Nil for a delivery created directly in a business transaction.
SourceEventID uuid.UUID
RecipientUserID uuid.UUID
Recipient EmailAddress
Content MailContent
ProviderAccount MailProviderAccount
CreatedAt time.Time
}
// NewDelivery validates input and returns a pending delivery that is due at
// CreatedAt, with version 1 and the idempotency key "delivery/<id>".
func NewDelivery(input NewDeliveryInput) (Delivery, error) {
const location = "domain.NewDelivery"
switch {
case input.ID == uuid.Nil:
return Delivery{}, invalidDelivery(location, "delivery ID must not be nil")
case input.RecipientUserID == uuid.Nil:
return Delivery{}, invalidDelivery(location, "recipient user ID must not be nil")
case input.Recipient.IsZero():
return Delivery{}, invalidDelivery(location, "recipient address must be set")
case input.Content.IsZero():
return Delivery{}, invalidDelivery(location, "content must be built by NewMailContent")
case input.ProviderAccount.IsZero():
return Delivery{}, invalidDelivery(location, "provider account must be set")
case input.CreatedAt.IsZero():
return Delivery{}, invalidDelivery(location, "creation time must be set")
}
return Delivery{
id: input.ID,
sourceEventID: input.SourceEventID,
recipientUserID: input.RecipientUserID,
recipient: input.Recipient,
content: input.Content,
providerAccount: input.ProviderAccount,
idempotencyKey: deliveryIdempotencyKeyPrefix + input.ID.String(),
status: DeliveryStatusPending,
nextAttemptAt: input.CreatedAt,
version: 1,
createdAt: input.CreatedAt,
updatedAt: input.CreatedAt,
}, nil
}
// DeliverySnapshot is a stored delivery row. A zero time means "not set".
type DeliverySnapshot struct {
ID uuid.UUID
SourceEventID uuid.UUID
RecipientUserID uuid.UUID
RecipientAddress string
Content MailContent
ProviderAccount MailProviderAccount
IdempotencyKey string
Status DeliveryStatus
AttemptCount int32
NextAttemptAt time.Time
LastAttemptAt time.Time
ProviderMessageID string
Version int64
CreatedAt time.Time
UpdatedAt time.Time
}
// RestoreDelivery rebuilds a stored delivery and checks the invariants that
// the database also enforces. The recipient is restored without the current
// address syntax rules, so a later, stricter rule does not make stored rows
// unreadable.
func RestoreDelivery(snapshot DeliverySnapshot) (Delivery, error) {
const location = "domain.RestoreDelivery"
recipient, err := RestoreEmailAddress(snapshot.RecipientAddress, normalizeEmailKey(snapshot.RecipientAddress))
if err != nil {
return Delivery{}, fmt.Errorf("%s - restore recipient: %w", location, err)
}
if _, err := ParseDeliveryStatus(string(snapshot.Status)); err != nil {
return Delivery{}, fmt.Errorf("%s - restore status: %w", location, err)
}
switch {
case snapshot.ID == uuid.Nil || snapshot.RecipientUserID == uuid.Nil:
return Delivery{}, invalidDelivery(location, "delivery and recipient user IDs must not be nil")
case snapshot.Content.IsZero() || snapshot.ProviderAccount.IsZero():
return Delivery{}, invalidDelivery(location, "content and provider account must be set")
case !idempotencyKeyPattern.MatchString(snapshot.IdempotencyKey):
return Delivery{}, invalidDelivery(location, "idempotency key must have 1 to 256 printable ASCII characters")
case snapshot.Version <= 0 || snapshot.AttemptCount < 0:
return Delivery{}, invalidDelivery(location, "version must be positive and the attempt count not negative")
case snapshot.CreatedAt.IsZero() || snapshot.UpdatedAt.Before(snapshot.CreatedAt):
return Delivery{}, invalidDelivery(location, "update time must not precede the creation time")
case (snapshot.AttemptCount == 0) != snapshot.LastAttemptAt.IsZero():
return Delivery{}, invalidDelivery(location, "last attempt time must be set exactly when an attempt was made")
case (snapshot.Status == DeliveryStatusAccepted) != (snapshot.ProviderMessageID != ""):
return Delivery{}, invalidDelivery(location, "provider message ID must be set exactly for an accepted delivery")
}
if err := checkNextAttempt(location, snapshot.Status, snapshot.NextAttemptAt); err != nil {
return Delivery{}, err
}
return Delivery{
id: snapshot.ID,
sourceEventID: snapshot.SourceEventID,
recipientUserID: snapshot.RecipientUserID,
recipient: recipient,
content: snapshot.Content,
providerAccount: snapshot.ProviderAccount,
idempotencyKey: snapshot.IdempotencyKey,
status: snapshot.Status,
attemptCount: snapshot.AttemptCount,
nextAttemptAt: snapshot.NextAttemptAt,
lastAttemptAt: snapshot.LastAttemptAt,
providerMessageID: snapshot.ProviderMessageID,
version: snapshot.Version,
createdAt: snapshot.CreatedAt,
updatedAt: snapshot.UpdatedAt,
}, nil
}
func checkNextAttempt(location string, status DeliveryStatus, nextAttemptAt time.Time) error {
switch {
case status.IsTerminal() && !nextAttemptAt.IsZero():
return invalidDelivery(location, "an accepted or rejected delivery has no next attempt")
case status.requiresNextAttempt() && nextAttemptAt.IsZero():
return invalidDelivery(location, "a pending delivery needs a next attempt time")
}
return nil
}
func (delivery Delivery) IsZero() bool { return delivery.id == uuid.Nil }
func (delivery Delivery) ID() uuid.UUID { return delivery.id }
// SourceEventID is the event the delivery was created from, or uuid.Nil.
func (delivery Delivery) SourceEventID() uuid.UUID { return delivery.sourceEventID }
func (delivery Delivery) RecipientUserID() uuid.UUID { return delivery.recipientUserID }
// Recipient is the address captured when the delivery was created. Use it
// only to send the message; never log it.
func (delivery Delivery) Recipient() EmailAddress { return delivery.recipient }
func (delivery Delivery) Kind() MailKind { return delivery.content.Kind() }
func (delivery Delivery) Content() MailContent { return delivery.content }
func (delivery Delivery) ProviderAccount() MailProviderAccount { return delivery.providerAccount }
// IdempotencyKey is sent with every attempt of this delivery.
func (delivery Delivery) IdempotencyKey() string { return delivery.idempotencyKey }
func (delivery Delivery) Status() DeliveryStatus { return delivery.status }
func (delivery Delivery) AttemptCount() int32 { return delivery.attemptCount }
// NextAttemptAt is when the delivery is due; zero when no automatic attempt
// is scheduled (accepted, rejected, unknown without a retry, or waiting_quota
// with an unknown reset).
func (delivery Delivery) NextAttemptAt() time.Time { return delivery.nextAttemptAt }
// LastAttemptAt is zero before the first attempt.
func (delivery Delivery) LastAttemptAt() time.Time { return delivery.lastAttemptAt }
// ProviderMessageID is set once the provider accepted the message.
func (delivery Delivery) ProviderMessageID() string { return delivery.providerMessageID }
// Version is the optimistic concurrency version, advanced by every attempt.
func (delivery Delivery) Version() int64 { return delivery.version }
func (delivery Delivery) CreatedAt() time.Time { return delivery.createdAt }
func (delivery Delivery) UpdatedAt() time.Time { return delivery.updatedAt }
// DeliveryAttemptInput is the result of one transport attempt. The fields
// mirror outbound.SendResult; At is when the attempt ended.
//
// NextAttemptAt is chosen by the caller's retry policy. It is required when
// the outcome leaves the delivery pending (temporary or rate_limited),
// optional for waiting_quota and unknown, where zero means that no automatic
// attempt is scheduled, and must be zero for accepted and for permanent or
// invalid_request rejections. It must not precede At.
type DeliveryAttemptInput struct {
At time.Time
Outcome DeliveryAttemptOutcome
Rejection DeliveryRejection
ProviderCode string
ProviderMessageID string
RetryAfter time.Duration
NextAttemptAt time.Time
}
// DeliveryAttempt is one recorded attempt. Number counts from 1 within its
// delivery. A zero NextAttemptAt means none was scheduled.
type DeliveryAttempt struct {
DeliveryID uuid.UUID
Number int32
At time.Time
Outcome DeliveryAttemptOutcome
Rejection DeliveryRejection
ProviderCode string
ProviderMessageID string
RetryAfter time.Duration
StatusAfter DeliveryStatus
NextAttemptAt time.Time
}
// RecordAttempt applies an attempt result and returns the next state of the
// delivery together with the attempt record. The receiver is not changed. An
// attempt on an accepted or rejected delivery returns ErrDeliveryTransition;
// a result that breaks the rules of DeliveryAttemptInput returns
// ErrInvalidDelivery. The returned delivery has the next version; storage
// applies it only over the receiver's version.
func (delivery Delivery) RecordAttempt(input DeliveryAttemptInput) (Delivery, DeliveryAttempt, error) {
const location = "Delivery.RecordAttempt"
if delivery.IsZero() {
return Delivery{}, DeliveryAttempt{}, invalidDelivery(location, "delivery was not built by NewDelivery or RestoreDelivery")
}
if delivery.status.IsTerminal() {
return Delivery{}, DeliveryAttempt{}, fmt.Errorf("%s - delivery is %s: %w", location, delivery.status, ErrDeliveryTransition)
}
if delivery.attemptCount == math.MaxInt32 {
return Delivery{}, DeliveryAttempt{}, invalidDelivery(location, "attempt numbers are exhausted")
}
switch {
case input.At.IsZero():
return Delivery{}, DeliveryAttempt{}, invalidDelivery(location, "attempt time must be set")
case input.At.Before(delivery.updatedAt):
return Delivery{}, DeliveryAttempt{}, invalidDelivery(location, "attempt time must not precede the last change of the delivery")
}
attempt := DeliveryAttempt{
DeliveryID: delivery.id,
Number: delivery.attemptCount + 1,
At: input.At,
Outcome: input.Outcome,
Rejection: input.Rejection,
ProviderCode: input.ProviderCode,
ProviderMessageID: input.ProviderMessageID,
RetryAfter: input.RetryAfter,
NextAttemptAt: input.NextAttemptAt,
}
statusAfter, err := validateAttempt(location, attempt)
if err != nil {
return Delivery{}, DeliveryAttempt{}, err
}
attempt.StatusAfter = statusAfter
next := delivery
next.status = statusAfter
next.attemptCount = attempt.Number
next.lastAttemptAt = input.At
next.nextAttemptAt = input.NextAttemptAt
if input.Outcome == DeliveryOutcomeAccepted {
next.providerMessageID = input.ProviderMessageID
}
next.version = delivery.version + 1
next.updatedAt = input.At
return next, attempt, nil
}
// WaitForQuota parks a pending or waiting_quota delivery in waiting_quota
// without an attempt, for example when a local quota defers the send before
// the transport is called. until is the expected reset; zero means unknown,
// so no automatic attempt is scheduled. at is the decision time. It returns
// the next state with the next version; no attempt record is written. An
// unknown delivery is refused: parking it would hide that an earlier attempt
// may have been accepted, and its retry is decided by the retry policy.
func (delivery Delivery) WaitForQuota(at, until time.Time) (Delivery, error) {
const location = "Delivery.WaitForQuota"
if err := delivery.checkChangeTime(location, at); err != nil {
return Delivery{}, err
}
if delivery.status != DeliveryStatusPending && delivery.status != DeliveryStatusWaitingQuota {
return Delivery{}, fmt.Errorf("%s - delivery is %s: %w", location, delivery.status, ErrDeliveryTransition)
}
if !until.IsZero() && until.Before(at) {
return Delivery{}, invalidDelivery(location, "quota reset must not precede the decision")
}
next := delivery
next.status = DeliveryStatusWaitingQuota
next.nextAttemptAt = until
next.version = delivery.version + 1
next.updatedAt = at
return next, nil
}
// Rebind pins a delivery that has no attempt yet to another provider
// account, for example after the stand moved from EMAIL_PROVIDER=disabled to
// a real transport. Once an attempt was made, a provider may hold the
// idempotency key, so the account is fixed and Rebind returns
// ErrDeliveryTransition, as it does for an accepted or rejected delivery.
func (delivery Delivery) Rebind(at time.Time, providerAccount MailProviderAccount) (Delivery, error) {
const location = "Delivery.Rebind"
if err := delivery.checkChangeTime(location, at); err != nil {
return Delivery{}, err
}
if providerAccount.IsZero() {
return Delivery{}, invalidDelivery(location, "provider account must be set")
}
if delivery.attemptCount != 0 || delivery.status.IsTerminal() {
return Delivery{}, fmt.Errorf("%s - delivery has attempts or is %s: %w", location, delivery.status, ErrDeliveryTransition)
}
next := delivery
next.providerAccount = providerAccount
next.version = delivery.version + 1
next.updatedAt = at
return next, nil
}
// checkChangeTime rejects a zero delivery and a change time before the last
// recorded change.
func (delivery Delivery) checkChangeTime(location string, at time.Time) error {
if delivery.IsZero() {
return invalidDelivery(location, "delivery was not built by NewDelivery or RestoreDelivery")
}
if at.IsZero() || at.Before(delivery.updatedAt) {
return invalidDelivery(location, "change time must be set and not precede the last change")
}
return nil
}
// RestoreDeliveryAttempt checks a stored attempt with the rules that
// RecordAttempt applied when it was made.
func RestoreDeliveryAttempt(attempt DeliveryAttempt) (DeliveryAttempt, error) {
const location = "domain.RestoreDeliveryAttempt"
if attempt.DeliveryID == uuid.Nil || attempt.Number <= 0 || attempt.At.IsZero() {
return DeliveryAttempt{}, invalidDelivery(location, "attempt needs a delivery ID, a positive number, and a time")
}
statusAfter, err := validateAttempt(location, attempt)
if err != nil {
return DeliveryAttempt{}, err
}
if attempt.StatusAfter != statusAfter {
return DeliveryAttempt{}, invalidDelivery(location, "stored status does not follow from the attempt outcome")
}
return attempt, nil
}
// validateAttempt checks the result fields and returns the status the
// outcome leads to.
func validateAttempt(location string, attempt DeliveryAttempt) (DeliveryStatus, error) {
if attempt.ProviderCode != "" && !mailProviderCodePattern.MatchString(attempt.ProviderCode) {
return "", invalidDelivery(location, "provider code must be a lowercase snake_case name of at most 64 characters")
}
if attempt.RetryAfter < 0 {
return "", invalidDelivery(location, "retry-after must not be negative")
}
statusAfter, err := statusAfterAttempt(location, attempt)
if err != nil {
return "", err
}
if err := checkNextAttempt(location, statusAfter, attempt.NextAttemptAt); err != nil {
return "", err
}
if !attempt.NextAttemptAt.IsZero() && attempt.NextAttemptAt.Before(attempt.At) {
return "", invalidDelivery(location, "next attempt must not precede the attempt")
}
return statusAfter, nil
}
func statusAfterAttempt(location string, attempt DeliveryAttempt) (DeliveryStatus, error) {
if attempt.Outcome != DeliveryOutcomeAccepted && attempt.ProviderMessageID != "" {
return "", invalidDelivery(location, "only an accepted attempt carries a provider message ID")
}
if attempt.Outcome != DeliveryOutcomeRejected && attempt.Rejection != "" {
return "", invalidDelivery(location, "only a rejected attempt carries a rejection reason")
}
switch attempt.Outcome {
case DeliveryOutcomeAccepted:
if !providerMessageIDPattern.MatchString(attempt.ProviderMessageID) {
return "", invalidDelivery(location, "an accepted attempt needs a provider message ID of 1 to 128 printable ASCII characters")
}
if attempt.ProviderCode != "" || attempt.RetryAfter != 0 {
return "", invalidDelivery(location, "an accepted attempt carries no provider code or retry-after")
}
return DeliveryStatusAccepted, nil
case DeliveryOutcomeUnknown:
return DeliveryStatusUnknown, nil
case DeliveryOutcomeRejected:
switch attempt.Rejection {
case DeliveryRejectionPermanent, DeliveryRejectionInvalidRequest:
return DeliveryStatusRejected, nil
case DeliveryRejectionTemporary, DeliveryRejectionRateLimited:
return DeliveryStatusPending, nil
case DeliveryRejectionQuotaExhausted:
return DeliveryStatusWaitingQuota, nil
default:
return "", invalidDelivery(location, "a rejected attempt needs a known rejection reason")
}
default:
return "", invalidDelivery(location, "attempt outcome must be accepted, rejected, or unknown")
}
}
func invalidDelivery(location, reason string) error {
return fmt.Errorf("%s - %s: %w", location, reason, ErrInvalidDelivery)
}
func (delivery Delivery) String() string {
if delivery.IsZero() {
return "[empty delivery]"
}
return fmt.Sprintf("[delivery %s %s %s]", delivery.id, delivery.content.Kind(), delivery.status)
}
func (delivery Delivery) GoString() string { return delivery.String() }
// Format applies String to every verb; without it %+v would print the fields.
func (delivery Delivery) Format(state fmt.State, _ rune) {
_, _ = state.Write([]byte(delivery.String()))
}
// LogValue carries only bounded or opaque fields: the ID, kind, status, and
// provider. The recipient, its account ID, and the content stay out of logs.
func (delivery Delivery) LogValue() slog.Value {
return slog.GroupValue(
slog.String("delivery_id", delivery.id.String()),
slog.String("kind", string(delivery.content.Kind())),
slog.String("status", string(delivery.status)),
slog.String("provider", delivery.providerAccount.provider),
)
}
+526
View File
@@ -0,0 +1,526 @@
package domain
import (
"bytes"
"errors"
"fmt"
"log/slog"
"strings"
"testing"
"time"
"github.com/google/uuid"
)
const (
testDeliveryAddress = "Recipient.Person@Example.com"
testDeliverySubject = "Subject with a private detail"
testDeliveryText = "Text body https://lincodex.example/verify-email#token=SyntheticToken_0123456789-abcdefghij\n"
testDeliveryHTML = "<p>HTML body with a private detail</p>\n"
testMessageID = "4ef9a417-02e9-4d39-ad75-9611e0fcc33c"
)
var testDeliveryCreated = time.Date(2026, 10, 6, 9, 0, 0, 0, time.UTC)
func testMailContent(t *testing.T) MailContent {
t.Helper()
content, err := NewMailContent(MailKindVerification, "verification.v1", testDeliverySubject, testDeliveryText, testDeliveryHTML)
if err != nil {
t.Fatalf("NewMailContent() error = %v", err)
}
return content
}
func testProviderAccount(t *testing.T) MailProviderAccount {
t.Helper()
account, err := NewMailProviderAccount("resend", "main")
if err != nil {
t.Fatalf("NewMailProviderAccount() error = %v", err)
}
return account
}
func testDeliveryInput(t *testing.T) NewDeliveryInput {
t.Helper()
recipient, err := NewEmailAddress(testDeliveryAddress)
if err != nil {
t.Fatalf("NewEmailAddress() error = %v", err)
}
return NewDeliveryInput{
ID: uuid.MustParse("01926f3a-7c00-7000-8000-000000000001"),
RecipientUserID: uuid.MustParse("01926f3a-7c00-7000-8000-000000000002"),
Recipient: recipient,
Content: testMailContent(t),
ProviderAccount: testProviderAccount(t),
CreatedAt: testDeliveryCreated,
}
}
func newTestDelivery(t *testing.T) Delivery {
t.Helper()
delivery, err := NewDelivery(testDeliveryInput(t))
if err != nil {
t.Fatalf("NewDelivery() error = %v", err)
}
return delivery
}
// after returns a time minutes after the creation of the test delivery.
func after(minutes int) time.Time {
return testDeliveryCreated.Add(time.Duration(minutes) * time.Minute)
}
func mustRecord(t *testing.T, delivery Delivery, input DeliveryAttemptInput) Delivery {
t.Helper()
next, _, err := delivery.RecordAttempt(input)
if err != nil {
t.Fatalf("RecordAttempt(%s/%s) error = %v", input.Outcome, input.Rejection, err)
}
return next
}
func TestMailContentHashCoversEveryPart(t *testing.T) {
base := MailContentHash("verification.v1", "subject", "text", "html")
if base != MailContentHash("verification.v1", "subject", "text", "html") {
t.Fatal("the same parts give different hashes")
}
for name, other := range map[string][MailContentHashSize]byte{
"version": MailContentHash("verification.v2", "subject", "text", "html"),
"subject": MailContentHash("verification.v1", "subject!", "text", "html"),
"text": MailContentHash("verification.v1", "subject", "text!", "html"),
"html": MailContentHash("verification.v1", "subject", "text", "html!"),
"shifted border": MailContentHash("verification.v1", "subjec", "ttext", "html"),
} {
if other == base {
t.Fatalf("content hash ignores a change of the %s", name)
}
}
}
func TestNewMailContentRejectsUnsendableContent(t *testing.T) {
tests := []struct {
name string
kind MailKind
version, subject, text, htmlBody string
}{
{name: "unknown kind", kind: "digest", version: "digest.v1", subject: "s", text: "t"},
{name: "version of another kind", kind: MailKindNotification, version: "verification.v1", subject: "s", text: "t"},
{name: "version prefix of another kind", kind: MailKindPasswordReset, version: "password.v1", subject: "s", text: "t"},
{name: "version without number", kind: MailKindNotification, version: "notification.v0", subject: "s", text: "t"},
{name: "blank subject", kind: MailKindNotification, version: "notification.v1", subject: " ", text: "t"},
{name: "subject with a header line", kind: MailKindNotification, version: "notification.v1", subject: "s\r\nBcc: x@example.com", text: "t"},
{name: "subject too long", kind: MailKindNotification, version: "notification.v1", subject: strings.Repeat("я", maxMailSubjectRunes+1), text: "t"},
{name: "blank bodies", kind: MailKindNotification, version: "notification.v1", subject: "s", text: " \n", htmlBody: ""},
{name: "NUL in body", kind: MailKindNotification, version: "notification.v1", subject: "s", text: "t\x00"},
{name: "invalid UTF-8", kind: MailKindNotification, version: "notification.v1", subject: "s", text: "\xff"},
{name: "oversized body", kind: MailKindNotification, version: "notification.v1", subject: "s", text: strings.Repeat("t", maxMailPartBytes+1)},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
_, err := NewMailContent(test.kind, test.version, test.subject, test.text, test.htmlBody)
if !errors.Is(err, ErrInvalidMailContent) {
t.Fatalf("NewMailContent() error = %v, want ErrInvalidMailContent", err)
}
})
}
}
func TestRestoreMailContentDetectsAChangedBody(t *testing.T) {
content := testMailContent(t)
hash := content.Hash()
restored, err := RestoreMailContent(content.Kind(), content.TemplateVersion(), content.Subject(), content.Text(), content.HTML(), hash[:])
if err != nil || restored.Hash() != hash {
t.Fatalf("RestoreMailContent() = %v, %v, want the stored content", restored, err)
}
_, err = RestoreMailContent(content.Kind(), content.TemplateVersion(), content.Subject(), content.Text()+"changed", content.HTML(), hash[:])
if !errors.Is(err, ErrMailContentIntegrity) {
t.Fatalf("RestoreMailContent(changed text) error = %v, want ErrMailContentIntegrity", err)
}
_, err = RestoreMailContent(content.Kind(), content.TemplateVersion(), content.Subject(), content.Text(), content.HTML(), hash[:16])
if !errors.Is(err, ErrMailContentIntegrity) {
t.Fatalf("RestoreMailContent(short hash) error = %v, want ErrMailContentIntegrity", err)
}
}
func TestNewDeliveryStartsPendingWithAStableKey(t *testing.T) {
input := testDeliveryInput(t)
delivery := newTestDelivery(t)
switch {
case delivery.ID() != input.ID || delivery.RecipientUserID() != input.RecipientUserID:
t.Fatal("NewDelivery() changed the IDs")
case delivery.Recipient().Address() != testDeliveryAddress:
t.Fatal("NewDelivery() changed the recipient")
case delivery.Kind() != MailKindVerification || delivery.Content().Hash() != input.Content.Hash():
t.Fatal("NewDelivery() changed the content")
case delivery.IdempotencyKey() != "delivery/"+input.ID.String():
t.Fatalf("IdempotencyKey() = %q", delivery.IdempotencyKey())
case delivery.Status() != DeliveryStatusPending || !delivery.NextAttemptAt().Equal(testDeliveryCreated):
t.Fatalf("new delivery is %s due at %s, want pending and due at creation", delivery.Status(), delivery.NextAttemptAt())
case delivery.AttemptCount() != 0 || !delivery.LastAttemptAt().IsZero() || delivery.ProviderMessageID() != "":
t.Fatal("new delivery has attempt state")
case delivery.Version() != 1 || !delivery.CreatedAt().Equal(testDeliveryCreated) || !delivery.UpdatedAt().Equal(testDeliveryCreated):
t.Fatal("new delivery has the wrong version or times")
}
}
func TestNewDeliveryRejectsIncompleteInput(t *testing.T) {
tests := map[string]func(*NewDeliveryInput){
"nil ID": func(input *NewDeliveryInput) { input.ID = uuid.Nil },
"nil recipient user": func(input *NewDeliveryInput) { input.RecipientUserID = uuid.Nil },
"zero recipient": func(input *NewDeliveryInput) { input.Recipient = EmailAddress{} },
"zero content": func(input *NewDeliveryInput) { input.Content = MailContent{} },
"zero provider": func(input *NewDeliveryInput) { input.ProviderAccount = MailProviderAccount{} },
"zero creation time": func(input *NewDeliveryInput) { input.CreatedAt = time.Time{} },
}
for name, change := range tests {
t.Run(name, func(t *testing.T) {
input := testDeliveryInput(t)
change(&input)
if _, err := NewDelivery(input); !errors.Is(err, ErrInvalidDelivery) {
t.Fatalf("NewDelivery() error = %v, want ErrInvalidDelivery", err)
}
})
}
}
func TestNewMailProviderAccountRejectsCredentialsAndFreeText(t *testing.T) {
for _, test := range []struct{ provider, account string }{
{"", "main"},
{"Resend", "main"},
{"resend", ""},
{"resend", "re_SecretKeyValue"},
{"resend", "main account"},
{"resend", strings.Repeat("a", 65)},
} {
if _, err := NewMailProviderAccount(test.provider, test.account); !errors.Is(err, ErrInvalidDelivery) {
t.Fatalf("NewMailProviderAccount(%q, %q) error = %v, want ErrInvalidDelivery", test.provider, test.account, err)
}
}
}
// TestDeliveryStatusTransitions applies every attempt outcome to every
// status that accepts an attempt, and checks that the terminal statuses
// accept none.
func TestDeliveryStatusTransitions(t *testing.T) {
outcomes := []struct {
name string
input DeliveryAttemptInput
want DeliveryStatus
}{
{"accepted", DeliveryAttemptInput{Outcome: DeliveryOutcomeAccepted, ProviderMessageID: testMessageID}, DeliveryStatusAccepted},
{"permanent", DeliveryAttemptInput{Outcome: DeliveryOutcomeRejected, Rejection: DeliveryRejectionPermanent, ProviderCode: "validation_error"}, DeliveryStatusRejected},
{"invalid request", DeliveryAttemptInput{Outcome: DeliveryOutcomeRejected, Rejection: DeliveryRejectionInvalidRequest, ProviderCode: "invalid_api_key"}, DeliveryStatusRejected},
{"temporary", DeliveryAttemptInput{Outcome: DeliveryOutcomeRejected, Rejection: DeliveryRejectionTemporary, NextAttemptAt: after(90)}, DeliveryStatusPending},
{"rate limited", DeliveryAttemptInput{Outcome: DeliveryOutcomeRejected, Rejection: DeliveryRejectionRateLimited, RetryAfter: time.Second, NextAttemptAt: after(90)}, DeliveryStatusPending},
{"quota", DeliveryAttemptInput{Outcome: DeliveryOutcomeRejected, Rejection: DeliveryRejectionQuotaExhausted, ProviderCode: "daily_quota_exceeded", RetryAfter: time.Hour, NextAttemptAt: after(120)}, DeliveryStatusWaitingQuota},
{"quota with unknown reset", DeliveryAttemptInput{Outcome: DeliveryOutcomeRejected, Rejection: DeliveryRejectionQuotaExhausted, ProviderCode: "monthly_quota_exceeded"}, DeliveryStatusWaitingQuota},
{"unknown with retry", DeliveryAttemptInput{Outcome: DeliveryOutcomeUnknown, ProviderCode: "concurrent_idempotent_requests", NextAttemptAt: after(90)}, DeliveryStatusUnknown},
{"unknown without retry", DeliveryAttemptInput{Outcome: DeliveryOutcomeUnknown, ProviderCode: "invalid_idempotent_request"}, DeliveryStatusUnknown},
}
start := newTestDelivery(t)
starts := map[DeliveryStatus]Delivery{
DeliveryStatusPending: start,
DeliveryStatusWaitingQuota: mustRecord(t, start, DeliveryAttemptInput{
At: after(1), Outcome: DeliveryOutcomeRejected, Rejection: DeliveryRejectionQuotaExhausted, NextAttemptAt: after(60),
}),
DeliveryStatusUnknown: mustRecord(t, start, DeliveryAttemptInput{At: after(1), Outcome: DeliveryOutcomeUnknown}),
}
for from, delivery := range starts {
for _, outcome := range outcomes {
t.Run(string(from)+" then "+outcome.name, func(t *testing.T) {
input := outcome.input
input.At = after(30)
next, attempt, err := delivery.RecordAttempt(input)
if err != nil {
t.Fatalf("RecordAttempt() error = %v", err)
}
if next.Status() != outcome.want || attempt.StatusAfter != outcome.want {
t.Fatalf("status = %s, attempt status = %s, want %s", next.Status(), attempt.StatusAfter, outcome.want)
}
if next.AttemptCount() != delivery.AttemptCount()+1 || attempt.Number != next.AttemptCount() {
t.Fatalf("attempt number = %d, count = %d after %d", attempt.Number, next.AttemptCount(), delivery.AttemptCount())
}
if next.Version() != delivery.Version()+1 || !next.LastAttemptAt().Equal(input.At) || !next.UpdatedAt().Equal(input.At) {
t.Fatal("the attempt did not advance the version and times")
}
if !next.NextAttemptAt().Equal(input.NextAttemptAt) {
t.Fatalf("NextAttemptAt() = %s, want %s", next.NextAttemptAt(), input.NextAttemptAt)
}
if wantID := input.ProviderMessageID; next.ProviderMessageID() != wantID {
t.Fatalf("ProviderMessageID() = %q, want %q", next.ProviderMessageID(), wantID)
}
if next.IdempotencyKey() != delivery.IdempotencyKey() || next.Content().Hash() != delivery.Content().Hash() {
t.Fatal("an attempt changed the key or the content")
}
})
}
}
terminal := map[DeliveryStatus]Delivery{
DeliveryStatusAccepted: mustRecord(t, start, DeliveryAttemptInput{At: after(1), Outcome: DeliveryOutcomeAccepted, ProviderMessageID: testMessageID}),
DeliveryStatusRejected: mustRecord(t, start, DeliveryAttemptInput{At: after(1), Outcome: DeliveryOutcomeRejected, Rejection: DeliveryRejectionPermanent}),
}
for from, delivery := range terminal {
for _, outcome := range outcomes {
t.Run(string(from)+" refuses "+outcome.name, func(t *testing.T) {
input := outcome.input
input.At = after(30)
if _, _, err := delivery.RecordAttempt(input); !errors.Is(err, ErrDeliveryTransition) {
t.Fatalf("RecordAttempt() error = %v, want ErrDeliveryTransition", err)
}
})
}
}
}
func TestRecordAttemptLeavesTheReceiverUnchanged(t *testing.T) {
delivery := newTestDelivery(t)
next := mustRecord(t, delivery, DeliveryAttemptInput{At: after(1), Outcome: DeliveryOutcomeAccepted, ProviderMessageID: testMessageID})
if delivery.Status() != DeliveryStatusPending || delivery.Version() != 1 || delivery.AttemptCount() != 0 {
t.Fatal("RecordAttempt() changed its receiver")
}
if next.Status() != DeliveryStatusAccepted || next.ProviderMessageID() != testMessageID || !next.NextAttemptAt().IsZero() {
t.Fatalf("accepted delivery = %s with ID %q due %s", next.Status(), next.ProviderMessageID(), next.NextAttemptAt())
}
}
func TestRecordAttemptRejectsInconsistentResults(t *testing.T) {
delivery := mustRecord(t, newTestDelivery(t), DeliveryAttemptInput{At: after(10), Outcome: DeliveryOutcomeUnknown})
tests := map[string]DeliveryAttemptInput{
"zero time": {Outcome: DeliveryOutcomeUnknown},
"before the previous attempt": {At: after(5), Outcome: DeliveryOutcomeUnknown},
"unknown outcome": {At: after(20), Outcome: "delivered"},
"accepted without message ID": {At: after(20), Outcome: DeliveryOutcomeAccepted},
"accepted with spaces in ID": {At: after(20), Outcome: DeliveryOutcomeAccepted, ProviderMessageID: "an id"},
"accepted with provider code": {At: after(20), Outcome: DeliveryOutcomeAccepted, ProviderMessageID: testMessageID, ProviderCode: "validation_error"},
"accepted with next attempt": {At: after(20), Outcome: DeliveryOutcomeAccepted, ProviderMessageID: testMessageID, NextAttemptAt: after(30)},
"rejected without reason": {At: after(20), Outcome: DeliveryOutcomeRejected},
"rejected with unknown reason": {At: after(20), Outcome: DeliveryOutcomeRejected, Rejection: "bounced"},
"rejected with message ID": {At: after(20), Outcome: DeliveryOutcomeRejected, Rejection: DeliveryRejectionPermanent, ProviderMessageID: testMessageID},
"permanent with next attempt": {At: after(20), Outcome: DeliveryOutcomeRejected, Rejection: DeliveryRejectionPermanent, NextAttemptAt: after(30)},
"temporary without next": {At: after(20), Outcome: DeliveryOutcomeRejected, Rejection: DeliveryRejectionTemporary},
"next before the attempt": {At: after(20), Outcome: DeliveryOutcomeRejected, Rejection: DeliveryRejectionTemporary, NextAttemptAt: after(15)},
"unknown with a rejection": {At: after(20), Outcome: DeliveryOutcomeUnknown, Rejection: DeliveryRejectionTemporary},
"provider free text": {At: after(20), Outcome: DeliveryOutcomeUnknown, ProviderCode: "Upstream said: no"},
"negative retry-after": {At: after(20), Outcome: DeliveryOutcomeUnknown, RetryAfter: -time.Second},
"oversized provider message ID": {At: after(20), Outcome: DeliveryOutcomeAccepted, ProviderMessageID: strings.Repeat("a", 129)},
}
for name, input := range tests {
t.Run(name, func(t *testing.T) {
if _, _, err := delivery.RecordAttempt(input); !errors.Is(err, ErrInvalidDelivery) {
t.Fatalf("RecordAttempt() error = %v, want ErrInvalidDelivery", err)
}
})
}
if _, _, err := (Delivery{}).RecordAttempt(DeliveryAttemptInput{At: after(20), Outcome: DeliveryOutcomeUnknown}); !errors.Is(err, ErrInvalidDelivery) {
t.Fatalf("RecordAttempt() on a zero delivery error = %v, want ErrInvalidDelivery", err)
}
}
func deliverySnapshot(delivery Delivery) DeliverySnapshot {
return DeliverySnapshot{
ID: delivery.ID(),
SourceEventID: delivery.SourceEventID(),
RecipientUserID: delivery.RecipientUserID(),
RecipientAddress: delivery.Recipient().Address(),
Content: delivery.Content(),
ProviderAccount: delivery.ProviderAccount(),
IdempotencyKey: delivery.IdempotencyKey(),
Status: delivery.Status(),
AttemptCount: delivery.AttemptCount(),
NextAttemptAt: delivery.NextAttemptAt(),
LastAttemptAt: delivery.LastAttemptAt(),
ProviderMessageID: delivery.ProviderMessageID(),
Version: delivery.Version(),
CreatedAt: delivery.CreatedAt(),
UpdatedAt: delivery.UpdatedAt(),
}
}
func TestRestoreDeliveryChecksTheStoredInvariants(t *testing.T) {
accepted := mustRecord(t, newTestDelivery(t), DeliveryAttemptInput{At: after(1), Outcome: DeliveryOutcomeAccepted, ProviderMessageID: testMessageID})
restored, err := RestoreDelivery(deliverySnapshot(accepted))
if err != nil {
t.Fatalf("RestoreDelivery() error = %v", err)
}
if restored.Status() != DeliveryStatusAccepted || restored.ProviderMessageID() != testMessageID ||
restored.Recipient().Normalized() != strings.ToLower(testDeliveryAddress) || restored.Version() != accepted.Version() {
t.Fatal("RestoreDelivery() did not keep the stored state")
}
tests := map[string]func(*DeliverySnapshot){
"unknown status": func(snapshot *DeliverySnapshot) { snapshot.Status = "sent" },
"accepted without message ID": func(snapshot *DeliverySnapshot) { snapshot.ProviderMessageID = "" },
"terminal with next attempt": func(snapshot *DeliverySnapshot) { snapshot.NextAttemptAt = after(5) },
"pending without next": func(snapshot *DeliverySnapshot) {
snapshot.Status, snapshot.ProviderMessageID = DeliveryStatusPending, ""
},
"attempts without last time": func(snapshot *DeliverySnapshot) { snapshot.LastAttemptAt = time.Time{} },
"zero version": func(snapshot *DeliverySnapshot) { snapshot.Version = 0 },
"empty idempotency key": func(snapshot *DeliverySnapshot) { snapshot.IdempotencyKey = "" },
"updated before creation": func(snapshot *DeliverySnapshot) { snapshot.UpdatedAt = testDeliveryCreated.Add(-time.Second) },
"empty recipient": func(snapshot *DeliverySnapshot) { snapshot.RecipientAddress = "" },
}
for name, change := range tests {
t.Run(name, func(t *testing.T) {
snapshot := deliverySnapshot(accepted)
change(&snapshot)
if _, err := RestoreDelivery(snapshot); err == nil {
t.Fatal("RestoreDelivery() accepted a broken row")
}
})
}
}
func TestRestoreDeliveryAttemptChecksTheStatusAfter(t *testing.T) {
_, attempt, err := newTestDelivery(t).RecordAttempt(DeliveryAttemptInput{
At: after(1), Outcome: DeliveryOutcomeRejected, Rejection: DeliveryRejectionRateLimited, RetryAfter: 2 * time.Second, NextAttemptAt: after(2),
})
if err != nil {
t.Fatalf("RecordAttempt() error = %v", err)
}
if _, err := RestoreDeliveryAttempt(attempt); err != nil {
t.Fatalf("RestoreDeliveryAttempt() error = %v", err)
}
attempt.StatusAfter = DeliveryStatusRejected
if _, err := RestoreDeliveryAttempt(attempt); !errors.Is(err, ErrInvalidDelivery) {
t.Fatalf("RestoreDeliveryAttempt(mismatched status) error = %v, want ErrInvalidDelivery", err)
}
}
// deliveryHolder has the delivery in an unexported field, where fmt does not
// call its methods.
type deliveryHolder struct {
delivery Delivery
content MailContent
}
func TestDeliveryNeverPrintsTheRecipientOrContent(t *testing.T) {
delivery := newTestDelivery(t)
holder := deliveryHolder{delivery: delivery, content: delivery.Content()}
var output bytes.Buffer
for _, format := range []string{"%v", "%+v", "%#v", "%s", "%q"} {
fmt.Fprintf(&output, format+"\n", delivery)
fmt.Fprintf(&output, format+"\n", delivery.Content())
}
// For an enclosing struct fmt prints the pointer fields as addresses with
// the value verbs. Other verbs report a bad verb with the pointee, the
// known limit shared with EmailAddress and SecretToken.
for _, format := range []string{"%v", "%+v", "%#v"} {
fmt.Fprintf(&output, format+"\n", holder)
fmt.Fprintf(&output, format+"\n", &holder)
}
for _, logger := range []*slog.Logger{
slog.New(slog.NewTextHandler(&output, nil)),
slog.New(slog.NewJSONHandler(&output, nil)),
} {
logger.Info("delivery", "delivery", delivery, "content", delivery.Content(), "holder", holder)
}
printed := output.String()
for _, secret := range []string{
testDeliveryAddress, strings.ToLower(testDeliveryAddress), testDeliverySubject, "SyntheticToken", "private detail",
delivery.RecipientUserID().String(),
} {
if strings.Contains(printed, secret) {
t.Fatalf("printed delivery contains %q:\n%s", secret, printed)
}
}
for _, expected := range []string{delivery.ID().String(), "verification.v1", "pending", "resend"} {
if !strings.Contains(printed, expected) {
t.Fatalf("printed delivery lacks the bounded field %q:\n%s", expected, printed)
}
}
}
func TestNewDeliveryKeepsTheSourceEvent(t *testing.T) {
input := testDeliveryInput(t)
if delivery := newTestDelivery(t); delivery.SourceEventID() != uuid.Nil {
t.Fatal("a delivery without a source event names one")
}
input.SourceEventID = uuid.MustParse("01926f3a-7c00-7000-8000-0000000000ee")
delivery, err := NewDelivery(input)
if err != nil || delivery.SourceEventID() != input.SourceEventID {
t.Fatalf("NewDelivery() = %v, %v; want the source event kept", delivery, err)
}
restored, err := RestoreDelivery(deliverySnapshot(delivery))
if err != nil || restored.SourceEventID() != input.SourceEventID {
t.Fatalf("RestoreDelivery() = %v, %v; want the source event kept", restored, err)
}
}
func TestWaitForQuotaParksWithoutAnAttempt(t *testing.T) {
pending := newTestDelivery(t)
for name, until := range map[string]time.Time{"known reset": after(60), "unknown reset": {}} {
t.Run(name, func(t *testing.T) {
waiting, err := pending.WaitForQuota(after(1), until)
if err != nil {
t.Fatalf("WaitForQuota() error = %v", err)
}
if waiting.Status() != DeliveryStatusWaitingQuota || !waiting.NextAttemptAt().Equal(until) ||
waiting.AttemptCount() != 0 || waiting.Version() != 2 || !waiting.UpdatedAt().Equal(after(1)) {
t.Fatalf("waiting delivery = %s due %s with %d attempts at version %d", waiting.Status(), waiting.NextAttemptAt(), waiting.AttemptCount(), waiting.Version())
}
if _, err := RestoreDelivery(deliverySnapshot(waiting)); err != nil {
t.Fatalf("RestoreDelivery(waiting) error = %v", err)
}
// A later decision may move the reset again.
if moved, err := waiting.WaitForQuota(after(2), after(90)); err != nil || !moved.NextAttemptAt().Equal(after(90)) {
t.Fatalf("second WaitForQuota() = %s, %v", moved.NextAttemptAt(), err)
}
})
}
unknown := mustRecord(t, pending, DeliveryAttemptInput{At: after(1), Outcome: DeliveryOutcomeUnknown})
accepted := mustRecord(t, pending, DeliveryAttemptInput{At: after(1), Outcome: DeliveryOutcomeAccepted, ProviderMessageID: testMessageID})
for name, delivery := range map[string]Delivery{"unknown": unknown, "accepted": accepted} {
if _, err := delivery.WaitForQuota(after(5), after(60)); !errors.Is(err, ErrDeliveryTransition) {
t.Fatalf("WaitForQuota() on %s error = %v, want ErrDeliveryTransition", name, err)
}
}
for name, times := range map[string][2]time.Time{
"reset before the decision": {after(5), after(4)},
"decision before the change": {testDeliveryCreated.Add(-time.Minute), after(4)},
"zero decision time": {{}, after(4)},
} {
if _, err := pending.WaitForQuota(times[0], times[1]); !errors.Is(err, ErrInvalidDelivery) {
t.Fatalf("WaitForQuota() with %s error = %v, want ErrInvalidDelivery", name, err)
}
}
// An attempt after the wait must not precede the wait.
waiting, err := pending.WaitForQuota(after(10), time.Time{})
if err != nil {
t.Fatalf("WaitForQuota() error = %v", err)
}
if _, _, err := waiting.RecordAttempt(DeliveryAttemptInput{At: after(5), Outcome: DeliveryOutcomeUnknown}); !errors.Is(err, ErrInvalidDelivery) {
t.Fatalf("RecordAttempt() before the wait error = %v, want ErrInvalidDelivery", err)
}
}
func TestRebindIsAllowedOnlyBeforeTheFirstAttempt(t *testing.T) {
pending := newTestDelivery(t)
other, err := NewMailProviderAccount("resend", "eu")
if err != nil {
t.Fatalf("NewMailProviderAccount() error = %v", err)
}
rebound, err := pending.Rebind(after(1), other)
if err != nil {
t.Fatalf("Rebind() error = %v", err)
}
if rebound.ProviderAccount() != other || rebound.Version() != 2 || rebound.IdempotencyKey() != pending.IdempotencyKey() ||
rebound.Status() != DeliveryStatusPending || !rebound.NextAttemptAt().Equal(pending.NextAttemptAt()) {
t.Fatal("Rebind() changed more than the provider account and version")
}
if waiting, err := pending.WaitForQuota(after(1), time.Time{}); err != nil {
t.Fatalf("WaitForQuota() error = %v", err)
} else if _, err := waiting.Rebind(after(2), other); err != nil {
t.Fatalf("Rebind() of a waiting delivery without attempts error = %v", err)
}
if _, err := pending.Rebind(after(1), MailProviderAccount{}); !errors.Is(err, ErrInvalidDelivery) {
t.Fatalf("Rebind(zero account) error = %v, want ErrInvalidDelivery", err)
}
attempted := mustRecord(t, pending, DeliveryAttemptInput{At: after(1), Outcome: DeliveryOutcomeRejected, Rejection: DeliveryRejectionTemporary, NextAttemptAt: after(2)})
if _, err := attempted.Rebind(after(3), other); !errors.Is(err, ErrDeliveryTransition) {
t.Fatalf("Rebind() after an attempt error = %v, want ErrDeliveryTransition", err)
}
}
+214
View File
@@ -0,0 +1,214 @@
package domain
import (
"crypto/sha256"
"crypto/subtle"
"encoding/hex"
"errors"
"fmt"
"io"
"log/slog"
"regexp"
"strings"
"unicode/utf8"
)
const (
// maxMailSubjectRunes matches the rendered subject bound of the mail
// templates; a longer stored subject is not a rendering.
maxMailSubjectRunes = 150
// maxMailPartBytes bounds one stored body part. Rendered service mail is
// a few kilobytes; the bound keeps a broken renderer from filling a row.
maxMailPartBytes = 256 << 10
// MailContentHashSize is the size of the SHA-256 content digest.
MailContentHashSize = sha256.Size
)
var (
// ErrInvalidMailContent reports content that no transport could send or
// that does not belong to its kind. Errors name the rule, never the text.
ErrInvalidMailContent = errors.New("invalid mail content")
// ErrMailContentIntegrity reports stored content whose parts no longer
// match the stored digest: the row was changed outside the application.
ErrMailContentIntegrity = errors.New("mail content does not match its hash")
// "<kind>.v<N>", the template version naming of the mail templates.
mailTemplateVersionPattern = regexp.MustCompile(`^[a-z][a-z_]*\.v[1-9][0-9]{0,8}$`)
)
// MailKind names what a message is for. The values equal the template kinds
// of the mail templates.
type MailKind string
const (
MailKindVerification MailKind = "verification"
MailKindPasswordReset MailKind = "password_reset"
MailKindNotification MailKind = "notification"
)
// ParseMailKind accepts a known kind.
func ParseMailKind(value string) (MailKind, error) {
switch kind := MailKind(value); kind {
case MailKindVerification, MailKindPasswordReset, MailKindNotification:
return kind, nil
default:
return "", fmt.Errorf("domain.ParseMailKind - unknown mail kind: %w", ErrInvalidMailContent)
}
}
// CarriesBearerToken reports kinds whose body holds a one-time bearer token
// in a link. Their stored bodies are secrets until the token expires.
func (kind MailKind) CarriesBearerToken() bool {
return kind == MailKindVerification || kind == MailKindPasswordReset
}
// MailContentHash is SHA-256 over the template version, subject, text part,
// and HTML part, each encoded as a netstring ("<len>:<part>,"), so moving
// bytes from one part to the next changes the digest. The mail templates and
// stored deliveries use this one definition.
func MailContentHash(templateVersion, subject, text, html string) [MailContentHashSize]byte {
digest := sha256.New()
for _, part := range []string{templateVersion, subject, text, html} {
// hash.Hash.Write never returns an error.
_, _ = fmt.Fprintf(digest, "%d:", len(part))
_, _ = io.WriteString(digest, part)
_, _ = io.WriteString(digest, ",")
}
var sum [MailContentHashSize]byte
copy(sum[:], digest.Sum(nil))
return sum
}
// MailContent is one immutable rendered message: its kind, template version,
// subject, plain-text part, HTML part, and content hash. A body of a kind
// that CarriesBearerToken holds a live token.
//
// The parts sit behind a pointer with read-only accessors, so printing an
// enclosing struct shows only an address. String, GoString, Format, and
// LogValue show the kind, version, and hash, never the subject or bodies.
type MailContent struct {
value *mailContentValue
}
type mailContentValue struct {
kind MailKind
templateVersion string
subject string
text string
html string
hash [MailContentHashSize]byte
}
// NewMailContent validates a rendering and computes its hash. The template
// version must name the kind ("<kind>.v<N>"), the subject must be one line
// of 1 to 150 characters, and at least one body part must be non-blank.
func NewMailContent(kind MailKind, templateVersion, subject, text, html string) (MailContent, error) {
if _, err := ParseMailKind(string(kind)); err != nil {
return MailContent{}, fmt.Errorf("domain.NewMailContent - validate kind: %w", err)
}
if err := validateMailContent(kind, templateVersion, subject, text, html); err != nil {
return MailContent{}, err
}
return MailContent{value: &mailContentValue{
kind: kind,
templateVersion: templateVersion,
subject: subject,
text: text,
html: html,
hash: MailContentHash(templateVersion, subject, text, html),
}}, nil
}
// RestoreMailContent rebuilds stored content and checks it against the
// stored hash. A mismatch wraps ErrMailContentIntegrity.
func RestoreMailContent(kind MailKind, templateVersion, subject, text, html string, hash []byte) (MailContent, error) {
content, err := NewMailContent(kind, templateVersion, subject, text, html)
if err != nil {
return MailContent{}, fmt.Errorf("domain.RestoreMailContent - validate stored content: %w", err)
}
stored := content.value.hash
if subtle.ConstantTimeCompare(hash, stored[:]) != 1 {
return MailContent{}, fmt.Errorf("domain.RestoreMailContent - %w", ErrMailContentIntegrity)
}
return content, nil
}
func validateMailContent(kind MailKind, templateVersion, subject, text, html string) error {
switch {
case !mailTemplateVersionPattern.MatchString(templateVersion) || !strings.HasPrefix(templateVersion, string(kind)+".v"):
return invalidMailContent("template version must be <kind>.v<N> of the content kind")
case !utf8.ValidString(subject) || !utf8.ValidString(text) || !utf8.ValidString(html):
return invalidMailContent("subject and body parts must be valid UTF-8")
case strings.TrimSpace(subject) == "" || utf8.RuneCountInString(subject) > maxMailSubjectRunes:
return invalidMailContent(fmt.Sprintf("subject must have 1 to %d characters", maxMailSubjectRunes))
// A control character in the subject could inject header lines.
case strings.ContainsFunc(subject, isMailControlCharacter):
return invalidMailContent("subject must not contain control characters")
case strings.TrimSpace(text) == "" && strings.TrimSpace(html) == "":
return invalidMailContent("text or HTML part must not be blank")
case len(text) > maxMailPartBytes || len(html) > maxMailPartBytes:
return invalidMailContent("body parts must have at most 256 KiB each")
// PostgreSQL text cannot store NUL.
case strings.ContainsRune(text, 0) || strings.ContainsRune(html, 0):
return invalidMailContent("body parts must not contain NUL characters")
}
return nil
}
func isMailControlCharacter(character rune) bool {
return character < ' ' || character == 0x7f
}
func invalidMailContent(reason string) error {
return fmt.Errorf("domain.NewMailContent - %s: %w", reason, ErrInvalidMailContent)
}
// IsZero reports content not built by NewMailContent or RestoreMailContent.
func (content MailContent) IsZero() bool { return content.value == nil }
func (content MailContent) Kind() MailKind { return content.read().kind }
func (content MailContent) TemplateVersion() string { return content.read().templateVersion }
func (content MailContent) Subject() string { return content.read().subject }
// Text returns the plain-text part. It may hold a bearer token; never log it.
func (content MailContent) Text() string { return content.read().text }
// HTML returns the HTML part. It may hold a bearer token; never log it.
func (content MailContent) HTML() string { return content.read().html }
// Hash returns the SHA-256 content digest. It is not secret: a digest over a
// body that holds a 256-bit token cannot be reversed.
func (content MailContent) Hash() [MailContentHashSize]byte { return content.read().hash }
func (content MailContent) read() mailContentValue {
if content.value == nil {
return mailContentValue{}
}
return *content.value
}
func (content MailContent) String() string {
if content.value == nil {
return "[empty mail content]"
}
return fmt.Sprintf("[mail content %s %s, redacted]", content.value.templateVersion, hex.EncodeToString(content.value.hash[:]))
}
func (content MailContent) GoString() string { return content.String() }
// Format applies String to every verb; without it %+v would print the fields.
func (content MailContent) Format(state fmt.State, _ rune) {
_, _ = state.Write([]byte(content.String()))
}
func (content MailContent) LogValue() slog.Value {
value := content.read()
return slog.GroupValue(
slog.String("kind", string(value.kind)),
slog.String("template_version", value.templateVersion),
slog.String("content_hash", hex.EncodeToString(value.hash[:])),
)
}
+102
View File
@@ -0,0 +1,102 @@
package domain
import (
"errors"
"fmt"
"log/slog"
"strings"
"time"
"unicode/utf8"
"github.com/google/uuid"
)
const (
// Raw caller text is bounded before the template normalizes it; the
// rendered subject and body have tighter template limits.
maxMailRequestSubjectRunes = 1000
maxMailRequestBodyRunes = 16000
maxMailRequestLinkPathSize = 256
redactedNotificationText = "[redacted notification text]"
)
// ErrInvalidMailRequest reports a mail request that cannot be stored.
// Errors name the rule, never the text.
var ErrInvalidMailRequest = errors.New("invalid mail request")
// NotificationText is the caller text of a notification mail: the subject,
// the body, and a path inside the application for the link. It is personal
// data addressed to the recipient, so String, GoString, Format, LogValue,
// and MarshalJSON redact it.
type NotificationText struct {
Subject string
Body string
LinkPath string
}
func (text NotificationText) String() string { return redactedNotificationText }
func (text NotificationText) GoString() string { return redactedNotificationText }
// Format redacts every verb; without it %+v would print the fields.
func (text NotificationText) Format(state fmt.State, _ rune) {
_, _ = state.Write([]byte(redactedNotificationText))
}
func (text NotificationText) LogValue() slog.Value { return slog.StringValue(redactedNotificationText) }
// MarshalJSON redacts the text, because slog and other encoders reach a
// nested struct through encoding/json. Nothing serializes the text as JSON.
func (text NotificationText) MarshalJSON() ([]byte, error) {
return []byte(`"` + redactedNotificationText + `"`), nil
}
// MailRequest is a stored request for one mail to one account. It lives in
// the database only until the delivery consumer turned it into a Delivery,
// so the event that announces it carries the request ID and no text.
// Deleting the account deletes a request that is still waiting.
type MailRequest struct {
ID uuid.UUID
RecipientUserID uuid.UUID
Kind MailKind
Notification NotificationText
CreatedAt time.Time
}
// NewMailRequest checks the storage rules of a request. Only notification
// mail is requested this way: mail with a one-time token is created in the
// 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")
case request.Kind != MailKindNotification:
return MailRequest{}, invalidMailRequest("only notification mail can be requested")
case request.CreatedAt.IsZero():
return MailRequest{}, invalidMailRequest("creation time must be set")
case !utf8.ValidString(text.Subject) || !utf8.ValidString(text.Body) || !utf8.ValidString(text.LinkPath):
return MailRequest{}, 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")
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 request, nil
}
// LogValue carries the IDs and kind only.
func (request MailRequest) LogValue() slog.Value {
return slog.GroupValue(
slog.String("mail_request_id", request.ID.String()),
slog.String("kind", string(request.Kind)),
)
}
func invalidMailRequest(reason string) error {
return fmt.Errorf("domain.NewMailRequest - %s: %w", reason, ErrInvalidMailRequest)
}
@@ -0,0 +1,68 @@
package domain
import (
"bytes"
"errors"
"fmt"
"log/slog"
"strings"
"testing"
"time"
"github.com/google/uuid"
)
func testMailRequest() MailRequest {
return MailRequest{
ID: uuid.MustParse("01926f3a-7c00-7000-8000-000000000101"),
RecipientUserID: uuid.MustParse("01926f3a-7c00-7000-8000-000000000102"),
Kind: MailKindNotification,
Notification: NotificationText{Subject: "PRIVATE-SUBJECT", Body: "PRIVATE-BODY", LinkPath: "/candidate/invitations"},
CreatedAt: time.Date(2026, 10, 6, 9, 0, 0, 0, time.UTC),
}
}
func TestNewMailRequestChecksTheStorageRules(t *testing.T) {
if _, err := NewMailRequest(testMailRequest()); err != nil {
t.Fatalf("NewMailRequest() error = %v", err)
}
tests := map[string]func(*MailRequest){
"nil ID": func(request *MailRequest) { request.ID = uuid.Nil },
"nil recipient": func(request *MailRequest) { request.RecipientUserID = uuid.Nil },
"token mail kind": func(request *MailRequest) { request.Kind = MailKindVerification },
"zero creation time": func(request *MailRequest) { request.CreatedAt = time.Time{} },
"NUL in the body": func(request *MailRequest) { request.Notification.Body += "\x00" },
"invalid UTF-8": func(request *MailRequest) { request.Notification.Subject = "\xff" },
"oversized body": func(request *MailRequest) {
request.Notification.Body = strings.Repeat("я", maxMailRequestBodyRunes+1)
},
"oversized link": func(request *MailRequest) {
request.Notification.LinkPath = "/" + strings.Repeat("a", maxMailRequestLinkPathSize)
},
}
for name, change := range tests {
t.Run(name, func(t *testing.T) {
request := testMailRequest()
change(&request)
if _, err := NewMailRequest(request); !errors.Is(err, ErrInvalidMailRequest) {
t.Fatalf("NewMailRequest() error = %v, want ErrInvalidMailRequest", err)
}
})
}
}
func TestMailRequestNeverPrintsItsText(t *testing.T) {
request := testMailRequest()
var output bytes.Buffer
for _, format := range []string{"%v", "%+v", "%#v", "%s"} {
fmt.Fprintf(&output, format+"\n", request)
fmt.Fprintf(&output, format+"\n", &request)
}
type holder struct{ Request MailRequest }
for _, logger := range []*slog.Logger{slog.New(slog.NewJSONHandler(&output, nil)), slog.New(slog.NewTextHandler(&output, nil))} {
logger.Info("request", "request", request, "holder", holder{Request: request})
}
if printed := output.String(); strings.Contains(printed, "PRIVATE") {
t.Fatalf("printed mail request contains its text:\n%s", printed)
}
}
@@ -0,0 +1,94 @@
package outbound
import (
"context"
"errors"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
var (
// ErrDeliveryNotFound reports that no delivery has the ID.
ErrDeliveryNotFound = errors.New("delivery not found")
// ErrDeliveryVersionConflict reports that RecordAttempt matched no row:
// another worker recorded an attempt first, or the delivery no longer
// exists. Nothing was written; read the delivery again.
ErrDeliveryVersionConflict = errors.New("delivery changed concurrently")
// ErrDeliveryContentImmutable reports a statement that tried to change
// the recipient, content, provider account, or idempotency key of a
// stored delivery, or a recorded attempt. The database refuses it; it
// signals a code defect.
ErrDeliveryContentImmutable = errors.New("delivery content is immutable")
// ErrDeliveryProviderPinned reports a statement that tried to change the
// provider account of a delivery after its first attempt. The database
// refuses it; domain.Delivery.Rebind refuses it first.
ErrDeliveryProviderPinned = errors.New("delivery provider account is pinned")
// ErrMailRequestNotFound reports that no mail request has the ID: it was
// already turned into a delivery, or its account was deleted.
ErrMailRequestNotFound = errors.New("mail request not found")
)
// DeliveryRepository stores mail deliveries and their attempts. UnitOfWork
// binds it to one transaction; an adapter may also provide it outside a
// transaction, where every call is its own statement. Errors never quote the
// recipient or the content.
type DeliveryRepository interface {
// Create stores a delivery built by domain.NewDelivery and reports
// created=true. When a delivery with the same ID exists, it stores
// nothing, keeps the stored content, and reports created=false. It
// returns an error wrapping ErrUserNotFound when the recipient account
// does not exist; the surrounding transaction is then aborted.
Create(ctx context.Context, delivery domain.Delivery) (created bool, err error)
// Get returns ErrDeliveryNotFound when no delivery has the ID, and an
// error wrapping domain.ErrMailContentIntegrity when the stored content
// no longer matches its hash.
Get(ctx context.Context, id uuid.UUID) (domain.Delivery, error)
// ListAttempts returns the recorded attempts in attempt order; an empty
// list for a delivery without attempts or an unknown ID.
ListAttempts(ctx context.Context, id uuid.UUID) ([]domain.DeliveryAttempt, error)
// RecordAttempt stores next and attempt as returned by
// domain.Delivery.RecordAttempt, atomically, when the stored version
// still equals the version before the attempt (next.Version() - 1).
// Otherwise it writes nothing and returns ErrDeliveryVersionConflict.
RecordAttempt(ctx context.Context, next domain.Delivery, attempt domain.DeliveryAttempt) error
// WaitForQuota stores next as returned by domain.Delivery.WaitForQuota,
// without an attempt record, when the stored version still equals
// next.Version() - 1. Otherwise it returns ErrDeliveryVersionConflict.
WaitForQuota(ctx context.Context, next domain.Delivery) error
// Rebind stores the provider account of next as returned by
// domain.Delivery.Rebind under the same version rule as WaitForQuota. A
// delivery that has an attempt meanwhile fails with
// ErrDeliveryVersionConflict; the database refuses a provider change
// after an attempt with ErrDeliveryProviderPinned.
Rebind(ctx context.Context, next domain.Delivery) error
}
// MailRequestRepository stores mail requests between the producer
// transaction and the consumer transaction that turns them into deliveries.
// Errors never quote the request text.
type MailRequestRepository interface {
// Create stores a request built by domain.NewMailRequest. It returns an
// error wrapping ErrUserNotFound when the recipient account does not
// exist; the surrounding transaction is then aborted.
Create(ctx context.Context, request domain.MailRequest) error
// Lock reads the request and locks it until the transaction ends. A
// concurrent caller waits and then gets ErrMailRequestNotFound when the
// first transaction deleted it.
Lock(ctx context.Context, id uuid.UUID) (domain.MailRequest, error)
// Delete removes the request; deleting a missing request is not an
// error.
Delete(ctx context.Context, id uuid.UUID) error
}
+5 -4
View File
@@ -59,7 +59,7 @@ var (
// therefore calls InvalidateActive before UpdateRegistration or Insert; the
// opposite order can deadlock against a concurrent confirmation. The only
// exception is DeleteUnverifiedRegisteredBefore, which locks the account
// before its tokens and sessions; it is safe because every lock it takes uses
// before its tokens, sessions, and deliveries; it is safe because every lock it takes uses
// SKIP LOCKED and never waits. A deadlock that still happens, for example
// between callers that ignore this order, aborts one transaction with
// ErrTransactionConflict, and the caller may retry it.
@@ -99,9 +99,10 @@ type UserRepository interface {
// DeleteUnverifiedRegisteredBefore deletes at most limit accounts that are
// unverified and were last registered before cutoff, oldest first, with
// their tokens and sessions, and returns how many it deleted. It never
// waits for a lock: an account whose row, token, or session is locked by
// another transaction is skipped and stays for the next run. A cleanup job
// their tokens, sessions, and mail deliveries, and returns how many it
// deleted. It never waits for a lock: an account whose row, token,
// session, or delivery is locked by another transaction is skipped and
// stays for the next run. A cleanup job
// repeats it until the result is below limit and runs again later.
DeleteUnverifiedRegisteredBefore(ctx context.Context, cutoff time.Time, limit int32) (int64, error)
}
@@ -50,6 +50,8 @@ type Transactor interface {
type UnitOfWork interface {
IdentityRepositories
Policies() PolicyRepository
Deliveries() DeliveryRepository
MailRequests() MailRequestRepository
Outbox() OutboxWriter
}
@@ -0,0 +1,199 @@
package notification
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/notification/mailtemplate"
)
// DeliveryConsumerName names the consumer group and scopes deduplication.
// Renaming it makes the consumer process every retained request again; the
// delivery IDs then keep the deliveries unique, but do not rename it lightly.
const DeliveryConsumerName = "notification_delivery"
// DeliveryHandler creates one Delivery for each notification.mail_requested
// event, in the consumer transaction that records the event as processed.
//
// The delivery ID is the request ID, so a duplicate event, a replayed dead
// letter, or a renamed consumer maps to the same delivery. The content is
// rendered once, here, and stored; a later template version does not change
// it. The request row is deleted in the same transaction, so its text lives
// only as long as it is needed.
type DeliveryHandler struct {
renderer NotificationRenderer
providerAccount domain.MailProviderAccount
clock func() time.Time
logger *slog.Logger
}
var _ inbound.EventHandler = (*DeliveryHandler)(nil)
// NewDeliveryHandler pins new deliveries to providerAccount, the transport
// and account configured when the event is handled. clock is the
// application clock for the creation time.
func NewDeliveryHandler(
renderer NotificationRenderer,
providerAccount domain.MailProviderAccount,
clock func() time.Time,
logger *slog.Logger,
) *DeliveryHandler {
return &DeliveryHandler{renderer: renderer, providerAccount: providerAccount, clock: clock, logger: logger}
}
func (*DeliveryHandler) ConsumerName() string { return DeliveryConsumerName }
func (*DeliveryHandler) Handles(eventType string) bool { return eventType == MailRequestedEventType }
// Handle turns the request into a delivery:
//
// - A request that breaks the event contract, data the template refuses,
// or an existing delivery under the same ID for another recipient or
// kind is rejected for good (inbound.ErrEventRejected).
// - A request that no longer exists, because it was already turned into a
// delivery or its account was deleted, is skipped.
// - A notification to an account whose address is not verified is skipped
// and its request deleted: notifications go only to confirmed addresses.
// - Storage errors are returned for a retry. That includes an account
// deleted after it was read, which aborts the insert; the retry then
// finds the request gone with the account and skips it.
//
// Errors and logs carry the delivery and event IDs, never the address or
// the notification text.
func (handler *DeliveryHandler) Handle(ctx context.Context, unit outbound.UnitOfWork, event outbound.ConsumedEvent) error {
const location = "DeliveryHandler.Handle"
payload, err := decodeMailRequest(event)
if err != nil {
return err
}
request, err := unit.MailRequests().Lock(ctx, payload.MailRequestID)
if errors.Is(err, outbound.ErrMailRequestNotFound) {
handler.logSkip(ctx, "mail request skipped because it was already handled or its account was deleted", event)
return nil
}
if err != nil {
return fmt.Errorf("%s - lock mail request: %w", location, err)
}
if string(request.Kind) != payload.Kind {
return fmt.Errorf("%s - event kind does not match the stored request: %w", location, inbound.ErrEventRejected)
}
recipient, err := unit.Users().GetByID(ctx, request.RecipientUserID)
if errors.Is(err, outbound.ErrUserNotFound) {
// The foreign key deletes a request with its account, so this is a
// defensive branch.
handler.logSkip(ctx, "mail request skipped because the recipient account does not exist", event)
return handler.finish(ctx, unit, request.ID)
}
if err != nil {
return fmt.Errorf("%s - read recipient account: %w", location, err)
}
if recipient.EmailVerifiedAt == nil {
handler.logSkip(ctx, "notification skipped because the recipient address is not verified", event)
return handler.finish(ctx, unit, request.ID)
}
content, err := handler.renderer.RenderNotification(mailtemplate.NotificationData{
Subject: request.Notification.Subject,
Body: request.Notification.Body,
LinkPath: request.Notification.LinkPath,
})
if errors.Is(err, mailtemplate.ErrInvalidTemplateData) || errors.Is(err, domain.ErrInvalidMailContent) {
return fmt.Errorf("%s - render notification: %w: %w", location, inbound.ErrEventRejected, err)
}
if err != nil {
return fmt.Errorf("%s - render notification: %w", location, err)
}
delivery, err := domain.NewDelivery(domain.NewDeliveryInput{
ID: request.ID,
SourceEventID: event.EventID,
RecipientUserID: recipient.ID,
Recipient: recipient.Email,
Content: content,
ProviderAccount: handler.providerAccount,
CreatedAt: handler.clock(),
})
if err != nil {
return fmt.Errorf("%s - build delivery: %w: %w", location, inbound.ErrEventRejected, err)
}
created, err := unit.Deliveries().Create(ctx, delivery)
if err != nil {
return fmt.Errorf("%s - store delivery: %w", location, err)
}
if !created {
if err := checkExistingDelivery(ctx, unit, request); err != nil {
return err
}
}
return handler.finish(ctx, unit, request.ID)
}
// checkExistingDelivery accepts a delivery stored earlier under the request
// ID only when it is for the same recipient and kind; its content stays as
// stored.
func checkExistingDelivery(ctx context.Context, unit outbound.UnitOfWork, request domain.MailRequest) error {
const location = "notification.checkExistingDelivery"
existing, err := unit.Deliveries().Get(ctx, request.ID)
if err != nil {
return fmt.Errorf("%s - read existing delivery: %w", location, err)
}
if existing.RecipientUserID() != request.RecipientUserID || existing.Kind() != request.Kind {
return fmt.Errorf("%s - a delivery for another recipient or kind has the request ID: %w", location, inbound.ErrEventRejected)
}
return nil
}
// finish deletes the handled request in the consumer transaction.
func (handler *DeliveryHandler) finish(ctx context.Context, unit outbound.UnitOfWork, requestID uuid.UUID) error {
if err := unit.MailRequests().Delete(ctx, requestID); err != nil {
return fmt.Errorf("DeliveryHandler.finish - delete mail request: %w", err)
}
return nil
}
func (handler *DeliveryHandler) logSkip(ctx context.Context, message string, event outbound.ConsumedEvent) {
handler.logger.InfoContext(ctx, message,
slog.String("delivery_id", event.AggregateID.String()),
slog.String("event_id", event.EventID.String()))
}
// decodeMailRequest checks the envelope and payload of a version 1 request.
// Errors name the broken rule and never quote the payload.
func decodeMailRequest(event outbound.ConsumedEvent) (mailRequestedPayload, error) {
const location = "notification.decodeMailRequest"
rejected := func(reason string) error {
return fmt.Errorf("%s - %s: %w", location, reason, inbound.ErrEventRejected)
}
if event.SchemaVersion != mailRequestedSchemaVersion {
return mailRequestedPayload{}, rejected(fmt.Sprintf("schema version %d is not supported", event.SchemaVersion))
}
if event.AggregateType != mailRequestAggregateType || event.AggregateID == uuid.Nil {
return mailRequestedPayload{}, rejected("aggregate must be a mail_request with an ID")
}
var payload mailRequestedPayload
decoder := json.NewDecoder(bytes.NewReader(event.Payload))
// The decoder error can quote a fragment of the payload, so it is not
// wrapped. A second value after the object is refused as well.
if err := decoder.Decode(&payload); err != nil {
return mailRequestedPayload{}, rejected("payload is not a valid mail request")
}
if _, err := decoder.Token(); !errors.Is(err, io.EOF) {
return mailRequestedPayload{}, rejected("payload has data after the mail request")
}
switch {
case payload.MailRequestID != event.AggregateID:
return mailRequestedPayload{}, rejected("mail_request_id must equal the aggregate ID")
case payload.Kind != string(domain.MailKindNotification):
return mailRequestedPayload{}, rejected("kind must be notification in schema version 1")
}
return payload, nil
}
@@ -0,0 +1,148 @@
// Package notification turns mail requests into durable deliveries.
//
// A product usecase requests a notification mail inside its own transaction
// with MailRequester, which stores the request text in mail_requests and
// appends a notification.mail_requested event that names only the request.
// DeliveryHandler consumes the event and, in the transaction of the
// consumer's dedup marker, reads the request, resolves the recipient address
// from the account, renders the current template version once, stores the
// Delivery, and deletes the request. Sending the stored content is the job
// of the delivery worker, which is planned.
package notification
import (
"context"
"encoding/json"
"fmt"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/notification/mailtemplate"
)
const (
// MailRequestedEventType announces a stored mail request.
MailRequestedEventType = "notification.mail_requested"
// mailRequestedSchemaVersion 1 is mailRequestedPayload.
mailRequestedSchemaVersion = 1
// mailRequestAggregateType names the request. Its aggregate ID is the
// request ID and the ID of the delivery it becomes; a request is never
// changed, so its version is 1.
mailRequestAggregateType = "mail_request"
mailRequestAggregateVersion = 1
)
// mailRequestedPayload is version 1 of the event payload. It names the
// request and its kind only. The text and the recipient stay in
// mail_requests, which the account's deletion removes, so neither the
// outbox table nor the event bus keeps personal data after the account is
// gone.
type mailRequestedPayload struct {
MailRequestID uuid.UUID `json:"mail_request_id"`
Kind string `json:"kind"`
}
// NotificationRenderer renders notification mail as the content a delivery
// stores.
type NotificationRenderer interface {
RenderNotification(data mailtemplate.NotificationData) (domain.MailContent, error)
}
// TemplateRenderer renders with the current versions of the embedded mail
// templates.
type TemplateRenderer struct {
renderer *mailtemplate.Renderer
}
func NewTemplateRenderer(renderer *mailtemplate.Renderer) TemplateRenderer {
return TemplateRenderer{renderer: renderer}
}
func (renderer TemplateRenderer) RenderNotification(data mailtemplate.NotificationData) (domain.MailContent, error) {
rendered, err := renderer.renderer.RenderNotification(data)
if err != nil {
return domain.MailContent{}, fmt.Errorf("TemplateRenderer.RenderNotification - render: %w", err)
}
content, err := rendered.Content()
if err != nil {
return domain.MailContent{}, fmt.Errorf("TemplateRenderer.RenderNotification - convert rendering: %w", err)
}
return content, nil
}
// NotificationRequest asks for one notification mail to one account.
type NotificationRequest struct {
RecipientUserID uuid.UUID
Notification mailtemplate.NotificationData
}
// MailRequester records mail requests in the caller's transaction.
type MailRequester struct {
renderer NotificationRenderer
clock func() time.Time
}
// NewMailRequester takes the renderer only to refuse data that the template
// would refuse at handling time, so a bad request fails its own transaction
// instead of becoming a dead letter later. clock is the application clock
// for the request time.
func NewMailRequester(renderer NotificationRenderer, clock func() time.Time) *MailRequester {
return &MailRequester{renderer: renderer, clock: clock}
}
// RequestNotification stores the request and appends a
// notification.mail_requested event through unit, which must be the caller's
// transaction, and returns the ID that the delivery will have. The mail is
// created only if that transaction commits. Invalid input returns an error
// wrapping domain.ErrInvalidMailRequest and writes nothing; an unknown
// recipient account returns an error wrapping outbound.ErrUserNotFound and
// aborts the transaction.
func (requester *MailRequester) RequestNotification(ctx context.Context, unit outbound.UnitOfWork, request NotificationRequest) (uuid.UUID, error) {
const location = "MailRequester.RequestNotification"
if _, err := requester.renderer.RenderNotification(request.Notification); err != nil {
return uuid.Nil, fmt.Errorf("%s - validate notification: %w: %w", location, domain.ErrInvalidMailRequest, err)
}
requestID, err := uuid.NewV7()
if err != nil {
return uuid.Nil, fmt.Errorf("%s - generate request ID: %w", location, err)
}
stored, err := domain.NewMailRequest(domain.MailRequest{
ID: requestID,
RecipientUserID: request.RecipientUserID,
Kind: domain.MailKindNotification,
Notification: domain.NotificationText{
Subject: request.Notification.Subject,
Body: request.Notification.Body,
LinkPath: request.Notification.LinkPath,
},
CreatedAt: requester.clock(),
})
if err != nil {
return uuid.Nil, fmt.Errorf("%s - build request: %w", location, err)
}
payload, err := json.Marshal(mailRequestedPayload{MailRequestID: requestID, Kind: string(domain.MailKindNotification)})
if err != nil {
return uuid.Nil, fmt.Errorf("%s - encode payload: %w", location, err)
}
event, err := domain.NewDomainEvent(domain.DomainEventInput{
EventType: MailRequestedEventType,
SchemaVersion: mailRequestedSchemaVersion,
AggregateType: mailRequestAggregateType,
AggregateID: requestID,
AggregateVersion: mailRequestAggregateVersion,
Payload: payload,
})
if err != nil {
return uuid.Nil, fmt.Errorf("%s - build event: %w", location, err)
}
if err := unit.MailRequests().Create(ctx, stored); err != nil {
return uuid.Nil, fmt.Errorf("%s - store request: %w", location, err)
}
if err := unit.Outbox().Append(ctx, event); err != nil {
return uuid.Nil, fmt.Errorf("%s - append event: %w", location, err)
}
return requestID, nil
}
@@ -1,7 +1,6 @@
package mailtemplate
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"log/slog"
@@ -15,7 +14,7 @@ import (
// the same digest, and any change to any part gives another one. The delivery
// layer can store it with the idempotency key to pin the body of one logical
// delivery and to detect a different body offered under the same key.
type ContentHash [sha256.Size]byte
type ContentHash [domain.MailContentHashSize]byte
// String returns the lowercase hex digest. It is not secret: SHA-256 over a
// body that holds a 256-bit token cannot be reversed.
@@ -50,7 +49,7 @@ func newRenderedMail(kind Kind, version TemplateVersion, subject, text, html str
subject: subject,
text: text,
html: html,
contentHash: contentHash(string(version), subject, text, html),
contentHash: ContentHash(domain.MailContentHash(string(version), subject, text, html)),
}}
}
@@ -78,6 +77,18 @@ func (mail RenderedMail) read() renderedContent {
return *mail.content
}
// Content returns the rendering as domain.MailContent, the form a delivery
// stores. The kinds and the hash are the same: both use
// domain.MailContentHash.
func (mail RenderedMail) Content() (domain.MailContent, error) {
content := mail.read()
stored, err := domain.NewMailContent(domain.MailKind(content.kind), string(content.version), content.subject, content.text, content.html)
if err != nil {
return domain.MailContent{}, fmt.Errorf("RenderedMail.Content - %w", err)
}
return stored, nil
}
// ToOutgoingMail addresses the rendering for the MailSender port. The
// recipient and the idempotency key come from the delivery, never from the
// template data.
@@ -13,7 +13,6 @@ package mailtemplate
import (
"bytes"
"crypto/sha256"
"embed"
"errors"
"fmt"
@@ -172,21 +171,6 @@ func finishPart(part string) string {
return strings.TrimSpace(part) + "\n"
}
// contentHash is SHA-256 over the parts encoded as netstrings ("<len>:<part>,"),
// so moving bytes from one part to the next changes the digest.
func contentHash(parts ...string) ContentHash {
digest := sha256.New()
for _, part := range parts {
// hash.Hash.Write never returns an error.
_, _ = fmt.Fprintf(digest, "%d:", len(part))
_, _ = io.WriteString(digest, part)
_, _ = io.WriteString(digest, ",")
}
var sum ContentHash
copy(sum[:], digest.Sum(nil))
return sum
}
// parseTemplates reads every file in the template directory. Each version
// must provide the subject, text, and HTML parts, and no other file may be
// present, so a misnamed file cannot be silently ignored.
@@ -306,9 +306,20 @@ func TestContentHashPinsTheBody(t *testing.T) {
if mail.ContentHash() != second[kind].ContentHash() {
t.Fatalf("%s content hash differs for the same version and data", kind)
}
if mail.ContentHash() != contentHash(string(mail.TemplateVersion()), mail.Subject(), mail.Text(), mail.HTML()) {
if mail.ContentHash() != ContentHash(domain.MailContentHash(string(mail.TemplateVersion()), mail.Subject(), mail.Text(), mail.HTML())) {
t.Fatalf("%s content hash does not cover the version, subject, and parts", kind)
}
// A delivery stores the rendering as domain.MailContent; both forms
// must name the same kind, version, parts, and hash.
content, err := mail.Content()
if err != nil {
t.Fatalf("%s Content() error = %v", kind, err)
}
if string(content.Kind()) != string(kind) || content.TemplateVersion() != string(mail.TemplateVersion()) ||
content.Subject() != mail.Subject() || content.Text() != mail.Text() || content.HTML() != mail.HTML() ||
ContentHash(content.Hash()) != mail.ContentHash() {
t.Fatalf("%s Content() does not carry the rendering", kind)
}
seen[mail.ContentHash()] = kind
}
if len(seen) != len(first) {
@@ -350,19 +361,6 @@ func TestContentHashPinsTheBody(t *testing.T) {
t.Fatalf("content hash did not change with the %s", change.name)
}
}
base := contentHash("verification.v1", "subject", "text", "html")
for name, other := range map[string]ContentHash{
"version": contentHash("verification.v2", "subject", "text", "html"),
"subject": contentHash("verification.v1", "subject!", "text", "html"),
"text": contentHash("verification.v1", "subject", "text!", "html"),
"html": contentHash("verification.v1", "subject", "text", "html!"),
"shifted border": contentHash("verification.v1", "subjec", "ttext", "html"),
} {
if other == base {
t.Fatalf("content hash ignores a change of the %s", name)
}
}
}
// TestRenderingNeverReachesLogs plays the render harness: it prints every
@@ -0,0 +1,453 @@
package notification
import (
"bytes"
"context"
"encoding/json"
"errors"
"log/slog"
"strings"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/notification/mailtemplate"
)
const (
testOrigin = "https://lincodex.example"
// The private markers must never reach logs, errors, or events.
testRecipientAddress = "Private.Recipient@Example.com"
testSubject = "PRIVATE-SUBJECT invitation"
testBody = "PRIVATE-BODY: a company invited you."
testLinkPath = "/candidate/invitations"
)
var (
testNow = time.Date(2026, 10, 6, 12, 0, 0, 0, time.UTC)
errStorageDown = errors.New("storage unavailable")
privateMarkers = []string{testRecipientAddress, strings.ToLower(testRecipientAddress), "PRIVATE-SUBJECT", "PRIVATE-BODY"}
)
type fakeUsers struct {
outbound.UserRepository
users map[uuid.UUID]domain.User
err error
}
func (users *fakeUsers) GetByID(_ context.Context, id uuid.UUID) (domain.User, error) {
if users.err != nil {
return domain.User{}, users.err
}
user, ok := users.users[id]
if !ok {
return domain.User{}, outbound.ErrUserNotFound
}
return user, nil
}
type fakeDeliveries struct {
outbound.DeliveryRepository
stored map[uuid.UUID]domain.Delivery
createErr error
}
func (deliveries *fakeDeliveries) Create(_ context.Context, delivery domain.Delivery) (bool, error) {
if deliveries.createErr != nil {
return false, deliveries.createErr
}
if _, ok := deliveries.stored[delivery.ID()]; ok {
return false, nil
}
deliveries.stored[delivery.ID()] = delivery
return true, nil
}
func (deliveries *fakeDeliveries) Get(_ context.Context, id uuid.UUID) (domain.Delivery, error) {
delivery, ok := deliveries.stored[id]
if !ok {
return domain.Delivery{}, outbound.ErrDeliveryNotFound
}
return delivery, nil
}
type fakeMailRequests struct {
stored map[uuid.UUID]domain.MailRequest
createErr error
}
func (requests *fakeMailRequests) Create(_ context.Context, request domain.MailRequest) error {
if requests.createErr != nil {
return requests.createErr
}
requests.stored[request.ID] = request
return nil
}
func (requests *fakeMailRequests) Lock(_ context.Context, id uuid.UUID) (domain.MailRequest, error) {
request, ok := requests.stored[id]
if !ok {
return domain.MailRequest{}, outbound.ErrMailRequestNotFound
}
return request, nil
}
func (requests *fakeMailRequests) Delete(_ context.Context, id uuid.UUID) error {
delete(requests.stored, id)
return nil
}
type recordingOutbox struct {
events []domain.DomainEvent
err error
}
func (outbox *recordingOutbox) Append(_ context.Context, events ...domain.DomainEvent) error {
if outbox.err != nil {
return outbox.err
}
outbox.events = append(outbox.events, events...)
return nil
}
// fakeUnit implements the repositories the usecases use; any other call
// panics on the nil embedded interface.
type fakeUnit struct {
outbound.UnitOfWork
users *fakeUsers
deliveries *fakeDeliveries
requests *fakeMailRequests
outbox *recordingOutbox
}
func (unit fakeUnit) Users() outbound.UserRepository { return unit.users }
func (unit fakeUnit) Deliveries() outbound.DeliveryRepository { return unit.deliveries }
func (unit fakeUnit) MailRequests() outbound.MailRequestRepository { return unit.requests }
func (unit fakeUnit) Outbox() outbound.OutboxWriter { return unit.outbox }
type harness struct {
recipient domain.User
unit fakeUnit
handler *DeliveryHandler
requester *MailRequester
logs *bytes.Buffer
}
func newHarness(t *testing.T) *harness {
t.Helper()
renderer, err := mailtemplate.NewRenderer(testOrigin)
if err != nil {
t.Fatalf("NewRenderer() error = %v", err)
}
email, err := domain.NewEmailAddress(testRecipientAddress)
if err != nil {
t.Fatalf("NewEmailAddress() error = %v", err)
}
providerAccount, err := domain.NewMailProviderAccount("resend", "main")
if err != nil {
t.Fatalf("NewMailProviderAccount() error = %v", err)
}
verifiedAt := testNow.Add(-time.Hour)
recipient := domain.User{ID: uuid.MustParse("01926f3a-7c00-7000-8000-0000000000aa"), Email: email, EmailVerifiedAt: &verifiedAt}
logs := &bytes.Buffer{}
templates := NewTemplateRenderer(renderer)
clock := func() time.Time { return testNow }
return &harness{
recipient: recipient,
unit: fakeUnit{
users: &fakeUsers{users: map[uuid.UUID]domain.User{recipient.ID: recipient}},
deliveries: &fakeDeliveries{stored: make(map[uuid.UUID]domain.Delivery)},
requests: &fakeMailRequests{stored: make(map[uuid.UUID]domain.MailRequest)},
outbox: &recordingOutbox{},
},
handler: NewDeliveryHandler(templates, providerAccount, clock, slog.New(slog.NewJSONHandler(logs, nil))),
requester: NewMailRequester(templates, clock),
logs: logs,
}
}
func testNotification() mailtemplate.NotificationData {
return mailtemplate.NotificationData{Subject: testSubject, Body: testBody, LinkPath: testLinkPath}
}
// request records a notification request and returns its event as the
// consumer receives it from the event bus.
func (h *harness) request(t *testing.T) outbound.ConsumedEvent {
t.Helper()
before := len(h.unit.outbox.events)
requestID, err := h.requester.RequestNotification(t.Context(), h.unit, NotificationRequest{
RecipientUserID: h.recipient.ID,
Notification: testNotification(),
})
if err != nil {
t.Fatalf("RequestNotification() error = %v", err)
}
if len(h.unit.outbox.events) != before+1 || h.unit.outbox.events[before].AggregateID() != requestID {
t.Fatalf("RequestNotification() did not append one event for request %s", requestID)
}
return consumedEvent(h.unit.outbox.events[before])
}
func consumedEvent(event domain.DomainEvent) outbound.ConsumedEvent {
return outbound.ConsumedEvent{
EventID: event.EventID(),
EventType: event.EventType(),
SchemaVersion: event.SchemaVersion(),
AggregateType: event.AggregateType(),
AggregateID: event.AggregateID(),
AggregateVersion: event.AggregateVersion(),
OccurredAt: testNow,
Payload: event.Payload(),
}
}
func (h *harness) assertNoPrivateData(t *testing.T, texts ...string) {
t.Helper()
for _, text := range append(texts, h.logs.String()) {
for _, marker := range privateMarkers {
if strings.Contains(text, marker) {
t.Fatalf("personal data %q reached an error, event, or log: %s", marker, text)
}
}
}
}
func TestRequestNotificationStoresTheTextAndAnnouncesOnlyIDs(t *testing.T) {
h := newHarness(t)
event := h.request(t)
if event.EventType != MailRequestedEventType || event.SchemaVersion != 1 ||
event.AggregateType != "mail_request" || event.AggregateVersion != 1 {
t.Fatalf("event = %s v%d %s/%d", event.EventType, event.SchemaVersion, event.AggregateType, event.AggregateVersion)
}
var payload map[string]any
if err := json.Unmarshal(event.Payload, &payload); err != nil {
t.Fatalf("decode payload: %v", err)
}
if len(payload) != 2 || payload["mail_request_id"] != event.AggregateID.String() || payload["kind"] != "notification" {
t.Fatalf("payload = %v, want only the request ID and the kind", payload)
}
h.assertNoPrivateData(t, string(event.Payload))
stored, ok := h.unit.requests.stored[event.AggregateID]
if !ok || stored.RecipientUserID != h.recipient.ID || stored.Kind != domain.MailKindNotification ||
stored.Notification.Subject != testSubject || stored.Notification.Body != testBody ||
stored.Notification.LinkPath != testLinkPath || !stored.CreatedAt.Equal(testNow) {
t.Fatal("the request text was not stored under the event's aggregate ID")
}
}
func TestRequestNotificationRefusesInvalidRequestsBeforeWriting(t *testing.T) {
h := newHarness(t)
hostileLink := testNotification()
hostileLink.LinkPath = "https://evil.example/phish"
nul := testNotification()
nul.Subject += "\x00"
tests := map[string]NotificationRequest{
"nil recipient": {Notification: testNotification()},
"link outside the app": {RecipientUserID: h.recipient.ID, Notification: hostileLink},
"empty notification": {RecipientUserID: h.recipient.ID},
"NUL in the subject": {RecipientUserID: h.recipient.ID, Notification: nul},
}
for name, request := range tests {
t.Run(name, func(t *testing.T) {
_, err := h.requester.RequestNotification(t.Context(), h.unit, request)
if !errors.Is(err, domain.ErrInvalidMailRequest) {
t.Fatalf("RequestNotification() error = %v, want ErrInvalidMailRequest", err)
}
if len(h.unit.outbox.events) != 0 || len(h.unit.requests.stored) != 0 {
t.Fatal("an invalid request was written")
}
h.assertNoPrivateData(t, err.Error())
})
}
h.unit.requests.createErr = outbound.ErrUserNotFound
_, err := h.requester.RequestNotification(t.Context(), h.unit, NotificationRequest{RecipientUserID: h.recipient.ID, Notification: testNotification()})
if !errors.Is(err, outbound.ErrUserNotFound) || len(h.unit.outbox.events) != 0 {
t.Fatalf("RequestNotification() for an unknown account error = %v, events = %d", err, len(h.unit.outbox.events))
}
}
func TestDeliveryHandlerStoresTheRenderedRequest(t *testing.T) {
h := newHarness(t)
event := h.request(t)
if h.handler.ConsumerName() != DeliveryConsumerName || !h.handler.Handles(event.EventType) || h.handler.Handles("identity.user_registered") {
t.Fatal("the handler does not claim exactly the mail request events")
}
if err := h.handler.Handle(t.Context(), h.unit, event); err != nil {
t.Fatalf("Handle() error = %v", err)
}
delivery, ok := h.unit.deliveries.stored[event.AggregateID]
if !ok || len(h.unit.deliveries.stored) != 1 {
t.Fatalf("Handle() stored %d deliveries, want one under the request ID", len(h.unit.deliveries.stored))
}
switch {
case delivery.SourceEventID() != event.EventID:
t.Fatal("the delivery does not name its source event")
case delivery.RecipientUserID() != h.recipient.ID || delivery.Recipient().Address() != testRecipientAddress:
t.Fatal("the delivery is not addressed to the account email")
case delivery.Kind() != domain.MailKindNotification || delivery.Content().TemplateVersion() != "notification.v1":
t.Fatalf("the delivery has kind %s and version %s", delivery.Kind(), delivery.Content().TemplateVersion())
case !strings.Contains(delivery.Content().Text(), "PRIVATE-BODY") || !strings.Contains(delivery.Content().Text(), testOrigin+testLinkPath):
t.Fatal("the stored body is not the rendering of the request")
case delivery.ProviderAccount().Provider() != "resend" || delivery.ProviderAccount().Account() != "main":
t.Fatal("the delivery is not pinned to the configured provider account")
case delivery.Status() != domain.DeliveryStatusPending || !delivery.CreatedAt().Equal(testNow):
t.Fatalf("the delivery is %s, created %s", delivery.Status(), delivery.CreatedAt())
}
if len(h.unit.requests.stored) != 0 {
t.Fatal("the handled request was not deleted")
}
// The same event again finds no request and keeps the first delivery.
if err := h.handler.Handle(t.Context(), h.unit, event); err != nil {
t.Fatalf("second Handle() error = %v", err)
}
if len(h.unit.deliveries.stored) != 1 {
t.Fatal("a repeated request created a second delivery")
}
h.assertNoPrivateData(t)
}
func TestDeliveryHandlerChecksAnExistingDeliveryUnderTheRequestID(t *testing.T) {
h := newHarness(t)
event := h.request(t)
request := h.unit.requests.stored[event.AggregateID]
// A delivery for the same recipient and kind is accepted as the result.
if err := h.handler.Handle(t.Context(), h.unit, event); err != nil {
t.Fatalf("Handle() error = %v", err)
}
h.unit.requests.stored[request.ID] = request
if err := h.handler.Handle(t.Context(), h.unit, event); err != nil {
t.Fatalf("Handle() over a matching delivery error = %v", err)
}
if len(h.unit.requests.stored) != 0 {
t.Fatal("the request was not deleted after the matching delivery")
}
// A delivery for another recipient under the same ID is a contract
// violation.
other := request
other.RecipientUserID = uuid.MustParse("01926f3a-7c00-7000-8000-0000000000bb")
h.unit.users.users[other.RecipientUserID] = domain.User{ID: other.RecipientUserID, Email: h.recipient.Email, EmailVerifiedAt: h.recipient.EmailVerifiedAt}
h.unit.requests.stored[request.ID] = other
err := h.handler.Handle(t.Context(), h.unit, event)
if !errors.Is(err, inbound.ErrEventRejected) {
t.Fatalf("Handle() over a delivery for another recipient error = %v, want ErrEventRejected", err)
}
h.assertNoPrivateData(t, err.Error())
}
func TestDeliveryHandlerRejectsBrokenRequestsWithoutQuotingThem(t *testing.T) {
h := newHarness(t)
valid := h.request(t)
tests := map[string]func(*outbound.ConsumedEvent){
"newer schema version": func(event *outbound.ConsumedEvent) { event.SchemaVersion = 2 },
"other aggregate": func(event *outbound.ConsumedEvent) { event.AggregateType = "user" },
"nil aggregate ID": func(event *outbound.ConsumedEvent) { event.AggregateID = uuid.Nil },
"payload not an object": func(event *outbound.ConsumedEvent) { event.Payload = json.RawMessage(`["PRIVATE-SUBJECT"]`) },
"trailing data": func(event *outbound.ConsumedEvent) {
event.Payload = append(append(json.RawMessage{}, event.Payload...), []byte(` {"PRIVATE-SUBJECT":1}`)...)
},
"request ID not the aggregate": func(event *outbound.ConsumedEvent) {
event.Payload = json.RawMessage(`{"mail_request_id":"01926f3a-7c00-7000-8000-0000000000cc","kind":"notification"}`)
},
"request ID not a UUID": func(event *outbound.ConsumedEvent) {
event.Payload = json.RawMessage(`{"mail_request_id":"PRIVATE-SUBJECT","kind":"notification"}`)
},
"token mail kind": func(event *outbound.ConsumedEvent) {
event.Payload = json.RawMessage(`{"mail_request_id":"` + event.AggregateID.String() + `","kind":"verification"}`)
},
}
for name, change := range tests {
t.Run(name, func(t *testing.T) {
event := valid
change(&event)
err := h.handler.Handle(t.Context(), h.unit, event)
if !errors.Is(err, inbound.ErrEventRejected) {
t.Fatalf("Handle() error = %v, want ErrEventRejected", err)
}
if len(h.unit.deliveries.stored) != 0 {
t.Fatal("a rejected request created a delivery")
}
h.assertNoPrivateData(t, err.Error())
})
}
t.Run("text the template refuses", func(t *testing.T) {
request := h.unit.requests.stored[valid.AggregateID]
request.Notification.LinkPath = "//evil.example/PRIVATE-SUBJECT"
h.unit.requests.stored[valid.AggregateID] = request
err := h.handler.Handle(t.Context(), h.unit, valid)
if !errors.Is(err, inbound.ErrEventRejected) || len(h.unit.deliveries.stored) != 0 {
t.Fatalf("Handle() error = %v, want ErrEventRejected and no delivery", err)
}
h.assertNoPrivateData(t, err.Error())
})
}
func TestDeliveryHandlerSkipsRequestsItMustNotDeliver(t *testing.T) {
tests := map[string]func(*harness, outbound.ConsumedEvent){
"request already gone": func(h *harness, event outbound.ConsumedEvent) {
delete(h.unit.requests.stored, event.AggregateID)
},
"account gone": func(h *harness, _ outbound.ConsumedEvent) {
delete(h.unit.users.users, h.recipient.ID)
},
"address not verified": func(h *harness, _ outbound.ConsumedEvent) {
unverified := h.recipient
unverified.EmailVerifiedAt = nil
h.unit.users.users[h.recipient.ID] = unverified
},
}
for name, change := range tests {
t.Run(name, func(t *testing.T) {
h := newHarness(t)
event := h.request(t)
change(h, event)
if err := h.handler.Handle(t.Context(), h.unit, event); err != nil {
t.Fatalf("Handle() error = %v, want the request skipped", err)
}
if len(h.unit.deliveries.stored) != 0 || len(h.unit.requests.stored) != 0 {
t.Fatal("a skipped request created a delivery or stayed stored")
}
if !strings.Contains(h.logs.String(), event.AggregateID.String()) || !strings.Contains(h.logs.String(), event.EventID.String()) {
t.Fatalf("the skip log does not name the delivery and event IDs: %s", h.logs.String())
}
h.assertNoPrivateData(t)
})
}
}
func TestDeliveryHandlerRetriesStorageFailures(t *testing.T) {
for name, change := range map[string]func(*fakeUnit){
"account read": func(unit *fakeUnit) { unit.users.err = errStorageDown },
"insert": func(unit *fakeUnit) { unit.deliveries.createErr = errStorageDown },
// The account was deleted between its read and the insert. The insert
// aborted the transaction, so the handler cannot skip here; the retry
// finds the request deleted with the account and skips it.
"account deleted before the insert": func(unit *fakeUnit) { unit.deliveries.createErr = outbound.ErrUserNotFound },
} {
t.Run(name, func(t *testing.T) {
h := newHarness(t)
event := h.request(t)
change(&h.unit)
err := h.handler.Handle(t.Context(), h.unit, event)
if err == nil || errors.Is(err, inbound.ErrEventRejected) {
t.Fatalf("Handle() error = %v, want a retryable storage error", err)
}
if len(h.unit.requests.stored) != 1 {
t.Fatal("a failed attempt deleted the request")
}
h.assertNoPrivateData(t, err.Error())
})
}
}