feat(mail): send service identity mail through a leased worker
This commit is contained in:
1 parent
204c6bae62
commit
d21fd49a42
58 files changed
+7577
-164
No files matched your search
@@ -0,0 +1,29 @@
|
||||
package resend
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net"
|
||||
"net/url"
|
||||
"time"
|
||||
)
|
||||
|
||||
// NewLoopbackSender builds the transport against a Resend API fixture that
|
||||
// runs on this machine, for tests of the delivery layer. It accepts only an
|
||||
// http URL whose host is a loopback address, so the API key and the messages
|
||||
// of a deployment can never be pointed at another host through it; the
|
||||
// bootstrap code uses NewSender and its fixed endpoint.
|
||||
func NewLoopbackSender(apiKey, from string, timeout time.Duration, endpoint string, now func() time.Time) (*Sender, error) {
|
||||
target, err := url.Parse(endpoint)
|
||||
if err != nil || target.Scheme != "http" || !isLoopbackHost(target.Hostname()) {
|
||||
return nil, errors.New("resend.NewLoopbackSender - endpoint must be an http URL on a loopback address")
|
||||
}
|
||||
return newSender(apiKey, from, timeout, endpoint, now)
|
||||
}
|
||||
|
||||
func isLoopbackHost(host string) bool {
|
||||
if host == "localhost" {
|
||||
return true
|
||||
}
|
||||
address := net.ParseIP(host)
|
||||
return address != nil && address.IsLoopback()
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
// Package resendfixture is a local stand-in for the Resend HTTP API, for
|
||||
// tests of the delivery layer. It speaks the part of the API that the
|
||||
// resend transport uses: POST /emails with a bearer key and an
|
||||
// Idempotency-Key, answered with {"id": ...} or a Resend error object. It
|
||||
// keeps what it receives so a test can check the recipient, the key, and the
|
||||
// number of provider calls, and it deduplicates a repeated key the way
|
||||
// Resend does, so a test can tell a second call from a second message.
|
||||
//
|
||||
// It is a test fixture only; production keeps the real Resend transport and
|
||||
// never imports this package.
|
||||
package resendfixture
|
||||
|
||||
import (
|
||||
"crypto/subtle"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// APIKey is the key the fixture accepts.
|
||||
const APIKey = "re_fixture_key" //nolint:gosec // A key of the local fixture, not a credential.
|
||||
|
||||
const maxRequestBytes = 1 << 20
|
||||
|
||||
// Request is one call that reached the fixture.
|
||||
type Request struct {
|
||||
IdempotencyKey string
|
||||
To []string
|
||||
Subject string
|
||||
Text string
|
||||
HTML string
|
||||
// Replayed is set when the key was already used with the same body: the
|
||||
// fixture answered with the original message and created no new one.
|
||||
Replayed bool
|
||||
}
|
||||
|
||||
// Reply is a scripted answer.
|
||||
type Reply struct {
|
||||
Status int
|
||||
// Name is the Resend error name for a non-2xx answer, for example
|
||||
// "daily_quota_exceeded".
|
||||
Name string
|
||||
}
|
||||
|
||||
// Server is the fixture. Create it with New.
|
||||
type Server struct {
|
||||
http *httptest.Server
|
||||
|
||||
// arrivals counts calls from the moment they are received, before the
|
||||
// delay, so a test can tell that a call is in flight.
|
||||
arrivals atomic.Int64
|
||||
delay atomic.Int64 // nanoseconds
|
||||
|
||||
mu sync.Mutex
|
||||
requests []Request
|
||||
messages map[string]message // by idempotency key
|
||||
scripted []Reply
|
||||
}
|
||||
|
||||
type message struct {
|
||||
id string
|
||||
body string
|
||||
}
|
||||
|
||||
// New starts the fixture on a loopback address.
|
||||
func New() *Server {
|
||||
server := &Server{messages: make(map[string]message)}
|
||||
server.http = httptest.NewServer(http.HandlerFunc(server.serve))
|
||||
return server
|
||||
}
|
||||
|
||||
// URL is the endpoint to give the loopback transport.
|
||||
func (server *Server) URL() string { return server.http.URL + "/emails" }
|
||||
|
||||
// Close stops the fixture.
|
||||
func (server *Server) Close() { server.http.Close() }
|
||||
|
||||
// Script queues answers for the next calls, in order; calls after them are
|
||||
// accepted as usual.
|
||||
func (server *Server) Script(replies ...Reply) {
|
||||
server.mu.Lock()
|
||||
defer server.mu.Unlock()
|
||||
server.scripted = append(server.scripted, replies...)
|
||||
}
|
||||
|
||||
// SetDelay makes the fixture wait before it answers every later call, so a
|
||||
// test can act while a send is in flight.
|
||||
func (server *Server) SetDelay(delay time.Duration) { server.delay.Store(int64(delay)) }
|
||||
|
||||
// Arrivals returns how many calls the fixture has received, answered or
|
||||
// not yet.
|
||||
func (server *Server) Arrivals() int { return int(server.arrivals.Load()) }
|
||||
|
||||
// Requests returns every call received, in order.
|
||||
func (server *Server) Requests() []Request {
|
||||
server.mu.Lock()
|
||||
defer server.mu.Unlock()
|
||||
return append([]Request(nil), server.requests...)
|
||||
}
|
||||
|
||||
// Messages returns the number of distinct messages the fixture accepted: a
|
||||
// replayed key does not add one.
|
||||
func (server *Server) Messages() int {
|
||||
server.mu.Lock()
|
||||
defer server.mu.Unlock()
|
||||
return len(server.messages)
|
||||
}
|
||||
|
||||
func (server *Server) serve(response http.ResponseWriter, request *http.Request) {
|
||||
server.arrivals.Add(1)
|
||||
if delay := time.Duration(server.delay.Load()); delay > 0 {
|
||||
time.Sleep(delay)
|
||||
}
|
||||
if request.Method != http.MethodPost || request.URL.Path != "/emails" {
|
||||
writeError(response, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
if subtle.ConstantTimeCompare([]byte(request.Header.Get("Authorization")), []byte("Bearer "+APIKey)) != 1 {
|
||||
writeError(response, http.StatusUnauthorized, "invalid_api_key")
|
||||
return
|
||||
}
|
||||
payload, err := io.ReadAll(io.LimitReader(request.Body, maxRequestBytes))
|
||||
if err != nil {
|
||||
writeError(response, http.StatusBadRequest, "invalid_parameter")
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
To []string `json:"to"`
|
||||
Subject string `json:"subject"`
|
||||
Text string `json:"text"`
|
||||
HTML string `json:"html"`
|
||||
}
|
||||
if err := json.Unmarshal(payload, &body); err != nil {
|
||||
writeError(response, http.StatusBadRequest, "invalid_parameter")
|
||||
return
|
||||
}
|
||||
key := request.Header.Get("Idempotency-Key")
|
||||
record := Request{IdempotencyKey: key, To: body.To, Subject: body.Subject, Text: body.Text, HTML: body.HTML}
|
||||
|
||||
server.mu.Lock()
|
||||
defer server.mu.Unlock()
|
||||
if len(server.scripted) > 0 {
|
||||
reply := server.scripted[0]
|
||||
server.scripted = server.scripted[1:]
|
||||
server.requests = append(server.requests, record)
|
||||
writeError(response, reply.Status, reply.Name)
|
||||
return
|
||||
}
|
||||
known, seen := server.messages[key]
|
||||
switch {
|
||||
case seen && known.body != string(payload):
|
||||
// The key was used with another body: Resend refuses it.
|
||||
server.requests = append(server.requests, record)
|
||||
writeError(response, http.StatusConflict, "invalid_idempotent_request")
|
||||
return
|
||||
case seen:
|
||||
record.Replayed = true
|
||||
server.requests = append(server.requests, record)
|
||||
writeAccepted(response, known.id)
|
||||
return
|
||||
}
|
||||
accepted := message{id: uuid.NewString(), body: string(payload)}
|
||||
if key != "" {
|
||||
server.messages[key] = accepted
|
||||
} else {
|
||||
server.messages[accepted.id] = accepted
|
||||
}
|
||||
server.requests = append(server.requests, record)
|
||||
writeAccepted(response, accepted.id)
|
||||
}
|
||||
|
||||
func writeAccepted(response http.ResponseWriter, id string) {
|
||||
response.Header().Set("Content-Type", "application/json")
|
||||
response.WriteHeader(http.StatusOK)
|
||||
_ = json.NewEncoder(response).Encode(map[string]string{"id": id})
|
||||
}
|
||||
|
||||
func writeError(response http.ResponseWriter, status int, name string) {
|
||||
response.Header().Set("Content-Type", "application/json")
|
||||
response.WriteHeader(status)
|
||||
_ = json.NewEncoder(response).Encode(map[string]any{"statusCode": status, "name": name, "message": "fixture " + strconv.Itoa(status)})
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package resendfixture_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/mail/resend"
|
||||
"lincodex/backend/internal/adapter/secondary/mail/resend/resendfixture"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
func newMail(t *testing.T, subject, key string) outbound.OutgoingMail {
|
||||
t.Helper()
|
||||
to, err := domain.NewEmailAddress("fixture.user@example.com")
|
||||
if err != nil {
|
||||
t.Fatalf("NewEmailAddress() error = %v", err)
|
||||
}
|
||||
return outbound.OutgoingMail{To: to, Subject: subject, TextBody: "text\n", IdempotencyKey: key}
|
||||
}
|
||||
|
||||
func TestFixtureAnswersLikeResendForTheLoopbackTransport(t *testing.T) {
|
||||
fixture := resendfixture.New()
|
||||
defer fixture.Close()
|
||||
sender, err := resend.NewLoopbackSender(resendfixture.APIKey, "Lincodex <no-reply@example.com>", 5*time.Second, fixture.URL(), time.Now)
|
||||
if err != nil {
|
||||
t.Fatalf("NewLoopbackSender() error = %v", err)
|
||||
}
|
||||
|
||||
first, err := sender.Send(t.Context(), newMail(t, "Subject", "delivery/1"))
|
||||
if err != nil || first.Outcome != outbound.MailOutcomeAccepted || first.ProviderMessageID == "" {
|
||||
t.Fatalf("first Send() = %+v, %v; want accepted with a message ID", first, err)
|
||||
}
|
||||
// The same key and body gets the original answer and creates no message.
|
||||
again, err := sender.Send(t.Context(), newMail(t, "Subject", "delivery/1"))
|
||||
if err != nil || again.ProviderMessageID != first.ProviderMessageID {
|
||||
t.Fatalf("repeated Send() = %+v, %v; want the original message ID %q", again, err, first.ProviderMessageID)
|
||||
}
|
||||
if fixture.Messages() != 1 || len(fixture.Requests()) != 2 || !fixture.Requests()[1].Replayed {
|
||||
t.Fatalf("messages = %d, requests = %+v; want one message and a replayed second call", fixture.Messages(), fixture.Requests())
|
||||
}
|
||||
// The same key with another body is the documented conflict.
|
||||
conflict, err := sender.Send(t.Context(), newMail(t, "Other subject", "delivery/1"))
|
||||
if err != nil || conflict.Outcome != outbound.MailOutcomeUnknown || conflict.ProviderCode != "invalid_idempotent_request" {
|
||||
t.Fatalf("conflicting Send() = %+v, %v; want unknown invalid_idempotent_request", conflict, err)
|
||||
}
|
||||
|
||||
fixture.Script(resendfixture.Reply{Status: 429, Name: "daily_quota_exceeded"})
|
||||
quota, err := sender.Send(t.Context(), newMail(t, "Subject", "delivery/2"))
|
||||
if err != nil || quota.Outcome != outbound.MailOutcomeRejected || quota.Rejection != outbound.MailRejectionQuotaExhausted {
|
||||
t.Fatalf("scripted Send() = %+v, %v; want a quota refusal", quota, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoopbackSenderRefusesAnyOtherHost(t *testing.T) {
|
||||
for _, endpoint := range []string{
|
||||
"https://api.resend.com/emails",
|
||||
"http://api.resend.com/emails",
|
||||
"http://192.0.2.10:8080/emails",
|
||||
"https://127.0.0.1:8080/emails",
|
||||
"not a url",
|
||||
} {
|
||||
if _, err := resend.NewLoopbackSender(resendfixture.APIKey, "no-reply@example.com", time.Second, endpoint, time.Now); err == nil {
|
||||
t.Fatalf("NewLoopbackSender(%q) accepted a non-loopback endpoint", endpoint)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
@@ -22,6 +23,7 @@ import (
|
||||
// constraint name, never by text.
|
||||
var deliveryConstraintErrors = map[constraintViolation]error{
|
||||
{foreignKeyViolationCode, "deliveries_recipient_user_id_fkey"}: outbound.ErrUserNotFound,
|
||||
{foreignKeyViolationCode, "deliveries_email_token_id_fkey"}: outbound.ErrEmailTokenNotFound,
|
||||
{foreignKeyViolationCode, "delivery_attempts_delivery_id_fkey"}: outbound.ErrDeliveryNotFound,
|
||||
{integrityConstraintViolationCode, "deliveries_content_immutable"}: outbound.ErrDeliveryContentImmutable,
|
||||
{integrityConstraintViolationCode, "delivery_attempts_immutable"}: outbound.ErrDeliveryContentImmutable,
|
||||
@@ -45,7 +47,21 @@ func mapDeliveryError(err error) error {
|
||||
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})
|
||||
return markRowFault(markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName}))
|
||||
}
|
||||
|
||||
// markRowFault makes an error that the row itself causes (SQLSTATE class 22,
|
||||
// data exception, or 23, integrity constraint violation) also match
|
||||
// outbound.ErrRowFault. Anything else stays transient to the caller.
|
||||
func markRowFault(err error) error {
|
||||
var stateError sqlStateError
|
||||
if !errors.As(err, &stateError) {
|
||||
return err
|
||||
}
|
||||
if code := stateError.SQLState(); strings.HasPrefix(code, "22") || strings.HasPrefix(code, "23") {
|
||||
return fmt.Errorf("postgres.markRowFault - SQLSTATE %s: %w: %w", code, outbound.ErrRowFault, err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// DeliveryStore provides the delivery repository outside a transaction. Every
|
||||
@@ -106,6 +122,7 @@ func (repository deliveryRepository) Create(ctx context.Context, delivery domain
|
||||
NextAttemptAt: pgZeroableTime(delivery.NextAttemptAt()),
|
||||
LastAttemptAt: pgZeroableTime(delivery.LastAttemptAt()),
|
||||
ProviderMessageID: pgOptionalText(delivery.ProviderMessageID()),
|
||||
EmailTokenID: pgOptionalUUID(delivery.EmailTokenID()),
|
||||
Version: delivery.Version(),
|
||||
CreatedAt: pgTime(delivery.CreatedAt()),
|
||||
UpdatedAt: pgTime(delivery.UpdatedAt()),
|
||||
@@ -185,7 +202,19 @@ func (repository deliveryRepository) LatestForRecipient(ctx context.Context, rec
|
||||
}
|
||||
|
||||
func (repository deliveryRepository) RecordAttempt(ctx context.Context, next domain.Delivery, attempt domain.DeliveryAttempt) error {
|
||||
const location = "deliveryRepository.RecordAttempt"
|
||||
return repository.recordAttempt(ctx, "deliveryRepository.RecordAttempt", uuid.Nil, next, attempt)
|
||||
}
|
||||
|
||||
func (repository deliveryRepository) RecordClaimedAttempt(ctx context.Context, owner uuid.UUID, next domain.Delivery, attempt domain.DeliveryAttempt) error {
|
||||
if owner == uuid.Nil {
|
||||
return fmt.Errorf("deliveryRepository.RecordClaimedAttempt - lease owner must be set: %w", domain.ErrInvalidDelivery)
|
||||
}
|
||||
return repository.recordAttempt(ctx, "deliveryRepository.RecordClaimedAttempt", owner, next, attempt)
|
||||
}
|
||||
|
||||
// recordAttempt stores an attempt over the version before it; a non-nil owner
|
||||
// also has to hold the lease.
|
||||
func (repository deliveryRepository) recordAttempt(ctx context.Context, location string, owner uuid.UUID, next domain.Delivery, attempt domain.DeliveryAttempt) error {
|
||||
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)
|
||||
}
|
||||
@@ -202,6 +231,7 @@ func (repository deliveryRepository) RecordAttempt(ctx context.Context, next dom
|
||||
UpdatedAt: pgTime(next.UpdatedAt()),
|
||||
DeliveryID: pgUUID(next.ID()),
|
||||
ExpectedVersion: next.Version() - 1,
|
||||
LeaseOwner: pgOptionalUUID(owner),
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - update delivery and insert attempt: %w", location, mapDeliveryError(err))
|
||||
@@ -216,27 +246,38 @@ func (repository deliveryRepository) WaitForQuota(ctx context.Context, next doma
|
||||
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)
|
||||
return repository.updateState(ctx, "deliveryRepository.WaitForQuota", next, true)
|
||||
}
|
||||
|
||||
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)
|
||||
// The sending worker rebinds a delivery it holds and then sends it, so
|
||||
// its lease stays.
|
||||
return repository.updateState(ctx, "deliveryRepository.Rebind", next, false)
|
||||
}
|
||||
|
||||
func (repository deliveryRepository) Cancel(ctx context.Context, next domain.Delivery) error {
|
||||
if next.Status() != domain.DeliveryStatusCancelled {
|
||||
return fmt.Errorf("deliveryRepository.Cancel - state was not built by domain.Delivery.Cancel: %w", domain.ErrInvalidDelivery)
|
||||
}
|
||||
return repository.updateState(ctx, "deliveryRepository.Cancel", next, true)
|
||||
}
|
||||
|
||||
// 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 {
|
||||
// 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 {
|
||||
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()),
|
||||
CancelReason: pgOptionalText(string(next.CancelReason())),
|
||||
Provider: next.ProviderAccount().Provider(),
|
||||
ProviderAccount: next.ProviderAccount().Account(),
|
||||
ReleaseClaim: releaseClaim,
|
||||
UpdatedAt: pgTime(next.UpdatedAt()),
|
||||
ID: pgUUID(next.ID()),
|
||||
ExpectedVersion: next.Version() - 1,
|
||||
@@ -250,12 +291,170 @@ func (repository deliveryRepository) updateState(ctx context.Context, location s
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository deliveryRepository) ClaimDue(ctx context.Context, claim outbound.DeliveryClaim) (outbound.ClaimedDelivery, error) {
|
||||
const location = "deliveryRepository.ClaimDue"
|
||||
if claim.Owner == uuid.Nil || claim.Account.IsZero() || len(claim.Kinds) == 0 || claim.Now.IsZero() || claim.Lease <= 0 {
|
||||
return outbound.ClaimedDelivery{}, fmt.Errorf("%s - owner, account, kinds, time, and lease must be set: %w", location, domain.ErrInvalidDelivery)
|
||||
}
|
||||
kinds := make([]string, 0, len(claim.Kinds))
|
||||
for _, kind := range claim.Kinds {
|
||||
if _, err := domain.ParseMailKind(string(kind)); err != nil {
|
||||
return outbound.ClaimedDelivery{}, fmt.Errorf("%s - kind: %w", location, err)
|
||||
}
|
||||
kinds = append(kinds, string(kind))
|
||||
}
|
||||
row, err := repository.queries.ClaimDueDelivery(ctx, sqlc.ClaimDueDeliveryParams{
|
||||
LeaseOwner: pgUUID(claim.Owner),
|
||||
LeaseSeconds: claim.Lease.Seconds(),
|
||||
Kinds: kinds,
|
||||
Now: pgTime(claim.Now),
|
||||
Provider: claim.Account.Provider(),
|
||||
ProviderAccount: claim.Account.Account(),
|
||||
RebindProvider: claim.RebindProvider,
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return outbound.ClaimedDelivery{}, outbound.ErrNoDeliveryDue
|
||||
}
|
||||
if err != nil {
|
||||
return outbound.ClaimedDelivery{}, fmt.Errorf("%s - claim due delivery: %w", location, mapDeliveryError(err))
|
||||
}
|
||||
delivery, err := 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,
|
||||
EmailTokenID: row.EmailTokenID,
|
||||
CancelReason: row.CancelReason,
|
||||
BodyRedactedAt: row.BodyRedactedAt,
|
||||
Version: row.Version,
|
||||
CreatedAt: row.CreatedAt,
|
||||
UpdatedAt: row.UpdatedAt,
|
||||
})
|
||||
if err != nil {
|
||||
unreadable := &outbound.UnreadableDeliveryError{DeliveryID: uuid.UUID(row.ID.Bytes), FailureCount: row.FailureCount, Err: err}
|
||||
// Only a content hash mismatch is permanent: the row was changed
|
||||
// outside the application. It is cancelled here, in the caller's
|
||||
// transaction, so it does not stay at the head of the queue. Any
|
||||
// other cause may be transient, so the row is left alone and the
|
||||
// caller records a failure of the row.
|
||||
if errors.Is(err, domain.ErrMailContentIntegrity) {
|
||||
if _, cancelErr := repository.queries.CancelUnreadableDelivery(ctx, sqlc.CancelUnreadableDeliveryParams{
|
||||
Now: pgTime(claim.Now),
|
||||
ID: row.ID,
|
||||
}); cancelErr != nil {
|
||||
return outbound.ClaimedDelivery{}, fmt.Errorf("%s - cancel unreadable delivery: %w", location, mapDeliveryError(cancelErr))
|
||||
}
|
||||
unreadable.Cancelled = true
|
||||
}
|
||||
return outbound.ClaimedDelivery{}, fmt.Errorf("%s - decode claimed delivery: %w", location, unreadable)
|
||||
}
|
||||
claimed := outbound.ClaimedDelivery{
|
||||
Delivery: delivery,
|
||||
PreviousClaimedUntil: zeroableTime(row.PreviousClaimedUntil),
|
||||
FailureCount: row.FailureCount,
|
||||
}
|
||||
if row.SinceFirstSendSeconds >= 0 {
|
||||
claimed.FirstSendStarted = true
|
||||
claimed.SinceFirstSend = time.Duration(row.SinceFirstSendSeconds * float64(time.Second))
|
||||
}
|
||||
return claimed, nil
|
||||
}
|
||||
|
||||
func (repository deliveryRepository) LockClaimed(ctx context.Context, id, owner uuid.UUID) (bool, error) {
|
||||
_, err := repository.queries.LockClaimedDelivery(ctx, sqlc.LockClaimedDeliveryParams{ID: pgUUID(id), LeaseOwner: pgUUID(owner)})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("deliveryRepository.LockClaimed - lock delivery: %w", mapDeliveryError(err))
|
||||
}
|
||||
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))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository deliveryRepository) RecordFailure(ctx context.Context, id, owner uuid.UUID, at, nextAttemptAt time.Time, maxFailures int32, countFailure bool) (bool, error) {
|
||||
status, err := repository.queries.RecordDeliveryFailure(ctx, sqlc.RecordDeliveryFailureParams{
|
||||
CountFailure: countFailure,
|
||||
LeaseOwner: pgUUID(owner),
|
||||
MaxFailures: maxFailures,
|
||||
NextAttemptAt: pgTime(nextAttemptAt),
|
||||
Now: pgTime(at),
|
||||
ID: pgUUID(id),
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("deliveryRepository.RecordFailure - record failure: %w", mapDeliveryError(err))
|
||||
}
|
||||
return status == string(domain.DeliveryStatusCancelled), nil
|
||||
}
|
||||
|
||||
func (repository deliveryRepository) ReleaseClaim(ctx context.Context, id, owner uuid.UUID) (bool, error) {
|
||||
released, err := repository.queries.ReleaseDeliveryClaim(ctx, sqlc.ReleaseDeliveryClaimParams{
|
||||
ID: pgUUID(id),
|
||||
LeaseOwner: pgUUID(owner),
|
||||
})
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("deliveryRepository.ReleaseClaim - release lease: %w", mapDeliveryError(err))
|
||||
}
|
||||
return released == 1, nil
|
||||
}
|
||||
|
||||
func (repository deliveryRepository) ServiceMailState(ctx context.Context, id uuid.UUID) (domain.ServiceMailState, error) {
|
||||
const location = "deliveryRepository.ServiceMailState"
|
||||
row, err := repository.queries.GetServiceMailState(ctx, pgUUID(id))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.ServiceMailState{}, fmt.Errorf("%s - select state: %w", location, outbound.ErrDeliveryNotFound)
|
||||
}
|
||||
if err != nil {
|
||||
return domain.ServiceMailState{}, fmt.Errorf("%s - select state: %w", location, mapDeliveryError(err))
|
||||
}
|
||||
return domain.ServiceMailState{
|
||||
TokenFound: row.TokenFound,
|
||||
TokenPurpose: domain.EmailTokenPurpose(row.TokenPurpose.String),
|
||||
TokenUserID: optionalUUID(row.TokenUserID),
|
||||
TokenRegistrationVersion: row.TokenRegistrationVersion.Int64,
|
||||
TokenConsumedAt: zeroableTime(row.TokenConsumedAt),
|
||||
TokenInvalidatedAt: zeroableTime(row.TokenInvalidatedAt),
|
||||
TokenExpiresAt: zeroableTime(row.TokenExpiresAt),
|
||||
AccountRegistrationVersion: row.AccountRegistrationVersion,
|
||||
AccountEmailVerified: row.AccountEmailVerified,
|
||||
AccountEmailKey: row.AccountEmailKey,
|
||||
}, 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)
|
||||
var content domain.MailContent
|
||||
if row.BodyRedactedAt.Valid {
|
||||
content, err = domain.RestoreRedactedMailContent(kind, row.TemplateVersion, row.Subject, row.ContentSha256)
|
||||
} else {
|
||||
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)
|
||||
}
|
||||
@@ -276,6 +475,8 @@ func deliveryFromRow(row sqlc.Delivery) (domain.Delivery, error) {
|
||||
NextAttemptAt: zeroableTime(row.NextAttemptAt),
|
||||
LastAttemptAt: zeroableTime(row.LastAttemptAt),
|
||||
ProviderMessageID: row.ProviderMessageID.String,
|
||||
EmailTokenID: optionalUUID(row.EmailTokenID),
|
||||
CancelReason: domain.DeliveryCancelReason(row.CancelReason.String),
|
||||
Version: row.Version,
|
||||
CreatedAt: row.CreatedAt.Time,
|
||||
UpdatedAt: row.UpdatedAt.Time,
|
||||
|
||||
@@ -36,6 +36,11 @@ func (store *DeliveryStatisticsStore) DeliveryStatistics(ctx context.Context) (o
|
||||
}
|
||||
statistics.Counts = append(statistics.Counts, count)
|
||||
earliest := row.EarliestPendingAttemptAt
|
||||
// Only service mail is picked up by a worker; a due notification
|
||||
// waits for TASK-462 and must not count as overdue.
|
||||
if !count.Kind.IsServiceMail() {
|
||||
continue
|
||||
}
|
||||
if earliest.Valid && (statistics.EarliestPendingAttemptAt.IsZero() || earliest.Time.Before(statistics.EarliestPendingAttemptAt)) {
|
||||
statistics.EarliestPendingAttemptAt = earliest.Time
|
||||
}
|
||||
|
||||
@@ -61,3 +61,26 @@ func TestMapDeliveryErrorDropsTheTextOfOtherPostgreSQLErrors(t *testing.T) {
|
||||
t.Fatalf("mapped error lost the constraint name: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMapDeliveryErrorMarksOnlyDataFaultsAsRowFaults(t *testing.T) {
|
||||
for code, wantRowFault := range map[string]bool{
|
||||
"22001": true, // string data right truncation
|
||||
"23514": true, // check violation
|
||||
"23505": true, // unique violation without a known constraint
|
||||
"40P01": false, // deadlock
|
||||
"40001": false, // serialization failure
|
||||
"08006": false, // connection failure
|
||||
"53300": false, // too many connections
|
||||
"57014": false, // statement timeout (query canceled)
|
||||
"57P01": false, // admin shutdown
|
||||
"XX000": false, // internal error
|
||||
} {
|
||||
err := mapDeliveryError(&pgconn.PgError{Code: code, ConstraintName: "some_constraint", Message: privateRowValue})
|
||||
if got := errors.Is(err, outbound.ErrRowFault); got != wantRowFault {
|
||||
t.Fatalf("SQLSTATE %s: ErrRowFault = %t, want %t", code, got, wantRowFault)
|
||||
}
|
||||
if strings.Contains(err.Error(), privateRowValue) {
|
||||
t.Fatalf("SQLSTATE %s: the error quotes the row", code)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,225 @@ import (
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const cancelUnreadableDelivery = `-- name: CancelUnreadableDelivery :execrows
|
||||
UPDATE deliveries
|
||||
SET
|
||||
status = 'cancelled',
|
||||
cancel_reason = 'content_invalid',
|
||||
next_attempt_at = NULL,
|
||||
claim_owner = NULL,
|
||||
claimed_until = NULL,
|
||||
text_body = CASE
|
||||
WHEN deliveries.kind IN ('verification', 'password_reset') THEN '' ELSE deliveries.text_body
|
||||
END,
|
||||
html_body = CASE
|
||||
WHEN deliveries.kind IN ('verification', 'password_reset') THEN '' ELSE deliveries.html_body
|
||||
END,
|
||||
body_redacted_at = CASE
|
||||
WHEN
|
||||
deliveries.kind IN ('verification', 'password_reset')
|
||||
THEN greatest(deliveries.updated_at, $1::timestamptz)
|
||||
ELSE deliveries.body_redacted_at
|
||||
END,
|
||||
version = deliveries.version + 1,
|
||||
updated_at = greatest(deliveries.updated_at, $1::timestamptz)
|
||||
WHERE
|
||||
id = $2
|
||||
AND status IN ('pending', 'waiting_quota')
|
||||
`
|
||||
|
||||
type CancelUnreadableDeliveryParams struct {
|
||||
Now pgtype.Timestamptz
|
||||
ID pgtype.UUID
|
||||
}
|
||||
|
||||
// Ends a claimed delivery whose stored content no longer matches its hash, so
|
||||
// one broken row never blocks the delivery queue. It matches only a delivery
|
||||
// that the worker could still send, ends the lease, advances the version, and
|
||||
// redacts the bodies of a token mail like any other cancellation. now is the
|
||||
// application clock.
|
||||
func (q *Queries) CancelUnreadableDelivery(ctx context.Context, arg CancelUnreadableDeliveryParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, cancelUnreadableDelivery, arg.Now, arg.ID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const claimDueDelivery = `-- name: ClaimDueDelivery :one
|
||||
WITH candidate AS (
|
||||
SELECT
|
||||
due.id,
|
||||
due.claimed_until AS previous_claimed_until,
|
||||
coalesce(
|
||||
extract(EPOCH FROM clock_timestamp() - due.first_send_started_at),
|
||||
-1
|
||||
)::float8 AS since_first_send_seconds
|
||||
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.next_attempt_at IS NOT NULL
|
||||
AND due.next_attempt_at <= $4::timestamptz
|
||||
AND (
|
||||
(
|
||||
due.provider = $5
|
||||
AND due.provider_account = $6
|
||||
)
|
||||
OR (
|
||||
due.provider = $7::text
|
||||
AND due.attempt_count = 0
|
||||
)
|
||||
)
|
||||
AND (
|
||||
due.claim_owner IS NULL
|
||||
OR due.claimed_until <= clock_timestamp()
|
||||
)
|
||||
ORDER BY due.next_attempt_at, due.id
|
||||
LIMIT 1
|
||||
FOR UPDATE SKIP LOCKED
|
||||
)
|
||||
|
||||
UPDATE deliveries AS claimed
|
||||
SET
|
||||
claim_owner = $1::uuid,
|
||||
claimed_until = clock_timestamp()
|
||||
+ make_interval(secs => $2::float8)
|
||||
FROM candidate
|
||||
WHERE claimed.id = candidate.id
|
||||
RETURNING
|
||||
claimed.id,
|
||||
claimed.source_event_id,
|
||||
claimed.recipient_user_id,
|
||||
claimed.recipient_email,
|
||||
claimed.kind,
|
||||
claimed.template_version,
|
||||
claimed.subject,
|
||||
claimed.text_body,
|
||||
claimed.html_body,
|
||||
claimed.content_sha256,
|
||||
claimed.provider,
|
||||
claimed.provider_account,
|
||||
claimed.idempotency_key,
|
||||
claimed.status,
|
||||
claimed.attempt_count,
|
||||
claimed.next_attempt_at,
|
||||
claimed.last_attempt_at,
|
||||
claimed.provider_message_id,
|
||||
claimed.email_token_id,
|
||||
claimed.cancel_reason,
|
||||
claimed.body_redacted_at,
|
||||
claimed.failure_count,
|
||||
claimed.version,
|
||||
claimed.created_at,
|
||||
claimed.updated_at,
|
||||
candidate.previous_claimed_until,
|
||||
candidate.since_first_send_seconds
|
||||
`
|
||||
|
||||
type ClaimDueDeliveryParams struct {
|
||||
LeaseOwner pgtype.UUID
|
||||
LeaseSeconds float64
|
||||
Kinds []string
|
||||
Now pgtype.Timestamptz
|
||||
Provider string
|
||||
ProviderAccount string
|
||||
RebindProvider string
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
// 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
|
||||
// (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
|
||||
// attempt, which the worker moves to the configured account), and held by no
|
||||
// live lease. A row that another worker locks is skipped without waiting, so
|
||||
// several processes never take the same delivery, and a delivery whose lease
|
||||
// expired, because its worker stopped, is claimed again.
|
||||
// The lease is measured by the database clock, never by the clock of an
|
||||
// application instance: it lasts lease_seconds from clock_timestamp(), and a
|
||||
// lease is live while claimed_until is later than clock_timestamp(). Due times
|
||||
// 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.
|
||||
func (q *Queries) ClaimDueDelivery(ctx context.Context, arg ClaimDueDeliveryParams) (ClaimDueDeliveryRow, error) {
|
||||
row := q.db.QueryRow(ctx, claimDueDelivery,
|
||||
arg.LeaseOwner,
|
||||
arg.LeaseSeconds,
|
||||
arg.Kinds,
|
||||
arg.Now,
|
||||
arg.Provider,
|
||||
arg.ProviderAccount,
|
||||
arg.RebindProvider,
|
||||
)
|
||||
var i ClaimDueDeliveryRow
|
||||
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.EmailTokenID,
|
||||
&i.CancelReason,
|
||||
&i.BodyRedactedAt,
|
||||
&i.FailureCount,
|
||||
&i.Version,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.PreviousClaimedUntil,
|
||||
&i.SinceFirstSendSeconds,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const deleteMailRequest = `-- name: DeleteMailRequest :execrows
|
||||
DELETE FROM mail_requests
|
||||
WHERE id = $1
|
||||
@@ -46,7 +265,14 @@ SELECT
|
||||
provider_message_id,
|
||||
version,
|
||||
created_at,
|
||||
updated_at
|
||||
updated_at,
|
||||
email_token_id,
|
||||
cancel_reason,
|
||||
claim_owner,
|
||||
claimed_until,
|
||||
first_send_started_at,
|
||||
failure_count,
|
||||
body_redacted_at
|
||||
FROM deliveries
|
||||
WHERE id = $1
|
||||
`
|
||||
@@ -76,6 +302,13 @@ func (q *Queries) GetDeliveryByID(ctx context.Context, id pgtype.UUID) (Delivery
|
||||
&i.Version,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.EmailTokenID,
|
||||
&i.CancelReason,
|
||||
&i.ClaimOwner,
|
||||
&i.ClaimedUntil,
|
||||
&i.FirstSendStartedAt,
|
||||
&i.FailureCount,
|
||||
&i.BodyRedactedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -176,6 +409,60 @@ func (q *Queries) GetLatestDeliveryStatus(ctx context.Context, arg GetLatestDeli
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getServiceMailState = `-- name: GetServiceMailState :one
|
||||
SELECT
|
||||
(token.id IS NOT NULL)::boolean AS token_found,
|
||||
token.purpose AS token_purpose,
|
||||
token.user_id AS token_user_id,
|
||||
token.registration_version AS token_registration_version,
|
||||
token.consumed_at AS token_consumed_at,
|
||||
token.invalidated_at AS token_invalidated_at,
|
||||
token.expires_at AS token_expires_at,
|
||||
owner.registration_version AS account_registration_version,
|
||||
(owner.email_verified_at IS NOT NULL)::boolean AS account_email_verified,
|
||||
owner.email_normalized AS account_email_key
|
||||
FROM deliveries AS delivery
|
||||
INNER JOIN users AS owner ON delivery.recipient_user_id = owner.id
|
||||
LEFT JOIN email_tokens AS token ON delivery.email_token_id = token.id
|
||||
WHERE delivery.id = $1
|
||||
`
|
||||
|
||||
type GetServiceMailStateRow struct {
|
||||
TokenFound bool
|
||||
TokenPurpose pgtype.Text
|
||||
TokenUserID pgtype.UUID
|
||||
TokenRegistrationVersion pgtype.Int8
|
||||
TokenConsumedAt pgtype.Timestamptz
|
||||
TokenInvalidatedAt pgtype.Timestamptz
|
||||
TokenExpiresAt pgtype.Timestamptz
|
||||
AccountRegistrationVersion int64
|
||||
AccountEmailVerified bool
|
||||
AccountEmailKey string
|
||||
}
|
||||
|
||||
// Reads the token a delivery is bound to and the account it is addressed to
|
||||
// in one statement, for the check right before a service mail is sent. It
|
||||
// takes no lock. It reads the account address only as the comparison key and
|
||||
// selects no token hash. A missing binding or token row gives NULL token
|
||||
// columns.
|
||||
func (q *Queries) GetServiceMailState(ctx context.Context, id pgtype.UUID) (GetServiceMailStateRow, error) {
|
||||
row := q.db.QueryRow(ctx, getServiceMailState, id)
|
||||
var i GetServiceMailStateRow
|
||||
err := row.Scan(
|
||||
&i.TokenFound,
|
||||
&i.TokenPurpose,
|
||||
&i.TokenUserID,
|
||||
&i.TokenRegistrationVersion,
|
||||
&i.TokenConsumedAt,
|
||||
&i.TokenInvalidatedAt,
|
||||
&i.TokenExpiresAt,
|
||||
&i.AccountRegistrationVersion,
|
||||
&i.AccountEmailVerified,
|
||||
&i.AccountEmailKey,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const insertDelivery = `-- name: InsertDelivery :execrows
|
||||
INSERT INTO deliveries (
|
||||
id,
|
||||
@@ -196,6 +483,7 @@ INSERT INTO deliveries (
|
||||
next_attempt_at,
|
||||
last_attempt_at,
|
||||
provider_message_id,
|
||||
email_token_id,
|
||||
version,
|
||||
created_at,
|
||||
updated_at
|
||||
@@ -220,7 +508,8 @@ INSERT INTO deliveries (
|
||||
$18,
|
||||
$19,
|
||||
$20,
|
||||
$21
|
||||
$21,
|
||||
$22
|
||||
)
|
||||
ON CONFLICT (id) DO NOTHING
|
||||
`
|
||||
@@ -244,6 +533,7 @@ type InsertDeliveryParams struct {
|
||||
NextAttemptAt pgtype.Timestamptz
|
||||
LastAttemptAt pgtype.Timestamptz
|
||||
ProviderMessageID pgtype.Text
|
||||
EmailTokenID pgtype.UUID
|
||||
Version int64
|
||||
CreatedAt pgtype.Timestamptz
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
@@ -274,6 +564,7 @@ func (q *Queries) InsertDelivery(ctx context.Context, arg InsertDeliveryParams)
|
||||
arg.NextAttemptAt,
|
||||
arg.LastAttemptAt,
|
||||
arg.ProviderMessageID,
|
||||
arg.EmailTokenID,
|
||||
arg.Version,
|
||||
arg.CreatedAt,
|
||||
arg.UpdatedAt,
|
||||
@@ -375,6 +666,31 @@ func (q *Queries) ListDeliveryAttempts(ctx context.Context, deliveryID pgtype.UU
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const lockClaimedDelivery = `-- name: LockClaimedDelivery :one
|
||||
SELECT id
|
||||
FROM deliveries
|
||||
WHERE
|
||||
id = $1
|
||||
AND claim_owner = $2
|
||||
FOR UPDATE
|
||||
`
|
||||
|
||||
type LockClaimedDeliveryParams struct {
|
||||
ID pgtype.UUID
|
||||
LeaseOwner pgtype.UUID
|
||||
}
|
||||
|
||||
// Locks the delivery row of the lease holder until the transaction ends, so
|
||||
// every path that settles a send takes the delivery lock before the quota
|
||||
// rows, the same order as the claim. No row means that owner no longer holds
|
||||
// the lease.
|
||||
func (q *Queries) LockClaimedDelivery(ctx context.Context, arg LockClaimedDeliveryParams) (pgtype.UUID, error) {
|
||||
row := q.db.QueryRow(ctx, lockClaimedDelivery, arg.ID, arg.LeaseOwner)
|
||||
var id pgtype.UUID
|
||||
err := row.Scan(&id)
|
||||
return id, err
|
||||
}
|
||||
|
||||
const lockMailRequest = `-- name: LockMailRequest :one
|
||||
SELECT
|
||||
id,
|
||||
@@ -409,6 +725,34 @@ func (q *Queries) LockMailRequest(ctx context.Context, id pgtype.UUID) (MailRequ
|
||||
return i, err
|
||||
}
|
||||
|
||||
const markDeliverySendStarted = `-- name: MarkDeliverySendStarted :execrows
|
||||
UPDATE deliveries
|
||||
SET
|
||||
first_send_started_at = coalesce(deliveries.first_send_started_at, clock_timestamp()),
|
||||
failure_count = 0
|
||||
WHERE
|
||||
id = $1
|
||||
AND claim_owner = $2
|
||||
`
|
||||
|
||||
type MarkDeliverySendStartedParams struct {
|
||||
ID pgtype.UUID
|
||||
LeaseOwner pgtype.UUID
|
||||
}
|
||||
|
||||
// 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.
|
||||
func (q *Queries) MarkDeliverySendStarted(ctx context.Context, arg MarkDeliverySendStartedParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, markDeliverySendStarted, arg.ID, arg.LeaseOwner)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const recordDeliveryAttempt = `-- name: RecordDeliveryAttempt :execrows
|
||||
WITH advanced AS (
|
||||
UPDATE deliveries
|
||||
@@ -420,11 +764,39 @@ WITH advanced AS (
|
||||
provider_message_id = coalesce(
|
||||
$6, deliveries.provider_message_id
|
||||
),
|
||||
claim_owner = NULL,
|
||||
claimed_until = NULL,
|
||||
failure_count = 0,
|
||||
text_body = CASE
|
||||
WHEN
|
||||
$8::text IN ('accepted', 'rejected')
|
||||
AND deliveries.kind IN ('verification', 'password_reset')
|
||||
THEN ''
|
||||
ELSE deliveries.text_body
|
||||
END,
|
||||
html_body = CASE
|
||||
WHEN
|
||||
$8::text IN ('accepted', 'rejected')
|
||||
AND deliveries.kind IN ('verification', 'password_reset')
|
||||
THEN ''
|
||||
ELSE deliveries.html_body
|
||||
END,
|
||||
body_redacted_at = CASE
|
||||
WHEN
|
||||
$8::text IN ('accepted', 'rejected')
|
||||
AND deliveries.kind IN ('verification', 'password_reset')
|
||||
THEN $10
|
||||
ELSE deliveries.body_redacted_at
|
||||
END,
|
||||
version = deliveries.version + 1,
|
||||
updated_at = $10
|
||||
WHERE
|
||||
deliveries.id = $11
|
||||
AND deliveries.version = $12
|
||||
AND (
|
||||
$13::uuid IS NULL
|
||||
OR deliveries.claim_owner = $13::uuid
|
||||
)
|
||||
RETURNING deliveries.id
|
||||
)
|
||||
|
||||
@@ -467,6 +839,7 @@ type RecordDeliveryAttemptParams struct {
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
DeliveryID pgtype.UUID
|
||||
ExpectedVersion int64
|
||||
LeaseOwner pgtype.UUID
|
||||
}
|
||||
|
||||
// Advances a delivery past one attempt and appends the attempt in one
|
||||
@@ -474,8 +847,12 @@ type RecordDeliveryAttemptParams struct {
|
||||
// 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.
|
||||
// cannot both succeed. The lease of the sending worker ends with the
|
||||
// attempt, and so does the count of worker failures. When lease_owner is
|
||||
// given, the update applies only while that worker still holds the lease.
|
||||
// A token mail that reaches a terminal status loses its bodies in the same
|
||||
// statement, so the one-time token does not stay at rest; the trigger allows
|
||||
// exactly this change of the content columns.
|
||||
func (q *Queries) RecordDeliveryAttempt(ctx context.Context, arg RecordDeliveryAttemptParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, recordDeliveryAttempt,
|
||||
arg.AttemptNumber,
|
||||
@@ -490,6 +867,7 @@ func (q *Queries) RecordDeliveryAttempt(ctx context.Context, arg RecordDeliveryA
|
||||
arg.UpdatedAt,
|
||||
arg.DeliveryID,
|
||||
arg.ExpectedVersion,
|
||||
arg.LeaseOwner,
|
||||
)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
@@ -497,40 +875,203 @@ func (q *Queries) RecordDeliveryAttempt(ctx context.Context, arg RecordDeliveryA
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const recordDeliveryFailure = `-- name: RecordDeliveryFailure :one
|
||||
UPDATE deliveries
|
||||
SET
|
||||
failure_count = CASE
|
||||
WHEN $1::boolean THEN deliveries.failure_count + 1 ELSE deliveries.failure_count
|
||||
END,
|
||||
status = CASE
|
||||
WHEN
|
||||
$1::boolean
|
||||
AND deliveries.failure_count + 1 >= $2::integer
|
||||
THEN 'cancelled'
|
||||
ELSE deliveries.status
|
||||
END,
|
||||
cancel_reason = CASE
|
||||
WHEN
|
||||
$1::boolean
|
||||
AND deliveries.failure_count + 1 >= $2::integer
|
||||
THEN 'processing_failed'
|
||||
ELSE deliveries.cancel_reason
|
||||
END,
|
||||
next_attempt_at = CASE
|
||||
WHEN
|
||||
$1::boolean
|
||||
AND deliveries.failure_count + 1 >= $2::integer
|
||||
THEN NULL
|
||||
ELSE $3::timestamptz
|
||||
END,
|
||||
text_body = CASE
|
||||
WHEN
|
||||
$1::boolean
|
||||
AND deliveries.failure_count + 1 >= $2::integer
|
||||
AND deliveries.kind IN ('verification', 'password_reset')
|
||||
THEN ''
|
||||
ELSE deliveries.text_body
|
||||
END,
|
||||
html_body = CASE
|
||||
WHEN
|
||||
$1::boolean
|
||||
AND deliveries.failure_count + 1 >= $2::integer
|
||||
AND deliveries.kind IN ('verification', 'password_reset')
|
||||
THEN ''
|
||||
ELSE deliveries.html_body
|
||||
END,
|
||||
body_redacted_at = CASE
|
||||
WHEN
|
||||
$1::boolean
|
||||
AND deliveries.failure_count + 1 >= $2::integer
|
||||
AND deliveries.kind IN ('verification', 'password_reset')
|
||||
THEN greatest(deliveries.updated_at, $4::timestamptz)
|
||||
ELSE deliveries.body_redacted_at
|
||||
END,
|
||||
claim_owner = NULL,
|
||||
claimed_until = NULL,
|
||||
version = deliveries.version + 1,
|
||||
updated_at = greatest(deliveries.updated_at, $4::timestamptz)
|
||||
WHERE
|
||||
id = $5
|
||||
AND status IN ('pending', 'waiting_quota')
|
||||
AND (
|
||||
claim_owner IS NULL
|
||||
OR claim_owner = $6::uuid
|
||||
OR claimed_until <= clock_timestamp()
|
||||
)
|
||||
RETURNING status
|
||||
`
|
||||
|
||||
type RecordDeliveryFailureParams struct {
|
||||
CountFailure bool
|
||||
MaxFailures int32
|
||||
NextAttemptAt pgtype.Timestamptz
|
||||
Now pgtype.Timestamptz
|
||||
ID pgtype.UUID
|
||||
LeaseOwner pgtype.UUID
|
||||
}
|
||||
|
||||
// Records that the sending worker failed on a delivery, so a broken row does
|
||||
// not stay at the head of the queue: the delivery is due again at
|
||||
// next_attempt_at and its lease ends. With count_failure the failure is
|
||||
// counted; after max_failures consecutive failures the delivery is cancelled
|
||||
// with the reason processing_failed, which an operator sees, and a token mail
|
||||
// loses its bodies. Without it nothing is counted and nothing is cancelled:
|
||||
// the failure says nothing about the row (a transient storage error, or a
|
||||
// stretch of failures across many rows). The row is touched only when no other
|
||||
// worker holds a live lease on it: lease_owner may hold it, or the lease is
|
||||
// free or expired. It returns the status after the change; no row means that
|
||||
// the delivery is no longer pending or waiting, or another worker holds it.
|
||||
// now is the application clock.
|
||||
func (q *Queries) RecordDeliveryFailure(ctx context.Context, arg RecordDeliveryFailureParams) (string, error) {
|
||||
row := q.db.QueryRow(ctx, recordDeliveryFailure,
|
||||
arg.CountFailure,
|
||||
arg.MaxFailures,
|
||||
arg.NextAttemptAt,
|
||||
arg.Now,
|
||||
arg.ID,
|
||||
arg.LeaseOwner,
|
||||
)
|
||||
var status string
|
||||
err := row.Scan(&status)
|
||||
return status, err
|
||||
}
|
||||
|
||||
const releaseDeliveryClaim = `-- name: ReleaseDeliveryClaim :execrows
|
||||
UPDATE deliveries
|
||||
SET
|
||||
claim_owner = NULL,
|
||||
claimed_until = NULL
|
||||
WHERE
|
||||
id = $1
|
||||
AND claim_owner = $2
|
||||
`
|
||||
|
||||
type ReleaseDeliveryClaimParams struct {
|
||||
ID pgtype.UUID
|
||||
LeaseOwner pgtype.UUID
|
||||
}
|
||||
|
||||
// Gives a claimed delivery back without changing it, so the next pass may
|
||||
// claim it. It matches only the lease of lease_owner: a delivery that another
|
||||
// worker took over after the lease expired is left alone.
|
||||
func (q *Queries) ReleaseDeliveryClaim(ctx context.Context, arg ReleaseDeliveryClaimParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, releaseDeliveryClaim, arg.ID, arg.LeaseOwner)
|
||||
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,
|
||||
cancel_reason = $3,
|
||||
failure_count = 0,
|
||||
provider = $4,
|
||||
provider_account = $5,
|
||||
claim_owner = CASE
|
||||
WHEN $6::boolean THEN NULL ELSE deliveries.claim_owner
|
||||
END,
|
||||
claimed_until = CASE
|
||||
WHEN $6::boolean THEN NULL ELSE deliveries.claimed_until
|
||||
END,
|
||||
text_body = CASE
|
||||
WHEN
|
||||
$1::text = 'cancelled'
|
||||
AND deliveries.kind IN ('verification', 'password_reset')
|
||||
THEN ''
|
||||
ELSE deliveries.text_body
|
||||
END,
|
||||
html_body = CASE
|
||||
WHEN
|
||||
$1::text = 'cancelled'
|
||||
AND deliveries.kind IN ('verification', 'password_reset')
|
||||
THEN ''
|
||||
ELSE deliveries.html_body
|
||||
END,
|
||||
body_redacted_at = CASE
|
||||
WHEN
|
||||
$1::text = 'cancelled'
|
||||
AND deliveries.kind IN ('verification', 'password_reset')
|
||||
THEN $7
|
||||
ELSE deliveries.body_redacted_at
|
||||
END,
|
||||
version = deliveries.version + 1,
|
||||
updated_at = $5
|
||||
updated_at = $7
|
||||
WHERE
|
||||
deliveries.id = $6
|
||||
AND deliveries.version = $7
|
||||
deliveries.id = $8
|
||||
AND deliveries.version = $9
|
||||
`
|
||||
|
||||
type UpdateDeliveryStateParams struct {
|
||||
Status string
|
||||
NextAttemptAt pgtype.Timestamptz
|
||||
CancelReason pgtype.Text
|
||||
Provider string
|
||||
ProviderAccount string
|
||||
ReleaseClaim bool
|
||||
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.
|
||||
// Stores a change of the delivery state that is not an attempt: a quota wait,
|
||||
// a cancellation, 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. release_claim ends the lease of the sending worker with the
|
||||
// change; a new provider account keeps it, because the worker rebinds a
|
||||
// delivery it holds and then sends it.
|
||||
func (q *Queries) UpdateDeliveryState(ctx context.Context, arg UpdateDeliveryStateParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, updateDeliveryState,
|
||||
arg.Status,
|
||||
arg.NextAttemptAt,
|
||||
arg.CancelReason,
|
||||
arg.Provider,
|
||||
arg.ProviderAccount,
|
||||
arg.ReleaseClaim,
|
||||
arg.UpdatedAt,
|
||||
arg.ID,
|
||||
arg.ExpectedVersion,
|
||||
|
||||
@@ -113,6 +113,20 @@ type Delivery struct {
|
||||
Version int64
|
||||
CreatedAt pgtype.Timestamptz
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
// The token whose link the body carries; set for verification and password reset mail, NULL for notifications. The worker checks the token before it sends.
|
||||
EmailTokenID pgtype.UUID
|
||||
// Why a cancelled delivery was not sent; set exactly when the status is cancelled.
|
||||
CancelReason pgtype.Text
|
||||
// Lease owner of the sending worker that claimed the delivery; NULL when no worker holds it.
|
||||
ClaimOwner pgtype.UUID
|
||||
// When the lease of claim_owner expires; another worker may claim the delivery after it.
|
||||
ClaimedUntil pgtype.Timestamptz
|
||||
// When the first request of this delivery was started, by the database clock; the provider keeps the idempotency key for a window counted from here.
|
||||
FirstSendStartedAt pgtype.Timestamptz
|
||||
// Consecutive failures of the sending worker on this row (not provider answers); reset by a recorded attempt.
|
||||
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
|
||||
}
|
||||
|
||||
type DeliveryAttempt struct {
|
||||
|
||||
@@ -19,6 +19,32 @@ type Querier interface {
|
||||
// handler committed the job is done and nothing is canceled; otherwise the
|
||||
// worker finds its lease gone and does not run or complete the job.
|
||||
CancelScheduledJob(ctx context.Context, arg CancelScheduledJobParams) (int64, error)
|
||||
// Ends a claimed delivery whose stored content no longer matches its hash, so
|
||||
// one broken row never blocks the delivery queue. It matches only a delivery
|
||||
// that the worker could still send, ends the lease, advances the version, and
|
||||
// redacts the bodies of a token mail like any other cancellation. now is the
|
||||
// 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
|
||||
// (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
|
||||
// attempt, which the worker moves to the configured account), and held by no
|
||||
// live lease. A row that another worker locks is skipped without waiting, so
|
||||
// several processes never take the same delivery, and a delivery whose lease
|
||||
// expired, because its worker stopped, is claimed again.
|
||||
// The lease is measured by the database clock, never by the clock of an
|
||||
// application instance: it lasts lease_seconds from clock_timestamp(), and a
|
||||
// lease is live while claimed_until is later than clock_timestamp(). Due times
|
||||
// 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.
|
||||
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
|
||||
// because their worker stopped without finishing them. Rows that another
|
||||
@@ -156,6 +182,12 @@ type Querier interface {
|
||||
// the handler transaction that holds its row lock: only that transaction
|
||||
// can have changed it, for example by canceling its own job.
|
||||
GetScheduledJobStatus(ctx context.Context, id int64) (string, error)
|
||||
// Reads the token a delivery is bound to and the account it is addressed to
|
||||
// in one statement, for the check right before a service mail is sent. It
|
||||
// takes no lock. It reads the account address only as the comparison key and
|
||||
// selects no token hash. A missing binding or token row gives NULL token
|
||||
// columns.
|
||||
GetServiceMailState(ctx context.Context, id pgtype.UUID) (GetServiceMailStateRow, error)
|
||||
GetUnrevokedConsentRecordByVersion(ctx context.Context, arg GetUnrevokedConsentRecordByVersionParams) (GetUnrevokedConsentRecordByVersionRow, error)
|
||||
GetUserByEmailNormalized(ctx context.Context, emailNormalized string) (User, error)
|
||||
GetUserByID(ctx context.Context, id pgtype.UUID) (User, error)
|
||||
@@ -253,6 +285,11 @@ type Querier interface {
|
||||
// published or open the category, until the transaction ends. The key is
|
||||
// namespaced, so it cannot collide with another use of advisory locks.
|
||||
LockAssessmentCategory(ctx context.Context, category string) error
|
||||
// Locks the delivery row of the lease holder until the transaction ends, so
|
||||
// every path that settles a send takes the delivery lock before the quota
|
||||
// rows, the same order as the claim. No row means that owner no longer holds
|
||||
// the lease.
|
||||
LockClaimedDelivery(ctx context.Context, arg LockClaimedDeliveryParams) (pgtype.UUID, error)
|
||||
// Locks a claimed job for its handler transaction and checks that the lease
|
||||
// still belongs to this attempt. It returns no row when the job was
|
||||
// canceled, or reclaimed after the lease expired. While the lock is held,
|
||||
@@ -279,6 +316,12 @@ type Querier interface {
|
||||
// because aggregate writers check the expected version, so scanning without a
|
||||
// position watermark cannot overtake an earlier version.
|
||||
LockPendingOutboxEvents(ctx context.Context, batchLimit int32) ([]LockPendingOutboxEventsRow, 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.
|
||||
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
|
||||
// gate stops admitting sends until the window resets or an operator raises
|
||||
@@ -304,11 +347,32 @@ type Querier interface {
|
||||
// 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.
|
||||
// cannot both succeed. The lease of the sending worker ends with the
|
||||
// attempt, and so does the count of worker failures. When lease_owner is
|
||||
// given, the update applies only while that worker still holds the lease.
|
||||
// A token mail that reaches a terminal status loses its bodies in the same
|
||||
// statement, so the one-time token does not stay at rest; the trigger allows
|
||||
// exactly this change of the content columns.
|
||||
RecordDeliveryAttempt(ctx context.Context, arg RecordDeliveryAttemptParams) (int64, error)
|
||||
// Records that the sending worker failed on a delivery, so a broken row does
|
||||
// not stay at the head of the queue: the delivery is due again at
|
||||
// next_attempt_at and its lease ends. With count_failure the failure is
|
||||
// counted; after max_failures consecutive failures the delivery is cancelled
|
||||
// with the reason processing_failed, which an operator sees, and a token mail
|
||||
// loses its bodies. Without it nothing is counted and nothing is cancelled:
|
||||
// the failure says nothing about the row (a transient storage error, or a
|
||||
// stretch of failures across many rows). The row is touched only when no other
|
||||
// worker holds a live lease on it: lease_owner may hold it, or the lease is
|
||||
// free or expired. It returns the status after the change; no row means that
|
||||
// the delivery is no longer pending or waiting, or another worker holds it.
|
||||
// now is the application clock.
|
||||
RecordDeliveryFailure(ctx context.Context, arg RecordDeliveryFailureParams) (string, error)
|
||||
// Records the latest settled outcome of a send under the reservation.
|
||||
RecordMailQuotaOutcome(ctx context.Context, arg RecordMailQuotaOutcomeParams) (int64, error)
|
||||
// Gives a claimed delivery back without changing it, so the next pass may
|
||||
// claim it. It matches only the lease of lease_owner: a delivery that another
|
||||
// worker took over after the lease expired is left alone.
|
||||
ReleaseDeliveryClaim(ctx context.Context, arg ReleaseDeliveryClaimParams) (int64, error)
|
||||
// Marks a reservation released. It matches only an open reservation, so a
|
||||
// repeated release changes nothing and returns 0 rows.
|
||||
ReleaseMailQuotaReservation(ctx context.Context, arg ReleaseMailQuotaReservationParams) (int64, error)
|
||||
@@ -365,10 +429,13 @@ 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.
|
||||
// Stores a change of the delivery state that is not an attempt: a quota wait,
|
||||
// a cancellation, 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. release_claim ends the lease of the sending worker with the
|
||||
// change; a new provider account keeps it, because the worker rebinds a
|
||||
// delivery it holds and then sends it.
|
||||
UpdateDeliveryState(ctx context.Context, arg UpdateDeliveryStateParams) (int64, error)
|
||||
// Changes the profile of an organization over the version the caller read
|
||||
// and advances the version in the same statement. It names no verification
|
||||
|
||||
@@ -32,6 +32,13 @@ type mailMetrics struct {
|
||||
quotaUsed *client.GaugeVec
|
||||
quotaLimit *client.GaugeVec
|
||||
quotaProviderExhausted *client.GaugeVec
|
||||
// senderRunning is 1 while this process's mail sending loop runs. It is
|
||||
// per process, not database-wide, so dashboards and alerts aggregate it
|
||||
// with max across instances.
|
||||
senderRunning client.Gauge
|
||||
// senderCancelled counts deliveries that the sending worker ended without
|
||||
// sending, by cancel reason, a closed set from the domain.
|
||||
senderCancelled *client.CounterVec
|
||||
}
|
||||
|
||||
// deliveryKinds and deliveryStatuses list the series that always exist, so a
|
||||
@@ -48,18 +55,19 @@ var (
|
||||
domain.DeliveryStatusUnknown,
|
||||
domain.DeliveryStatusAccepted,
|
||||
domain.DeliveryStatusRejected,
|
||||
domain.DeliveryStatusCancelled,
|
||||
}
|
||||
)
|
||||
|
||||
func newMailMetrics() mailMetrics {
|
||||
return mailMetrics{
|
||||
metrics := mailMetrics{
|
||||
deliveries: client.NewGaugeVec(client.GaugeOpts{
|
||||
Name: "lincodex_mail_deliveries",
|
||||
Help: "Stored mail deliveries by kind and status at the last statistics read: pending, waiting_quota, unknown, accepted, or rejected.",
|
||||
Help: "Stored mail deliveries by kind and status at the last statistics read: pending, waiting_quota, unknown, accepted (by the provider, not delivered to a person), rejected, or cancelled.",
|
||||
}, []string{"kind", "status"}),
|
||||
oldestDuePendingAge: client.NewGaugeVec(client.GaugeOpts{
|
||||
Name: "lincodex_mail_delivery_oldest_due_pending_age_seconds",
|
||||
Help: "How long the earliest pending delivery has been due for its next attempt, by the application clock, at the last statistics read; 0 without due pending deliveries, absent before the first read.",
|
||||
Help: "How long the earliest pending service mail (verification or password reset, the kinds the sending worker handles) has been due for its next attempt, by the application clock, at the last statistics read; 0 without due pending service mail, absent before the first read. Notifications are not counted until they are sent.",
|
||||
}, nil),
|
||||
lastSuccess: client.NewGaugeVec(client.GaugeOpts{
|
||||
Name: "lincodex_mail_metrics_last_success_timestamp_seconds",
|
||||
@@ -77,13 +85,28 @@ func newMailMetrics() mailMetrics {
|
||||
Name: "lincodex_mail_quota_provider_exhausted",
|
||||
Help: "1 when the provider itself reported the quota of the current UTC window used up, 0 otherwise, by provider and window.",
|
||||
}, []string{"provider", "window"}),
|
||||
senderCancelled: client.NewCounterVec(client.CounterOpts{
|
||||
Name: "lincodex_mail_sender_cancelled_total",
|
||||
Help: "Deliveries that the mail sending worker of this process ended without sending, by cancel reason. content_invalid and processing_failed mean a broken row or a defect.",
|
||||
}, []string{"reason"}),
|
||||
senderRunning: client.NewGauge(client.GaugeOpts{
|
||||
Name: "lincodex_mail_sender_running",
|
||||
Help: "1 while the mail sending loop of this process runs, 0 while it does not, for example with EMAIL_PROVIDER=disabled or after shutdown began.",
|
||||
}),
|
||||
}
|
||||
// Every reason exists at zero, so an alert on an increase sees the first
|
||||
// cancellation instead of a new series.
|
||||
for _, reason := range domain.DeliveryCancelReasons() {
|
||||
metrics.senderCancelled.WithLabelValues(string(reason))
|
||||
}
|
||||
return metrics
|
||||
}
|
||||
|
||||
func (mail mailMetrics) collectors() []client.Collector {
|
||||
return []client.Collector{
|
||||
mail.deliveries, mail.oldestDuePendingAge, mail.lastSuccess,
|
||||
mail.quotaUsed, mail.quotaLimit, mail.quotaProviderExhausted,
|
||||
mail.senderRunning, mail.senderCancelled,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -112,6 +135,27 @@ func (metrics *Metrics) ObserveDeliveryStates(counts []outbound.DeliveryStatusCo
|
||||
metrics.mail.oldestDuePendingAge.WithLabelValues().Set(oldestDuePending.Seconds())
|
||||
}
|
||||
|
||||
// ObserveMailCancelled counts one cancelled delivery by its cancel reason. A
|
||||
// reason outside the domain set counts as processing_failed, so the label stays
|
||||
// bounded.
|
||||
func (metrics *Metrics) ObserveMailCancelled(reason string) {
|
||||
if _, err := domain.ParseDeliveryCancelReason(reason); err != nil {
|
||||
reason = string(domain.DeliveryCancelProcessingFailed)
|
||||
}
|
||||
metrics.mail.senderCancelled.WithLabelValues(reason).Inc()
|
||||
}
|
||||
|
||||
// SetMailSenderRunning reports whether this process's mail sending loop
|
||||
// runs: 1 from the moment it starts until it stops, 0 otherwise. The series
|
||||
// exists at 0 from startup, also when the loop never starts.
|
||||
func (metrics *Metrics) SetMailSenderRunning(running bool) {
|
||||
value := 0.0
|
||||
if running {
|
||||
value = 1
|
||||
}
|
||||
metrics.mail.senderRunning.Set(value)
|
||||
}
|
||||
|
||||
// PrepareMailMetricsReads exposes the last success time at 0 when the
|
||||
// sampler starts, so an alert sees a sampler that never reads successfully.
|
||||
func (metrics *Metrics) PrepareMailMetricsReads() {
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package prometheus
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMetricsHandlerExposesWhetherTheMailSenderRuns(t *testing.T) {
|
||||
metrics := New()
|
||||
// The series exists before any loop starts, so an alert that needs
|
||||
// "the sender runs" sees 0 instead of a missing series.
|
||||
requireSeries(t, scrape(t, metrics), "lincodex_mail_sender_running 0")
|
||||
|
||||
metrics.SetMailSenderRunning(true)
|
||||
requireSeries(t, scrape(t, metrics), "lincodex_mail_sender_running 1")
|
||||
|
||||
metrics.SetMailSenderRunning(false)
|
||||
requireSeries(t, scrape(t, metrics), "lincodex_mail_sender_running 0")
|
||||
}
|
||||
|
||||
func TestMetricsHandlerCountsCancelledMailByABoundedReason(t *testing.T) {
|
||||
metrics := New()
|
||||
// Every reason exists at zero before the first cancellation.
|
||||
body := scrape(t, metrics)
|
||||
requireSeries(t, body,
|
||||
`lincodex_mail_sender_cancelled_total{reason="content_invalid"} 0`,
|
||||
`lincodex_mail_sender_cancelled_total{reason="processing_failed"} 0`,
|
||||
`lincodex_mail_sender_cancelled_total{reason="token_revoked"} 0`,
|
||||
)
|
||||
metrics.ObserveMailCancelled("content_invalid")
|
||||
metrics.ObserveMailCancelled("content_invalid")
|
||||
// A reason outside the domain set cannot become a label.
|
||||
metrics.ObserveMailCancelled("someone@example.com")
|
||||
requireSeries(t, scrape(t, metrics),
|
||||
`lincodex_mail_sender_cancelled_total{reason="content_invalid"} 2`,
|
||||
`lincodex_mail_sender_cancelled_total{reason="processing_failed"} 1`,
|
||||
)
|
||||
if strings.Contains(scrape(t, metrics), "someone@example.com") {
|
||||
t.Fatal("an arbitrary reason became a label")
|
||||
}
|
||||
}
|
||||
@@ -60,6 +60,7 @@ func TestMetricsHandlerExposesEveryDeliveryState(t *testing.T) {
|
||||
`lincodex_mail_deliveries{kind="password_reset",status="waiting_quota"} 0`,
|
||||
`lincodex_mail_deliveries{kind="verification",status="accepted"} 0`,
|
||||
`lincodex_mail_deliveries{kind="notification",status="rejected"} 0`,
|
||||
`lincodex_mail_deliveries{kind="verification",status="cancelled"} 0`,
|
||||
"lincodex_mail_delivery_oldest_due_pending_age_seconds 90",
|
||||
)
|
||||
|
||||
|
||||
Reference in new issue
Block a user