console: bound stuck purchases; no app operation on no-change polls
Co-Authored-By: Astra (gpt-6-astra) via Codex <noreply@openai.com>
10 files changed,
+524
−80
docs/superpowers/specs/2026-11-01-domain-registration-design.md+10 −0internal/billing/billing.go+1 −0internal/billing/billingtest/fake.go+9 −1internal/billing/billingtest/fake_test.go+41 −0internal/billingstripe/prepared.go+1 −1internal/billingstripe/prepared_test.go+2 −2internal/console/domainbuy.go+167 −64internal/console/domainbuy_test.go+285 −7internal/console/domainstore.go+7 −4internal/console/jobs_test.go+1 −1
diff --git a/docs/superpowers/specs/2026-11-01-domain-registration-design.md b/docs/superpowers/specs/2026-11-01-domain-registration-design.md| index aa89fa90b..3db3c9131 100644 |
| --- a/docs/superpowers/specs/2026-11-01-domain-registration-design.md |
| +++ b/docs/superpowers/specs/2026-11-01-domain-registration-design.md |
| @@ -211,6 +211,16 @@ out of step in a way nobody notices: |
| rule is that an ambiguous answer is never read as a failure). The |
| reconcile must settle well inside the card authorisation's lifetime |
| (days for cards); the plan states the bound. |
| + |
| + Implementation note (Plan 1): `registering` has a 24 h deadline from |
| + the first Register attempt. Before it, retry with backoff and Lookup |
| + first each time; alert the operator once at 1 h unresolved. At the |
| + deadline, if Lookup still does not find the domain in our account, |
| + cancel the authorisation, delete the zone, mark the purchase `failed` |
| + with reason `unconfirmed`, and alert the operator. A registration that |
| + appears after 24 h is ours unpaid; the loss is bounded by one |
| + registration fee, the operator is alerted, and Plan 2's daily |
| + reconcile catches it. |
| 7. If the registration succeeded but the capture then fails (an expired |
| or revoked authorisation), Carloku keeps the registration, marks it |
| unpaid, turns auto-renew off, emails the owner a payment link and |
diff --git a/internal/billing/billing.go b/internal/billing/billing.go| index e1692f7ed..a0bb61f0c 100644 |
| --- a/internal/billing/billing.go |
| +++ b/internal/billing/billing.go |
| @@ -189,6 +189,7 @@ const ( |
| // CheckoutInfo is a read of one Checkout session. |
| type CheckoutInfo struct { |
| ID, URL, Subscription, Customer, IntentID string |
| + Reference string |
| State CheckoutState |
| ExpiresAt time.Time |
| } |
diff --git a/internal/billing/billingtest/fake.go b/internal/billing/billingtest/fake.go| index 1729539a4..445fbebe5 100644 |
| --- a/internal/billing/billingtest/fake.go |
| +++ b/internal/billing/billingtest/fake.go |
| @@ -649,10 +649,17 @@ func (f *Fake) CustomerCheckouts(ctx context.Context, customer string, createdAf |
| f.mu.Lock() |
| defer f.mu.Unlock() |
| ids := sortedKeys(f.Sessions, func(s *Session) bool { return s.Customer == customer && !s.Created.Before(createdAfter) }) |
| + ids = append(ids, sortedKeys(f.paymentSessions, func(s *paymentSession) bool { |
| + return s.Request.Customer == customer && !s.Created.Before(createdAfter) |
| + })...) |
| + slices.Sort(ids) |
| out := []billing.CheckoutInfo{} |
| err := f.list(ctx, "CustomerCheckouts", ids, func(id string) { |
| if s := f.Sessions[id]; s != nil { |
| out = append(out, s.CheckoutInfo) |
| + } else if s := f.paymentSessions[id]; s != nil { |
| + out = append(out, billing.CheckoutInfo{ID: s.SessionID, URL: s.URL, Customer: s.Request.Customer, |
| + Reference: s.Request.Reference, State: billing.CheckoutState(s.Status), ExpiresAt: s.Request.ExpiresAt}) |
| } |
| }) |
| if err != nil { |
| @@ -1093,7 +1100,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} |
| + Status: "open", Amount: b.Request.Amount, AmountTotal: b.Request.Amount, Currency: b.Request.Currency}, Request: b.Request, Created: f.ProviderClock} |
| f.paymentSessions[id] = s |
| info := s.PaymentInfo |
| return billing.Result{Payment: &info}, nil |
| @@ -1444,6 +1451,7 @@ var _ billing.Provider = (*Fake)(nil) |
| type paymentSession struct { |
| billing.PaymentInfo |
| + Created time.Time |
| Request billing.PaymentCheckoutRequest |
| } |
diff --git a/internal/billing/billingtest/fake_test.go b/internal/billing/billingtest/fake_test.go| index c4f309229..ab1f579e3 100644 |
| --- a/internal/billing/billingtest/fake_test.go |
| +++ b/internal/billing/billingtest/fake_test.go |
| @@ -989,3 +989,44 @@ func TestFakeCheckHonoursHeaderlessTimeout(t *testing.T) { |
| t.Fatalf("Check after: %v", err) |
| } |
| } |
| + |
| +func TestCustomerCheckoutsIncludesPaymentReferences(t *testing.T) { |
| + ctx := context.Background() |
| + f := newFake(t) |
| + f.PageSize = 1 |
| + f.AddSession(&Session{CheckoutInfo: billing.CheckoutInfo{ID: "cs_sub", Customer: "cus_1", IntentID: "ci_subscription", State: billing.CheckoutOpen}, Created: t0}) |
| + prepared, err := f.PreparePaymentCheckout(billing.PaymentCheckoutRequest{ |
| + AccountSqid: "bab", Customer: "cus_1", Currency: "usd", Amount: 1500, Description: "shop.com", Reference: "dp_purchase", Key: "dp_purchase", ExpiresAt: t0.Add(time.Hour), |
| + SuccessURL: "https://example.test/ok", CancelURL: "https://example.test/back", |
| + }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + result, err := f.Send(ctx, prepared) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := f.CompletePaymentCheckout(result.Payment.SessionID); err != nil { |
| + t.Fatal(err) |
| + } |
| + listed, err := f.CustomerCheckouts(ctx, "cus_1", t0) |
| + if err != nil || len(listed) != 2 || f.CallsBy["CustomerCheckouts"] != 2 { |
| + t.Fatalf("list=%+v err=%v pages=%d", listed, err, f.CallsBy["CustomerCheckouts"]) |
| + } |
| + payment := listed[0] |
| + if payment.ID != result.Payment.SessionID || payment.Reference != "dp_purchase" || payment.IntentID != "" || payment.State != billing.CheckoutComplete || !payment.ExpiresAt.Equal(t0.Add(time.Hour)) { |
| + t.Fatalf("payment=%+v", payment) |
| + } |
| + if listed[1].IntentID != "ci_subscription" || listed[1].Reference != "" { |
| + t.Fatalf("subscription=%+v", listed[1]) |
| + } |
| + for _, query := range []struct { |
| + customer string |
| + after time.Time |
| + }{{"cus_other", t0}, {"cus_1", t0.Add(time.Second)}} { |
| + listed, err := f.CustomerCheckouts(ctx, query.customer, query.after) |
| + if err != nil || len(listed) != 0 { |
| + t.Fatalf("filtered list=%+v err=%v", listed, err) |
| + } |
| + } |
| +} |
diff --git a/internal/billingstripe/prepared.go b/internal/billingstripe/prepared.go| index d09fd5b45..c48942e5d 100644 |
| --- a/internal/billingstripe/prepared.go |
| +++ b/internal/billingstripe/prepared.go |
| @@ -303,7 +303,7 @@ func classify(err error) error { |
| // sessionInfo maps a Checkout Session onto the neutral read. |
| func sessionInfo(s *Session) (billing.CheckoutInfo, error) { |
| info := billing.CheckoutInfo{ |
| - ID: s.ID, Subscription: s.SubscriptionID, Customer: s.CustomerID, IntentID: s.Metadata["checkout_intent"], |
| + ID: s.ID, Subscription: s.SubscriptionID, Customer: s.CustomerID, IntentID: s.Metadata["checkout_intent"], Reference: s.Metadata["purchase"], |
| } |
| switch s.Status { |
| case "open": |
diff --git a/internal/billingstripe/prepared_test.go b/internal/billingstripe/prepared_test.go| index 47a46ea92..3b4622f7c 100644 |
| --- a/internal/billingstripe/prepared_test.go |
| +++ b/internal/billingstripe/prepared_test.go |
| @@ -817,7 +817,7 @@ func TestCustomerCheckoutsPages(t *testing.T) { |
| ls.objects = append(ls.objects, fmt.Sprintf(`{"id":%q,"livemode":false,"status":"expired","customer":"cus_1","expires_at":1793000000,"metadata":{"checkout_intent":"ci_%d"}}`, id, i)) |
| } |
| ls.ids = append(ls.ids, "cs_9999") |
| - ls.objects = append(ls.objects, `{"id":"cs_9999","livemode":false,"status":"open","url":"https://checkout.stripe.com/c/pay/cs_9999","customer":"cus_1","subscription":null,"expires_at":1793000000,"metadata":{"checkout_intent":"ci_new"}}`) |
| + ls.objects = append(ls.objects, `{"id":"cs_9999","livemode":false,"status":"open","url":"https://checkout.stripe.com/c/pay/cs_9999","customer":"cus_1","subscription":null,"expires_at":1793000000,"metadata":{"checkout_intent":"ci_new","purchase":"dp_purchase"}}`) |
| srv := httptest.NewServer(ls) |
| defer srv.Close() |
| after := providerDate.Add(1500 * time.Millisecond) |
| @@ -826,7 +826,7 @@ func TestCustomerCheckoutsPages(t *testing.T) { |
| t.Fatalf("%d sessions, %v, after %d requests", len(got), err, ls.requests()) |
| } |
| last := got[150] |
| - want := billing.CheckoutInfo{ID: "cs_9999", URL: "https://checkout.stripe.com/c/pay/cs_9999", Customer: "cus_1", IntentID: "ci_new", |
| + want := billing.CheckoutInfo{ID: "cs_9999", URL: "https://checkout.stripe.com/c/pay/cs_9999", Customer: "cus_1", IntentID: "ci_new", Reference: "dp_purchase", |
| State: billing.CheckoutOpen, ExpiresAt: time.Unix(1793000000, 0).UTC()} |
| if last != want { |
| t.Errorf("last = %+v\nwant %+v", last, want) |
diff --git a/internal/console/domainbuy.go b/internal/console/domainbuy.go| index 686347c3c..39eaff23b 100644 |
| --- a/internal/console/domainbuy.go |
| +++ b/internal/console/domainbuy.go |
| @@ -154,34 +154,58 @@ func (s *Server) movePurchase(ctx context.Context, p *DomainPurchase, to Purchas |
| } |
| func (s *Server) purchaseCheckout(ctx context.Context, p *DomainPurchase) (string, error) { |
| - acct, err := s.store.AccountByID(p.AccountID) |
| - if err != nil { |
| - return "", err |
| + provider := s.billing.cfg.Provider |
| + if p.CheckoutSession != "" { |
| + info, err := provider.PaymentCheckout(ctx, p.CheckoutSession) |
| + return info.URL, err |
| } |
| - if acct == nil { |
| - return "", sql.ErrNoRows |
| + if !time.Now().Before(p.CheckoutExpires) && p.CheckoutPrepared != nil { |
| + if time.Now().Before(p.CheckoutExpires.Add(time.Hour)) { |
| + return "", billing.ErrIndeterminate |
| + } |
| + b, err := s.store.BillingAccount(p.AccountID) |
| + if err != nil { |
| + return "", err |
| + } |
| + if b == nil { |
| + return "", sql.ErrNoRows |
| + } |
| + // The journal uses the console clock; it cannot bound provider creation times. |
| + sessions, err := provider.CustomerCheckouts(ctx, b.Customer, time.Unix(0, 0)) |
| + if err != nil { |
| + return "", err |
| + } |
| + var session billing.CheckoutInfo |
| + for _, candidate := range sessions { |
| + if candidate.Customer == b.Customer && candidate.Reference == p.ID && candidate.ID != "" { |
| + session = candidate |
| + break |
| + } |
| + } |
| + err = s.purchaseMutation(ctx, p, func(ctx context.Context) error { |
| + if session.ID == "" { |
| + return s.movePurchase(ctx, p, PurchaseExpired, nil) |
| + } |
| + return s.movePurchase(ctx, p, p.State, func(p *DomainPurchase) { p.CheckoutSession = session.ID }) |
| + }) |
| + return session.URL, err |
| } |
| var checkout string |
| - var stepErr error |
| - err = s.claimAppMutation(ctx, acct, p.App, "domain-checkout", func(pctx context.Context) error { |
| - checkout, stepErr = s.purchaseCheckoutStep(pctx, p) |
| - return nil |
| + err := s.purchaseMutation(ctx, p, func(ctx context.Context) error { |
| + var err error |
| + checkout, err = s.purchaseCheckoutStep(ctx, p) |
| + return err |
| }) |
| - return checkout, errors.Join(err, stepErr) |
| + return checkout, err |
| } |
| func (s *Server) purchaseCheckoutStep(ctx context.Context, p *DomainPurchase) (string, error) { |
| provider := s.billing.cfg.Provider |
| - if p.CheckoutSession != "" { |
| - info, err := provider.PaymentCheckout(ctx, p.CheckoutSession) |
| - return info.URL, err |
| - } |
| if !time.Now().Before(p.CheckoutExpires) { |
| - if p.CheckoutPrepared == nil { |
| - return "", s.movePurchase(ctx, p, PurchaseExpired, nil) |
| + if p.CheckoutPrepared != nil { |
| + return "", billing.ErrIndeterminate |
| } |
| - // A lost checkout response may have authorised money. Absence locally is not failure. |
| - return "", billing.ErrIndeterminate |
| + return "", s.movePurchase(ctx, p, PurchaseExpired, nil) |
| } |
| if p.OwnerHandle == "" { |
| _, existing, err := s.store.DomainContact(p.AccountID) |
| @@ -221,6 +245,9 @@ func (s *Server) purchaseCheckoutStep(ctx context.Context, p *DomainPurchase) (s |
| prepared, err := provider.PreparePaymentCheckout(billing.PaymentCheckoutRequest{AccountSqid: acct.Sqid, Customer: b.Customer, Currency: p.Currency, Amount: p.Amount, |
| Description: p.Domain, Reference: p.ID, SuccessURL: back, CancelURL: back, ExpiresAt: p.CheckoutExpires, Key: p.ID}) |
| if err != nil { |
| + if errors.Is(err, billing.ErrRefused) { |
| + return "", errors.Join(err, s.movePurchase(ctx, p, PurchaseFailed, func(p *DomainPurchase) { p.Reason = "payment_setup" })) |
| + } |
| return "", err |
| } |
| if err := s.movePurchase(ctx, p, p.State, func(p *DomainPurchase) { p.CheckoutPrepared = &prepared }); err != nil { |
| @@ -229,6 +256,9 @@ func (s *Server) purchaseCheckoutStep(ctx context.Context, p *DomainPurchase) (s |
| } |
| result, err := provider.Send(ctx, *p.CheckoutPrepared) |
| if err != nil { |
| + if errors.Is(err, billing.ErrRefused) { |
| + return "", errors.Join(err, s.movePurchase(ctx, p, PurchaseFailed, func(p *DomainPurchase) { p.Reason = "payment_setup" })) |
| + } |
| return "", err |
| } |
| if result.Payment == nil || result.Payment.SessionID == "" { |
| @@ -241,6 +271,31 @@ func (s *Server) purchaseCheckoutStep(ctx context.Context, p *DomainPurchase) (s |
| return info.URL, nil |
| } |
| +func (s *Server) purchaseMutation(ctx context.Context, p *DomainPurchase, call func(context.Context) error) error { |
| + acct, err := s.store.AccountByID(p.AccountID) |
| + if err != nil { |
| + return err |
| + } |
| + if acct == nil { |
| + return sql.ErrNoRows |
| + } |
| + var stepErr error |
| + err = s.claimAppMutation(ctx, acct, p.App, "domain-purchase", func(ctx context.Context) error { |
| + fresh, err := s.store.DomainPurchase(p.ID) |
| + if err != nil { |
| + return err |
| + } |
| + if fresh == nil || fresh.State != p.State || fresh.Revision != p.Revision { |
| + return ErrPurchaseStateMoved |
| + } |
| + *p = *fresh |
| + // The journal owns retries after provider errors, including lost responses. |
| + stepErr = call(ctx) |
| + return nil |
| + }) |
| + return errors.Join(err, stepErr) |
| +} |
| + |
| func (s *Server) advancePurchase(ctx context.Context, id string) error { |
| if !s.domainPurchaseReady() { |
| return nil |
| @@ -262,20 +317,7 @@ func (s *Server) advancePurchase(ctx context.Context, id string) error { |
| } |
| ctx, cancel := context.WithTimeout(ctx, 30*time.Second) |
| defer cancel() |
| - var stepErr error |
| - if p.State == PurchaseCaptured { |
| - // Attach takes its own lifecycle registration, which requires an open app admission. |
| - stepErr = s.advancePurchaseStep(ctx, acct, p) |
| - } else { |
| - err = s.claimAppMutation(ctx, acct, p.App, "domain-purchase", func(pctx context.Context) error { |
| - // The purchase journal owns retries; this operation excludes app changes during the provider calls. |
| - stepErr = s.advancePurchaseStep(pctx, acct, p) |
| - return nil |
| - }) |
| - } |
| - if err != nil { |
| - return errors.Join(err, stepErr) |
| - } |
| + stepErr := s.advancePurchaseStep(ctx, acct, p) |
| if errors.Is(stepErr, ErrPurchaseStateMoved) { |
| return nil |
| } |
| @@ -298,12 +340,27 @@ func (s *Server) advancePurchaseStep(ctx context.Context, acct *Account, p *Doma |
| if info.PaymentIntent == "" || info.Currency != p.Currency || info.Amount != p.Amount { |
| return billing.ErrIndeterminate |
| } |
| - return s.movePurchase(ctx, p, PurchaseAuthorised, func(p *DomainPurchase) { p.PaymentIntent = info.PaymentIntent }) |
| + return s.purchaseMutation(ctx, p, func(ctx context.Context) error { |
| + return s.movePurchase(ctx, p, PurchaseAuthorised, func(p *DomainPurchase) { p.PaymentIntent = info.PaymentIntent }) |
| + }) |
| } |
| if info.Status == "expired" || (info.Status == "open" && !time.Now().Before(p.CheckoutExpires)) { |
| - return s.movePurchase(ctx, p, PurchaseExpired, nil) |
| + return s.purchaseMutation(ctx, p, func(ctx context.Context) error { return s.movePurchase(ctx, p, PurchaseExpired, nil) }) |
| } |
| return nil |
| + case PurchaseRegistering: |
| + return s.reconcileRegisteringPurchase(ctx, acct, p) |
| + case PurchaseCaptured: |
| + // Attach owns its lifecycle admission and exclusive operation. |
| + return s.advancePurchaseEffects(ctx, acct, p) |
| + default: |
| + return s.purchaseMutation(ctx, p, func(ctx context.Context) error { return s.advancePurchaseEffects(ctx, acct, p) }) |
| + } |
| +} |
| + |
| +func (s *Server) advancePurchaseEffects(ctx context.Context, acct *Account, p *DomainPurchase) error { |
| + provider := s.billing.cfg.Provider |
| + switch p.State { |
| case PurchaseAuthorised: |
| z, err := s.cfg.ZoneHost.CreateZone(ctx, p.Domain, p.ID) |
| if err != nil { |
| @@ -329,29 +386,10 @@ func (s *Server) advancePurchaseStep(ctx context.Context, acct *Account, p *Doma |
| } |
| return s.movePurchase(ctx, p, PurchaseZoneReady, func(p *DomainPurchase) { p.ZoneID = z.ID }) |
| case PurchaseZoneReady: |
| - if err := s.movePurchase(ctx, p, PurchaseRegistering, func(p *DomainPurchase) { p.Attempts = 1 }); err != nil { |
| - return err |
| - } |
| - return s.registerPurchase(ctx, p) |
| - case PurchaseRegistering: |
| - if p.Reason == "taken" || p.Reason == "refused" { |
| - return s.failPurchase(ctx, p) |
| - } |
| - registered, found, err := s.cfg.Registrar.Lookup(ctx, p.Domain) |
| - if err != nil { |
| - return err |
| - } |
| - if found { |
| - return s.registeredPurchase(ctx, p, registered) |
| - } |
| - if time.Since(p.UpdatedAt) < 10*time.Minute { |
| - return nil |
| - } |
| - if err := s.movePurchase(ctx, p, p.State, func(p *DomainPurchase) { |
| - if p.Attempts < 1 { |
| - p.Attempts = 1 |
| - } |
| - p.Attempts++ |
| + if err := s.movePurchase(ctx, p, PurchaseRegistering, func(p *DomainPurchase) { |
| + p.Attempts = 1 |
| + p.RegisterStartedAt = time.Now().UTC() |
| + p.RegisterNextAt = p.RegisterStartedAt.Add(10 * time.Minute) |
| }); err != nil { |
| return err |
| } |
| @@ -368,7 +406,7 @@ func (s *Server) advancePurchaseStep(ctx context.Context, acct *Account, p *Doma |
| // The capture may already have landed, including before the key expired. |
| info, err := provider.PaymentCheckout(ctx, p.CheckoutSession) |
| if err != nil { |
| - return err |
| + return errors.Join(sendErr, err) |
| } |
| if info.PaymentIntent != p.PaymentIntent { |
| return billing.ErrIndeterminate |
| @@ -414,6 +452,69 @@ func (s *Server) advancePurchaseStep(ctx context.Context, acct *Account, p *Doma |
| return nil |
| } |
| +func (s *Server) reconcileRegisteringPurchase(ctx context.Context, acct *Account, p *DomainPurchase) error { |
| + if p.Reason == "taken" || p.Reason == "refused" || p.Reason == "unconfirmed" { |
| + return s.purchaseMutation(ctx, p, func(ctx context.Context) error { return s.failPurchase(ctx, p) }) |
| + } |
| + now := time.Now().UTC() |
| + started := p.RegisterStartedAt |
| + if started.IsZero() { |
| + // Legacy journals have no first-attempt clock; do not extend their hold. |
| + started = p.CreatedAt |
| + } |
| + deadline := started.Add(24 * time.Hour) |
| + alert := !p.RegisterAlerted && !now.Before(started.Add(time.Hour)) |
| + due := !now.Before(deadline) || !now.Before(p.RegisterNextAt) |
| + var registered registrar.Registered |
| + var found bool |
| + var lookupErr error |
| + if due { |
| + registered, found, lookupErr = s.cfg.Registrar.Lookup(ctx, p.Domain) |
| + } |
| + if !alert && (!due || lookupErr != nil) { |
| + return lookupErr |
| + } |
| + return s.purchaseMutation(ctx, p, func(ctx context.Context) error { |
| + if alert { |
| + if err := s.movePurchase(ctx, p, p.State, func(p *DomainPurchase) { p.RegisterAlerted = true }); err != nil { |
| + return errors.Join(lookupErr, err) |
| + } |
| + s.purchaseAlert(ctx, acct, p.Domain, p.ID, "registering") |
| + } |
| + if lookupErr != nil || !due { |
| + return lookupErr |
| + } |
| + if found { |
| + return s.registeredPurchase(ctx, p, registered) |
| + } |
| + if !now.Before(deadline) { |
| + if err := s.movePurchase(ctx, p, p.State, func(p *DomainPurchase) { p.Reason = "unconfirmed" }); err != nil { |
| + return err |
| + } |
| + s.purchaseAlert(ctx, acct, p.Domain, p.ID, "unconfirmed") |
| + return s.failPurchase(ctx, p) |
| + } |
| + if err := s.movePurchase(ctx, p, p.State, func(p *DomainPurchase) { |
| + p.RegisterStartedAt = started |
| + if p.Attempts < 1 { |
| + p.Attempts = 1 |
| + } |
| + p.Attempts++ |
| + delay := 10 * time.Minute |
| + for attempt := 1; attempt < p.Attempts && delay < time.Hour; attempt++ { |
| + delay *= 2 |
| + } |
| + if delay > time.Hour { |
| + delay = time.Hour |
| + } |
| + p.RegisterNextAt = now.Add(delay) |
| + }); err != nil { |
| + return err |
| + } |
| + return s.registerPurchase(ctx, p) |
| + }) |
| +} |
| + |
| func (s *Server) registerPurchase(ctx context.Context, p *DomainPurchase) error { |
| r, err := s.cfg.Registrar.Register(ctx, registrar.Registration{Domain: p.Domain, Years: 1, Nameservers: s.cfg.ZoneHost.Nameservers(), OwnerHandle: p.OwnerHandle, Key: p.ID}) |
| if err == nil { |
| @@ -423,12 +524,12 @@ func (s *Server) registerPurchase(ctx context.Context, p *DomainPurchase) error |
| // Any earlier attempt may have registered it. Even a definite refusal of this request cannot disprove that. |
| r, found, readErr := s.cfg.Registrar.Lookup(ctx, p.Domain) |
| if readErr != nil { |
| - return readErr |
| + return errors.Join(err, readErr) |
| } |
| if found { |
| return s.registeredPurchase(ctx, p, r) |
| } |
| - return nil |
| + return err |
| } |
| reason := "" |
| if errors.Is(err, registrar.ErrUnavailable) { |
| @@ -437,12 +538,12 @@ func (s *Server) registerPurchase(ctx context.Context, p *DomainPurchase) error |
| reason = "refused" |
| } |
| if reason == "" { |
| - return nil |
| + return err |
| } |
| if err := s.movePurchase(ctx, p, p.State, func(p *DomainPurchase) { p.Reason = reason }); err != nil { |
| return err |
| } |
| - return s.failPurchase(ctx, p) |
| + return errors.Join(err, s.failPurchase(ctx, p)) |
| } |
| func (s *Server) registeredPurchase(ctx context.Context, p *DomainPurchase, r registrar.Registered) error { |
| @@ -472,10 +573,10 @@ func (s *Server) failPurchase(ctx context.Context, p *DomainPurchase) error { |
| if err != nil || result.Payment == nil || result.Payment.IntentStatus != "canceled" { |
| info, readErr := provider.PaymentCheckout(ctx, p.CheckoutSession) |
| if readErr != nil { |
| - return readErr |
| + return errors.Join(err, readErr) |
| } |
| if info.PaymentIntent != p.PaymentIntent || info.IntentStatus != "canceled" { |
| - return billing.ErrIndeterminate |
| + return errors.Join(err, billing.ErrIndeterminate) |
| } |
| } |
| if err := s.cfg.ZoneHost.DeleteZone(ctx, zonehost.Zone{ID: p.ZoneID, Domain: p.Domain}); err != nil { |
| @@ -522,6 +623,8 @@ func (s *Server) domainPurchasePass(ctx context.Context) error { |
| return ctx.Err() |
| } |
| if err := s.advancePurchase(ctx, p.ID); err != nil { |
| + log.Printf("console: purchase %s: %v", p.ID, err) |
| + jobFailed(ctx, err) |
| errs = append(errs, fmt.Errorf("purchase %s: %w", p.ID, err)) |
| } |
| } |
diff --git a/internal/console/domainbuy_test.go b/internal/console/domainbuy_test.go| index 34cdce957..7d1e5273f 100644 |
| --- a/internal/console/domainbuy_test.go |
| +++ b/internal/console/domainbuy_test.go |
| @@ -1,9 +1,11 @@ |
| package console |
| import ( |
| + "bytes" |
| "context" |
| "encoding/json" |
| "errors" |
| + "log" |
| "path/filepath" |
| "reflect" |
| "strings" |
| @@ -12,6 +14,7 @@ import ( |
| "time" |
| "github.com/carlosframework/platform/internal/billing" |
| + "github.com/carlosframework/platform/internal/billing/billingtest" |
| "github.com/carlosframework/platform/internal/domainreg" |
| "github.com/carlosframework/platform/internal/domains" |
| "github.com/carlosframework/platform/internal/registrar" |
| @@ -77,7 +80,11 @@ func (f *purchaseFixture) read(t *testing.T, id string) *DomainPurchase { |
| func (f *purchaseFixture) advance(t *testing.T, id string) *DomainPurchase { |
| t.Helper() |
| if err := f.srv.advancePurchase(context.Background(), id); err != nil { |
| - t.Fatal(err) |
| + p := f.read(t, id) |
| + expected := (errors.Is(err, registrar.ErrIndeterminate) || errors.Is(err, registrar.ErrRefused) || errors.Is(err, registrar.ErrUnavailable)) && (p.State == PurchaseRegistering || p.State == PurchaseFailed) |
| + if !expected { |
| + t.Fatal(err) |
| + } |
| } |
| return f.read(t, id) |
| } |
| @@ -171,6 +178,7 @@ func TestPurchaseIndeterminateRegisterNeverCancels(t *testing.T) { |
| t.Fatal("unknown outcome cancelled or retried early") |
| } |
| f.reg.Domains[p.Domain] = registrar.Registered{Domain: p.Domain, RegistrarID: "ours", Expires: time.Now().AddDate(1, 0, 0)} |
| + ageRegisteringPurchase(t, f, p.ID, 11*time.Minute) |
| f.until(t, p.ID, PurchaseRegistered) |
| } |
| func TestPurchaseResumesAfterRestartWithoutDoubleRegister(t *testing.T) { |
| @@ -180,6 +188,7 @@ func TestPurchaseResumesAfterRestartWithoutDoubleRegister(t *testing.T) { |
| f.reg.RegisterErr = registrar.ErrIndeterminate |
| f.until(t, p.ID, PurchaseRegistering) |
| f.reg.Domains[p.Domain] = registrar.Registered{Domain: p.Domain, RegistrarID: "ours", Expires: time.Now().AddDate(1, 0, 0)} |
| + ageRegisteringPurchase(t, f, p.ID, 11*time.Minute) |
| srv, err := NewServer(f.srv.cfg, f.st) |
| if err != nil { |
| t.Fatal(err) |
| @@ -305,9 +314,7 @@ func TestPurchaseRetryAfterIndeterminateTakenMeansOurs(t *testing.T) { |
| f.reg.RegisterErr = registrar.ErrIndeterminate |
| f.until(t, p.ID, PurchaseRegistering) |
| f.advance(t, p.ID) |
| - if _, err := f.st.db.Exec(`UPDATE domain_purchases SET updated_at=? WHERE id=?`, time.Now().Add(-11*time.Minute).Unix(), p.ID); err != nil { |
| - t.Fatal(err) |
| - } |
| + ageRegisteringPurchase(t, f, p.ID, 11*time.Minute) |
| f.until(t, p.ID, PurchaseDone) |
| if r.retries != 2 || f.sent(billing.PreparedCancelPayment) != 0 || f.sent(billing.PreparedCapture) != 1 { |
| t.Fatalf("retry: %d %+v", r.retries, f.fake.Sent) |
| @@ -603,9 +610,7 @@ func TestPurchaseRetryRefusalDoesNotDisproveEarlierRegistration(t *testing.T) { |
| f.authorise(t, p) |
| f.reg.RegisterErr = registrar.ErrIndeterminate |
| f.until(t, p.ID, PurchaseRegistering) |
| - if _, err := f.st.db.Exec(`UPDATE domain_purchases SET updated_at=? WHERE id=?`, time.Now().Add(-11*time.Minute).Unix(), p.ID); err != nil { |
| - t.Fatal(err) |
| - } |
| + ageRegisteringPurchase(t, f, p.ID, 11*time.Minute) |
| f.reg.RegisterErr = registrar.ErrRefused |
| p = f.advance(t, p.ID) |
| if p.State != PurchaseRegistering || p.Attempts != 2 || f.sent(billing.PreparedCancelPayment) != 0 { |
| @@ -720,3 +725,276 @@ func TestPurchaseResumesContactSnapshotBeforeCheckout(t *testing.T) { |
| t.Fatalf("contact snapshot was not saved: handle=%q error=%v", stored, err) |
| } |
| } |
| + |
| +// Seed retry clocks through the durable JSON so the regression also runs on |
| +// the pre-fix schema, whose decoder ignores these new fields. |
| +func ageRegisteringPurchase(t *testing.T, f *purchaseFixture, id string, age time.Duration) { |
| + t.Helper() |
| + var raw string |
| + if err := f.st.db.QueryRow(`SELECT details FROM domain_purchases WHERE id=?`, id).Scan(&raw); err != nil { |
| + t.Fatal(err) |
| + } |
| + var details map[string]any |
| + if err := json.Unmarshal([]byte(raw), &details); err != nil { |
| + t.Fatal(err) |
| + } |
| + details["RegisterStartedAt"] = time.Now().Add(-age).UTC() |
| + details["RegisterNextAt"] = time.Now().Add(-time.Second).UTC() |
| + data, err := json.Marshal(details) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := f.st.db.Exec(`UPDATE domain_purchases SET details=?, updated_at=? WHERE id=?`, string(data), time.Now().Add(-11*time.Minute).Unix(), id); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func unresolvedPurchase(t *testing.T, f *purchaseFixture) *DomainPurchase { |
| + t.Helper() |
| + p := f.start(t) |
| + f.authorise(t, p) |
| + f.until(t, p.ID, PurchaseZoneReady) |
| + f.reg.RegisterErr = registrar.ErrIndeterminate |
| + err := f.srv.advancePurchase(context.Background(), p.ID) |
| + if err != nil && !errors.Is(err, registrar.ErrIndeterminate) { |
| + t.Fatal(err) |
| + } |
| + return f.read(t, p.ID) |
| +} |
| + |
| +func TestRegisteringDeadlineCancelsAndFails(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + p := unresolvedPurchase(t, f) |
| + ageRegisteringPurchase(t, f, p.ID, 24*time.Hour) |
| + alerts := 0 |
| + pageDomainPurchase = func(context.Context, string, string, string) error { alerts++; return nil } |
| + f.reg.RegisterErr = registrar.ErrRefused |
| + if err := f.srv.advancePurchase(context.Background(), p.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + p = f.read(t, p.ID) |
| + if p.State != PurchaseFailed || p.Reason != "unconfirmed" || f.sent(billing.PreparedCancelPayment) != 1 || len(f.zone.Zones) != 0 || alerts == 0 { |
| + t.Fatalf("deadline: state=%s reason=%s cancels=%d zones=%d alerts=%d", p.State, p.Reason, f.sent(billing.PreparedCancelPayment), len(f.zone.Zones), alerts) |
| + } |
| + if f.sent(billing.PreparedCapture) != 0 || purchaseCalls(f.reg.Calls, "register:") != 1 { |
| + t.Fatal("deadline retried or captured") |
| + } |
| +} |
| + |
| +func TestRegisteringAlertsOperatorAfterAnHour(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + p := unresolvedPurchase(t, f) |
| + alerts := 0 |
| + pageDomainPurchase = func(context.Context, string, string, string) error { alerts++; return nil } |
| + if err := f.srv.advancePurchase(context.Background(), p.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + if alerts != 0 { |
| + t.Fatal("early alert") |
| + } |
| + ageRegisteringPurchase(t, f, p.ID, time.Hour) |
| + f.reg.RegisterErr = registrar.ErrIndeterminate |
| + err := f.srv.advancePurchase(context.Background(), p.ID) |
| + if err != nil && !errors.Is(err, registrar.ErrIndeterminate) { |
| + t.Fatal(err) |
| + } |
| + calls := len(f.reg.Calls) |
| + for i := 0; i < 3; i++ { |
| + if err := f.srv.advancePurchase(context.Background(), p.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if alerts != 1 || f.read(t, p.ID).State != PurchaseRegistering || f.sent(billing.PreparedCancelPayment) != 0 { |
| + t.Fatalf("alerts=%d state=%s", alerts, f.read(t, p.ID).State) |
| + } |
| + if len(f.reg.Calls) != calls { |
| + t.Fatal("registrar polled during retry backoff") |
| + } |
| +} |
| + |
| +func TestCheckoutCreateRefusedFailsAtOnce(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + f.fake.BeforeSend = func(billing.Prepared) error { return billing.ErrRefused } |
| + p, _, ref := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer@example.test") |
| + if p == nil || ref == nil { |
| + t.Fatal("expected refused create") |
| + } |
| + p = f.read(t, p.ID) |
| + if p.State != PurchaseFailed || p.Reason != "payment_setup" || p.CheckoutSession != "" { |
| + t.Fatalf("state=%s reason=%s session=%s", p.State, p.Reason, p.CheckoutSession) |
| + } |
| + if len(f.zone.Zones) != 0 || f.sent(billing.PreparedCancelPayment) != 0 { |
| + t.Fatal("refused create made effects") |
| + } |
| +} |
| + |
| +func TestStepErrorsAreReturnedAndLogged(t *testing.T) { |
| + for _, fault := range []error{registrar.ErrIndeterminate, errors.New("registrar credentials rejected")} { |
| + t.Run(fault.Error(), func(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + p := f.start(t) |
| + f.authorise(t, p) |
| + f.until(t, p.ID, PurchaseZoneReady) |
| + f.reg.RegisterErr = fault |
| + if err := f.srv.advancePurchase(context.Background(), p.ID); !errors.Is(err, fault) { |
| + t.Errorf("step error=%v, want %v", err, fault) |
| + } |
| + ageRegisteringPurchase(t, f, p.ID, 20*time.Minute) |
| + f.reg.RegisterErr = fault |
| + var logs bytes.Buffer |
| + previous := log.Writer() |
| + log.SetOutput(&logs) |
| + defer log.SetOutput(previous) |
| + // A later purchase must still run after the first one reports an error. |
| + other := DomainPurchase{ID: "dp_after_error", AccountID: f.acct.ID, App: "kass", Domain: "other.com", State: PurchaseAwaitingPayment, CheckoutExpires: time.Now().Add(-time.Hour)} |
| + if err := f.st.CreateDomainPurchase(other); err != nil { |
| + t.Fatal(err) |
| + } |
| + err := f.srv.domainPurchasePass(context.Background()) |
| + if !errors.Is(err, fault) || !strings.Contains(logs.String(), p.ID) || !strings.Contains(logs.String(), fault.Error()) { |
| + t.Errorf("pass error=%v logs=%q", err, logs.String()) |
| + } |
| + if f.read(t, other.ID).State != PurchaseExpired { |
| + t.Fatal("pass stopped after error") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestLostCheckoutCreateExpiresWhenNoneListed(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + f.fake.Err = billing.ErrIndeterminate |
| + p, _, _ := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer@example.test") |
| + if p == nil { |
| + t.Fatal("missing purchase") |
| + } |
| + f.fake.Err = nil |
| + if err := f.st.AdvanceDomainPurchase(p.ID, p.State, p.State, func(p *DomainPurchase) { p.CheckoutExpires = time.Now().Add(-time.Hour - time.Second) }); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := f.srv.advancePurchase(context.Background(), p.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + if f.read(t, p.ID).State != PurchaseExpired { |
| + t.Fatal("lost checkout never expired") |
| + } |
| + if f.fake.CallsBy["CustomerCheckouts"] == 0 { |
| + t.Fatal("expired without checking provider sessions") |
| + } |
| + if f.sent(billing.PreparedCapture) != 0 || f.sent(billing.PreparedCancelPayment) != 0 { |
| + t.Fatal("expired checkout touched payment") |
| + } |
| +} |
| + |
| +func TestLostCheckoutCreateAdoptsListedSession(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + f.fake.LoseNextResponse = true |
| + p, _, _ := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer@example.test") |
| + if p == nil || p.CheckoutSession != "" { |
| + t.Fatal("expected lost response") |
| + } |
| + // Retrieve the response only in the test; the engine must recover by listing. |
| + result, err := f.fake.Send(context.Background(), *p.CheckoutPrepared) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + session := result.Payment.SessionID |
| + if _, err := f.fake.CompletePaymentCheckout(session); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := f.st.AdvanceDomainPurchase(p.ID, p.State, p.State, func(p *DomainPurchase) { p.CheckoutExpires = time.Now().Add(-time.Hour - time.Second) }); err != nil { |
| + t.Fatal(err) |
| + } |
| + sent := len(f.fake.Sent) |
| + if err := f.srv.advancePurchase(context.Background(), p.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + if f.read(t, p.ID).CheckoutSession != session || len(f.fake.Sent) != sent || f.fake.CallsBy["CustomerCheckouts"] == 0 { |
| + t.Fatal("did not adopt listed session") |
| + } |
| + f.until(t, p.ID, PurchaseDone) |
| +} |
| + |
| +type purchaseCountingStore struct { |
| + *claimCountingStore |
| + operations int |
| + before func(context.Context) error |
| +} |
| + |
| +func (s *purchaseCountingStore) RunAppMutation(ctx context.Context, account, app, action string, fn func(context.Context) error) error { |
| + s.operations++ |
| + return s.Store.(interface { |
| + RunAppMutation(context.Context, string, string, string, func(context.Context) error) error |
| + }).RunAppMutation(ctx, account, app, action, func(ctx context.Context) error { |
| + if s.before != nil { |
| + if err := s.before(ctx); err != nil { |
| + return err |
| + } |
| + } |
| + return fn(ctx) |
| + }) |
| +} |
| + |
| +func TestPollStepsTakeNoAppOperation(t *testing.T) { |
| + cx := newClaimCase(t) |
| + setupClaimPurchase(t, cx) |
| + // No transition on this pass: a live, open payment session is just a poll. |
| + fake := cx.srv.billing.cfg.Provider |
| + prepared, err := fake.PreparePaymentCheckout(billing.PaymentCheckoutRequest{AccountSqid: "bab", Customer: "cus_1", Currency: "usd", Amount: 1500, Description: "shop.com", Reference: "dp_claim_purchase", SuccessURL: "https://example.test/ok", CancelURL: "https://example.test/back", ExpiresAt: time.Now().Add(time.Hour), Key: "dp_claim_purchase"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + result, err := fake.Send(context.Background(), prepared) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + p, err := cx.st.DomainPurchase("dp_claim_purchase") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := cx.srv.movePurchase(context.Background(), p, p.State, func(p *DomainPurchase) { |
| + p.CheckoutSession = result.Payment.SessionID |
| + p.CheckoutExpires = time.Now().Add(time.Hour) |
| + }); err != nil { |
| + t.Fatal(err) |
| + } |
| + counter := &purchaseCountingStore{claimCountingStore: &claimCountingStore{Store: cx.srv.cfg.Releases}} |
| + cx.srv.cfg.Releases = counter |
| + billingFake := fake.(*billingtest.Fake) |
| + reads := billingFake.CallsBy["PaymentCheckout"] |
| + err = cx.srv.domainPurchasePass(context.Background()) |
| + if billingFake.CallsBy["PaymentCheckout"] != reads+1 { |
| + t.Fatal("open poll must make exactly one Stripe session read") |
| + } |
| + if err != nil || counter.operations != 0 || counter.calls.Load() != 0 { |
| + t.Fatalf("pass=%v operations=%d store calls=%d", err, counter.operations, counter.calls.Load()) |
| + } |
| +} |
| + |
| +func TestPurchaseRereadsJournalInsideOperation(t *testing.T) { |
| + cx := newClaimCase(t) |
| + setupClaimPurchase(t, cx) |
| + p, err := cx.st.DomainPurchase("dp_claim_purchase") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := cx.srv.movePurchase(context.Background(), p, PurchaseAuthorised, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + counter := &purchaseCountingStore{claimCountingStore: &claimCountingStore{Store: cx.srv.cfg.Releases}} |
| + counter.before = func(ctx context.Context) error { |
| + return cx.srv.movePurchase(ctx, p, PurchaseFailed, nil) |
| + } |
| + cx.srv.cfg.Releases = counter |
| + if err := cx.srv.advancePurchase(context.Background(), p.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + zone := cx.srv.cfg.ZoneHost.(*zonehosttest.Fake) |
| + if len(zone.Calls) != 0 { |
| + t.Fatalf("stale worker made zone effects: %v", zone.Calls) |
| + } |
| + fresh, err := cx.st.DomainPurchase(p.ID) |
| + if err != nil || fresh.State != PurchaseFailed { |
| + t.Fatalf("purchase=%+v error=%v", fresh, err) |
| + } |
| +} |
diff --git a/internal/console/domainstore.go b/internal/console/domainstore.go| index e2b1e3479..1b33de725 100644 |
| --- a/internal/console/domainstore.go |
| +++ b/internal/console/domainstore.go |
| @@ -34,10 +34,13 @@ var ( |
| ) |
| type purchaseDetails struct { |
| - Principal string |
| - OwnerHandle string |
| - Contact registrar.Contact |
| - CheckoutPrepared *billing.Prepared |
| + Principal string |
| + OwnerHandle string |
| + Contact registrar.Contact |
| + CheckoutPrepared *billing.Prepared |
| + RegisterStartedAt time.Time |
| + RegisterNextAt time.Time |
| + RegisterAlerted bool |
| } |
| type DomainPurchase struct { |
diff --git a/internal/console/jobs_test.go b/internal/console/jobs_test.go| index dccb77e98..816710dce 100644 |
| --- a/internal/console/jobs_test.go |
| +++ b/internal/console/jobs_test.go |
| @@ -50,7 +50,7 @@ var jobPassFuncs = map[string][]string{ |
| "StartPlanLimitsPass": {"planLimitsPass"}, |
| "StartPlanGracePass": {"planGracePass", "planGraceAccountLocked", "notifyPlanOwners", |
| "convergeStoreDeny", "dropStaleLapseItem", "resumeStaleCapPause"}, |
| - "StartDomainPurchasePass": {"domainPurchasePass", "advancePurchase", "advancePurchaseStep", "purchaseCheckout", "purchaseCheckoutStep", "registerPurchase", "registeredPurchase", "failPurchase", "purchaseAlert", "purchaseOwnerNotice"}, |
| + "StartDomainPurchasePass": {"domainPurchasePass", "advancePurchase", "advancePurchaseStep", "advancePurchaseEffects", "reconcileRegisteringPurchase", "purchaseMutation", "purchaseCheckout", "purchaseCheckoutStep", "registerPurchase", "registeredPurchase", "failPurchase", "purchaseAlert", "purchaseOwnerNotice"}, |
| "StartBillingSyncPass": {"billingSyncPass", "billingDiscoveryPass", "discoverCustomer", "transitionAccountPlan"}, |
| "PublishPlansMarker": {"publishPlansMarkerOnce"}, |
| "StartRunSweep": {"runSweepPass", "sweepExpireQueued", "sweepLostRun", "sweepTerminalRun", "sweepOrphanRuns", |