feat(identity): add server sessions and audited mail recovery
This commit is contained in:
1 parent
20c03288d6
commit
4ee53d9a74
58 files changed
+5359
-567
No files matched your search
@@ -36,8 +36,12 @@ type leasedRow struct {
|
||||
attempts []domain.DeliveryAttempt
|
||||
// firstSend is when the first request started, by the fake clock; zero
|
||||
// when none did. failures counts failures of the worker on the row.
|
||||
firstSend time.Time
|
||||
failures int32
|
||||
firstSend time.Time
|
||||
manualRetryAuthorizedAt time.Time
|
||||
manualRetryStartedAt time.Time
|
||||
sendStartedAttemptCount int32
|
||||
hasSendStarted bool
|
||||
failures int32
|
||||
// seq is the insertion order, so the fake claims in a stable order like
|
||||
// the store, which orders by the due time and then by identifier.
|
||||
seq int
|
||||
@@ -60,8 +64,18 @@ type memoryDeliveries struct {
|
||||
brokenDecode uuid.UUID
|
||||
// stateErr makes the token and account read fail; stateSeq, when set,
|
||||
// answers successive reads with successive states.
|
||||
stateErr error
|
||||
stateSeq []domain.ServiceMailState
|
||||
stateErr error
|
||||
stateSeq []domain.ServiceMailState
|
||||
retryDecisions []memoryRetryDecision
|
||||
}
|
||||
|
||||
type memoryRetryDecision struct {
|
||||
deliveryID uuid.UUID
|
||||
attemptCount int32
|
||||
actor string
|
||||
duplicateRiskAcknowledged bool
|
||||
previousLeaseExpired bool
|
||||
decidedAt time.Time
|
||||
}
|
||||
|
||||
func (store *memoryDeliveries) Get(_ context.Context, id uuid.UUID) (domain.Delivery, error) {
|
||||
@@ -88,7 +102,7 @@ func (store *memoryDeliveries) ClaimDue(_ context.Context, claim outbound.Delive
|
||||
due := !delivery.NextAttemptAt().IsZero() && !delivery.NextAttemptAt().After(claim.Now)
|
||||
pinned := delivery.ProviderAccount() == claim.Account ||
|
||||
(delivery.ProviderAccount().Provider() == claim.RebindProvider && delivery.AttemptCount() == 0)
|
||||
waiting := delivery.Status() == domain.DeliveryStatusPending || delivery.Status() == domain.DeliveryStatusWaitingQuota
|
||||
waiting := delivery.Status() == domain.DeliveryStatusPending || delivery.Status() == domain.DeliveryStatusWaitingQuota || delivery.Status() == domain.DeliveryStatusUnknown
|
||||
free := row.owner == uuid.Nil || !row.until.After(claim.Now)
|
||||
if !due || !pinned || !waiting || !free || !containsKind(claim.Kinds, delivery.Kind()) {
|
||||
continue
|
||||
@@ -109,7 +123,17 @@ func (store *memoryDeliveries) ClaimDue(_ context.Context, claim outbound.Delive
|
||||
return outbound.ClaimedDelivery{}, &outbound.UnreadableDeliveryError{DeliveryID: delivery.ID(), Cancelled: true, Err: domain.ErrMailContentIntegrity}
|
||||
}
|
||||
row.owner, row.until = claim.Owner, claim.Now.Add(claim.Lease)
|
||||
claimed := outbound.ClaimedDelivery{Delivery: delivery, PreviousClaimedUntil: previous, FailureCount: row.failures}
|
||||
claimed := outbound.ClaimedDelivery{
|
||||
Delivery: delivery,
|
||||
PreviousClaimedUntil: previous,
|
||||
ManualRetryPending: !row.manualRetryAuthorizedAt.IsZero() && row.manualRetryStartedAt.IsZero(),
|
||||
ManualRetryCycleStarted: !row.manualRetryStartedAt.IsZero(),
|
||||
SendStartUnsettled: row.hasSendStarted && row.sendStartedAttemptCount == delivery.AttemptCount(),
|
||||
HasUncertainAttempt: slices.ContainsFunc(row.attempts, func(attempt domain.DeliveryAttempt) bool {
|
||||
return attempt.Outcome == domain.DeliveryOutcomeUnknown
|
||||
}),
|
||||
FailureCount: row.failures,
|
||||
}
|
||||
if !row.firstSend.IsZero() {
|
||||
claimed.FirstSendStarted, claimed.SinceFirstSend = true, claim.Now.Sub(row.firstSend)
|
||||
}
|
||||
@@ -127,6 +151,76 @@ func containsKind(kinds []domain.MailKind, kind domain.MailKind) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func (store *memoryDeliveries) GetRetrySnapshot(_ context.Context, id uuid.UUID) (outbound.DeliveryRetrySnapshot, error) {
|
||||
row := store.rows[id]
|
||||
if row == nil {
|
||||
return outbound.DeliveryRetrySnapshot{}, outbound.ErrDeliveryNotFound
|
||||
}
|
||||
return outbound.DeliveryRetrySnapshot{
|
||||
ID: id,
|
||||
Provider: row.delivery.ProviderAccount().Provider(),
|
||||
ProviderAccount: row.delivery.ProviderAccount().Account(),
|
||||
Status: row.delivery.Status(),
|
||||
AttemptCount: row.delivery.AttemptCount(),
|
||||
NextAttemptAt: row.delivery.NextAttemptAt(),
|
||||
FirstSendStartedAt: row.firstSend,
|
||||
ManualRetryStartedAt: row.manualRetryStartedAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (store *memoryDeliveries) AuthorizeUnknownRetry(
|
||||
_ context.Context,
|
||||
id uuid.UUID,
|
||||
account domain.MailProviderAccount,
|
||||
actor domain.MailRetryActor,
|
||||
acknowledgeDuplicateRisk bool,
|
||||
at time.Time,
|
||||
minimumAge time.Duration,
|
||||
) error {
|
||||
row := store.rows[id]
|
||||
if row == nil || account != row.delivery.ProviderAccount() || row.delivery.Status() != domain.DeliveryStatusUnknown ||
|
||||
!row.delivery.NextAttemptAt().IsZero() || row.delivery.AttemptCount() == 0 || actor == "" ||
|
||||
!acknowledgeDuplicateRisk || minimumAge < 0 ||
|
||||
(row.owner != uuid.Nil && row.until.After(store.now())) {
|
||||
return outbound.ErrDeliveryRetryNotAllowed
|
||||
}
|
||||
started := row.firstSend
|
||||
if started.IsZero() || at.Sub(started) < minimumAge {
|
||||
return outbound.ErrDeliveryRetryNotAllowed
|
||||
}
|
||||
previousLeaseExpired := row.owner != uuid.Nil
|
||||
if !row.manualRetryStartedAt.IsZero() && row.hasSendStarted && row.sendStartedAttemptCount == row.delivery.AttemptCount() {
|
||||
lostAttemptAt := latest(at, latest(row.delivery.UpdatedAt(), row.delivery.LastAttemptAt()))
|
||||
lost, attempt, err := row.delivery.RecordAttempt(domain.DeliveryAttemptInput{
|
||||
At: lostAttemptAt,
|
||||
Outcome: domain.DeliveryOutcomeUnknown,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
row.delivery = lost
|
||||
row.attempts = append(row.attempts, attempt)
|
||||
}
|
||||
updatedAt := latest(at, row.delivery.UpdatedAt())
|
||||
next, err := restoreMemoryDelivery(row.delivery, updatedAt, updatedAt, row.delivery.Version()+1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
row.delivery = next
|
||||
row.manualRetryAuthorizedAt = at
|
||||
row.manualRetryStartedAt = time.Time{}
|
||||
row.owner, row.until = uuid.Nil, time.Time{}
|
||||
store.retryDecisions = append(store.retryDecisions, memoryRetryDecision{
|
||||
deliveryID: id,
|
||||
attemptCount: row.delivery.AttemptCount(),
|
||||
actor: string(actor),
|
||||
duplicateRiskAcknowledged: acknowledgeDuplicateRisk,
|
||||
previousLeaseExpired: previousLeaseExpired,
|
||||
decidedAt: at,
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *memoryDeliveries) ReleaseClaim(_ context.Context, id, owner uuid.UUID) (bool, error) {
|
||||
row := store.rows[id]
|
||||
if row == nil || row.owner != owner {
|
||||
@@ -162,6 +256,44 @@ func (store *memoryDeliveries) replace(next domain.Delivery, release bool) error
|
||||
return nil
|
||||
}
|
||||
|
||||
func restoreMemoryDelivery(delivery domain.Delivery, nextAttemptAt, updatedAt time.Time, version int64) (domain.Delivery, error) {
|
||||
return domain.RestoreDelivery(domain.DeliverySnapshot{
|
||||
ID: delivery.ID(),
|
||||
SourceEventID: delivery.SourceEventID(),
|
||||
RecipientUserID: delivery.RecipientUserID(),
|
||||
RecipientAddress: delivery.Recipient().Address(),
|
||||
Content: delivery.Content(),
|
||||
ProviderAccount: delivery.ProviderAccount(),
|
||||
IdempotencyKey: delivery.IdempotencyKey(),
|
||||
Status: delivery.Status(),
|
||||
AttemptCount: delivery.AttemptCount(),
|
||||
NextAttemptAt: nextAttemptAt,
|
||||
LastAttemptAt: delivery.LastAttemptAt(),
|
||||
ProviderMessageID: delivery.ProviderMessageID(),
|
||||
EmailTokenID: delivery.EmailTokenID(),
|
||||
CancelReason: delivery.CancelReason(),
|
||||
Version: version,
|
||||
CreatedAt: delivery.CreatedAt(),
|
||||
UpdatedAt: updatedAt,
|
||||
})
|
||||
}
|
||||
|
||||
func (store *memoryDeliveries) StopUnknownRetry(_ context.Context, owner uuid.UUID, next domain.Delivery) error {
|
||||
row := store.rows[next.ID()]
|
||||
if row == nil || row.owner != owner || next.Status() != domain.DeliveryStatusUnknown || !next.NextAttemptAt().IsZero() {
|
||||
return outbound.ErrDeliveryVersionConflict
|
||||
}
|
||||
return store.replace(next, true)
|
||||
}
|
||||
|
||||
func (store *memoryDeliveries) ScheduleUnknownRetry(_ context.Context, owner uuid.UUID, next domain.Delivery) error {
|
||||
row := store.rows[next.ID()]
|
||||
if row == nil || row.owner != owner || next.Status() != domain.DeliveryStatusUnknown || next.NextAttemptAt().IsZero() {
|
||||
return outbound.ErrDeliveryVersionConflict
|
||||
}
|
||||
return store.replace(next, true)
|
||||
}
|
||||
|
||||
func (store *memoryDeliveries) RecordAttempt(_ context.Context, next domain.Delivery, attempt domain.DeliveryAttempt) error {
|
||||
if err := store.replace(next, true); err != nil {
|
||||
return err
|
||||
@@ -185,11 +317,31 @@ func (store *memoryDeliveries) LockClaimed(_ context.Context, id, owner uuid.UUI
|
||||
return row != nil && row.owner == owner, nil
|
||||
}
|
||||
|
||||
func (store *memoryDeliveries) MarkSendStarted(_ context.Context, id, owner uuid.UUID) error {
|
||||
if row := store.rows[id]; row != nil && row.owner == owner && row.firstSend.IsZero() {
|
||||
func (store *memoryDeliveries) MarkSendStarted(_ context.Context, id, owner uuid.UUID, requireDedupWindow bool, safeWindow time.Duration) (bool, error) {
|
||||
row := store.rows[id]
|
||||
if row == nil || row.owner != owner {
|
||||
return false, nil
|
||||
}
|
||||
manualPending := !row.manualRetryAuthorizedAt.IsZero() && row.manualRetryStartedAt.IsZero()
|
||||
startedAt := row.firstSend
|
||||
if requireDedupWindow && !manualPending && !startedAt.IsZero() && store.now().Sub(startedAt) >= safeWindow {
|
||||
return false, nil
|
||||
}
|
||||
if row.firstSend.IsZero() {
|
||||
row.firstSend = store.now()
|
||||
}
|
||||
return nil
|
||||
row.sendStartedAttemptCount = row.delivery.AttemptCount()
|
||||
row.hasSendStarted = true
|
||||
if manualPending {
|
||||
row.manualRetryStartedAt = store.now()
|
||||
next, err := restoreMemoryDelivery(row.delivery, time.Time{}, row.delivery.UpdatedAt(), row.delivery.Version())
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
row.delivery = next
|
||||
}
|
||||
row.failures = 0
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (store *memoryDeliveries) RecordFailure(_ context.Context, id, owner uuid.UUID, at, nextAttemptAt time.Time, maxFailures int32, countFailure bool) (bool, error) {
|
||||
@@ -435,14 +587,14 @@ func TestServiceMailSenderMapsEveryTransportResultToTheDeliveryState(t *testing.
|
||||
wantOutcome: inbound.MailPassWaitingQuota, wantStatus: domain.DeliveryStatusWaitingQuota, wantAttempts: 1,
|
||||
},
|
||||
{
|
||||
name: "an uncertain answer is unknown, counted, and not retried",
|
||||
name: "an uncertain answer is unknown and retried within the provider window",
|
||||
result: outbound.SendResult{Outcome: outbound.MailOutcomeUnknown, ProviderCode: "application_error"},
|
||||
wantOutcome: inbound.MailPassUnknown, wantStatus: domain.DeliveryStatusUnknown, wantAttempts: 1, wantUsed: 1,
|
||||
wantOutcome: inbound.MailPassUnknown, wantStatus: domain.DeliveryStatusUnknown, wantNext: start.Add(time.Minute), wantAttempts: 1, wantUsed: 1,
|
||||
},
|
||||
{
|
||||
name: "a transport that answers without an outcome is unknown, never not sent",
|
||||
name: "a transport that answers without an outcome is unknown and retried within the provider window",
|
||||
result: outbound.SendResult{},
|
||||
wantOutcome: inbound.MailPassUnknown, wantStatus: domain.DeliveryStatusUnknown, wantAttempts: 1, wantUsed: 1,
|
||||
wantOutcome: inbound.MailPassUnknown, wantStatus: domain.DeliveryStatusUnknown, wantNext: start.Add(time.Minute), wantAttempts: 1, wantUsed: 1,
|
||||
},
|
||||
{
|
||||
name: "no transport leaves the delivery as it was",
|
||||
@@ -490,6 +642,53 @@ func TestServiceMailSenderMapsEveryTransportResultToTheDeliveryState(t *testing.
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceMailSenderKeepsEarlierUnknownVisibleAcrossConfirmedRefusal(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
age time.Duration
|
||||
wantOutcome inbound.MailPassOutcome
|
||||
wantStatus domain.DeliveryStatus
|
||||
wantCalls int
|
||||
}{
|
||||
{name: "before cutoff continues under the same key", age: 22 * time.Hour, wantOutcome: inbound.MailPassAccepted, wantStatus: domain.DeliveryStatusAccepted, wantCalls: 3},
|
||||
{name: "at cutoff stops without inventing an attempt", age: 23 * time.Hour, wantOutcome: inbound.MailPassUnknown, wantStatus: domain.DeliveryStatusUnknown, wantCalls: 2},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
h := newSenderTestHarness(t, testIdempotencyWindow)
|
||||
h.transport.result = outbound.SendResult{Outcome: outbound.MailOutcomeUnknown, ProviderCode: "application_error"}
|
||||
if result := h.pass(t); result.Outcome != inbound.MailPassUnknown {
|
||||
t.Fatalf("initial pass = %+v, want unknown", result)
|
||||
}
|
||||
|
||||
h.now = h.now.Add(time.Minute)
|
||||
h.transport.result = outbound.SendResult{
|
||||
Outcome: outbound.MailOutcomeRejected,
|
||||
Rejection: outbound.MailRejectionRateLimited,
|
||||
RetryAfter: time.Minute,
|
||||
}
|
||||
if result := h.pass(t); result.Outcome != inbound.MailPassRetry {
|
||||
t.Fatalf("confirmed 429 pass = %+v, want retry", result)
|
||||
}
|
||||
row := h.stored()
|
||||
if row.delivery.Status() != domain.DeliveryStatusPending || len(row.attempts) != 2 ||
|
||||
row.attempts[0].Outcome != domain.DeliveryOutcomeUnknown || row.attempts[1].Rejection != domain.DeliveryRejectionRateLimited {
|
||||
t.Fatalf("delivery = %s with attempts %+v, want pending after unknown then confirmed 429", row.delivery.Status(), row.attempts)
|
||||
}
|
||||
|
||||
h.now = row.firstSend.Add(test.age)
|
||||
h.transport.result = outbound.SendResult{Outcome: outbound.MailOutcomeAccepted, ProviderMessageID: testMessageID}
|
||||
result := h.pass(t)
|
||||
if result.Outcome != test.wantOutcome || row.delivery.Status() != test.wantStatus || len(h.transport.mails) != test.wantCalls {
|
||||
t.Fatalf("pass = %+v, delivery %s, provider calls %d; want %s and %d calls", result, row.delivery.Status(), len(h.transport.mails), test.wantOutcome, test.wantCalls)
|
||||
}
|
||||
if test.wantStatus == domain.DeliveryStatusUnknown &&
|
||||
(len(row.attempts) != 2 || !row.delivery.NextAttemptAt().IsZero()) {
|
||||
t.Fatalf("cutoff stop added an attempt or remained due: %s, due %s, attempts %+v", row.delivery.Status(), row.delivery.NextAttemptAt(), row.attempts)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceMailSenderCancelsBeforeTheTransportWhenTheMailIsNoLongerValid(t *testing.T) {
|
||||
tests := map[string]struct {
|
||||
change func(*domain.ServiceMailState, time.Time)
|
||||
|
||||
Reference in new issue
Block a user