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