package outbound import ( "context" "errors" "time" "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") // 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") ) // 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 // LatestForRecipient returns the status of the newest delivery of kind // addressed to the account, by creation time, or ErrDeliveryNotFound // when there is none. It reads no address and no content. LatestForRecipient(ctx context.Context, recipientUserID uuid.UUID, kind domain.MailKind) (DeliveryStatusSnapshot, 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. 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 { DeliveryID uuid.UUID Kind domain.MailKind Status domain.DeliveryStatus NextAttemptAt time.Time CreatedAt time.Time UpdatedAt time.Time } // 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 }