feat(mail): send service identity mail through a leased worker

This commit is contained in:
shira committed 2026-10-06 21:08:11 +03:00
1 parent 204c6bae62
commit d21fd49a42
58 files changed
+7577 -164

No files matched your search

@@ -0,0 +1,77 @@
package inbound
import (
"context"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
// MailPassOutcome is what one pass of the sending worker did. The values
// are closed and safe to log and to use as a label.
type MailPassOutcome string
const (
// MailPassIdle: no delivery was due.
MailPassIdle MailPassOutcome = "idle"
// MailPassAccepted: the provider accepted the message. It is not
// delivery to a person.
MailPassAccepted MailPassOutcome = "accepted"
// MailPassRejected: the provider refused the message for good.
MailPassRejected MailPassOutcome = "rejected"
// MailPassRetry: the provider refused for now; the delivery is pending
// again at its scheduled time.
MailPassRetry MailPassOutcome = "retry"
// MailPassWaitingQuota: the local or the provider quota is used up; the
// delivery waits for the reset.
MailPassWaitingQuota MailPassOutcome = "waiting_quota"
// MailPassUnknown: the attempt may have reached the provider without a
// conclusive answer, or an earlier attempt that lost its worker is in
// doubt beyond the provider's idempotency window.
MailPassUnknown MailPassOutcome = "unknown"
// MailPassCancelled: the message must not be sent, and the delivery
// ended with a reason.
MailPassCancelled MailPassOutcome = "cancelled"
// MailPassChannelUnavailable: no transport is active
// (EMAIL_PROVIDER=disabled). Nothing was sent, and the delivery is left
// as it was.
MailPassChannelUnavailable MailPassOutcome = "channel_unavailable"
// MailPassInterrupted: the context ended before the request was sent.
// Nothing was sent, and the delivery is left as it was.
MailPassInterrupted MailPassOutcome = "interrupted"
// MailPassRowFailed: the worker itself failed on a delivery (not a
// provider answer); it is due again later and counted, and is cancelled
// as processing_failed after repeated failures.
MailPassRowFailed MailPassOutcome = "row_failed"
// MailPassLeaseLost: another worker recorded the result of this delivery
// first; nothing of this attempt is kept.
MailPassLeaseLost MailPassOutcome = "lease_lost"
)
// MailPassResult is the outcome of one pass. It carries identifiers and
// closed values only, never the address or the content.
type MailPassResult struct {
Outcome MailPassOutcome
DeliveryID uuid.UUID
Kind domain.MailKind
// CancelReason is set for MailPassCancelled.
CancelReason domain.DeliveryCancelReason
}
// MailPass runs one pass of the sending worker: it takes the next due
// delivery through the claim, the single transport call, and the stored
// result.
type MailPass interface {
// ProcessNext claims no new work once ctx ends; workCtx bounds the
// transport call and should outlive ctx by a shutdown grace. An error
// reports a database failure, after which the delivery stays under its
// lease until it expires.
ProcessNext(ctx, workCtx context.Context) (MailPassResult, error)
// PauseFailureCounting tells the pass not to count failures of single rows
// (a failing row is still moved back, but not counted and never
// cancelled). The worker pauses it when failures hit one row after another,
// which points at a global fault, and resumes it when a pass succeeds.
PauseFailureCounting(paused bool)
}
+132 -1
View File
@@ -30,6 +30,21 @@ var (
// refuses it; domain.Delivery.Rebind refuses it first.
ErrDeliveryProviderPinned = errors.New("delivery provider account is pinned")
// ErrNoDeliveryDue reports that ClaimDue found no delivery to send: none
// is due, every due one is held by a live lease or locked by another
// worker, or none is pinned to the configured provider account.
ErrNoDeliveryDue = errors.New("no delivery is due")
// ErrRowFault marks a storage error that the row itself causes and that
// repeating cannot cure: a value that violates a data or integrity
// constraint (SQLSTATE classes 22 and 23). Every other storage error
// (deadlock, timeout, lost connection, resource or admin shutdown) is
// transient and says nothing about the row.
ErrRowFault = errors.New("storage refused the row")
// ErrDeliveryUnreadable is matched by UnreadableDeliveryError.
ErrDeliveryUnreadable = errors.New("claimed delivery cannot be restored")
// 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")
@@ -76,10 +91,126 @@ type DeliveryRepository interface {
// 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.
// after an attempt with ErrDeliveryProviderPinned. A lease of the sending
// worker survives it.
Rebind(ctx context.Context, next domain.Delivery) error
// Cancel stores next as returned by domain.Delivery.Cancel, without an
// attempt record, under the same version rule as WaitForQuota, and ends
// the sending worker's lease.
Cancel(ctx context.Context, next domain.Delivery) error
// ClaimDue gives the claim's owner a lease on the most overdue delivery
// it may send and returns it, or returns ErrNoDeliveryDue. A claimed row
// that cannot be restored is reported as an *UnreadableDeliveryError;
// a content hash mismatch also cancels it, so it never blocks the queue. It never
// waits for a row that another transaction holds, so concurrent callers,
// in one process or many, never claim the same delivery. The lease does
// not change the delivery's version or update time. It reads the stored
// content with the same integrity check as Get.
ClaimDue(ctx context.Context, claim DeliveryClaim) (ClaimedDelivery, error)
// RecordClaimedAttempt is RecordAttempt that also requires owner to hold
// the delivery's lease; otherwise it writes nothing and returns
// ErrDeliveryVersionConflict. An expired lease that nobody took over still
// counts as held.
RecordClaimedAttempt(ctx context.Context, owner uuid.UUID, next domain.Delivery, attempt domain.DeliveryAttempt) error
// LockClaimed locks the delivery row of the lease holder until the
// transaction ends and reports false when owner no longer holds the
// lease. Settlement calls it first, so that every path takes the delivery
// lock before the quota rows, as the claim does.
LockClaimed(ctx context.Context, id, owner uuid.UUID) (bool, error)
// MarkSendStarted records, by the database clock and only the first time,
// that the first request of the claimed delivery is about to start.
MarkSendStarted(ctx context.Context, id, owner uuid.UUID) error
// RecordFailure counts a failure of the sending worker on the delivery
// (not a provider answer), ends its lease, and makes it due again at
// nextAttemptAt. After maxFailures consecutive failures it cancels the
// delivery with domain.DeliveryCancelProcessingFailed instead and reports
// cancelled. A delivery that is no longer pending or waiting is left
// alone.
//
// owner is the caller's lease owner: the row is left alone when another
// worker holds a live lease on it. With countFailure false the failure is
// not counted and the row is never cancelled; it only moves back by
// nextAttemptAt and its lease ends.
RecordFailure(ctx context.Context, id, owner uuid.UUID, at, nextAttemptAt time.Time, maxFailures int32, countFailure bool) (cancelled bool, err error)
// ReleaseClaim ends the lease of owner on the delivery without changing
// it. It reports false when owner no longer holds the delivery: the lease
// expired and another worker took it, or it finished.
ReleaseClaim(ctx context.Context, id uuid.UUID, owner uuid.UUID) (bool, error)
// ServiceMailState reads the token the delivery is bound to and the
// recipient account right now, for the check before a service mail is
// sent. It locks nothing. It returns ErrDeliveryNotFound when the
// delivery does not exist.
ServiceMailState(ctx context.Context, id uuid.UUID) (domain.ServiceMailState, error)
}
// DeliveryClaim selects and leases the next delivery for a sending worker.
type DeliveryClaim struct {
// Owner identifies the worker; a lease belongs to it.
Owner uuid.UUID
// Account is the configured provider account. Only deliveries pinned to
// it are claimed, because a delivery sent through another account would
// bypass its quota and idempotency window.
Account domain.MailProviderAccount
// RebindProvider is the provider name whose deliveries may be claimed
// before their first attempt although they are pinned elsewhere, so the
// caller can move them with domain.Delivery.Rebind; empty for none. It is
// the disabled transport: mail stored while no transport ran.
RebindProvider string
// Kinds lists the kinds to send. Mail of other kinds is never claimed.
Kinds []domain.MailKind
// Now is the application clock reading: due times and lease expiry are
// compared with it.
Now time.Time
// Lease is how long the claim holds the delivery.
Lease time.Duration
}
// ClaimedDelivery is a delivery under the lease of its claim.
type ClaimedDelivery struct {
Delivery domain.Delivery
// PreviousClaimedUntil is the deadline of the lease that a worker held
// and let expire without finishing, so an attempt may be in doubt; zero
// when no worker held the delivery before.
PreviousClaimedUntil time.Time
// SinceFirstSend is how long ago, by the database clock, the first
// request of the delivery started; meaningful only when FirstSendStarted.
// The provider keeps the idempotency key for a window counted from then.
SinceFirstSend time.Duration
FirstSendStarted bool
// FailureCount is the number of consecutive failures of the worker on
// this delivery so far.
FailureCount int32
}
// UnreadableDeliveryError reports that ClaimDue claimed a delivery whose
// stored row cannot be restored. When the content no longer matches its hash
// ClaimDue has cancelled the row in the caller's transaction (status
// cancelled, reason content_invalid, Cancelled set), so it does not block the
// queue; the caller commits that and reports it. Any other cause may be
// transient, so the row is left as it was and the caller records a failure of
// the row (RecordFailure). Err names the broken rule and never quotes the
// row. It matches ErrDeliveryUnreadable.
type UnreadableDeliveryError struct {
DeliveryID uuid.UUID
FailureCount int32
Cancelled bool
Err error
}
func (err *UnreadableDeliveryError) Error() string {
return "delivery " + err.DeliveryID.String() + " cannot be restored: " + err.Err.Error()
}
func (err *UnreadableDeliveryError) Unwrap() []error { return []error{ErrDeliveryUnreadable, err.Err} }
// DeliveryStatusSnapshot is the state of a delivery without its recipient
// address or content. A zero NextAttemptAt means none is scheduled.
type DeliveryStatusSnapshot struct {
@@ -21,8 +21,10 @@ type DeliveryStatistics struct {
// Counts has one entry per kind and status that has deliveries.
Counts []DeliveryStatusCount
// EarliestPendingAttemptAt is the earliest NextAttemptAt of a pending
// delivery, by the application clock that wrote it; zero without
// pending deliveries.
// service mail delivery (domain.ServiceMailKinds, the kinds a worker
// sends), by the application clock that wrote it; zero without one. A
// notification waits for its sending to be connected (TASK-462) and is
// not counted, so it never looks overdue.
EarliestPendingAttemptAt time.Time
}