transfers: bound sends, reads and notices; expire on Stripe's word
Final-review fixes F1 to F5 in the transfer engine. - Capture, hold release, refund create and Checkout expiry each persist a next-send time (1 min, 5 min, 30 min, 1 h, then 6 h; capture at most 30 min in the hold's last day). decideTransfer reads it as a fact and waits; reads and alerts go on. Capture, release and expiry keys carry an attempt number after a stored answer (Stripe replays a stored 500 for 24 h); the refund key never changes within an attempt. - cancel-failing and refund-failing alerts after three failed sends, then daily. - The payment is read every pass only while a money action is due or the Checkout waits; a captured transfer waiting on the registrar reads it with the status read. - Owner emails are recorded per owner; every notice retries on 1 h, 6 h, then daily; a blocked owner, no email sender or a deleted account gives the notice up with one notice-dropped alert. - Past the console's expiry the provider is asked to expire the Checkout; only its expired session ends the purchase. A hold authorised after that is released. - The captured total (tax included) is recorded; the card and the status reply state the refund as that total. - The simulation gains flaky sends, a lagging provider clock, a customer paying in the gap, and next-send-time checks.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
12 files changed,
+1,194
−106
internal/billing/billingtest/fake.go+16 −3internal/console/apidomainbuy.go+9 −1internal/console/appdomainbuy.go+11 −1internal/console/delivery.go+5 −1internal/console/domaintransfer.go+143 −26internal/console/domaintransfer_bounded_test.go+435 −0internal/console/domaintransfer_copy.go+12 −0internal/console/domaintransfer_decide.go+91 −13internal/console/domaintransfer_decide_test.go+197 −11internal/console/domaintransfer_facts.go+48 −4internal/console/domaintransfer_notices.go+172 −29internal/console/domaintransfer_test.go+55 −17
diff --git a/internal/billing/billingtest/fake.go b/internal/billing/billingtest/fake.go| index 3e1ab3bc6..e13e9a1cd 100644 |
| --- a/internal/billing/billingtest/fake.go |
| +++ b/internal/billing/billingtest/fake.go |
| @@ -231,6 +231,10 @@ type Fake struct { |
| // makes stays capturable (PaymentInfo.CaptureBefore): 0 is seven days, |
| // as for most cards; negative is a provider that does not say. |
| CaptureWindow time.Duration |
| + // PaymentTax is the exclusive tax a one-off Checkout created from now |
| + // on adds to its total (AmountTotal = Amount + PaymentTax), as automatic |
| + // tax does: 0 is none. |
| + PaymentTax int64 |
| // LapseAuthorisations, when set, makes an uncaptured authorisation |
| // lapse at its CaptureBefore, as a card's does: the PaymentIntent turns |
| // canceled and a capture refuses. Off by default (authorisations never |
| @@ -1164,7 +1168,7 @@ func (f *Fake) execute(body any) (billing.Result, error) { |
| case *paymentCheckoutBody: |
| id := f.nextID("cs") |
| s := &paymentSession{PaymentInfo: billing.PaymentInfo{SessionID: id, URL: "https://checkout.example.test/c/" + id, |
| - Status: "open", Amount: b.Request.Amount, AmountTotal: b.Request.Amount, Currency: b.Request.Currency}, Request: b.Request, Created: f.ProviderClock} |
| + Status: "open", Amount: b.Request.Amount, AmountTotal: b.Request.Amount + f.PaymentTax, Currency: b.Request.Currency}, Request: b.Request, Created: f.ProviderClock} |
| f.paymentSessions[id] = s |
| info := s.PaymentInfo |
| return billing.Result{Payment: &info}, nil |
| @@ -1209,6 +1213,14 @@ func (f *Fake) execute(body any) (billing.Result, error) { |
| info := s.CheckoutInfo |
| return billing.Result{Checkout: &info}, nil |
| case *expireBody: |
| + if ps, ok := f.paymentSessions[b.Session]; ok { |
| + // A one-off Checkout: only an open one can be expired. |
| + if ps.Status != "open" { |
| + return billing.Result{}, fmt.Errorf("%w: only an open session can be expired", billing.ErrRefused) |
| + } |
| + ps.Status = "expired" |
| + return billing.Result{Checkout: &billing.CheckoutInfo{ID: ps.SessionID, Reference: ps.Request.Reference, State: billing.CheckoutExpired, ExpiresAt: ps.Request.ExpiresAt}}, nil |
| + } |
| s, ok := f.Sessions[b.Session] |
| if !ok { |
| return billing.Result{}, fmt.Errorf("%w: no such session", billing.ErrRefused) |
| @@ -1535,7 +1547,7 @@ type paymentActionBody struct { |
| } |
| // PreparePaymentCheckout encodes a one-off payment for later capture using |
| -// req.Key. It makes no provider call; the fake adds no tax. |
| +// req.Key. It makes no provider call; the session adds PaymentTax. |
| func (f *Fake) PreparePaymentCheckout(req billing.PaymentCheckoutRequest) (billing.Prepared, error) { |
| if req.AccountSqid == "" || req.Customer == "" || req.Currency == "" || req.Amount <= 0 || req.Description == "" || req.Reference == "" || req.SuccessURL == "" || req.CancelURL == "" || req.ExpiresAt.IsZero() { |
| return billing.Prepared{}, billing.ErrRefused |
| @@ -1564,7 +1576,8 @@ func (f *Fake) PrepareCancelPayment(paymentIntent, key string) (billing.Prepared |
| } |
| // PaymentCheckout reads the session and PaymentIntent status. ErrNotFound if |
| -// absent. Amount and AmountTotal both equal the requested pre-tax amount. |
| +// absent. Amount is the requested pre-tax amount; AmountTotal adds the |
| +// PaymentTax the session was created with. |
| func (f *Fake) PaymentCheckout(ctx context.Context, sessionID string) (billing.PaymentInfo, error) { |
| f.mu.Lock() |
| defer f.mu.Unlock() |
diff --git a/internal/console/apidomainbuy.go b/internal/console/apidomainbuy.go| index dc3406b55..bd0d2606b 100644 |
| --- a/internal/console/apidomainbuy.go |
| +++ b/internal/console/apidomainbuy.go |
| @@ -269,7 +269,12 @@ type domainPurchaseReply struct { |
| Stage string `json:"stage,omitempty"` |
| // Money is a failed transfer's transferMoneyKey: not_charged, refunded |
| // or refunded_outside. Absent otherwise. |
| - Money string `json:"money,omitempty"` |
| + Money string `json:"money,omitempty"` |
| + // Refund is, beside Money refunded or refunded_outside, what the refund |
| + // returned in minor units of Currency: the captured total, tax |
| + // included. Absent otherwise. |
| + Refund int64 `json:"refund,omitempty"` |
| + Currency string `json:"currency,omitempty"` |
| Domain string `json:"domain"` |
| App string `json:"app"` |
| State PurchaseState `json:"state"` |
| @@ -300,6 +305,9 @@ func (s *Server) writeDomainPurchaseStatus(w http.ResponseWriter, r *http.Reques |
| out.Stage = transferStageKey(p) |
| if p.State == PurchaseFailed { |
| out.Money = transferMoneyKey(p) |
| + if out.Money == "refunded" || out.Money == "refunded_outside" { |
| + out.Refund, out.Currency = transferRefundAmount(p), p.Currency |
| + } |
| } |
| } |
| ctx, cancel := context.WithTimeout(r.Context(), instanceStoreTimeout) |
diff --git a/internal/console/appdomainbuy.go b/internal/console/appdomainbuy.go| index aa434e522..39c5320ec 100644 |
| --- a/internal/console/appdomainbuy.go |
| +++ b/internal/console/appdomainbuy.go |
| @@ -335,6 +335,16 @@ func transferSentWhen(sent, now time.Time) string { |
| } |
| } |
| +// transferRefundAmount is what a refund of p returns, in minor units: the |
| +// captured total, tax included, or the price on a record from before the |
| +// total was kept. |
| +func transferRefundAmount(p *DomainPurchase) int64 { |
| + if p.Facts.CapturedTotal > 0 { |
| + return p.Facts.CapturedTotal |
| + } |
| + return p.Amount |
| +} |
| + |
| // transferCard is p's card at now. The failure's words come from the |
| // reason the transfer recorded (an unknown or empty one is the generic |
| // line), and the money chip from what the payment last read: captured is |
| @@ -344,7 +354,7 @@ func transferSentWhen(sent, now time.Time) string { |
| func transferCard(acct *Account, p *DomainPurchase, now time.Time) transferCardView { |
| c := transferCardCopy |
| st := transferStageOf(p) |
| - amount := plans.FormatMinor(p.Currency, p.Amount) |
| + amount := plans.FormatMinor(p.Currency, transferRefundAmount(p)) |
| fill := strings.NewReplacer("{domain}", p.Domain, "{amount}", amount).Replace |
| v := transferCardView{Eyebrow: domainsFill(domainsPageCopy.PageEyebrow, "{account}", acct.Name), Heading: c.Heading, |
| Stage: st.Kind, PollError: c.PollError} |
diff --git a/internal/console/delivery.go b/internal/console/delivery.go| index 2debd9e2b..888bf6207 100644 |
| --- a/internal/console/delivery.go |
| +++ b/internal/console/delivery.go |
| @@ -16,6 +16,10 @@ const ( |
| deliveredEmail deliveryChannel = "email" |
| ) |
| +// errNoEmailSender is deliver's answer when the console has no mailer: no |
| +// retry will reach the address until one is configured. |
| +var errNoEmailSender = errors.New("console: no email sender is configured") |
| + |
| // domainOf is the lowercased part of addr after its last "@", "" if none. |
| func domainOf(addr string) string { |
| i := strings.LastIndex(addr, "@") |
| @@ -68,7 +72,7 @@ func (s *Server) deliver(ctx context.Context, to, subject, body string, keymailS |
| } |
| } |
| if s.consoleMail == nil { |
| - return "", errors.New("console: no email sender is configured") |
| + return "", errNoEmailSender |
| } |
| if err := s.consoleMail.Send(ctx, to, subject, body); err != nil { |
| log.Printf("console: delivery to %s by email: %v", to, err) |
diff --git a/internal/console/domaintransfer.go b/internal/console/domaintransfer.go| index 4d2108329..43994f090 100644 |
| --- a/internal/console/domaintransfer.go |
| +++ b/internal/console/domaintransfer.go |
| @@ -100,6 +100,8 @@ type transferObservation struct { |
| // with what was captured. |
| payment billing.PaymentInfo |
| paymentOK bool |
| + // statusRead is whether this pass read the registrar's status. |
| + statusRead bool |
| } |
| // advanceTransferStep is one pass over a live transfer. |
| @@ -143,7 +145,8 @@ func purchaseLive(state PurchaseState) bool { |
| } |
| func cloneTransferFacts(f transferFacts) transferFacts { |
| - f.Alerts, f.Owed = maps.Clone(f.Alerts), maps.Clone(f.Owed) |
| + f.Alerts, f.Owed, f.Dropped = maps.Clone(f.Alerts), maps.Clone(f.Owed), maps.Clone(f.Dropped) |
| + f.Delivery = cloneDeliveries(f.Delivery) |
| if f.Completed != nil { |
| c := *f.Completed |
| c.Nameservers = slices.Clone(c.Nameservers) |
| @@ -204,6 +207,7 @@ func (s *Server) readTransferStatus(ctx context.Context, p *DomainPurchase, o *t |
| st, ours = unpinnedTransferRecord(records, f.SubmittedAt) |
| } |
| o.nextStatusAt = nextTransferStatusAt(now, f.SubmittedAt) |
| + o.statusRead = true |
| if err != nil { |
| log.Printf("console: transfer %s: status: %v", p.ID, err) |
| jobFailed(ctx, err) |
| @@ -293,13 +297,41 @@ func unpinnedTransferRecord(records []registrar.TransferStatus, submitted time.T |
| return registrar.TransferStatus{}, false |
| } |
| +// transferPaymentReadDue says whether this pass reads the payment, given |
| +// the facts after the registrar's read. Every pass while the Checkout is |
| +// waiting for its authorisation (the webhook nudges a pass when it |
| +// completes), while a money action is due or was just sent, and once the |
| +// registrar's outcome is definite. While the payment only waits on the |
| +// registrar (captured, or held for a transfer not yet seen accepted), it is |
| +// read with the registrar's status, on that schedule. |
| +func transferPaymentReadDue(f transferFacts, paymentIntent string, statusRead bool) bool { |
| + if paymentIntent == "" || statusRead { |
| + return true |
| + } |
| + switch reg := effectiveRegistrar(f); reg { |
| + case rPending, rUnknown: |
| + switch f.Payment { |
| + case pCaptured: |
| + return false |
| + case pAuthorised: |
| + // A capture is due once the transfer was seen accepted. |
| + return reg == rPending || f.Accepted |
| + } |
| + } |
| + return true |
| +} |
| + |
| // gatherTransferPayment reads the Checkout. Before any authorisation an |
| // open session is pAwaiting whatever its PaymentIntent says (a declined |
| // card may be retried in it) and an expired one pCancelled. After: the |
| // recorded PaymentIntent's status, requires_payment_method reading as |
| -// pFailed only once a capture was sent. |
| +// pFailed only once a capture was sent. A read not due |
| +// (transferPaymentReadDue) keeps the payment as last read. |
| func (s *Server) gatherTransferPayment(ctx context.Context, p *DomainPurchase, o *transferObservation, now time.Time) { |
| f := &o.facts |
| + if o.session != "" && !transferPaymentReadDue(*f, o.paymentIntent, o.statusRead) { |
| + return |
| + } |
| if o.session == "" { |
| switch { |
| case p.CheckoutPrepared == nil: |
| @@ -360,6 +392,10 @@ func (s *Server) gatherTransferPayment(ctx context.Context, p *DomainPurchase, o |
| f.Payment = pAuthorised |
| case "succeeded": |
| f.Payment = pCaptured |
| + if f.CapturedTotal == 0 { |
| + // What a refund gives back: the total, tax included. |
| + f.CapturedTotal = info.AmountTotal |
| + } |
| case "canceled": |
| f.Payment = pCancelled |
| case "requires_payment_method": |
| @@ -448,8 +484,9 @@ func (s *Server) gatherTransferRefund(ctx context.Context, p *DomainPurchase, o |
| } |
| f.RefundID, f.RefundReason = r.ID, "" |
| } |
| - // A refund made for the attempt ends a run of refused creates. |
| - f.RefundRefusals, f.RefundMismatch = 0, false |
| + // A refund made for the attempt ends a run of refused creates, and of |
| + // failed sends. |
| + f.RefundRefusals, f.RefundMismatch, f.RefundSend = 0, false, transferSends{} |
| switch r.Status { |
| case billing.RefundSucceeded: |
| f.Refund = fPending |
| @@ -537,18 +574,16 @@ func (s *Server) actTransfer(ctx context.Context, acct *Account, p *DomainPurcha |
| case aCapture: |
| return s.captureTransfer(ctx, p, o) |
| case aCancelAuthorisation: |
| - if err := s.recordTransferIfChanged(ctx, p, o); err != nil { |
| - return err |
| - } |
| - if err := transferStep("cancel:recorded"); err != nil { |
| - return err |
| - } |
| - prepared, err := provider.PrepareCancelPayment(o.paymentIntent, p.ID+":cancel") |
| - if err != nil { |
| - return err |
| - } |
| - _, err = provider.Send(ctx, prepared) |
| - return err |
| + return s.boundedSend(ctx, p, o, "cancel", &o.facts.Cancel, func(key string) (billing.Prepared, error) { |
| + return provider.PrepareCancelPayment(o.paymentIntent, key) |
| + }) |
| + case aExpireCheckout: |
| + if o.session == "" { |
| + return fmt.Errorf("console: transfer %s: no Checkout to expire", p.ID) |
| + } |
| + return s.boundedSend(ctx, p, o, "expire", &o.facts.Expire, func(key string) (billing.Prepared, error) { |
| + return provider.PrepareExpire(o.session, key) |
| + }) |
| case aCreateRefund: |
| return s.refundTransfer(ctx, p, o, d) |
| case aRecordDone, aRecordUnpaid: |
| @@ -571,18 +606,21 @@ func (s *Server) actTransfer(ctx context.Context, acct *Account, p *DomainPurcha |
| // captureTransfer sends the capture. CaptureAttempted is recorded before |
| // the send (only then can requires_payment_method read as a failed |
| // capture). A failed send is counted, with its kind, apart from the payment |
| -// outcome, which only the next read decides; the count stops at the alert |
| -// threshold, so a capture stuck for days writes nothing new each pass. |
| +// outcome, which only the next read decides, and sets the next-send time |
| +// (nextCaptureAt); an answer the provider keeps under the key moves the key |
| +// on (transferSendKey). A send that succeeded waits the schedule's first |
| +// step too, so a read that has not caught up yet does not resend each pass. |
| func (s *Server) captureTransfer(ctx context.Context, p *DomainPurchase, o *transferObservation) error { |
| provider := s.billing.cfg.Provider |
| - o.facts.CaptureAttempted = true |
| + f := &o.facts |
| + f.CaptureAttempted = true |
| if err := s.recordTransferIfChanged(ctx, p, o); err != nil { |
| return err |
| } |
| if err := transferStep("capture:recorded"); err != nil { |
| return err |
| } |
| - prepared, err := provider.PrepareCapture(o.paymentIntent, p.ID+":capture") |
| + prepared, err := provider.PrepareCapture(o.paymentIntent, transferSendKey(p.ID, "capture", f.CaptureKey)) |
| if err == nil { |
| _, err = provider.Send(ctx, prepared) |
| } |
| @@ -590,16 +628,78 @@ func (s *Server) captureTransfer(ctx context.Context, p *DomainPurchase, o *tran |
| return err |
| } |
| if err != nil { |
| - if o.facts.CaptureFailures < transferCaptureFailingAfter { |
| - o.facts.CaptureFailures++ |
| + f.CaptureFailures = min(f.CaptureFailures+1, len(transferSendSchedule)) |
| + f.CaptureError = captureErrorKind(err) |
| + f.CaptureNextAt = nextCaptureAt(f.Now, f.CaptureFailures, f.CaptureBefore) |
| + if sendAnswerKept(err) { |
| + f.CaptureKey++ |
| } |
| - o.facts.CaptureError = captureErrorKind(err) |
| return errors.Join(err, s.recordTransferIfChanged(ctx, p, o)) |
| } |
| - o.facts.CaptureFailures, o.facts.CaptureError = 0, "" |
| + f.CaptureFailures, f.CaptureError, f.CaptureNextAt = 0, "", f.Now.Add(transferSendSchedule[0]) |
| return s.recordTransferIfChanged(ctx, p, o) |
| } |
| +// boundedSend is the release of the hold or the Checkout's expiry: Asked is |
| +// recorded, then the send, counted as the capture's is (noteSend). The next |
| +// read, never the answer, says what happened. |
| +func (s *Server) boundedSend(ctx context.Context, p *DomainPurchase, o *transferObservation, verb string, sends *transferSends, prepare func(key string) (billing.Prepared, error)) error { |
| + sends.Asked = true |
| + if err := s.recordTransferIfChanged(ctx, p, o); err != nil { |
| + return err |
| + } |
| + if err := transferStep(verb + ":recorded"); err != nil { |
| + return err |
| + } |
| + prepared, err := prepare(transferSendKey(p.ID, verb, sends.Key)) |
| + if err == nil { |
| + _, err = s.billing.cfg.Provider.Send(ctx, prepared) |
| + } |
| + if transferPassStopped(err) { |
| + return err |
| + } |
| + noteSend(sends, o.facts.Now, err) |
| + return errors.Join(err, s.recordTransferIfChanged(ctx, p, o)) |
| +} |
| + |
| +// noteSend records a send's answer: a failure counts (capped at the |
| +// schedule's length), names its kind and waits out the backoff, and an |
| +// answer kept under the key moves the key on; a success clears the count |
| +// and waits the first step, for the read to catch up. |
| +func noteSend(sends *transferSends, now time.Time, err error) { |
| + if err == nil { |
| + sends.Failures, sends.Error, sends.NextAt = 0, "", now.Add(transferSendSchedule[0]) |
| + return |
| + } |
| + sends.Failures = min(sends.Failures+1, len(transferSendSchedule)) |
| + sends.Error = captureErrorKind(err) |
| + sends.NextAt = now.Add(transferSendBackoff(sends.Failures)) |
| + if sendAnswerKept(err) { |
| + sends.Key++ |
| + } |
| +} |
| + |
| +// transferSendKey is a capture, release or expiry's idempotency key: the |
| +// purchase and the verb, then the key's number after the first. The |
| +// provider keeps a request's answer under its key for at least 24 hours, |
| +// a 500 included, so after such an answer a resend under the same key would |
| +// only replay it: the number moves on instead. A new key cannot do the |
| +// thing twice: the provider refuses to capture or release a PaymentIntent |
| +// already captured or released, and to expire a session that is not open. |
| +func transferSendKey(id, verb string, n int) string { |
| + if n == 0 { |
| + return id + ":" + verb |
| + } |
| + return fmt.Sprintf("%s:%s:%d", id, verb, n) |
| +} |
| + |
| +// sendAnswerKept says whether the provider stores err's answer under the |
| +// key (fact 5 and the executed refusals): a 5xx, a refusal or a decline. A |
| +// lost answer, a 409 in flight or a 429 is resent under the same key. |
| +func sendAnswerKept(err error) bool { |
| + return errors.Is(err, billing.ErrIndeterminate) || errors.Is(err, billing.ErrRefused) || errors.Is(err, billing.ErrPaymentFailed) |
| +} |
| + |
| // captureErrorKind names a capture send's failure for the record. |
| func captureErrorKind(err error) string { |
| for _, c := range []struct { |
| @@ -670,6 +770,7 @@ func (s *Server) refundTransfer(ctx context.Context, p *DomainPurchase, o *trans |
| return err |
| } |
| o.facts.RefundAttempt, o.facts.RefundID, o.facts.Refund, o.facts.RefundReason = n, "", fNone, "" |
| + o.facts.RefundSend = transferSends{} |
| if err := s.recordTransfer(ctx, p, o, transferLiveState(o.facts, p.State), func(q *DomainPurchase) { q.RefundPrepared = &prepared }); err != nil { |
| return err |
| } |
| @@ -690,13 +791,29 @@ func (s *Server) refundTransfer(ctx context.Context, p *DomainPurchase, o *trans |
| // through the refused alerts (no failed-refund alert is owed for it). |
| o.facts.Refund, o.facts.RefundReason, o.facts.RefundFailedAt = fFailed, refundRefused, o.facts.Now |
| o.facts.RefundRefusals++ |
| + o.facts.RefundSend = transferSends{} |
| return errors.Join(err, s.recordTransfer(ctx, p, o, transferLiveState(o.facts, p.State), nil)) |
| } |
| - if err != nil { |
| + if transferPassStopped(err) { |
| return err |
| } |
| + // Any other answer is counted and waits out the backoff, as the |
| + // capture's does, but the key stays: the attempt's stored request is |
| + // resent verbatim, never under a new key. Only a new attempt (after this |
| + // one's refund is read failed) is a new request, and before every send |
| + // the list read has found no refund made for this attempt, so a create |
| + // whose answer was lost is read, not made twice. After a 500 kept under |
| + // the key, the resends replay it until the provider drops the key (after |
| + // 24 hours), while the refund-failing alert tells the operator. |
| + refundSends := o.facts.RefundSend |
| + noteSend(&refundSends, o.facts.Now, err) |
| + refundSends.Key = 0 |
| + o.facts.RefundSend = refundSends |
| + if err != nil { |
| + return errors.Join(err, s.recordTransferIfChanged(ctx, p, o)) |
| + } |
| if res.Refund == nil || res.Refund.ID == "" { |
| - return nil |
| + return s.recordTransferIfChanged(ctx, p, o) |
| } |
| o.facts.RefundID, o.facts.RefundRefusals = res.Refund.ID, 0 |
| return s.recordTransfer(ctx, p, o, transferLiveState(o.facts, p.State), nil) |
diff --git a/internal/console/domaintransfer_bounded_test.go b/internal/console/domaintransfer_bounded_test.go| new file mode 100644 |
| index 000000000..ce5d2304b |
| --- /dev/null |
| +++ b/internal/console/domaintransfer_bounded_test.go |
| @@ -0,0 +1,435 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "net/http/httptest" |
| + "slices" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/billing" |
| + "github.com/carlosframework/platform/internal/plans" |
| + "github.com/carlosframework/platform/internal/registrar" |
| +) |
| + |
| +// The final review's fixes to the transfer engine: bounded sends (F1), |
| +// payment reads on a schedule (F2), bounded notices (F3), Checkout expiry on |
| +// the provider's word (F4) and the refund's amount with tax (F5). |
| + |
| +// failSends fails every send of the given kinds with a 500, recording keys. |
| +func (tf *transferFixture) failSends(kinds ...string) *[]string { |
| + var keys []string |
| + tf.fake.BeforeSend = func(pr billing.Prepared) error { |
| + if slices.Contains(kinds, pr.Kind) { |
| + keys = append(keys, pr.Key) |
| + return fmt.Errorf("%w: 500", billing.ErrIndeterminate) |
| + } |
| + return nil |
| + } |
| + return &keys |
| +} |
| + |
| +// TestTransferReleaseOfHoldBacksOffAndAlerts: a refused transfer's hold |
| +// release that keeps failing waits out the send backoff (and a restart does |
| +// not shorten it), moves its key on after each 500, and alerts the operator |
| +// from the third failure, then daily. Once the provider answers, the hold is |
| +// released and the transfer ends failed. |
| +func TestTransferReleaseOfHoldBacksOffAndAlerts(t *testing.T) { |
| + tf := newTransferFixture(t) |
| + keys := tf.failSends(billing.PreparedCancelPayment) |
| + p := tf.submitted(t) |
| + tf.reg.Advance("shop.com", registrar.TransferStatus{State: registrar.TransferFailed, Reason: "auth_code"}) |
| + p = tf.pass(t, p.ID) // failed: the first release fails |
| + for step, wait := range transferSendSchedule[:3] { |
| + if p.Facts.Cancel.Failures != step+1 || !p.Facts.Cancel.NextAt.Equal(tf.now.Add(wait)) { |
| + t.Fatalf("after failure %d: %+v", step+1, p.Facts.Cancel) |
| + } |
| + tf.tick(wait - time.Second) |
| + tf.restart(t) |
| + before := tf.sent(billing.PreparedCancelPayment) |
| + p = tf.pass(t, p.ID) |
| + if tf.sent(billing.PreparedCancelPayment) != before { |
| + t.Fatalf("release sent inside its %s backoff", wait) |
| + } |
| + tf.tick(time.Second) |
| + p = tf.pass(t, p.ID) |
| + } |
| + if want := []string{p.ID + ":cancel", p.ID + ":cancel:1", p.ID + ":cancel:2", p.ID + ":cancel:3"}; !slices.Equal(*keys, want) { |
| + t.Fatalf("release keys %v, want %v", *keys, want) |
| + } |
| + if tf.alerts(alertCancelFailing) != 1 || p.Facts.Cancel.Failures != 4 { |
| + t.Fatalf("cancel-failing alerts %d after %d failures", tf.alerts(alertCancelFailing), p.Facts.Cancel.Failures) |
| + } |
| + for i := 0; i < 8; i++ { // two days at 6 h |
| + tf.tick(6 * time.Hour) |
| + p = tf.pass(t, p.ID) |
| + } |
| + if n := tf.alerts(alertCancelFailing); n < 2 || n > 3 { |
| + t.Fatalf("cancel-failing alerts %d over two more days, want daily", n) |
| + } |
| + tf.fake.BeforeSend = nil |
| + tf.tick(6 * time.Hour) |
| + for i := 0; i < 2 && purchaseLive(p.State); i++ { |
| + p = tf.pass(t, p.ID) |
| + tf.tick(time.Minute) |
| + } |
| + if p.State != PurchaseFailed || tf.intentStatus(t, p) != "canceled" { |
| + t.Fatalf("not released and failed: %s %s", p.State, tf.intentStatus(t, p)) |
| + } |
| +} |
| + |
| +// TestTransferRefundSendsBackOffWithOneKey: a refund create that keeps |
| +// failing (not refused) is resent on the backoff under the same key, the |
| +// attempt's stored request, never as a new attempt; the operator hears from |
| +// the third failure. Once the provider answers, exactly one refund is made. |
| +func TestTransferRefundSendsBackOffWithOneKey(t *testing.T) { |
| + tf := newTransferFixture(t) |
| + p := tf.failAfterCapture(t, "rejected") |
| + keys := tf.failSends(billing.PreparedRefund) |
| + p = tf.pass(t, p.ID) // failed: refund attempt 1 fails to send |
| + for step, wait := range transferSendSchedule[:3] { |
| + if p.Facts.RefundSend.Failures != step+1 || !p.Facts.RefundSend.NextAt.Equal(tf.now.Add(wait)) || p.Facts.RefundAttempt != 1 { |
| + t.Fatalf("after failure %d: %+v attempt %d", step+1, p.Facts.RefundSend, p.Facts.RefundAttempt) |
| + } |
| + tf.tick(wait - time.Second) |
| + before := tf.sent(billing.PreparedRefund) |
| + p = tf.pass(t, p.ID) |
| + if tf.sent(billing.PreparedRefund) != before { |
| + t.Fatalf("refund sent inside its %s backoff", wait) |
| + } |
| + tf.tick(time.Second) |
| + p = tf.pass(t, p.ID) |
| + } |
| + for _, k := range *keys { |
| + if k != p.ID+":refund:1" { |
| + t.Fatalf("refund resent under a new key: %v", *keys) |
| + } |
| + } |
| + if tf.alerts(alertRefundFailing) != 1 { |
| + t.Fatalf("refund-failing alerts = %d", tf.alerts(alertRefundFailing)) |
| + } |
| + tf.fake.BeforeSend = nil |
| + tf.tick(time.Hour) |
| + for i := 0; i < 3 && purchaseLive(p.State); i++ { |
| + p = tf.pass(t, p.ID) |
| + tf.tick(time.Minute) |
| + } |
| + if refunds := tf.refunds(t, p); p.State != PurchaseFailed || len(refunds) != 1 || refunds[0].Attempt != 1 { |
| + t.Fatalf("not refunded once: %s %+v", p.State, refunds) |
| + } |
| +} |
| + |
| +// TestTransferCapturedWaitReadsPaymentWithStatus: a captured transfer |
| +// waiting on the registrar reads the payment only with the registrar's |
| +// status (every 30 minutes), not every pass; one waiting on its capture |
| +// reads every pass. |
| +func TestTransferCapturedWaitReadsPaymentWithStatus(t *testing.T) { |
| + tf := newTransferFixture(t) |
| + p := tf.submitted(t) |
| + p = tf.pass(t, p.ID) // pending: capture |
| + p = tf.pass(t, p.ID) // captured observed |
| + if p.Facts.Payment != pCaptured { |
| + t.Fatalf("not captured: %+v", p.Facts) |
| + } |
| + reads := tf.fake.CallsBy["PaymentCheckout"] |
| + for i := 0; i < 240; i++ { // an hour of 15 s passes |
| + tf.tick(15 * time.Second) |
| + p = tf.pass(t, p.ID) |
| + } |
| + if n := tf.fake.CallsBy["PaymentCheckout"] - reads; n < 1 || n > 3 { |
| + t.Fatalf("payment read %d times in an hour of passes, want with the status reads only", n) |
| + } |
| + |
| + // Authorised and accepted, the capture failing: read every pass. |
| + tf2 := newTransferFixture(t) |
| + tf2.failSends(billing.PreparedCapture) |
| + p2 := tf2.submitted(t) |
| + p2 = tf2.pass(t, p2.ID) |
| + reads = tf2.fake.CallsBy["PaymentCheckout"] |
| + for i := 0; i < 4; i++ { |
| + tf2.tick(15 * time.Second) |
| + p2 = tf2.pass(t, p2.ID) |
| + } |
| + if n := tf2.fake.CallsBy["PaymentCheckout"] - reads; n != 4 { |
| + t.Fatalf("a capture under way read the payment %d times in 4 passes", n) |
| + } |
| +} |
| + |
| +// addressMail fails delivery to the addresses in fail and records the rest. |
| +type addressMail struct { |
| + mu sync.Mutex |
| + fail map[string]error |
| + sent []string // to|subject |
| +} |
| + |
| +func (m *addressMail) Ready(context.Context) bool { return true } |
| + |
| +func (m *addressMail) Send(_ context.Context, to, subject, _ string) error { |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + if err := m.fail[to]; err != nil { |
| + return err |
| + } |
| + m.sent = append(m.sent, to+"|"+subject) |
| + return nil |
| +} |
| + |
| +func (m *addressMail) count(to string) int { |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + n := 0 |
| + for _, s := range m.sent { |
| + if strings.HasPrefix(s, to+"|") { |
| + n++ |
| + } |
| + } |
| + return n |
| +} |
| + |
| +// doneTransfer drives a transfer to done with its owner email still owed. |
| +func (tf *transferFixture) doneTransfer(t *testing.T) *DomainPurchase { |
| + t.Helper() |
| + p := tf.submitted(t) |
| + p = tf.pass(t, p.ID) // capture |
| + tf.reg.Advance("shop.com", registrar.TransferStatus{State: registrar.TransferCompleted, Registered: registrar.Registered{Domain: "shop.com", RegistrarID: "reg-shop", Expires: tf.now.AddDate(1, 0, 0).Truncate(time.Second)}}) |
| + tf.tick(transferStatusEvery) |
| + for i := 0; i < 3 && purchaseLive(p.State); i++ { |
| + p = tf.pass(t, p.ID) |
| + } |
| + if p.State != PurchaseDone { |
| + t.Fatalf("not done: %+v", p) |
| + } |
| + return p |
| +} |
| + |
| +// noticePass runs the ended purchases' notice step. |
| +func (tf *transferFixture) noticePass(t *testing.T) { |
| + t.Helper() |
| + if err := tf.srv.transferNoticesPass(context.Background()); err != nil { |
| + t.Logf("notices: %v", err) |
| + } |
| +} |
| + |
| +// TestTransferNoticePerOwnerWithBackoff: with two owners and one of them |
| +// failing, the healthy owner is emailed once, the failing one is retried on |
| +// the notice backoff (1 h, 6 h, then daily) and never more often, and once |
| +// it gets through, nobody is emailed again. |
| +func TestTransferNoticePerOwnerWithBackoff(t *testing.T) { |
| + tf := newTransferFixture(t) |
| + owner := ownerAddress(t, tf) |
| + second := "second-owner@example.test" |
| + if err := tf.st.AddMember(tf.acct.ID, second, RoleOwner, time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + mail := &addressMail{fail: map[string]error{second: errors.New("mail down for this one")}} |
| + tf.srv.consoleMail = mail |
| + p := tf.doneTransfer(t) |
| + if mail.count(owner) != 1 || mail.count(second) != 0 { |
| + t.Fatalf("first try: owner %d, second %d", mail.count(owner), mail.count(second)) |
| + } |
| + for _, wait := range []time.Duration{time.Hour, 6 * time.Hour, 24 * time.Hour, 24 * time.Hour} { |
| + p = tf.read(t, p.ID) |
| + d := p.Facts.Delivery[noticeOwnerDone] |
| + if !slices.Equal(d.To, []string{owner}) || d.NextAt.Sub(tf.now) != wait { |
| + t.Fatalf("delivery %+v, want the next try %s from now", d, wait) |
| + } |
| + tf.tick(wait - time.Minute) |
| + tf.noticePass(t) |
| + if mail.count(owner) != 1 { |
| + t.Fatalf("the reached owner was emailed again: %d", mail.count(owner)) |
| + } |
| + tf.tick(time.Minute) |
| + tf.noticePass(t) |
| + } |
| + mail.mu.Lock() |
| + mail.fail = nil |
| + mail.mu.Unlock() |
| + tf.tick(24 * time.Hour) |
| + tf.noticePass(t) |
| + tf.tick(24 * time.Hour) |
| + tf.noticePass(t) |
| + p = tf.read(t, p.ID) |
| + if mail.count(owner) != 1 || mail.count(second) != 1 || len(outstandingNotices(p.Facts)) != 0 || p.Facts.Alerts[noticeOwnerDone].IsZero() { |
| + t.Fatalf("owner %d, second %d, outstanding %v", mail.count(owner), mail.count(second), outstandingNotices(p.Facts)) |
| + } |
| + if tf.alerts(alertNoticeDropped) != 0 { |
| + t.Fatal("a delivered notice was reported dropped") |
| + } |
| +} |
| + |
| +// TestTransferNoticeDroppedOnPermanentFailures: an owner who blocked the |
| +// console, no email sender, or an account deleted after the transfer ended |
| +// end the notice's retries: it is given up with one operator alert, and |
| +// not tried again. |
| +func TestTransferNoticeDroppedOnPermanentFailures(t *testing.T) { |
| + for _, mode := range []string{"no email sender", "account gone"} { |
| + t.Run(mode, func(t *testing.T) { |
| + tf := newTransferFixture(t) |
| + tf.mailFails(errors.New("mail down")) |
| + p := tf.doneTransfer(t) |
| + switch mode { |
| + case "no email sender": |
| + tf.srv.consoleMail = nil |
| + case "account gone": |
| + tf.mailFails(nil) |
| + if _, err := tf.st.db.Exec(`DELETE FROM accounts WHERE id=?`, tf.acct.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + for i := 0; i < 4; i++ { |
| + tf.tick(25 * time.Hour) |
| + tf.noticePass(t) |
| + } |
| + p = tf.read(t, p.ID) |
| + if p.Facts.Dropped[noticeOwnerDone].IsZero() || len(outstandingNotices(p.Facts)) != 0 { |
| + t.Fatalf("not dropped: %+v", p.Facts) |
| + } |
| + if tf.alerts(alertNoticeDropped+noticeOwnerDone) != 1 { |
| + t.Fatalf("dropped alerts %d, want 1: %v", tf.alerts(alertNoticeDropped+noticeOwnerDone), tf.pages) |
| + } |
| + if owing, _ := tf.st.TransfersOwingNotices(context.Background()); len(owing) != 0 { |
| + t.Fatalf("still owing: %d", len(owing)) |
| + } |
| + }) |
| + } |
| + if !deliveryPermanent(fmt.Errorf("x: %w", errNoEmailSender)) || deliveryPermanent(errors.New("mail down")) { |
| + t.Fatal("deliveryPermanent misreads") |
| + } |
| + |
| + // A blocked owner is given up on alone: the other owner gets it, and the |
| + // operator hears once that one could not be reached. |
| + tf := newTransferFixture(t) |
| + owner := ownerAddress(t, tf) |
| + blocked := "blocked-owner@example.test" |
| + if err := tf.st.AddMember(tf.acct.ID, blocked, RoleOwner, time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + mail := &addressMail{} |
| + tf.srv.consoleMail = mail |
| + tf.srv.sendFederated = func(_ context.Context, to, _, _ string) (string, error) { |
| + if to == blocked { |
| + return "", &keymailError{Status: 403, Msg: "blocked"} |
| + } |
| + return "", ErrNoKeymailMailbox |
| + } |
| + p := tf.doneTransfer(t) |
| + for i := 0; i < 3; i++ { |
| + tf.tick(25 * time.Hour) |
| + tf.noticePass(t) |
| + } |
| + p = tf.read(t, p.ID) |
| + if mail.count(owner) != 1 || mail.count(blocked) != 0 || p.Facts.Alerts[noticeOwnerDone].IsZero() || len(outstandingNotices(p.Facts)) != 0 { |
| + t.Fatalf("owner %d, blocked %d, facts %+v", mail.count(owner), mail.count(blocked), p.Facts) |
| + } |
| + if tf.alerts(alertNoticeDropped+noticeOwnerDone) != 1 { |
| + t.Fatalf("dropped alerts %d, want 1", tf.alerts(alertNoticeDropped+noticeOwnerDone)) |
| + } |
| +} |
| + |
| +// ownerAddress is the fixture account's owner. |
| +func ownerAddress(t *testing.T, tf *transferFixture) string { |
| + t.Helper() |
| + members, err := tf.st.Members(tf.acct.ID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, m := range members { |
| + if m.Role == RoleOwner { |
| + return m.Name |
| + } |
| + } |
| + t.Fatal("no owner") |
| + return "" |
| +} |
| + |
| +// TestTransferCheckoutExpiryOnTheProvidersWord: the console's clock runs |
| +// ahead of the provider's. Past expiry on the console's clock the purchase |
| +// is not ended: the provider is asked to expire the session, and only its |
| +// expired session ends it. A customer who pays in the gap, before the |
| +// console asks, is settled as any authorisation is (the transfer is sent); |
| +// one who pays just as the request arrives has the hold released, and the |
| +// purchase ends expired with nothing held. |
| +func TestTransferCheckoutExpiryOnTheProvidersWord(t *testing.T) { |
| + for _, mode := range []string{"nobody pays", "pays in the gap", "pays as the expiry arrives"} { |
| + t.Run(mode, func(t *testing.T) { |
| + tf := newTransferFixture(t) |
| + p := tf.start(t) |
| + tf.fake.SetProviderClock(tf.now.Add(-20 * time.Minute)) // the provider is behind |
| + tf.tick(time.Hour) // the console's expiry; the provider's is 20 minutes off |
| + switch mode { |
| + case "pays in the gap": |
| + tf.authorise(t, p) |
| + case "pays as the expiry arrives": |
| + tf.fake.BeforeSend = func(pr billing.Prepared) error { |
| + if pr.Kind == billing.PreparedExpire { |
| + tf.fake.BeforeSend = nil |
| + _, err := tf.fake.CompletePaymentCheckout(tf.read(t, p.ID).CheckoutSession) |
| + return err |
| + } |
| + return nil |
| + } |
| + } |
| + p = tf.pass(t, p.ID) |
| + if mode == "pays in the gap" { |
| + if p.State != PurchaseTransferSubmitting || tf.sent(billing.PreparedExpire) != 0 { |
| + t.Fatalf("an authorisation in the gap was not settled: %s, expiries %d", p.State, tf.sent(billing.PreparedExpire)) |
| + } |
| + return |
| + } |
| + if !purchaseLive(p.State) || !p.Facts.Expire.Asked || tf.sent(billing.PreparedExpire) != 1 { |
| + t.Fatalf("ended on the console's clock, or not asked: %s %+v", p.State, p.Facts.Expire) |
| + } |
| + for i := 0; i < 4 && purchaseLive(p.State); i++ { |
| + tf.tick(time.Minute) |
| + p = tf.pass(t, p.ID) |
| + } |
| + if p.State != PurchaseExpired { |
| + t.Fatalf("not expired: %s %+v", p.State, p.Facts) |
| + } |
| + info, err := tf.fake.PaymentCheckout(context.Background(), p.CheckoutSession) |
| + if err != nil || info.IntentStatus == "requires_capture" || info.IntentStatus == "succeeded" { |
| + t.Fatalf("ended with money held: %+v %v", info, err) |
| + } |
| + if mode == "pays as the expiry arrives" && (info.IntentStatus != "canceled" || tf.sent(billing.PreparedCancelPayment) != 1 || purchaseCalls(tf.reg.Calls, "request-transfer:") != 0) { |
| + t.Fatalf("the late hold was not released, or the transfer was sent: %+v %v", info, tf.reg.Calls) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestTransferRefundNoteIncludesTax: with exclusive tax on the Checkout, |
| +// the captured total is recorded, and the card, the status reply and the |
| +// CLI's line state the refund as that total, not the price. |
| +func TestTransferRefundNoteIncludesTax(t *testing.T) { |
| + tf := newTransferFixture(t) |
| + tf.fake.PaymentTax = 276 // 23% on 12.00 |
| + p := tf.failAfterCapture(t, "rejected") |
| + for i := 0; i < 4 && purchaseLive(p.State); i++ { |
| + p = tf.pass(t, p.ID) |
| + } |
| + if p.State != PurchaseFailed || p.Facts.CapturedTotal != p.Amount+276 { |
| + t.Fatalf("captured total %d (price %d): %s", p.Facts.CapturedTotal, p.Amount, p.State) |
| + } |
| + total := plans.FormatMinor(p.Currency, p.Amount+276) |
| + card := transferCard(tf.acct, p, tf.now) |
| + if !strings.Contains(card.Note, total) || strings.Contains(card.Note, plans.FormatMinor(p.Currency, p.Amount)+" ") { |
| + t.Fatalf("card note %q, want the total %s", card.Note, total) |
| + } |
| + w := httptest.NewRecorder() |
| + tf.srv.writeDomainPurchaseStatus(w, httptest.NewRequest("GET", "/", nil), tf.acct, p) |
| + var reply domainPurchaseReply |
| + if err := json.Unmarshal(w.Body.Bytes(), &reply); err != nil || reply.Money != "refunded" || reply.Refund != p.Amount+276 || reply.Currency != p.Currency { |
| + t.Fatalf("status reply %s: %v", w.Body.String(), err) |
| + } |
| + // A record from before the total was kept falls back to the price. |
| + old := *p |
| + old.Facts.CapturedTotal = 0 |
| + if transferRefundAmount(&old) != p.Amount { |
| + t.Fatal("no fallback to the price") |
| + } |
| +} |
diff --git a/internal/console/domaintransfer_copy.go b/internal/console/domaintransfer_copy.go| index 8c6d6845d..185a78583 100644 |
| --- a/internal/console/domaintransfer_copy.go |
| +++ b/internal/console/domaintransfer_copy.go |
| @@ -1,6 +1,7 @@ |
| package console |
| import ( |
| + "fmt" |
| "net/http" |
| "strings" |
| ) |
| @@ -185,12 +186,23 @@ var transferAlertCopy = map[string]string{ |
| alertRefundMismatch: "a refund of a failed transfer succeeded for less than the capture; refund the rest by hand", |
| alertPaymentWrong: "the transfer authorisation does not match its amount, currency or payment; check the payment provider", |
| alertUnpaid: "transfer completed but nothing was captured: recorded unpaid", |
| + // Drafts for the Luna pass (final review fixes, F1): operator-facing. |
| + alertCancelFailing: "releasing the card hold of a transfer keeps failing; retried with backoff. check the payment provider before the hold lapses", |
| + alertRefundFailing: "the refund of a failed transfer keeps failing to send; retried with backoff. check the payment provider", |
| } |
| +// transferNoticeDroppedCopy is the operator's alert reason when an owner |
| +// email was given up (alertNoticeDropped); %s is the email's kind. Draft |
| +// for the Luna pass (final review fixes, F3): operator-facing. |
| +const transferNoticeDroppedCopy = "the owner email %s for this transfer could not reach every owner (blocked, no email sender, or the account is gone) and was given up; tell them another way" |
| + |
| func transferAlertReason(kind string) string { |
| if msg, ok := transferAlertCopy[kind]; ok { |
| return msg |
| } |
| + if notice, ok := strings.CutPrefix(kind, alertNoticeDropped); ok { |
| + return fmt.Sprintf(transferNoticeDroppedCopy, notice) |
| + } |
| if attempt, ok := strings.CutPrefix(kind, alertRefundFailed); ok { |
| return "transfer failed and refund attempt " + attempt + " failed; a new attempt is under way" |
| } |
diff --git a/internal/console/domaintransfer_decide.go b/internal/console/domaintransfer_decide.go| index 1c1579d08..280b0505f 100644 |
| --- a/internal/console/domaintransfer_decide.go |
| +++ b/internal/console/domaintransfer_decide.go |
| @@ -14,8 +14,10 @@ import ( |
| // facts, never an action's reply, say what happened. |
| // |
| // The money action and the alerts are independent: alerts are due whatever |
| -// the action (a capture retried every pass does not hold them back), and |
| -// delivering them never changes settlement. |
| +// the action (a capture waiting out its backoff does not hold them back), |
| +// and delivering them never changes settlement. Every send's backoff is a |
| +// fact (its next-send time): a send is chosen only once that time has come, |
| +// and until then the pass waits, reading and alerting as usual. |
| func decideTransfer(f transferFacts) transferDecision { |
| d := decideTransferMoney(f) |
| d.Alerts = dueTransferAlerts(f) |
| @@ -34,12 +36,13 @@ const ( |
| aRecordDone |
| aRecordUnpaid |
| aFinishFailed |
| + aExpireCheckout |
| ) |
| var transferActionNames = []string{ |
| aWait: "wait", aSubmit: "submit", aCapture: "capture", aCancelAuthorisation: "cancel-authorisation", |
| aCreateRefund: "create-refund", aRecordDone: "record-done", aRecordUnpaid: "record-unpaid", |
| - aFinishFailed: "finish-failed", |
| + aFinishFailed: "finish-failed", aExpireCheckout: "expire-checkout", |
| } |
| func (a transferAction) String() string { |
| @@ -73,6 +76,9 @@ const ( |
| alertUnknownWeekly = "weekly-unknown" // weekly while the outcome stays unknown |
| alertCaptureRefused = "capture-refused" // accepted, but the capture was refused or the hold ended |
| alertCaptureFailing = "capture-failing" // capture sends keep failing while the hold is in place: then daily |
| + alertCancelFailing = "cancel-failing" // sends releasing the hold keep failing while it is in place: then daily |
| + alertRefundFailing = "refund-failing" // refund create sends keep failing (not refused): then daily |
| + alertNoticeDropped = "notice-dropped:" // + the notice kind: it could not reach someone and was given up (owed) |
| alertRefundFailed = "refund-failed:" // + the attempt number: a refund attempt failed (owed) |
| alertRefundRefused = "refund-refused" // the provider refuses the refund create: at once, then daily |
| alertRefundMismatch = "refund-mismatch" // a refund succeeded that is not the full capture: then daily |
| @@ -94,7 +100,13 @@ const ( |
| transferUnknownRepeat = 7 * 24 * time.Hour |
| transferDailyRepeat = 24 * time.Hour |
| transferCaptureFailingAfter = 3 |
| - refundRefusedAlertEvery = transferDailyRepeat |
| + // transferSendFailingAfter is how many cancel or refund sends fail in a |
| + // row before their failing alert, as for the capture. |
| + transferSendFailingAfter = transferCaptureFailingAfter |
| + // transferCaptureLastDayWait caps the capture's backoff in the hold's |
| + // last day, so it is tried often until the hold lapses. |
| + transferCaptureLastDayWait = 30 * time.Minute |
| + refundRefusedAlertEvery = transferDailyRepeat |
| // refundRefusedOutsideAfter is how many refused refund creates the |
| // operator waits for before recording a refund made another way. |
| refundRefusedOutsideAfter = 3 |
| @@ -134,10 +146,20 @@ func decideTransferMoney(f transferFacts) transferDecision { |
| switch f.Payment { |
| case pAwaiting: |
| // Checkout is open; a declined card may still be retried in it. |
| + // Past its expiry on the console's clock, the provider is asked |
| + // to end it: only its word (an expired session) ends the |
| + // purchase, so a customer who paid in the gap is never stranded |
| + // with a hold. |
| if !f.CheckoutExpires.IsZero() && !f.Now.Before(f.CheckoutExpires) { |
| - return transferDecision{Action: aFinishFailed, Terminal: PurchaseExpired} |
| + return sendWhenDue(f, f.Expire.NextAt, transferDecision{Action: aExpireCheckout}) |
| } |
| case pAuthorised: |
| + if f.Expire.Asked { |
| + // Authorised in the gap after the console asked the provider |
| + // to end the Checkout: the purchase was already ending, so the |
| + // hold is released and it ends expired. |
| + return sendWhenDue(f, f.Cancel.NextAt, transferDecision{Action: aCancelAuthorisation}) |
| + } |
| return transferDecision{Action: aSubmit} |
| case pCancelled: |
| // Nothing was sent and nothing taken. |
| @@ -147,11 +169,11 @@ func decideTransferMoney(f transferFacts) transferDecision { |
| // Never settled blind. A transfer the registrar was seen to accept |
| // is captured as an accepted one is; nothing else moves money. |
| if f.Accepted && f.Payment == pAuthorised { |
| - return transferDecision{Action: aCapture} |
| + return sendWhenDue(f, f.CaptureNextAt, transferDecision{Action: aCapture}) |
| } |
| case rPending: |
| if f.Payment == pAuthorised { |
| - return transferDecision{Action: aCapture} |
| + return sendWhenDue(f, f.CaptureNextAt, transferDecision{Action: aCapture}) |
| } |
| case rCompleted: |
| switch f.Payment { |
| @@ -160,7 +182,7 @@ func decideTransferMoney(f transferFacts) transferDecision { |
| return transferDecision{Action: aRecordDone, Terminal: PurchaseDone} |
| } |
| case pAuthorised: |
| - return transferDecision{Action: aCapture} |
| + return sendWhenDue(f, f.CaptureNextAt, transferDecision{Action: aCapture}) |
| case pCancelled, pFailed: |
| if f.Completed != nil { |
| return transferDecision{Action: aRecordUnpaid, Terminal: PurchaseUnpaid} |
| @@ -169,7 +191,7 @@ func decideTransferMoney(f transferFacts) transferDecision { |
| case rFailed: |
| switch f.Payment { |
| case pAuthorised: |
| - return transferDecision{Action: aCancelAuthorisation} |
| + return sendWhenDue(f, f.Cancel.NextAt, transferDecision{Action: aCancelAuthorisation}) |
| case pCancelled, pFailed: |
| return transferDecision{Action: aFinishFailed, Terminal: PurchaseFailed} |
| case pCaptured: |
| @@ -179,7 +201,9 @@ func decideTransferMoney(f transferFacts) transferDecision { |
| } |
| switch f.Refund { |
| case fNone: |
| - return transferDecision{Action: aCreateRefund, RefundAttempt: max(f.RefundAttempt, 1)} |
| + // The current attempt again (its stored request, same key) |
| + // once its send's backoff is over. |
| + return sendWhenDue(f, f.RefundSend.NextAt, transferDecision{Action: aCreateRefund, RefundAttempt: max(f.RefundAttempt, 1)}) |
| case fFailed: |
| if f.RefundReason == refundRefused { |
| // Refused outright: the next attempt waits out the backoff; |
| @@ -198,6 +222,51 @@ func decideTransferMoney(f transferFacts) transferDecision { |
| return wait |
| } |
| +// sendWhenDue is d once the send's next-send time has come, else a wait. |
| +func sendWhenDue(f transferFacts, nextAt time.Time, d transferDecision) transferDecision { |
| + if f.Now.Before(nextAt) { |
| + return transferDecision{Action: aWait} |
| + } |
| + return d |
| +} |
| + |
| +// transferSendSchedule is the wait after the nth money send in a row fails |
| +// (capture, release of the hold, refund create, Checkout expiry): 1 min, |
| +// 5 min, 30 min, 1 h, then 6 h for good. |
| +var transferSendSchedule = []time.Duration{time.Minute, 5 * time.Minute, 30 * time.Minute, time.Hour, 6 * time.Hour} |
| + |
| +// transferSendBackoff is the wait after failures sends failed in a row. |
| +func transferSendBackoff(failures int) time.Duration { |
| + if failures < 1 { |
| + return 0 |
| + } |
| + return transferSendSchedule[min(failures, len(transferSendSchedule))-1] |
| +} |
| + |
| +// nextCaptureAt is when a capture that just failed for the nth time in a |
| +// row may be sent again: the backoff, but no more than |
| +// transferCaptureLastDayWait in the hold's last day, so the capture stays |
| +// well inside the hold window. |
| +func nextCaptureAt(now time.Time, failures int, captureBefore time.Time) time.Time { |
| + wait := transferSendBackoff(failures) |
| + if !captureBefore.IsZero() && !now.Before(captureBefore.Add(-transferLapseAlertBefore)) { |
| + wait = min(wait, transferCaptureLastDayWait) |
| + } |
| + return now.Add(wait) |
| +} |
| + |
| +// noticeBackoff is the wait after a notice's nth failed try: 1 h, 6 h, then |
| +// daily. |
| +func noticeBackoff(failures int) time.Duration { |
| + switch { |
| + case failures <= 1: |
| + return time.Hour |
| + case failures == 2: |
| + return 6 * time.Hour |
| + } |
| + return 24 * time.Hour |
| +} |
| + |
| // dueTransferAlerts is every scheduled alert that is due and not yet |
| // delivered: |
| // - an unknown outcome: a day after it became unknown, then weekly after |
| @@ -205,7 +274,9 @@ func decideTransferMoney(f transferFacts) transferDecision { |
| // - any authorised hold, whatever the registrar outcome: a day before it |
| // lapses, once; |
| // - capture sends failing three times in a row while the hold is in |
| -// place: then daily; |
| +// place: then daily; the same for the sends releasing it; |
| +// - refund create sends failing three times in a row (not refused): |
| +// then daily; |
| // - an accepted transfer whose capture was refused or whose hold ended: |
| // once; |
| // - refund creates refused outright: at the first refusal of a run, then |
| @@ -249,6 +320,9 @@ func dueTransferAlerts(f transferFacts) []string { |
| if f.Payment == pAuthorised && f.CaptureFailures >= transferCaptureFailingAfter && daily(alertCaptureFailing) { |
| due = append(due, alertCaptureFailing) |
| } |
| + if f.Payment == pAuthorised && f.Cancel.Failures >= transferSendFailingAfter && daily(alertCancelFailing) { |
| + due = append(due, alertCancelFailing) |
| + } |
| accepted := reg == rPending || (reg == rUnknown && f.Accepted) |
| if accepted && (f.Payment == pFailed || f.Payment == pCancelled) && !sent(alertCaptureRefused) { |
| due = append(due, alertCaptureRefused) |
| @@ -264,6 +338,9 @@ func dueTransferAlerts(f transferFacts) []string { |
| if f.RefundMismatch && daily(alertRefundMismatch) { |
| due = append(due, alertRefundMismatch) |
| } |
| + if f.RefundSend.Failures >= transferSendFailingAfter && daily(alertRefundFailing) { |
| + due = append(due, alertRefundFailing) |
| + } |
| } |
| if f.PaymentMismatch && f.Registrar == rNotSent && !sent(alertPaymentWrong) { |
| due = append(due, alertPaymentWrong) |
| @@ -304,11 +381,12 @@ func owedNotices(f *transferFacts, d transferDecision) { |
| } |
| } |
| -// outstandingNotices is f's owed notices not yet delivered, oldest first. |
| +// outstandingNotices is f's owed notices not yet delivered (nor given up), |
| +// oldest first. |
| func outstandingNotices(f transferFacts) []string { |
| var out []string |
| for kind := range f.Owed { |
| - if f.Alerts[kind].IsZero() { |
| + if f.Alerts[kind].IsZero() && f.Dropped[kind].IsZero() { |
| out = append(out, kind) |
| } |
| } |
diff --git a/internal/console/domaintransfer_decide_test.go b/internal/console/domaintransfer_decide_test.go| index f06c362ec..7305b5d7f 100644 |
| --- a/internal/console/domaintransfer_decide_test.go |
| +++ b/internal/console/domaintransfer_decide_test.go |
| @@ -117,6 +117,34 @@ func TestDecideTransferTable(t *testing.T) { |
| againUnknown := lateUnknownDue |
| againUnknown.Alerts = map[string]time.Time{alertUnknown24h: decideBase.Add(-3 * 24 * time.Hour)} |
| + // Bounded sends: each send waits out its next-send time; the reads and |
| + // the alerts go on meanwhile. |
| + inAnHour := decideBase.Add(time.Hour) |
| + expireWaiting := expired |
| + expireWaiting.Expire = transferSends{Asked: true, Failures: 1, NextAt: inAnHour} |
| + expiredAsked := quietFacts(rNotSent, pAuthorised, fNone) |
| + expiredAsked.Expire.Asked = true |
| + expiredAskedWaiting := expiredAsked |
| + expiredAskedWaiting.Cancel = transferSends{Asked: true, Failures: 2, NextAt: inAnHour} |
| + expiredAskedCancelled := quietFacts(rNotSent, pCancelled, fNone) |
| + expiredAskedCancelled.Expire.Asked = true |
| + captureWaiting := captureStuck |
| + captureWaiting.CaptureNextAt = inAnHour |
| + captureDue := quietFacts(rPending, pAuthorised, fNone) |
| + captureDue.CaptureFailures, captureDue.CaptureNextAt = 1, decideBase |
| + cancelFailing := quietFacts(rFailed, pAuthorised, fNone) |
| + cancelFailing.Cancel = transferSends{Asked: true, Failures: 3, NextAt: inAnHour} |
| + cancelFailingAlerted := cancelFailing |
| + cancelFailingAlerted.Alerts = map[string]time.Time{alertCancelFailing: decideBase.Add(-23 * time.Hour)} |
| + cancelTwice := quietFacts(rFailed, pAuthorised, fNone) |
| + cancelTwice.Cancel = transferSends{Asked: true, Failures: 2, NextAt: decideBase} |
| + refundFailing := quietFacts(rFailed, pCaptured, fNone) |
| + refundFailing.RefundAttempt = 1 |
| + refundFailing.RefundSend = transferSends{Failures: 3, NextAt: inAnHour} |
| + refundFailingDue := refundFailing |
| + refundFailingDue.RefundSend.NextAt = decideBase |
| + refundFailingDue.Alerts = map[string]time.Time{alertRefundFailing: decideBase.Add(-24 * time.Hour)} |
| + |
| refused := func(refusals int, since, alerted time.Duration) transferFacts { |
| f := quietFacts(rFailed, pCaptured, fFailed) |
| f.RefundAttempt, f.RefundReason, f.RefundRefusals, f.RefundFailedAt = refusals, refundRefused, refusals, decideBase.Add(-since) |
| @@ -138,7 +166,11 @@ func TestDecideTransferTable(t *testing.T) { |
| {"first refusal of a new run, alerted before it: alert", refused(1, 0, time.Hour), aWait, "", 0, alertRefundRefused, ""}, |
| {"refunds refused, the operator refunded outside: failed, owner told", outside, aFinishFailed, PurchaseFailed, 0, "", noticeOwnerFailed}, |
| {"not sent, checkout open: wait (a declined card may be retried)", quietFacts(rNotSent, pAwaiting, fNone), aWait, "", 0, "", ""}, |
| - {"not sent, checkout past its expiry: expired, not charged, nobody told", expired, aFinishFailed, PurchaseExpired, 0, "", ""}, |
| + {"not sent, checkout past its expiry on the console's clock: ask the provider to expire it", expired, aExpireCheckout, "", 0, "", ""}, |
| + {"not sent, the expiry send waiting out its backoff: wait", expireWaiting, aWait, "", 0, "", ""}, |
| + {"not sent, authorised after the expiry was asked: release the hold", expiredAsked, aCancelAuthorisation, "", 0, "", ""}, |
| + {"not sent, authorised after the expiry was asked, release waiting: wait", expiredAskedWaiting, aWait, "", 0, "", ""}, |
| + {"not sent, expiry asked, the session expired: expired, nobody told", expiredAskedCancelled, aFinishFailed, PurchaseExpired, 0, "", ""}, |
| {"not sent, authorised: submit", quietFacts(rNotSent, pAuthorised, fNone), aSubmit, "", 0, "", ""}, |
| {"not sent, authorised, hold lapsing: submit, and the lapse alert", notSentLapse, aSubmit, "", 0, alertLapse, ""}, |
| {"not sent, cancelled: finished, not charged", quietFacts(rNotSent, pCancelled, fNone), aFinishFailed, PurchaseExpired, 0, "", ""}, |
| @@ -158,6 +190,8 @@ func TestDecideTransferTable(t *testing.T) { |
| {"pending, capture failing, hold lapsing: capture, and both alerts", captureStuck, aCapture, "", 0, alertLapse + " " + alertCaptureFailing, ""}, |
| {"pending, capture failing, alerted 23 h ago: capture only", captureStuckAlerted, aCapture, "", 0, "", ""}, |
| {"pending, capture failing, alerted a day ago: capture, alerted again", captureStuckDaily, aCapture, "", 0, alertCaptureFailing, ""}, |
| + {"pending, capture failing, waiting out its backoff: wait, the alerts still due", captureWaiting, aWait, "", 0, alertLapse + " " + alertCaptureFailing, ""}, |
| + {"pending, capture failed once, its next-send time come: capture", captureDue, aCapture, "", 0, "", ""}, |
| {"pending, captured: wait", quietFacts(rPending, pCaptured, fNone), aWait, "", 0, "", ""}, |
| {"pending, capture failed: alerted once", pendingRefused, aWait, "", 0, alertCaptureRefused, ""}, |
| {"pending, capture failed, alerted: wait", pendingRefusedAlerted, aWait, "", 0, "", ""}, |
| @@ -167,11 +201,16 @@ func TestDecideTransferTable(t *testing.T) { |
| {"completed, capture failed (pFailed): unpaid", quietFacts(rCompleted, pFailed, fNone), aRecordUnpaid, PurchaseUnpaid, 0, "", noticeOwnerUnpaid + " " + alertUnpaid}, |
| {"completed, payment unread: wait", quietFacts(rCompleted, pUnknown, fNone), aWait, "", 0, "", ""}, |
| {"failed, authorised: cancel the authorisation", quietFacts(rFailed, pAuthorised, fNone), aCancelAuthorisation, "", 0, "", ""}, |
| + {"failed, releasing the hold failed twice, its time come: release, no alert yet", cancelTwice, aCancelAuthorisation, "", 0, "", ""}, |
| + {"failed, releasing the hold failing, waiting: wait, the failing alert", cancelFailing, aWait, "", 0, alertCancelFailing, ""}, |
| + {"failed, releasing the hold failing, alerted 23 h ago: wait", cancelFailingAlerted, aWait, "", 0, "", ""}, |
| {"failed, cancelled: failed, not charged, owner told", quietFacts(rFailed, pCancelled, fNone), aFinishFailed, PurchaseFailed, 0, "", noticeOwnerFailed}, |
| {"failed, capture failed: failed, not charged", quietFacts(rFailed, pFailed, fNone), aFinishFailed, PurchaseFailed, 0, "", noticeOwnerFailed}, |
| {"failed with an empty reason after capture: refund attempt 1", emptyReason, aCreateRefund, "", 1, "", ""}, |
| {"failed, captured, attempt 2 stored but unanswered: resend attempt 2", resend, aCreateRefund, "", 2, "", ""}, |
| {"failed, captured, refund attempt failed: a new attempt, its alert owed", quietFacts(rFailed, pCaptured, fFailed), aCreateRefund, "", 2, "", refundFailedAlert(1)}, |
| + {"failed, captured, refund sends failing, waiting: wait, the failing alert", refundFailing, aWait, "", 0, alertRefundFailing, ""}, |
| + {"failed, captured, refund sends failing, time come, alerted a day ago: resend attempt 1, alerted again", refundFailingDue, aCreateRefund, "", 1, alertRefundFailing, ""}, |
| {"failed, captured, refund pending: wait", quietFacts(rFailed, pCaptured, fPending), aWait, "", 0, "", ""}, |
| {"failed, captured, refund short of the capture: alerted", mismatch, aWait, "", 0, alertRefundMismatch, ""}, |
| {"failed, captured, refund short, alerted 23 h ago: wait", mismatchAlerted, aWait, "", 0, "", ""}, |
| @@ -210,8 +249,17 @@ func TestDecideTransferTable(t *testing.T) { |
| for refund := fNone; refund <= fFailed; refund++ { |
| for _, accepted := range []bool{false, true} { |
| for _, resolution := range []string{"", transferResolvedFailed, transferResolvedCompleted, "outside"} { |
| - for _, noCompleted := range []bool{false, true} { |
| + for _, variant := range []string{"", "completed-missing", "sends-waiting", "expire-asked"} { |
| + noCompleted := variant == "completed-missing" |
| f := quietFacts(reg, pay, refund) |
| + switch variant { |
| + case "sends-waiting": |
| + // Every send's next-send time still to come. |
| + later := decideBase.Add(time.Minute) |
| + f.CaptureNextAt, f.Cancel.NextAt, f.Expire.NextAt, f.RefundSend.NextAt = later, later, later, later |
| + case "expire-asked": |
| + f.Expire.Asked = true |
| + } |
| f.Accepted = accepted |
| if resolution == "outside" { |
| f.RefundedOutside = true |
| @@ -224,9 +272,28 @@ func TestDecideTransferTable(t *testing.T) { |
| if noCompleted { |
| f.Completed = nil |
| } |
| - name := fmt.Sprintf("%v/%v/%v accepted=%v resolution=%q completed=%v", reg, pay, refund, accepted, resolution, f.Completed != nil) |
| + name := fmt.Sprintf("%v/%v/%v accepted=%v resolution=%q completed=%v variant=%q", reg, pay, refund, accepted, resolution, f.Completed != nil, variant) |
| d := decideTransfer(f) |
| checkDecisionInvariants(t, name, f, d) |
| + if variant == "sends-waiting" { |
| + // A waiting send is never sent; nothing else changes. |
| + f2 := f |
| + f2.CaptureNextAt, f2.Cancel.NextAt, f2.Expire.NextAt, f2.RefundSend.NextAt = time.Time{}, time.Time{}, time.Time{}, time.Time{} |
| + due := decideTransfer(f2) |
| + gated := due.Action == aCapture || due.Action == aCancelAuthorisation || due.Action == aExpireCheckout || (due.Action == aCreateRefund && f.Refund == fNone) |
| + if (gated && d.Action != aWait) || (!gated && (d.Action != due.Action || d.Terminal != due.Terminal)) { |
| + t.Errorf("%s: got %v, want %v gated=%v", name, d.Action, due.Action, gated) |
| + } |
| + continue |
| + } |
| + if variant == "expire-asked" { |
| + // Asked to expire before submit: never submitted; an |
| + // authorisation is released. |
| + if d.Action == aSubmit || (reg == rNotSent && pay == pAuthorised && resolution == "" && d.Action != aCancelAuthorisation) { |
| + t.Errorf("%s: got %v after the expiry was asked", name, d.Action) |
| + } |
| + continue |
| + } |
| if accepted || resolution != "" || noCompleted { |
| continue // the table's rows above cover these variants |
| } |
| @@ -361,7 +428,11 @@ func TestOutstandingNoticesUntilDelivered(t *testing.T) { |
| // reason) after a delay, an answer that later reads "none", authorisations |
| // that lapse, refunds that sit pending or fail; and, on every pass, lost |
| // and stale reads, lost and crashed sends, console crashes after any step, |
| -// failed alert deliveries and restarts. Then the faults stop, outcomes |
| +// failed alert deliveries and restarts; capture, release, refund and |
| +// Checkout expiry sends that keep failing (each must wait out its next-send |
| +// time, a fact the decision reads); a provider clock behind the console's, |
| +// with a customer who pays in the gap after the console's expiry (the hold |
| +// must never be left in place). Then the faults stop, outcomes |
| // become definite, an operator resolves (most of) what the registrar never |
| // answered, and every purchase must end within 20 passes (I10). |
| // |
| @@ -416,6 +487,15 @@ type transferSim struct { |
| // a delivery and its record: each may send that notice once more. |
| crashedAfterDelivery map[string]int |
| + // current is the run's purchase, for the send checks. |
| + current string |
| + // racePay, when set, is a customer paying just as the console's expiry |
| + // request reaches the provider. |
| + racePay func() |
| + // sendFailed is the send kinds that failed this pass (the next-send |
| + // time must then lie ahead). |
| + sendFailed map[string]bool |
| + |
| passes int |
| outcomes map[PurchaseState]int |
| paths map[string]int // how often each risky path was reached |
| @@ -646,6 +726,41 @@ type simBilling struct { |
| // in place), refunds read 100 short of what was refunded, and the |
| // Checkout reads an amount that is not the purchase's. |
| captureFlaky, shortRefund, wrongAmount bool |
| + // cancelFlaky, refundFlaky and expireFlaky fail those sends with a 500 |
| + // while faults are on. |
| + cancelFlaky, refundFlaky, expireFlaky bool |
| +} |
| + |
| +// sendNextAt is the stored next-send time for a send of kind. |
| +func sendNextAt(f transferFacts, kind string) time.Time { |
| + switch kind { |
| + case billing.PreparedCapture: |
| + return f.CaptureNextAt |
| + case billing.PreparedCancelPayment: |
| + return f.Cancel.NextAt |
| + case billing.PreparedExpire: |
| + return f.Expire.NextAt |
| + case billing.PreparedRefund: |
| + return f.RefundSend.NextAt |
| + } |
| + return time.Time{} |
| +} |
| + |
| +// checkSendDue: a money send goes only once its stored next-send time has |
| +// come (bounded sends). The record read is the one the send's own pass |
| +// started from, with any moves it made before the send, which never move |
| +// the next-send time forward. |
| +func (b *simBilling) checkSendDue(p billing.Prepared) { |
| + if b.sim.current == "" { |
| + return |
| + } |
| + stored, err := b.sim.tf.st.DomainPurchase(b.sim.current) |
| + if err != nil || stored == nil { |
| + return |
| + } |
| + if at := sendNextAt(stored.Facts, p.Kind); b.sim.tf.now.Before(at) { |
| + b.sim.violation = fmt.Sprintf("%s sent %s before its next-send time", p.Kind, at.Sub(b.sim.tf.now)) |
| + } |
| } |
| func (b *simBilling) PaymentCheckout(ctx context.Context, session string) (billing.PaymentInfo, error) { |
| @@ -678,8 +793,15 @@ func (b *simBilling) Refunds(ctx context.Context, pi string) ([]billing.RefundIn |
| // Send checks a refund create: attempt n is only ever made once every |
| // earlier attempt has failed (I6). |
| func (b *simBilling) Send(ctx context.Context, p billing.Prepared) (billing.Result, error) { |
| - if p.Kind == billing.PreparedCapture && b.captureFlaky && b.sim.faults { |
| - b.sim.paths["capture send failed"]++ |
| + b.checkSendDue(p) |
| + if p.Kind == billing.PreparedExpire && b.sim.racePay != nil { |
| + b.sim.racePay() |
| + } |
| + flaky := map[string]bool{billing.PreparedCapture: b.captureFlaky, billing.PreparedCancelPayment: b.cancelFlaky, |
| + billing.PreparedRefund: b.refundFlaky, billing.PreparedExpire: b.expireFlaky} |
| + if flaky[p.Kind] && b.sim.faults && (p.Kind == billing.PreparedCapture || p.Kind == billing.PreparedRefund || b.sim.chance(0.7)) { |
| + b.sim.paths[p.Kind+" send failed"]++ |
| + b.sim.sendFailed[p.Kind] = true |
| return billing.Result{}, fmt.Errorf("%w: sim: 500", billing.ErrIndeterminate) |
| } |
| if p.Kind == billing.PreparedRefund { |
| @@ -777,15 +899,20 @@ func (sim *transferSim) run(i int) { |
| sim.pageFail = []float64{0, 0.1, 0.5}[sim.rng.IntN(3)] |
| sim.crashedAfterDelivery = map[string]int{} |
| sim.mail.subjects = nil |
| + sim.current = "" |
| // Fresh fakes per run keep the providers' lists short. |
| bill := billingtest.New() |
| - bill.SetProviderClock(tf.now) |
| + // The provider's clock, sometimes behind the console's: a Checkout the |
| + // console thinks expired may still take a payment. |
| + providerLag := []time.Duration{0, 0, 3 * time.Minute, 20 * time.Minute}[sim.rng.IntN(4)] |
| + bill.SetProviderClock(tf.now.Add(-providerLag)) |
| bill.LapseAuthorisations = sim.chance(0.3) |
| bill.CaptureWindow = []time.Duration{0, -1, 26 * time.Hour, 3 * 24 * time.Hour}[sim.rng.IntN(4)] |
| sim.bill = bill |
| sim.violation = "" |
| - sim.billing = &simBilling{Fake: bill, sim: sim, captureFlaky: sim.chance(0.15), shortRefund: sim.chance(0.1), wrongAmount: sim.chance(0.05)} |
| + sim.billing = &simBilling{Fake: bill, sim: sim, captureFlaky: sim.chance(0.15), shortRefund: sim.chance(0.1), wrongAmount: sim.chance(0.05), |
| + cancelFlaky: sim.chance(0.15), refundFlaky: sim.chance(0.15), expireFlaky: sim.chance(0.15)} |
| tf.srv.cfg.Billing.Provider = sim.billing |
| reg := &simRegistrar{Fake: registrartest.New(), sim: sim, lag: sim.rng.IntN(4), hidden: sim.chance(0.04), |
| skew: []time.Duration{0, time.Hour, 2 * time.Hour}[sim.rng.IntN(3)]} |
| @@ -830,11 +957,30 @@ func (sim *transferSim) run(i int) { |
| if err := tf.st.CreateDomainPurchase(p); err != nil { |
| sim.fail(i, "insert: %v", err) |
| } |
| + sim.current = p.ID |
| + sim.racePay = nil |
| // The customer: pays (perhaps after a decline) at some point in the |
| // hour, or never. |
| pays := sim.chance(0.85) |
| payAt := now.Add(time.Duration(sim.rng.IntN(55)) * time.Minute) |
| + if sim.chance(0.15) { |
| + // Late, after the console's expiry: in the gap while the provider's |
| + // clock is behind, else refused; sometimes just as the console's |
| + // expiry request arrives. |
| + payAt = now.Add(time.Hour + time.Duration(sim.rng.IntN(int(providerLag/time.Minute)+2))*time.Minute) |
| + sim.paths["pays after the console's expiry"]++ |
| + if sim.chance(0.5) { |
| + sim.racePay = func() { |
| + if session := sim.session(p.ID); session != "" && pays { |
| + if _, err := bill.CompletePaymentCheckout(session); err == nil { |
| + pays = false |
| + sim.paths["paid as the expiry arrived"]++ |
| + } |
| + } |
| + } |
| + } |
| + } |
| declineFirst := sim.chance(0.2) |
| refundPending := sim.chance(0.6) |
| var last *DomainPurchase |
| @@ -866,6 +1012,7 @@ func (sim *transferSim) run(i int) { |
| pass := func() { |
| sim.passes++ |
| sim.dirty = false |
| + sim.sendFailed = map[string]bool{} |
| customer() |
| reg.advanceProvider(domain) |
| if sim.faults { |
| @@ -897,6 +1044,12 @@ func (sim *transferSim) run(i int) { |
| sim.check(i, last, cur, code) |
| if !sim.dirty { |
| sim.checkScheduledAlerts(i, cur) |
| + for kind := range sim.sendFailed { |
| + // A failed send is followed by its backoff. |
| + if at := sendNextAt(cur.Facts, kind); !at.After(tf.now) && purchaseLive(cur.State) { |
| + sim.fail(i, "%s failed but its next-send time %s is not ahead", kind, at) |
| + } |
| + } |
| } |
| last = cur |
| } |
| @@ -905,7 +1058,7 @@ func (sim *transferSim) run(i int) { |
| liveNow := func() bool { return last == nil || purchaseLive(last.State) } |
| for n := 0; n < chaos && liveNow(); n++ { |
| pass() |
| - if tf.now.Before(p.CheckoutExpires) && (pays || sim.chance(0.5)) { |
| + if tf.now.Before(p.CheckoutExpires.Add(providerLag)) && (pays || sim.chance(0.5)) { |
| // Inside the Checkout hour time moves in minutes, so the |
| // customer gets to pay before it expires. |
| sim.tick(time.Duration(1+sim.rng.IntN(12)) * time.Minute) |
| @@ -951,10 +1104,15 @@ func (sim *transferSim) run(i int) { |
| sim.tick(24 * time.Hour) |
| } |
| // Ended: whatever it still owes goes out from the purchase pass's |
| - // notice step (faults are off now). |
| + // notice step (faults are off now), once each one's backoff (a day at |
| + // most) is over. |
| for k := 0; k < 3; k++ { |
| _ = tf.srv.transferNoticesPass(ctx) |
| + if !liveNow() { |
| + sim.tick(25 * time.Hour) |
| + } |
| } |
| + sim.current = "" |
| end := stored() |
| sim.outcomes[end.State]++ |
| sim.checkNoticesDelivered(i, end) |
| @@ -976,6 +1134,12 @@ func (sim *transferSim) run(i int) { |
| if len(sim.pages[p.ID]) > 0 { |
| sim.paths["alerted"]++ |
| } |
| + if end.Facts.Expire.Asked && end.Facts.Cancel.Asked { |
| + sim.paths["authorised after the expiry was asked: hold released"]++ |
| + } |
| + if end.Facts.Expire.Asked && end.State == PurchaseExpired { |
| + sim.paths["expired on the provider's word"]++ |
| + } |
| if purchaseLive(end.State) { |
| // Only an unknown the operator has not resolved may still be live. |
| if end.Facts.Registrar != rUnknown || end.Facts.Resolution != "" || !(reg.unanswered() || reg.ambiguous(end)) { |
| @@ -1194,7 +1358,8 @@ func (sim *transferSim) checkAlertsOnce(i int, p *DomainPurchase) { |
| for reason, n := range seen { |
| repeats := reason == alertUnknownWeekly || reason == alertRefundRefused || |
| reason == alertUnknown24h || |
| - reason == alertCaptureFailing || reason == alertRefundMismatch |
| + reason == alertCaptureFailing || reason == alertRefundMismatch || |
| + reason == alertCancelFailing || reason == alertRefundFailing |
| if !repeats && n > 1+sim.crashedFor(reason) { |
| sim.fail(i, "I10: alert %q delivered %d times", reason, n) |
| } |
| @@ -1307,6 +1472,21 @@ func (sim *transferSim) checkScheduledAlerts(i int, p *DomainPurchase) { |
| return at |
| } |
| need := func(kind string, delivered bool, why string) { |
| + // The unknown alerts are one schedule: the weekly one stands for the |
| + // day-after one once that went out. |
| + backoff := f.Delivery[kind].NextAt |
| + if kind == alertUnknown24h { |
| + backoff = maxTime(backoff, f.Delivery[alertUnknownWeekly].NextAt) |
| + } |
| + if !delivered && now.Before(backoff) { |
| + // An earlier try failed: it waits out the notice backoff, a day |
| + // at most. |
| + if backoff.Sub(now) > 24*time.Hour { |
| + sim.fail(i, "alert %s backing off for %s", kind, backoff.Sub(now)) |
| + } |
| + sim.paths["scheduled alert backing off: "+kind]++ |
| + return |
| + } |
| if !delivered { |
| sim.fail(i, "scheduled alert %s due (%s) but not delivered; facts %+v", kind, why, f) |
| } |
| @@ -1324,6 +1504,9 @@ func (sim *transferSim) checkScheduledAlerts(i int, p *DomainPurchase) { |
| if f.CaptureFailures >= transferCaptureFailingAfter { |
| need(alertCaptureFailing, within(latest(time.Time{}, alertCaptureFailing), 24*time.Hour), "capture failing") |
| } |
| + if f.Cancel.Failures >= transferSendFailingAfter && f.Payment == pAuthorised { |
| + need(alertCancelFailing, within(latest(time.Time{}, alertCancelFailing), 24*time.Hour), "release failing") |
| + } |
| } |
| accepted := reg == rPending || (reg == rUnknown && f.Accepted) |
| if accepted && ok && (info.IntentStatus == "canceled" || (info.IntentStatus == "requires_payment_method" && f.CaptureAttempted)) { |
| @@ -1346,6 +1529,9 @@ func (sim *transferSim) checkScheduledAlerts(i int, p *DomainPurchase) { |
| if f.RefundMismatch { |
| need(alertRefundMismatch, within(latest(time.Time{}, alertRefundMismatch), 24*time.Hour), "refund short of the capture") |
| } |
| + if f.RefundSend.Failures >= transferSendFailingAfter { |
| + need(alertRefundFailing, within(latest(time.Time{}, alertRefundFailing), 24*time.Hour), "refund sends failing") |
| + } |
| } |
| if f.PaymentMismatch && f.Registrar == rNotSent { |
| need(alertPaymentWrong, !latest(time.Time{}, alertPaymentWrong).IsZero(), "a payment not this purchase's") |
diff --git a/internal/console/domaintransfer_facts.go b/internal/console/domaintransfer_facts.go| index 61a4b4ef6..5be69ba61 100644 |
| --- a/internal/console/domaintransfer_facts.go |
| +++ b/internal/console/domaintransfer_facts.go |
| @@ -107,10 +107,29 @@ type transferFacts struct { |
| // and never cleared: one is outstanding until Alerts holds its delivery. |
| Owed map[string]time.Time `json:",omitempty"` |
| // CaptureFailures counts capture sends that failed in a row (capped at |
| - // transferCaptureFailingAfter); CaptureError is the last one's kind. |
| - // They never decide the payment: its read does. |
| - CaptureFailures int `json:",omitempty"` |
| - CaptureError string `json:",omitempty"` |
| + // the length of transferSendSchedule); CaptureError is the last one's |
| + // kind. They never decide the payment: its read does. CaptureNextAt is |
| + // when the next capture may be sent (the backoff after a failure), and |
| + // CaptureKey numbers its idempotency key (captureKey). |
| + CaptureFailures int `json:",omitempty"` |
| + CaptureError string `json:",omitempty"` |
| + CaptureNextAt time.Time `json:",omitzero"` |
| + CaptureKey int `json:",omitempty"` |
| + // Cancel is the release of the hold's sends, Expire the Checkout |
| + // expiry's, RefundSend the current refund attempt's create (whose key |
| + // never changes within the attempt): each bounded like the capture. |
| + Cancel transferSends `json:",omitzero"` |
| + Expire transferSends `json:",omitzero"` |
| + RefundSend transferSends `json:",omitzero"` |
| + // CapturedTotal is what was captured, tax included (the Checkout's |
| + // total), recorded when a read first shows the capture. A refund |
| + // returns it; 0 on a record from before it was kept. |
| + CapturedTotal int64 `json:",omitempty"` |
| + // Delivery is each notice's delivery while it is retried; Dropped is the |
| + // notices given up (no one left who can be reached), kind -> when. A |
| + // dropped notice is no longer outstanding. |
| + Delivery map[string]noticeDelivery `json:",omitempty"` |
| + Dropped map[string]time.Time `json:",omitempty"` |
| // UnknownSince is when the registrar outcome last became rUnknown (zero |
| // while it is not); ReadFailures counts status reads failing in a row. |
| UnknownSince time.Time `json:",omitzero"` |
| @@ -129,6 +148,31 @@ type transferFacts struct { |
| CaptureBefore time.Time `json:",omitzero"` |
| } |
| +// transferSends is one kind of money send's record: how many in a row |
| +// failed (capped at the length of transferSendSchedule), the last one's |
| +// kind, when the next may go (the backoff, a fact decideTransfer reads) and |
| +// the number its idempotency key carries. Asked is set once the first send |
| +// is recorded (the Checkout expiry: the console has asked the provider to |
| +// end the session). |
| +type transferSends struct { |
| + Asked bool `json:",omitempty"` |
| + Failures int `json:",omitempty"` |
| + Error string `json:",omitempty"` |
| + NextAt time.Time `json:",omitzero"` |
| + Key int `json:",omitempty"` |
| +} |
| + |
| +// noticeDelivery is one notice's delivery so far: the owners already |
| +// emailed (never emailed it again), the owners given up on (blocked, or no |
| +// way to reach them), how many tries in a row failed and when the next may |
| +// go. |
| +type noticeDelivery struct { |
| + To []string `json:",omitempty"` |
| + Refused []string `json:",omitempty"` |
| + Failures int `json:",omitempty"` |
| + NextAt time.Time `json:",omitzero"` |
| +} |
| + |
| func (o registrarOutcome) String() string { return outcomeName(registrarOutcomeNames, int(o)) } |
| func (o paymentOutcome) String() string { return outcomeName(paymentOutcomeNames, int(o)) } |
| func (o refundOutcome) String() string { return outcomeName(refundOutcomeNames, int(o)) } |
diff --git a/internal/console/domaintransfer_notices.go b/internal/console/domaintransfer_notices.go| index 651a63189..f641b24df 100644 |
| --- a/internal/console/domaintransfer_notices.go |
| +++ b/internal/console/domaintransfer_notices.go |
| @@ -2,7 +2,6 @@ package console |
| import ( |
| "context" |
| - "database/sql" |
| "errors" |
| "fmt" |
| "log" |
| @@ -16,15 +15,26 @@ import ( |
| // settlement. A notice a transition makes due is owed in the facts the |
| // transition's own move records (owedNotices); a scheduled alert is due |
| // from the facts (dueTransferAlerts). Delivery sends each and records it in |
| -// Facts.Alerts in a CAS move of its own; a failure records nothing, so the |
| -// notice stays due. It runs after every pass's action on a live purchase, |
| -// and from transferNoticesPass for an ended purchase that still owes one. |
| -// Settlement never waits on it, and it never changes settlement. |
| +// Facts.Alerts in a CAS move of its own. It runs after every pass's action |
| +// on a live purchase, and from transferNoticesPass for an ended purchase |
| +// that still owes one. Settlement never waits on it, and it never changes |
| +// settlement. |
| // |
| -// At least once: a crash between a delivery and its record sends it again. |
| +// Bounded: an owner email is recorded per owner as it goes out |
| +// (Facts.Delivery), so a retry mails only the owners it has not reached. |
| +// A try that fails waits out noticeBackoff (1 h, 6 h, then daily) before |
| +// the next. An owner who cannot be reached at all (they blocked the |
| +// console, or there is no email sender) is given up on, and a notice with |
| +// no one left to reach, or whose account is gone, is dropped with one |
| +// operator alert (alertNoticeDropped). Every other failure is transient. |
| +// |
| +// At least once: a crash between a delivery and its record sends it again, |
| +// to that one recipient; a recipient whose delivery is recorded never gets |
| +// it again. |
| // deliverTransferNotices sends p's outstanding owed notices, then, while p |
| -// is live, the scheduled alerts due. |
| +// is live, the scheduled alerts due, each once its backoff allows. acct is |
| +// nil when the account is gone. |
| func (s *Server) deliverTransferNotices(ctx context.Context, acct *Account, p *DomainPurchase, scheduled []string) error { |
| kinds := outstandingNotices(p.Facts) |
| if purchaseLive(p.State) { |
| @@ -36,40 +46,161 @@ func (s *Server) deliverTransferNotices(ctx context.Context, acct *Account, p *D |
| } |
| var errs []error |
| for _, kind := range kinds { |
| - if err := s.sendTransferNotice(ctx, acct, p, kind); err != nil { |
| + if s.transferNow().Before(p.Facts.Delivery[kind].NextAt) { |
| + continue // waiting out the backoff |
| + } |
| + finished, err := s.sendTransferNotice(ctx, acct, p, kind) |
| + if errors.Is(err, errTransferStopped) || errors.Is(err, ErrPurchaseStateMoved) { |
| + return errors.Join(append(errs, err)...) |
| + } |
| + if err != nil { |
| log.Printf("console: transfer %s: notice %s: %v", p.ID, kind, err) |
| jobFailed(ctx, err) |
| errs = append(errs, err) |
| - continue |
| - } |
| - if err := transferStep("notice:delivered:" + kind); err != nil { |
| - return errors.Join(append(errs, err)...) |
| } |
| at := s.transferNow() |
| - if err := s.movePurchase(ctx, p, p.State, func(q *DomainPurchase) { |
| - q.Facts.Alerts = maps.Clone(q.Facts.Alerts) |
| - if q.Facts.Alerts == nil { |
| - q.Facts.Alerts = map[string]time.Time{} |
| - } |
| - q.Facts.Alerts[kind] = at |
| - }); err != nil { |
| + if err := s.movePurchase(ctx, p, p.State, func(q *DomainPurchase) { recordNoticeTry(q, kind, finished, at) }); err != nil { |
| return errors.Join(append(errs, err)...) |
| } |
| } |
| return errors.Join(errs...) |
| } |
| +// recordNoticeTry records one try of kind on q: finished, it is delivered |
| +// (or, with no one reached, dropped), and owes the dropped alert when |
| +// anyone was missed; otherwise the next try waits out the backoff. |
| +func recordNoticeTry(q *DomainPurchase, kind string, finished bool, at time.Time) { |
| + f := &q.Facts |
| + f.Delivery = cloneDeliveries(f.Delivery) |
| + d := f.Delivery[kind] |
| + if !finished { |
| + d.Failures++ |
| + d.NextAt = at.Add(noticeBackoff(d.Failures)) |
| + if f.Delivery == nil { |
| + f.Delivery = map[string]noticeDelivery{} |
| + } |
| + f.Delivery[kind] = d |
| + return |
| + } |
| + delete(f.Delivery, kind) |
| + owner := strings.HasPrefix(kind, "owner-") |
| + if owner && len(d.To) == 0 { |
| + f.Dropped = maps.Clone(f.Dropped) |
| + if f.Dropped == nil { |
| + f.Dropped = map[string]time.Time{} |
| + } |
| + f.Dropped[kind] = at |
| + } else { |
| + f.Alerts = maps.Clone(f.Alerts) |
| + if f.Alerts == nil { |
| + f.Alerts = map[string]time.Time{} |
| + } |
| + f.Alerts[kind] = at |
| + } |
| + if owner && (len(d.To) == 0 || len(d.Refused) > 0) { |
| + f.Owed = maps.Clone(f.Owed) |
| + if f.Owed == nil { |
| + f.Owed = map[string]time.Time{} |
| + } |
| + if dropped := alertNoticeDropped + kind; f.Owed[dropped].IsZero() { |
| + f.Owed[dropped] = at |
| + } |
| + } |
| +} |
| + |
| +func cloneDeliveries(m map[string]noticeDelivery) map[string]noticeDelivery { |
| + if m == nil { |
| + return nil |
| + } |
| + out := make(map[string]noticeDelivery, len(m)) |
| + for k, d := range m { |
| + d.To, d.Refused = slices.Clone(d.To), slices.Clone(d.Refused) |
| + out[k] = d |
| + } |
| + return out |
| +} |
| + |
| // sendTransferNotice delivers one notice: an owner email for the owner |
| -// kinds, else an operator alert. |
| -func (s *Server) sendTransferNotice(ctx context.Context, acct *Account, p *DomainPurchase, kind string) error { |
| +// kinds, else an operator alert. finished is whether it needs no further |
| +// try. |
| +func (s *Server) sendTransferNotice(ctx context.Context, acct *Account, p *DomainPurchase, kind string) (finished bool, err error) { |
| if subject, body, ok := transferOwnerNotice(p, kind); ok { |
| - return s.ownerNoticeErr(ctx, acct, p.ID, subject, body) |
| + return s.deliverOwnerNotice(ctx, acct, p, kind, subject, body) |
| + } |
| + account := fmt.Sprintf("#%d", p.AccountID) // the account is gone |
| + if acct != nil { |
| + account = acct.Sqid |
| } |
| - log.Printf("console: domain transfer: account=%s domain=%s purchase=%s alert=%s", acct.Sqid, p.Domain, p.ID, kind) |
| + log.Printf("console: domain transfer: account=%s domain=%s purchase=%s alert=%s", account, p.Domain, p.ID, kind) |
| // The kind on its own line, so the alert says which one it is whatever |
| // its wording. |
| - body := fmt.Sprintf(domainPurchaseCopy.OperatorBody, p.Domain, p.ID, acct.Sqid, transferAlertReasonFor(kind, p.Facts)) + "Alert: " + kind + "\n" |
| - return s.alertOperator(ctx, domainPurchaseCopy.OperatorSubject, body) |
| + body := fmt.Sprintf(domainPurchaseCopy.OperatorBody, p.Domain, p.ID, account, transferAlertReasonFor(kind, p.Facts)) + "Alert: " + kind + "\n" |
| + if err := s.alertOperator(ctx, domainPurchaseCopy.OperatorSubject, body); err != nil { |
| + return false, err |
| + } |
| + if err := transferStep("notice:delivered:" + kind); err != nil { |
| + return false, err |
| + } |
| + return true, nil |
| +} |
| + |
| +// deliverOwnerNotice emails each owner of acct not yet reached for kind, |
| +// recording each delivery in its own move as it goes. An owner who cannot |
| +// be reached (deliveryPermanent) is given up on, recorded likewise. It is |
| +// finished once no owner is left to try; the account gone, at once. |
| +func (s *Server) deliverOwnerNotice(ctx context.Context, acct *Account, p *DomainPurchase, kind, subject, body string) (bool, error) { |
| + if acct == nil { |
| + return true, nil |
| + } |
| + members, err := s.store.Members(acct.ID) |
| + if err != nil { |
| + return false, fmt.Errorf("owners: %w", err) |
| + } |
| + var errs []error |
| + for _, member := range members { |
| + d := p.Facts.Delivery[kind] |
| + if member.Role != RoleOwner || slices.Contains(d.To, member.Name) || slices.Contains(d.Refused, member.Name) { |
| + continue |
| + } |
| + _, err := s.deliver(ctx, member.Name, subject, body, 8*time.Second) |
| + refused := err != nil && deliveryPermanent(err) |
| + if err != nil && !refused { |
| + errs = append(errs, err) |
| + continue |
| + } |
| + if err == nil { |
| + if err := transferStep("notice:delivered:" + kind); err != nil { |
| + return false, err |
| + } |
| + } else { |
| + log.Printf("console: transfer %s: notice %s: an owner cannot be reached, giving up on them: %v", p.ID, kind, err) |
| + } |
| + name := member.Name |
| + if err := s.movePurchase(ctx, p, p.State, func(q *DomainPurchase) { |
| + q.Facts.Delivery = cloneDeliveries(q.Facts.Delivery) |
| + if q.Facts.Delivery == nil { |
| + q.Facts.Delivery = map[string]noticeDelivery{} |
| + } |
| + d := q.Facts.Delivery[kind] |
| + if refused { |
| + d.Refused = append(d.Refused, name) |
| + } else { |
| + d.To = append(d.To, name) |
| + } |
| + q.Facts.Delivery[kind] = d |
| + }); err != nil { |
| + return false, err |
| + } |
| + } |
| + return len(errs) == 0, errors.Join(errs...) |
| +} |
| + |
| +// deliveryPermanent says whether deliver's error means no retry will reach |
| +// the address: the recipient blocked the console on Keymail, or there is |
| +// no email sender configured. deliver can tell nothing more; any other |
| +// error is transient. |
| +func deliveryPermanent(err error) bool { |
| + return IsKeymailBlocked(err) || errors.Is(err, errNoEmailSender) |
| } |
| // transferOwnerNotice is the owner email for an owner notice kind, from |
| @@ -91,7 +222,8 @@ func transferOwnerNotice(p *DomainPurchase, kind string) (subject, body string, |
| } |
| // transferNoticesPass delivers what ended transfers still owe. Run by the |
| -// purchase pass after the live purchases. |
| +// purchase pass after the live purchases. A purchase whose account is gone |
| +// drops its owner emails, with the operator's alert. |
| func (s *Server) transferNoticesPass(ctx context.Context) error { |
| owing, err := s.store.TransfersOwingNotices(ctx) |
| if err != nil { |
| @@ -103,10 +235,10 @@ func (s *Server) transferNoticesPass(ctx context.Context) error { |
| return ctx.Err() |
| } |
| p := &owing[i] |
| - acct, err := s.store.AccountByID(p.AccountID) |
| - if err == nil && acct == nil { |
| - err = sql.ErrNoRows |
| + if !transferNoticeDue(p.Facts, s.transferNow()) { |
| + continue |
| } |
| + acct, err := s.store.AccountByID(p.AccountID) |
| if err == nil { |
| err = s.purchaseMutation(ctx, p, func(ctx context.Context) error { return s.deliverTransferNotices(ctx, acct, p, nil) }) |
| } |
| @@ -118,3 +250,14 @@ func (s *Server) transferNoticesPass(ctx context.Context) error { |
| } |
| return errors.Join(errs...) |
| } |
| + |
| +// transferNoticeDue says whether any of f's outstanding notices may be |
| +// tried at now. |
| +func transferNoticeDue(f transferFacts, now time.Time) bool { |
| + for _, kind := range outstandingNotices(f) { |
| + if !now.Before(f.Delivery[kind].NextAt) { |
| + return true |
| + } |
| + } |
| + return false |
| +} |
diff --git a/internal/console/domaintransfer_test.go b/internal/console/domaintransfer_test.go| index af5a7185e..a51e0cd04 100644 |
| --- a/internal/console/domaintransfer_test.go |
| +++ b/internal/console/domaintransfer_test.go |
| @@ -890,17 +890,25 @@ func TestAlertOperatorReportsDeliveryFailure(t *testing.T) { |
| if err := tf.srv.alertOperator(context.Background(), "subject", "body"); err == nil || !strings.Contains(err.Error(), "sns down") { |
| t.Fatalf("undelivered alert: %v", err) |
| } |
| - // An undelivered transfer alert is not recorded and is sent again. |
| + // An undelivered transfer alert is not recorded as delivered; it is |
| + // sent again once the notice backoff (an hour after the first failure) |
| + // is over, and not before. |
| p := tf.start(t) |
| tf.authorise(t, p) |
| tf.reg.RequestErr = registrar.ErrIndeterminate |
| p = tf.pass(t, p.ID) |
| tf.tick(25 * time.Hour) |
| p = tf.pass(t, p.ID) |
| - if !p.Facts.Alerts[alertUnknown24h].IsZero() { |
| - t.Fatalf("an undelivered alert was recorded: %+v", p.Facts.Alerts) |
| + if !p.Facts.Alerts[alertUnknown24h].IsZero() || p.Facts.Delivery[alertUnknown24h].Failures != 1 { |
| + t.Fatalf("an undelivered alert was recorded, or its failure not: %+v %+v", p.Facts.Alerts, p.Facts.Delivery) |
| } |
| tf.pageErr = nil |
| + tf.tick(59 * time.Minute) |
| + p = tf.pass(t, p.ID) |
| + if tf.alerts(alertUnknown24h) != 0 { |
| + t.Fatalf("sent again inside the backoff: %v", tf.pages) |
| + } |
| + tf.tick(time.Minute) |
| p = tf.pass(t, p.ID) |
| if p.Facts.Alerts[alertUnknown24h].IsZero() || tf.alerts(alertUnknown24h) != 1 { |
| t.Fatalf("alert not delivered once: %+v %v", p.Facts.Alerts, tf.pages) |
| @@ -1230,6 +1238,8 @@ func TestTransferUnpaidTurnsRenewalOffAlertsAndTellsOwner(t *testing.T) { |
| tf.restart(t) |
| tf.pageErr = nil |
| tf.mailFails(nil) |
| + // The notice backoff after one failed try is an hour. |
| + tf.tick(time.Hour) |
| // Ended: only the purchase pass's notice step reaches it. |
| if err := tf.srv.domainPurchasePass(context.Background()); err != nil { |
| t.Log(err) |
| @@ -1270,6 +1280,7 @@ func TestTransferNoticesSurviveTheTerminalMove(t *testing.T) { |
| } |
| tf.mailFails(nil) |
| for i := 0; i < 2; i++ { |
| + tf.tick(6 * time.Hour) // past the notice backoff |
| if err := tf.srv.domainPurchasePass(context.Background()); err != nil { |
| t.Log(err) |
| } |
| @@ -1290,45 +1301,72 @@ func TestTransferNoticesSurviveTheTerminalMove(t *testing.T) { |
| } |
| // TestTransferCaptureFailuresAlertWhileRetrying: an accepted transfer whose |
| -// capture send keeps failing (the hold still in place) is retried every |
| -// pass, and the alerts flow meanwhile: capture-failing after the third |
| -// failure in a row, then daily; the lapse alert a day before the hold |
| -// lapses, whatever the registrar says. A stuck capture writes nothing new |
| -// each pass once counted. |
| +// capture send keeps failing (the hold still in place) is retried on the |
| +// send backoff (1 min, 5 min, 30 min, 1 h, then 6 h), never inside it, and |
| +// the next-send time survives a restart. Each 500 moves the capture's key |
| +// on, since the provider replays a stored 500 under its key. The alerts |
| +// flow meanwhile: capture-failing after the third failure in a row, then |
| +// daily; the lapse alert a day before the hold lapses. |
| func TestTransferCaptureFailuresAlertWhileRetrying(t *testing.T) { |
| tf := newTransferFixture(t) |
| tf.fake.CaptureWindow = 4 * 24 * time.Hour |
| + var keys []string |
| tf.fake.BeforeSend = func(pr billing.Prepared) error { |
| if pr.Kind == billing.PreparedCapture { |
| + keys = append(keys, pr.Key) |
| return fmt.Errorf("%w: 500", billing.ErrIndeterminate) |
| } |
| return nil |
| } |
| p := tf.submitted(t) |
| - for i := 0; i < 3; i++ { |
| + p = tf.pass(t, p.ID) // pending: the first capture fails |
| + for step, wait := range transferSendSchedule[:4] { |
| + if p.Facts.CaptureFailures != step+1 || !p.Facts.CaptureNextAt.Equal(tf.now.Add(wait)) { |
| + t.Fatalf("after failure %d: next send at %s, want %s from now: %+v", step+1, p.Facts.CaptureNextAt.Sub(tf.now), wait, p.Facts) |
| + } |
| + sent := tf.sent(billing.PreparedCapture) |
| + tf.tick(wait - time.Second) |
| + if step == 1 { |
| + tf.restart(t) // the next-send time is a stored fact |
| + } |
| + p = tf.pass(t, p.ID) |
| + if tf.sent(billing.PreparedCapture) != sent { |
| + t.Fatalf("capture sent %s inside its backoff of %s", wait-time.Second, wait) |
| + } |
| + tf.tick(time.Second) |
| p = tf.pass(t, p.ID) |
| + if tf.sent(billing.PreparedCapture) != sent+1 { |
| + t.Fatalf("capture not resent once its backoff of %s was over", wait) |
| + } |
| + } |
| + if p.Facts.CaptureError != "indeterminate" || p.Facts.Payment != pAuthorised || !p.Facts.CaptureNextAt.Equal(tf.now.Add(6*time.Hour)) { |
| + t.Fatalf("failures not counted apart from the payment, or the backoff not 6 h: %+v", p.Facts) |
| } |
| - if p.Facts.CaptureFailures != transferCaptureFailingAfter || p.Facts.CaptureError != "indeterminate" || p.Facts.Payment != pAuthorised { |
| - t.Fatalf("failures not counted apart from the payment: %+v", p.Facts) |
| + want := []string{p.ID + ":capture", p.ID + ":capture:1", p.ID + ":capture:2", p.ID + ":capture:3", p.ID + ":capture:4"} |
| + if !slices.Equal(keys, want) { |
| + t.Fatalf("capture keys %v, want %v", keys, want) |
| } |
| if tf.alerts(alertCaptureFailing) != 1 { |
| - t.Fatalf("capture-failing alerts = %d after the third failure", tf.alerts(alertCaptureFailing)) |
| + t.Fatalf("capture-failing alerts = %d after five failures", tf.alerts(alertCaptureFailing)) |
| } |
| - rev := p.Revision |
| + // Waiting out the 6 h backoff writes nothing and reads on. |
| + rev, reads := p.Revision, tf.fake.CallsBy["PaymentCheckout"] |
| for i := 0; i < 5; i++ { |
| tf.tick(time.Minute) |
| p = tf.pass(t, p.ID) |
| } |
| - if p.Revision != rev { |
| - t.Fatalf("a stuck capture wrote each pass: revision %d -> %d", rev, p.Revision) |
| + if p.Revision != rev || tf.fake.CallsBy["PaymentCheckout"] != reads+5 { |
| + t.Fatalf("a waiting capture wrote (revision %d -> %d) or stopped reading", rev, p.Revision) |
| } |
| captures := tf.sent(billing.PreparedCapture) |
| for i := 0; i < 4*24*2 && purchaseLive(p.State) && p.Facts.Payment == pAuthorised; i++ { |
| tf.tick(30 * time.Minute) |
| p = tf.pass(t, p.ID) |
| } |
| - if tf.sent(billing.PreparedCapture) <= captures { |
| - t.Fatal("the capture was not retried") |
| + // Four days at 6 h, with the last day at 30 min: about 12 + 48 sends, |
| + // not one every pass. |
| + if n := tf.sent(billing.PreparedCapture) - captures; n < 10 || n > 70 { |
| + t.Fatalf("capture sent %d times over four days", n) |
| } |
| if tf.alerts(alertLapse) != 1 || tf.alerts(alertCaptureFailing) < 3 || tf.alerts(alertCaptureFailing) > 5 { |
| t.Fatalf("lapse %d, capture-failing %d over four days", tf.alerts(alertLapse), tf.alerts(alertCaptureFailing)) |