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
@@ -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,
|
||||
|
||||
Reference in new issue
Block a user