feat(identity): add server sessions and audited mail recovery
This commit is contained in:
1 parent
20c03288d6
commit
4ee53d9a74
58 files changed
+5359
-567
No files matched your search
@@ -141,7 +141,95 @@ func (repository deliveryRepository) Get(ctx context.Context, id uuid.UUID) (dom
|
||||
if err != nil {
|
||||
return domain.Delivery{}, fmt.Errorf("deliveryRepository.Get - select delivery: %w", mapDeliveryError(err))
|
||||
}
|
||||
return deliveryFromRow(row)
|
||||
return deliveryFromRow(sqlc.Delivery{
|
||||
ID: row.ID,
|
||||
SourceEventID: row.SourceEventID,
|
||||
RecipientUserID: row.RecipientUserID,
|
||||
RecipientEmail: row.RecipientEmail,
|
||||
Kind: row.Kind,
|
||||
TemplateVersion: row.TemplateVersion,
|
||||
Subject: row.Subject,
|
||||
TextBody: row.TextBody,
|
||||
HtmlBody: row.HtmlBody,
|
||||
ContentSha256: row.ContentSha256,
|
||||
Provider: row.Provider,
|
||||
ProviderAccount: row.ProviderAccount,
|
||||
IdempotencyKey: row.IdempotencyKey,
|
||||
Status: row.Status,
|
||||
AttemptCount: row.AttemptCount,
|
||||
NextAttemptAt: row.NextAttemptAt,
|
||||
LastAttemptAt: row.LastAttemptAt,
|
||||
ProviderMessageID: row.ProviderMessageID,
|
||||
Version: row.Version,
|
||||
CreatedAt: row.CreatedAt,
|
||||
UpdatedAt: row.UpdatedAt,
|
||||
EmailTokenID: row.EmailTokenID,
|
||||
CancelReason: row.CancelReason,
|
||||
ClaimOwner: row.ClaimOwner,
|
||||
ClaimedUntil: row.ClaimedUntil,
|
||||
FirstSendStartedAt: row.FirstSendStartedAt,
|
||||
FailureCount: row.FailureCount,
|
||||
BodyRedactedAt: row.BodyRedactedAt,
|
||||
})
|
||||
}
|
||||
|
||||
func (repository deliveryRepository) GetRetrySnapshot(ctx context.Context, id uuid.UUID) (outbound.DeliveryRetrySnapshot, error) {
|
||||
const location = "deliveryRepository.GetRetrySnapshot"
|
||||
row, err := repository.queries.GetDeliveryRetrySnapshot(ctx, pgUUID(id))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return outbound.DeliveryRetrySnapshot{}, fmt.Errorf("%s - select delivery: %w", location, outbound.ErrDeliveryNotFound)
|
||||
}
|
||||
if err != nil {
|
||||
return outbound.DeliveryRetrySnapshot{}, fmt.Errorf("%s - select delivery: %w", location, mapDeliveryError(err))
|
||||
}
|
||||
if _, err := domain.NewMailProviderAccount(row.Provider, row.ProviderAccount); err != nil {
|
||||
return outbound.DeliveryRetrySnapshot{}, fmt.Errorf("%s - decode provider account: %w", location, err)
|
||||
}
|
||||
status, err := domain.ParseDeliveryStatus(row.Status)
|
||||
if err != nil {
|
||||
return outbound.DeliveryRetrySnapshot{}, fmt.Errorf("%s - decode status: %w", location, err)
|
||||
}
|
||||
return outbound.DeliveryRetrySnapshot{
|
||||
ID: uuid.UUID(row.ID.Bytes),
|
||||
Provider: row.Provider,
|
||||
ProviderAccount: row.ProviderAccount,
|
||||
Status: status,
|
||||
AttemptCount: row.AttemptCount,
|
||||
NextAttemptAt: zeroableTime(row.NextAttemptAt),
|
||||
FirstSendStartedAt: zeroableTime(row.FirstSendStartedAt),
|
||||
ManualRetryStartedAt: zeroableTime(row.ManualRetryStartedAt),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (repository deliveryRepository) AuthorizeUnknownRetry(
|
||||
ctx context.Context,
|
||||
id uuid.UUID,
|
||||
account domain.MailProviderAccount,
|
||||
actor domain.MailRetryActor,
|
||||
acknowledgeDuplicateRisk bool,
|
||||
at time.Time,
|
||||
minimumAge time.Duration,
|
||||
) error {
|
||||
const location = "deliveryRepository.AuthorizeUnknownRetry"
|
||||
if id == uuid.Nil || account.IsZero() || actor == "" || !acknowledgeDuplicateRisk || at.IsZero() || minimumAge < 0 {
|
||||
return fmt.Errorf("%s - invalid authorization request: %w", location, outbound.ErrDeliveryRetryNotAllowed)
|
||||
}
|
||||
updated, err := repository.queries.AuthorizeUnknownDeliveryRetry(ctx, sqlc.AuthorizeUnknownDeliveryRetryParams{
|
||||
Actor: string(actor),
|
||||
DuplicateRiskAcknowledged: acknowledgeDuplicateRisk,
|
||||
DeliveryID: pgUUID(id),
|
||||
Provider: account.Provider(),
|
||||
ProviderAccount: account.Account(),
|
||||
MinimumAgeSeconds: minimumAge.Seconds(),
|
||||
Now: pgTime(at),
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - authorize retry: %w", location, mapDeliveryError(err))
|
||||
}
|
||||
if updated == 0 {
|
||||
return fmt.Errorf("%s - current delivery state is not eligible: %w", location, outbound.ErrDeliveryRetryNotAllowed)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository deliveryRepository) ListAttempts(ctx context.Context, id uuid.UUID) ([]domain.DeliveryAttempt, error) {
|
||||
@@ -265,6 +353,33 @@ func (repository deliveryRepository) Cancel(ctx context.Context, next domain.Del
|
||||
return repository.updateState(ctx, "deliveryRepository.Cancel", next, true)
|
||||
}
|
||||
|
||||
func (repository deliveryRepository) StopUnknownRetry(ctx context.Context, owner uuid.UUID, next domain.Delivery) error {
|
||||
const location = "deliveryRepository.StopUnknownRetry"
|
||||
if next.IsZero() || next.Status() != domain.DeliveryStatusUnknown || !next.NextAttemptAt().IsZero() || owner == uuid.Nil || next.Version() <= 1 {
|
||||
return fmt.Errorf("%s - state was not built by domain.Delivery.StopAutomaticRetry: %w", location, domain.ErrInvalidDelivery)
|
||||
}
|
||||
updated, err := repository.queries.StopUnknownDeliveryRetry(ctx, sqlc.StopUnknownDeliveryRetryParams{
|
||||
Now: pgTime(next.UpdatedAt()),
|
||||
ID: pgUUID(next.ID()),
|
||||
LeaseOwner: pgUUID(owner),
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - stop retry: %w", location, mapDeliveryError(err))
|
||||
}
|
||||
if updated == 0 {
|
||||
return fmt.Errorf("%s - expected version %d: %w", location, next.Version()-1, outbound.ErrDeliveryVersionConflict)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository deliveryRepository) ScheduleUnknownRetry(ctx context.Context, owner uuid.UUID, next domain.Delivery) error {
|
||||
const location = "deliveryRepository.ScheduleUnknownRetry"
|
||||
if owner == uuid.Nil || next.IsZero() || next.Status() != domain.DeliveryStatusUnknown || next.NextAttemptAt().IsZero() || next.Version() <= 1 {
|
||||
return fmt.Errorf("%s - state was not built by domain.Delivery.ScheduleUnknownRetry: %w", location, domain.ErrInvalidDelivery)
|
||||
}
|
||||
return repository.updateState(ctx, location, next, true)
|
||||
}
|
||||
|
||||
// updateState stores a state change without an attempt over the version
|
||||
// before it. releaseClaim ends the sending worker's lease with the change.
|
||||
func (repository deliveryRepository) updateState(ctx context.Context, location string, next domain.Delivery, releaseClaim bool) error {
|
||||
@@ -363,9 +478,13 @@ func (repository deliveryRepository) ClaimDue(ctx context.Context, claim outboun
|
||||
return outbound.ClaimedDelivery{}, fmt.Errorf("%s - decode claimed delivery: %w", location, unreadable)
|
||||
}
|
||||
claimed := outbound.ClaimedDelivery{
|
||||
Delivery: delivery,
|
||||
PreviousClaimedUntil: zeroableTime(row.PreviousClaimedUntil),
|
||||
FailureCount: row.FailureCount,
|
||||
Delivery: delivery,
|
||||
PreviousClaimedUntil: zeroableTime(row.PreviousClaimedUntil),
|
||||
ManualRetryPending: row.ManualRetryPending.Bool,
|
||||
ManualRetryCycleStarted: row.ManualRetryCycleStarted,
|
||||
SendStartUnsettled: row.SendStartUnsettled,
|
||||
HasUncertainAttempt: row.HasUncertainAttempt,
|
||||
FailureCount: row.FailureCount,
|
||||
}
|
||||
if row.SinceFirstSendSeconds >= 0 {
|
||||
claimed.FirstSendStarted = true
|
||||
@@ -385,11 +504,17 @@ func (repository deliveryRepository) LockClaimed(ctx context.Context, id, owner
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (repository deliveryRepository) MarkSendStarted(ctx context.Context, id, owner uuid.UUID) error {
|
||||
if _, err := repository.queries.MarkDeliverySendStarted(ctx, sqlc.MarkDeliverySendStartedParams{ID: pgUUID(id), LeaseOwner: pgUUID(owner)}); err != nil {
|
||||
return fmt.Errorf("deliveryRepository.MarkSendStarted - mark send started: %w", mapDeliveryError(err))
|
||||
func (repository deliveryRepository) MarkSendStarted(ctx context.Context, id, owner uuid.UUID, requireDedupWindow bool, safeWindow time.Duration) (bool, error) {
|
||||
started, err := repository.queries.MarkDeliverySendStarted(ctx, sqlc.MarkDeliverySendStartedParams{
|
||||
ID: pgUUID(id),
|
||||
LeaseOwner: pgUUID(owner),
|
||||
RequireDedupWindow: requireDedupWindow,
|
||||
RetryWindowSeconds: safeWindow.Seconds(),
|
||||
})
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("deliveryRepository.MarkSendStarted - mark send started: %w", mapDeliveryError(err))
|
||||
}
|
||||
return nil
|
||||
return started == 1, nil
|
||||
}
|
||||
|
||||
func (repository deliveryRepository) RecordFailure(ctx context.Context, id, owner uuid.UUID, at, nextAttemptAt time.Time, maxFailures int32, countFailure bool) (bool, error) {
|
||||
|
||||
@@ -28,9 +28,8 @@ const (
|
||||
// consent records.
|
||||
consentSubjectForeignKey = "consent_records_subject_id_fkey"
|
||||
|
||||
// sessionTouchInterval is the minimum age of last_seen_at before Touch
|
||||
// writes it again. It bounds session writes to one per minute per session
|
||||
// at the cost of ending an idle session up to a minute early.
|
||||
// sessionTouchInterval coalesces session activity writes for frequent
|
||||
// requests. Touch also caps it at half the configured idle timeout.
|
||||
sessionTouchInterval = time.Minute
|
||||
)
|
||||
|
||||
@@ -614,11 +613,12 @@ func (repository sessionRepository) Touch(ctx context.Context, id uuid.UUID, at
|
||||
if err := validateSessionCheck("sessionRepository.Touch", at, idleTimeout); err != nil {
|
||||
return err
|
||||
}
|
||||
touchInterval := min(sessionTouchInterval, idleTimeout/2)
|
||||
result, err := repository.queries.TouchSession(ctx, sqlc.TouchSessionParams{
|
||||
ID: pgUUID(id),
|
||||
At: pgTime(at),
|
||||
IdleCutoff: pgTime(at.Add(-idleTimeout)),
|
||||
TouchCutoff: pgTime(at.Add(-sessionTouchInterval)),
|
||||
TouchCutoff: pgTime(at.Add(-touchInterval)),
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("sessionRepository.Touch - update session: %w", mapIdentityError(err))
|
||||
|
||||
@@ -11,6 +11,148 @@ import (
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const authorizeUnknownDeliveryRetry = `-- name: AuthorizeUnknownDeliveryRetry :execrows
|
||||
WITH eligible AS MATERIALIZED (
|
||||
SELECT
|
||||
due.id,
|
||||
(due.claim_owner IS NOT NULL) AS previous_lease_expired,
|
||||
(
|
||||
due.manual_retry_started_at IS NOT NULL
|
||||
AND due.send_started_attempt_count = due.attempt_count
|
||||
) AS unsettled_manual_send,
|
||||
greatest(
|
||||
clock_timestamp(),
|
||||
due.updated_at,
|
||||
coalesce(due.last_attempt_at, due.updated_at)
|
||||
) AS lost_attempt_at
|
||||
FROM deliveries AS due
|
||||
WHERE
|
||||
due.id = $3
|
||||
AND due.status = 'unknown'
|
||||
AND due.next_attempt_at IS NULL
|
||||
AND (
|
||||
due.claim_owner IS NULL
|
||||
OR due.claimed_until <= clock_timestamp()
|
||||
)
|
||||
AND due.attempt_count > 0
|
||||
AND due.provider = $4
|
||||
AND due.provider_account = $5
|
||||
AND due.first_send_started_at IS NOT NULL
|
||||
AND clock_timestamp() - due.first_send_started_at
|
||||
>= make_interval(secs => $6::float8)
|
||||
AND $2::boolean
|
||||
AND $1::text ~ '^operator:[a-z0-9][a-z0-9._-]*$'
|
||||
FOR UPDATE
|
||||
), authorized AS (
|
||||
UPDATE deliveries AS due
|
||||
SET
|
||||
attempt_count = due.attempt_count + CASE WHEN eligible.unsettled_manual_send THEN 1 ELSE 0 END,
|
||||
last_attempt_at = CASE
|
||||
WHEN eligible.unsettled_manual_send THEN eligible.lost_attempt_at
|
||||
ELSE due.last_attempt_at
|
||||
END,
|
||||
next_attempt_at = greatest(
|
||||
$7::timestamptz,
|
||||
due.updated_at,
|
||||
coalesce(eligible.lost_attempt_at, due.updated_at)
|
||||
),
|
||||
manual_retry_authorized_at = clock_timestamp(),
|
||||
manual_retry_started_at = NULL,
|
||||
claim_owner = NULL,
|
||||
claimed_until = NULL,
|
||||
version = due.version + 1,
|
||||
updated_at = greatest(
|
||||
due.updated_at,
|
||||
$7::timestamptz,
|
||||
coalesce(eligible.lost_attempt_at, due.updated_at)
|
||||
)
|
||||
FROM eligible
|
||||
WHERE due.id = eligible.id
|
||||
RETURNING
|
||||
due.id,
|
||||
due.attempt_count,
|
||||
eligible.previous_lease_expired,
|
||||
eligible.unsettled_manual_send,
|
||||
eligible.lost_attempt_at
|
||||
), recorded_lost_attempt AS (
|
||||
-- A manual send whose lease expired after Mark but before settlement has
|
||||
-- no provider answer. Preserve it as an unknown attempt before this new
|
||||
-- explicit decision schedules another possible send.
|
||||
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
|
||||
authorized.id,
|
||||
authorized.attempt_count,
|
||||
authorized.lost_attempt_at,
|
||||
'unknown',
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
0,
|
||||
'unknown',
|
||||
NULL
|
||||
FROM authorized
|
||||
WHERE authorized.unsettled_manual_send
|
||||
RETURNING delivery_id
|
||||
)
|
||||
INSERT INTO delivery_retry_decisions (
|
||||
delivery_id,
|
||||
attempt_count,
|
||||
actor,
|
||||
duplicate_risk_acknowledged,
|
||||
previous_lease_expired,
|
||||
decided_at
|
||||
)
|
||||
SELECT
|
||||
authorized.id,
|
||||
authorized.attempt_count,
|
||||
$1,
|
||||
$2,
|
||||
authorized.previous_lease_expired,
|
||||
clock_timestamp()
|
||||
FROM authorized
|
||||
`
|
||||
|
||||
type AuthorizeUnknownDeliveryRetryParams struct {
|
||||
Actor string
|
||||
DuplicateRiskAcknowledged bool
|
||||
DeliveryID pgtype.UUID
|
||||
Provider string
|
||||
ProviderAccount string
|
||||
MinimumAgeSeconds float64
|
||||
Now pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// Authorizes one retry of a terminal unknown delivery. The update and append-
|
||||
// only decision share one statement and lock the current row, so a second or
|
||||
// concurrent operator decision cannot schedule another send for the same
|
||||
// unknown attempt. The provider account must still match the delivery's pin.
|
||||
func (q *Queries) AuthorizeUnknownDeliveryRetry(ctx context.Context, arg AuthorizeUnknownDeliveryRetryParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, authorizeUnknownDeliveryRetry,
|
||||
arg.Actor,
|
||||
arg.DuplicateRiskAcknowledged,
|
||||
arg.DeliveryID,
|
||||
arg.Provider,
|
||||
arg.ProviderAccount,
|
||||
arg.MinimumAgeSeconds,
|
||||
arg.Now,
|
||||
)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const cancelUnreadableDelivery = `-- name: CancelUnreadableDelivery :execrows
|
||||
UPDATE deliveries
|
||||
SET
|
||||
@@ -64,12 +206,25 @@ WITH candidate AS (
|
||||
coalesce(
|
||||
extract(EPOCH FROM clock_timestamp() - due.first_send_started_at),
|
||||
-1
|
||||
)::float8 AS since_first_send_seconds
|
||||
)::float8 AS since_first_send_seconds,
|
||||
(due.manual_retry_authorized_at IS NOT NULL AND due.manual_retry_started_at IS NULL)
|
||||
AS manual_retry_pending,
|
||||
(due.manual_retry_started_at IS NOT NULL)::boolean AS manual_retry_cycle_started,
|
||||
(
|
||||
due.send_started_attempt_count IS NOT NULL
|
||||
AND due.send_started_attempt_count = due.attempt_count
|
||||
)::boolean AS send_start_unsettled,
|
||||
EXISTS (
|
||||
SELECT 1
|
||||
FROM delivery_attempts AS prior_attempt
|
||||
WHERE prior_attempt.delivery_id = due.id
|
||||
AND prior_attempt.outcome = 'unknown'
|
||||
)::boolean AS has_uncertain_attempt
|
||||
FROM deliveries AS due
|
||||
WHERE
|
||||
due.kind IN ('verification', 'password_reset')
|
||||
AND due.kind = any($3::text [])
|
||||
AND due.status IN ('pending', 'waiting_quota')
|
||||
AND due.status IN ('pending', 'waiting_quota', 'unknown')
|
||||
AND due.next_attempt_at IS NOT NULL
|
||||
AND due.next_attempt_at <= $4::timestamptz
|
||||
AND (
|
||||
@@ -125,7 +280,11 @@ RETURNING
|
||||
claimed.created_at,
|
||||
claimed.updated_at,
|
||||
candidate.previous_claimed_until,
|
||||
candidate.since_first_send_seconds
|
||||
candidate.since_first_send_seconds,
|
||||
candidate.manual_retry_pending,
|
||||
candidate.manual_retry_cycle_started,
|
||||
candidate.send_start_unsettled,
|
||||
candidate.has_uncertain_attempt
|
||||
`
|
||||
|
||||
type ClaimDueDeliveryParams struct {
|
||||
@@ -139,37 +298,41 @@ type ClaimDueDeliveryParams struct {
|
||||
}
|
||||
|
||||
type ClaimDueDeliveryRow struct {
|
||||
ID pgtype.UUID
|
||||
SourceEventID pgtype.UUID
|
||||
RecipientUserID pgtype.UUID
|
||||
RecipientEmail string
|
||||
Kind string
|
||||
TemplateVersion string
|
||||
Subject string
|
||||
TextBody string
|
||||
HtmlBody string
|
||||
ContentSha256 []byte
|
||||
Provider string
|
||||
ProviderAccount string
|
||||
IdempotencyKey string
|
||||
Status string
|
||||
AttemptCount int32
|
||||
NextAttemptAt pgtype.Timestamptz
|
||||
LastAttemptAt pgtype.Timestamptz
|
||||
ProviderMessageID pgtype.Text
|
||||
EmailTokenID pgtype.UUID
|
||||
CancelReason pgtype.Text
|
||||
BodyRedactedAt pgtype.Timestamptz
|
||||
FailureCount int32
|
||||
Version int64
|
||||
CreatedAt pgtype.Timestamptz
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
PreviousClaimedUntil pgtype.Timestamptz
|
||||
SinceFirstSendSeconds float64
|
||||
ID pgtype.UUID
|
||||
SourceEventID pgtype.UUID
|
||||
RecipientUserID pgtype.UUID
|
||||
RecipientEmail string
|
||||
Kind string
|
||||
TemplateVersion string
|
||||
Subject string
|
||||
TextBody string
|
||||
HtmlBody string
|
||||
ContentSha256 []byte
|
||||
Provider string
|
||||
ProviderAccount string
|
||||
IdempotencyKey string
|
||||
Status string
|
||||
AttemptCount int32
|
||||
NextAttemptAt pgtype.Timestamptz
|
||||
LastAttemptAt pgtype.Timestamptz
|
||||
ProviderMessageID pgtype.Text
|
||||
EmailTokenID pgtype.UUID
|
||||
CancelReason pgtype.Text
|
||||
BodyRedactedAt pgtype.Timestamptz
|
||||
FailureCount int32
|
||||
Version int64
|
||||
CreatedAt pgtype.Timestamptz
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
PreviousClaimedUntil pgtype.Timestamptz
|
||||
SinceFirstSendSeconds float64
|
||||
ManualRetryPending pgtype.Bool
|
||||
ManualRetryCycleStarted bool
|
||||
SendStartUnsettled bool
|
||||
HasUncertainAttempt bool
|
||||
}
|
||||
|
||||
// Claims the most overdue delivery that the sending worker may send, in one
|
||||
// statement: a pending or waiting_quota delivery of the service mail kinds
|
||||
// statement: a pending, waiting_quota, or scheduled unknown delivery of the service mail kinds
|
||||
// (the literals match the predicate of deliveries_due_idx, so an idle poll
|
||||
// reads only that small index) whose next_attempt_at has passed, pinned to the
|
||||
// configured provider account (or to rebind_provider before its first
|
||||
@@ -183,10 +346,15 @@ type ClaimDueDeliveryRow struct {
|
||||
// stay on the application clock that wrote them. Neither the version nor
|
||||
// updated_at changes: a claim is not a change of the delivery.
|
||||
// previous_claimed_until is the deadline of an abandoned lease, NULL for a
|
||||
// delivery nobody held; since_first_send_seconds is how long ago, by the
|
||||
// database clock, its first request started, -1 when none did. now is the
|
||||
// application clock. Deliveries that are unknown or wait for an unknown quota
|
||||
// reset have no due time here and wait for an operator.
|
||||
// delivery nobody held; since_first_send_seconds always measures from the
|
||||
// original first request by the database clock, and is -1 when none started.
|
||||
// manual_retry_pending is true until the first provider call of the latest
|
||||
// manual authorization starts. send_start_unsettled means a provider call
|
||||
// started at the current attempt_count but no result was recorded afterward.
|
||||
// has_uncertain_attempt keeps an earlier unknown result visible even if a
|
||||
// later confirmed refusal moved the current delivery back to pending.
|
||||
// now is the application clock. Unknown deliveries without a scheduled retry
|
||||
// and quota waits with an unknown reset wait for an operator.
|
||||
func (q *Queries) ClaimDueDelivery(ctx context.Context, arg ClaimDueDeliveryParams) (ClaimDueDeliveryRow, error) {
|
||||
row := q.db.QueryRow(ctx, claimDueDelivery,
|
||||
arg.LeaseOwner,
|
||||
@@ -226,6 +394,10 @@ func (q *Queries) ClaimDueDelivery(ctx context.Context, arg ClaimDueDeliveryPara
|
||||
&i.UpdatedAt,
|
||||
&i.PreviousClaimedUntil,
|
||||
&i.SinceFirstSendSeconds,
|
||||
&i.ManualRetryPending,
|
||||
&i.ManualRetryCycleStarted,
|
||||
&i.SendStartUnsettled,
|
||||
&i.HasUncertainAttempt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -277,9 +449,40 @@ FROM deliveries
|
||||
WHERE id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) GetDeliveryByID(ctx context.Context, id pgtype.UUID) (Delivery, error) {
|
||||
type GetDeliveryByIDRow struct {
|
||||
ID pgtype.UUID
|
||||
SourceEventID pgtype.UUID
|
||||
RecipientUserID pgtype.UUID
|
||||
RecipientEmail string
|
||||
Kind string
|
||||
TemplateVersion string
|
||||
Subject string
|
||||
TextBody string
|
||||
HtmlBody string
|
||||
ContentSha256 []byte
|
||||
Provider string
|
||||
ProviderAccount string
|
||||
IdempotencyKey string
|
||||
Status string
|
||||
AttemptCount int32
|
||||
NextAttemptAt pgtype.Timestamptz
|
||||
LastAttemptAt pgtype.Timestamptz
|
||||
ProviderMessageID pgtype.Text
|
||||
Version int64
|
||||
CreatedAt pgtype.Timestamptz
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
EmailTokenID pgtype.UUID
|
||||
CancelReason pgtype.Text
|
||||
ClaimOwner pgtype.UUID
|
||||
ClaimedUntil pgtype.Timestamptz
|
||||
FirstSendStartedAt pgtype.Timestamptz
|
||||
FailureCount int32
|
||||
BodyRedactedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
func (q *Queries) GetDeliveryByID(ctx context.Context, id pgtype.UUID) (GetDeliveryByIDRow, error) {
|
||||
row := q.db.QueryRow(ctx, getDeliveryByID, id)
|
||||
var i Delivery
|
||||
var i GetDeliveryByIDRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.SourceEventID,
|
||||
@@ -313,6 +516,49 @@ func (q *Queries) GetDeliveryByID(ctx context.Context, id pgtype.UUID) (Delivery
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getDeliveryRetrySnapshot = `-- name: GetDeliveryRetrySnapshot :one
|
||||
SELECT
|
||||
id,
|
||||
provider,
|
||||
provider_account,
|
||||
status,
|
||||
attempt_count,
|
||||
next_attempt_at,
|
||||
first_send_started_at,
|
||||
manual_retry_started_at
|
||||
FROM deliveries
|
||||
WHERE id = $1
|
||||
`
|
||||
|
||||
type GetDeliveryRetrySnapshotRow struct {
|
||||
ID pgtype.UUID
|
||||
Provider string
|
||||
ProviderAccount string
|
||||
Status string
|
||||
AttemptCount int32
|
||||
NextAttemptAt pgtype.Timestamptz
|
||||
FirstSendStartedAt pgtype.Timestamptz
|
||||
ManualRetryStartedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// Reads only the metadata needed by the local operator retry interface. It
|
||||
// intentionally does not select the address, token, subject, or message body.
|
||||
func (q *Queries) GetDeliveryRetrySnapshot(ctx context.Context, id pgtype.UUID) (GetDeliveryRetrySnapshotRow, error) {
|
||||
row := q.db.QueryRow(ctx, getDeliveryRetrySnapshot, id)
|
||||
var i GetDeliveryRetrySnapshotRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Provider,
|
||||
&i.ProviderAccount,
|
||||
&i.Status,
|
||||
&i.AttemptCount,
|
||||
&i.NextAttemptAt,
|
||||
&i.FirstSendStartedAt,
|
||||
&i.ManualRetryStartedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getDeliveryStatistics = `-- name: GetDeliveryStatistics :many
|
||||
SELECT
|
||||
kind,
|
||||
@@ -729,24 +975,53 @@ const markDeliverySendStarted = `-- name: MarkDeliverySendStarted :execrows
|
||||
UPDATE deliveries
|
||||
SET
|
||||
first_send_started_at = coalesce(deliveries.first_send_started_at, clock_timestamp()),
|
||||
send_started_attempt_count = deliveries.attempt_count,
|
||||
next_attempt_at = CASE
|
||||
WHEN deliveries.manual_retry_authorized_at IS NOT NULL
|
||||
AND deliveries.manual_retry_started_at IS NULL
|
||||
THEN NULL
|
||||
ELSE deliveries.next_attempt_at
|
||||
END,
|
||||
manual_retry_started_at = CASE
|
||||
WHEN deliveries.manual_retry_authorized_at IS NOT NULL
|
||||
AND deliveries.manual_retry_started_at IS NULL
|
||||
THEN clock_timestamp()
|
||||
ELSE deliveries.manual_retry_started_at
|
||||
END,
|
||||
failure_count = 0
|
||||
WHERE
|
||||
id = $1
|
||||
AND claim_owner = $2
|
||||
AND (
|
||||
NOT $3::boolean
|
||||
OR (deliveries.manual_retry_authorized_at IS NOT NULL AND deliveries.manual_retry_started_at IS NULL)
|
||||
OR coalesce(deliveries.manual_retry_started_at, deliveries.first_send_started_at) IS NULL
|
||||
OR clock_timestamp() - coalesce(deliveries.manual_retry_started_at, deliveries.first_send_started_at)
|
||||
< make_interval(secs => $4::float8)
|
||||
)
|
||||
`
|
||||
|
||||
type MarkDeliverySendStartedParams struct {
|
||||
ID pgtype.UUID
|
||||
LeaseOwner pgtype.UUID
|
||||
ID pgtype.UUID
|
||||
LeaseOwner pgtype.UUID
|
||||
RequireDedupWindow bool
|
||||
RetryWindowSeconds float64
|
||||
}
|
||||
|
||||
// Notes that the first request of a claimed delivery is about to start, by the
|
||||
// database clock, and clears the count of worker failures: the claim and the
|
||||
// preparation succeeded, so the failures are no longer consecutive. The provider keeps the idempotency key for a window counted
|
||||
// from this moment, so a later claim can tell whether repeating the request is
|
||||
// still safe. It never moves.
|
||||
// Notes that a request is about to start, by the database clock, and clears
|
||||
// the count of worker failures. For an operator-authorized send, this sets
|
||||
// its single-use marker without overwriting the original first-send time. The
|
||||
// marker captures the current attempt_count so a lost result can be recovered
|
||||
// as unknown instead of silently retried. When require_dedup_window is true,
|
||||
// the age check is repeated here after quota work and the row lock, immediately
|
||||
// before the network call; manual starts never reset that original window.
|
||||
func (q *Queries) MarkDeliverySendStarted(ctx context.Context, arg MarkDeliverySendStartedParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, markDeliverySendStarted, arg.ID, arg.LeaseOwner)
|
||||
result, err := q.db.Exec(ctx, markDeliverySendStarted,
|
||||
arg.ID,
|
||||
arg.LeaseOwner,
|
||||
arg.RequireDedupWindow,
|
||||
arg.RetryWindowSeconds,
|
||||
)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
@@ -1002,6 +1277,39 @@ func (q *Queries) ReleaseDeliveryClaim(ctx context.Context, arg ReleaseDeliveryC
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const stopUnknownDeliveryRetry = `-- name: StopUnknownDeliveryRetry :execrows
|
||||
UPDATE deliveries
|
||||
SET
|
||||
status = 'unknown',
|
||||
next_attempt_at = NULL,
|
||||
claim_owner = NULL,
|
||||
claimed_until = NULL,
|
||||
version = deliveries.version + 1,
|
||||
updated_at = greatest(deliveries.updated_at, $1::timestamptz)
|
||||
WHERE
|
||||
id = $2
|
||||
AND status IN ('pending', 'waiting_quota', 'unknown')
|
||||
AND next_attempt_at IS NOT NULL
|
||||
AND claim_owner = $3::uuid
|
||||
`
|
||||
|
||||
type StopUnknownDeliveryRetryParams struct {
|
||||
Now pgtype.Timestamptz
|
||||
ID pgtype.UUID
|
||||
LeaseOwner pgtype.UUID
|
||||
}
|
||||
|
||||
// Stops a due automatic retry of an unknown delivery without recording a
|
||||
// fictitious provider attempt, for example when the 23-hour safety cutoff is
|
||||
// reached after the claim but before the provider call.
|
||||
func (q *Queries) StopUnknownDeliveryRetry(ctx context.Context, arg StopUnknownDeliveryRetryParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, stopUnknownDeliveryRetry, arg.Now, arg.ID, arg.LeaseOwner)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const updateDeliveryState = `-- name: UpdateDeliveryState :execrows
|
||||
UPDATE deliveries
|
||||
SET
|
||||
|
||||
@@ -196,6 +196,12 @@ type Delivery struct {
|
||||
FailureCount int32
|
||||
// Set when the bodies of a token mail were cleared after the delivery reached a terminal status, so a database dump holds no live or dead token.
|
||||
BodyRedactedAt pgtype.Timestamptz
|
||||
// Database time of the latest audited operator authorization to retry a terminal unknown delivery; it does not replace the original send history.
|
||||
ManualRetryAuthorizedAt pgtype.Timestamptz
|
||||
// Database time when the first provider call of the latest manual authorization started; this is a single-use/recovery marker and never resets the provider deduplication window.
|
||||
ManualRetryStartedAt pgtype.Timestamptz
|
||||
// Attempt count when the latest provider call started. Equality with attempt_count means its result was not recorded; a greater attempt_count means a provider result was stored after that send-start.
|
||||
SendStartedAttemptCount pgtype.Int4
|
||||
}
|
||||
|
||||
type DeliveryAttempt struct {
|
||||
@@ -211,6 +217,21 @@ type DeliveryAttempt struct {
|
||||
NextAttemptAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// Append-only record of an operator decision to retry a terminal unknown mail delivery after its provider deduplication window. No foreign key so history survives account deletion.
|
||||
type DeliveryRetryDecision struct {
|
||||
DecisionID int64
|
||||
// Opaque ID of the delivery whose current unknown attempt was authorized for another send cycle.
|
||||
DeliveryID pgtype.UUID
|
||||
AttemptCount int32
|
||||
// Operator handle in the form operator:<handle>; never an email address or credential.
|
||||
Actor string
|
||||
// Must be true: after the provider key expires, reusing it does not guarantee deduplication.
|
||||
DuplicateRiskAcknowledged bool
|
||||
// True when this decision also cleared an expired worker lease after a manual send began but its result was not recorded.
|
||||
PreviousLeaseExpired bool
|
||||
DecidedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type EmailToken struct {
|
||||
ID pgtype.UUID
|
||||
UserID pgtype.UUID
|
||||
|
||||
@@ -28,6 +28,11 @@ type Querier interface {
|
||||
// ends every earlier token, and deletes the registration C1 of the earlier
|
||||
// registrant like UpdateUserRegistration does.
|
||||
AdvanceUserRegistration(ctx context.Context, arg AdvanceUserRegistrationParams) (AdvanceUserRegistrationRow, error)
|
||||
// Authorizes one retry of a terminal unknown delivery. The update and append-
|
||||
// only decision share one statement and lock the current row, so a second or
|
||||
// concurrent operator decision cannot schedule another send for the same
|
||||
// unknown attempt. The provider account must still match the delivery's pin.
|
||||
AuthorizeUnknownDeliveryRetry(ctx context.Context, arg AuthorizeUnknownDeliveryRetryParams) (int64, error)
|
||||
// Cancels a job that has not finished. A job whose handler transaction is
|
||||
// in progress holds its row lock, so the statement waits for it: after the
|
||||
// handler committed the job is done and nothing is canceled; otherwise the
|
||||
@@ -40,7 +45,7 @@ type Querier interface {
|
||||
// application clock.
|
||||
CancelUnreadableDelivery(ctx context.Context, arg CancelUnreadableDeliveryParams) (int64, error)
|
||||
// Claims the most overdue delivery that the sending worker may send, in one
|
||||
// statement: a pending or waiting_quota delivery of the service mail kinds
|
||||
// statement: a pending, waiting_quota, or scheduled unknown delivery of the service mail kinds
|
||||
// (the literals match the predicate of deliveries_due_idx, so an idle poll
|
||||
// reads only that small index) whose next_attempt_at has passed, pinned to the
|
||||
// configured provider account (or to rebind_provider before its first
|
||||
@@ -54,10 +59,15 @@ type Querier interface {
|
||||
// stay on the application clock that wrote them. Neither the version nor
|
||||
// updated_at changes: a claim is not a change of the delivery.
|
||||
// previous_claimed_until is the deadline of an abandoned lease, NULL for a
|
||||
// delivery nobody held; since_first_send_seconds is how long ago, by the
|
||||
// database clock, its first request started, -1 when none did. now is the
|
||||
// application clock. Deliveries that are unknown or wait for an unknown quota
|
||||
// reset have no due time here and wait for an operator.
|
||||
// delivery nobody held; since_first_send_seconds always measures from the
|
||||
// original first request by the database clock, and is -1 when none started.
|
||||
// manual_retry_pending is true until the first provider call of the latest
|
||||
// manual authorization starts. send_start_unsettled means a provider call
|
||||
// started at the current attempt_count but no result was recorded afterward.
|
||||
// has_uncertain_attempt keeps an earlier unknown result visible even if a
|
||||
// later confirmed refusal moved the current delivery back to pending.
|
||||
// now is the application clock. Unknown deliveries without a scheduled retry
|
||||
// and quota waits with an unknown reset wait for an operator.
|
||||
ClaimDueDelivery(ctx context.Context, arg ClaimDueDeliveryParams) (ClaimDueDeliveryRow, error)
|
||||
// Claims up to batch_limit jobs of the listed kinds in one statement: jobs
|
||||
// whose available_at has passed, and running jobs whose lease expired
|
||||
@@ -163,7 +173,10 @@ type Querier interface {
|
||||
// The database clock, which stamps the effective time of a policy version, so
|
||||
// "the version in force now" is judged against the same clock.
|
||||
GetDatabaseTime(ctx context.Context) (pgtype.Timestamptz, error)
|
||||
GetDeliveryByID(ctx context.Context, id pgtype.UUID) (Delivery, error)
|
||||
GetDeliveryByID(ctx context.Context, id pgtype.UUID) (GetDeliveryByIDRow, error)
|
||||
// Reads only the metadata needed by the local operator retry interface. It
|
||||
// intentionally does not select the address, token, subject, or message body.
|
||||
GetDeliveryRetrySnapshot(ctx context.Context, id pgtype.UUID) (GetDeliveryRetrySnapshotRow, error)
|
||||
// Aggregates the deliveries by kind and status for the metrics, at most once
|
||||
// per metrics interval. It reads only kind, status, and next_attempt_at,
|
||||
// never an address, a body, or an ID. No index covers status, so it scans
|
||||
@@ -406,11 +419,13 @@ type Querier interface {
|
||||
LockPendingOutboxEvents(ctx context.Context, batchLimit int32) ([]LockPendingOutboxEventsRow, error)
|
||||
// Locks the active registration C1 while its pending registration is applied.
|
||||
LockRegistrationConsentRecord(ctx context.Context, arg LockRegistrationConsentRecordParams) (LockRegistrationConsentRecordRow, error)
|
||||
// Notes that the first request of a claimed delivery is about to start, by the
|
||||
// database clock, and clears the count of worker failures: the claim and the
|
||||
// preparation succeeded, so the failures are no longer consecutive. The provider keeps the idempotency key for a window counted
|
||||
// from this moment, so a later claim can tell whether repeating the request is
|
||||
// still safe. It never moves.
|
||||
// Notes that a request is about to start, by the database clock, and clears
|
||||
// the count of worker failures. For an operator-authorized send, this sets
|
||||
// its single-use marker without overwriting the original first-send time. The
|
||||
// marker captures the current attempt_count so a lost result can be recovered
|
||||
// as unknown instead of silently retried. When require_dedup_window is true,
|
||||
// the age check is repeated here after quota work and the row lock, immediately
|
||||
// before the network call; manual starts never reset that original window.
|
||||
MarkDeliverySendStarted(ctx context.Context, arg MarkDeliverySendStartedParams) (int64, error)
|
||||
// Records that the provider refused a send because the quota of a window is
|
||||
// used up: the usage rises to at least the configured limit, so the local
|
||||
@@ -553,6 +568,10 @@ type Querier interface {
|
||||
// never started on a lease that another worker may take over. now is the
|
||||
// application clock.
|
||||
StartScheduledJob(ctx context.Context, arg StartScheduledJobParams) (int64, error)
|
||||
// Stops a due automatic retry of an unknown delivery without recording a
|
||||
// fictitious provider attempt, for example when the 23-hour safety cutoff is
|
||||
// reached after the claim but before the provider call.
|
||||
StopUnknownDeliveryRetry(ctx context.Context, arg StopUnknownDeliveryRetryParams) (int64, error)
|
||||
// Records activity on an active session and reports whether it is active.
|
||||
// The row is written only when last_seen_at is older than touch_cutoff, so
|
||||
// frequent requests do not rewrite it. last_seen_at never moves back, and a
|
||||
|
||||
Reference in new issue
Block a user