carlos / platform Public

console: checkout keeps an indeterminate create or expiry from being resent; the return observes and syncs a completed session (plans 6b task 9 review)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 78fca6f9f18df8fbafeb6d522cd93a40ab4b7086 parent de7e00b
3 files changed, +351 −20
  • internal/console/billingcheckout.go +65 −11
  • internal/console/billingcheckout_test.go +256 −0
  • internal/console/billingstore.go +30 −9
diff --git a/internal/console/billingcheckout.go b/internal/console/billingcheckout.go
index 8b427f049..60e207066 100644
--- a/internal/console/billingcheckout.go
+++ b/internal/console/billingcheckout.go
@@ -580,9 +580,22 @@ func (s *Server) retireCustomerLocked(h billingHold, b *billingAccount, out cust
// ---- the Checkout create ------------------------------------------------------
// intentResendState is a create's resend state: delivery unknown, its window
-// the key lifetime from its first send, cut off at the session's expiry.
+// the key lifetime from its first send, cut off at the session's expiry. A
+// create that got a cached 5xx is indeterminate (CreateIndeterminate), which
+// recoveryEligible never resends (Invariant 8).
func intentResendState(ci *checkoutIntent) resendState {
- return resendState{State: opUnresolved, FirstSent: ci.FirstSentAt, ResendUntil: ci.ExpiresAt, ContextCurrent: true}
+ return resendState{State: opUnresolved, Indeterminate: ci.CreateIndeterminate, FirstSent: ci.FirstSentAt,
+ ResendUntil: ci.ExpiresAt, ContextCurrent: true}
+}
+
+// gateProviderNow is the provider time a resend gate needs: none for an
+// indeterminate request, whose answer the gate gives without it (so no
+// probe is spent); otherwise providerNow.
+func (s *Server) gateProviderNow(ctx context.Context, indeterminate bool) (time.Time, error) {
+ if indeterminate {
+ return time.Time{}, nil
+ }
+ return s.providerNow(ctx)
}
// createSessionLocked prepares the intent's Checkout create with every
@@ -664,7 +677,7 @@ func (s *Server) sendCreateLocked(h billingHold, ctx context.Context, acct *Acco
if err != nil || found != sessionMissing {
return err // recorded, or the list could not be read: settled later
}
- pnow, err := s.providerNow(ctx)
+ pnow, err := s.gateProviderNow(ctx, ci.CreateIndeterminate)
if err != nil {
log.Printf("console: billing: intent %s: no provider time; not resent", ci.ID)
return nil
@@ -672,8 +685,9 @@ func (s *Server) sendCreateLocked(h billingHold, ctx context.Context, acct *Acco
if ok, reason := recoveryEligible(intentResendState(ci), pnow); !ok {
log.Printf("console: billing: intent %s: create not resent (%s)", ci.ID, reason)
if permanentlyIneligible(reason) {
- // Not in the exhaustive list and past its window: a late
- // session would be unusable (Risks R2).
+ // Not in the exhaustive list, and indeterminate or past its
+ // window: a late session would be unusable (Invariant 1's
+ // exception, Risks R2).
return s.endIntentLocked(h, ci, intentAbandoned, now)
}
return nil
@@ -702,6 +716,12 @@ func (s *Server) recordCreateLocked(h billingHold, ctx context.Context, acct *Ac
log.Printf("console: billing: intent %s: create refused: %v", ci.ID, err)
return s.endIntentLocked(h, ci, intentAbandoned, now)
case errors.Is(err, billing.ErrIndeterminate):
+ // Recorded before any observation, so a failed read cannot lose it:
+ // from here only an observation moves the intent on.
+ ci.CreateIndeterminate = true
+ if err := s.store.PutCheckoutIntent(*ci); err != nil {
+ return err
+ }
found, err := s.findIntentSessionLocked(h, ctx, acct, ci, now)
if err != nil || found != sessionMissing {
return err
@@ -805,7 +825,7 @@ func (s *Server) observeIntentLocked(h billingHold, ctx context.Context, acct *A
if err != nil || found != sessionMissing {
return err
}
- pnow, err := s.providerNow(ctx)
+ pnow, err := s.gateProviderNow(ctx, ci.CreateIndeterminate)
if err != nil {
return nil
}
@@ -839,7 +859,8 @@ func (s *Server) replaceIntentLocked(h billingHold, ctx context.Context, acct *A
// window the key lifetime from its own first send, cut off at the session's
// expiry (after which the provider has expired it anyway).
func expireResendState(ci *checkoutIntent) resendState {
- return resendState{State: opUnresolved, FirstSent: ci.ExpireFirstSentAt, ResendUntil: ci.ExpiresAt, ContextCurrent: true}
+ return resendState{State: opUnresolved, Indeterminate: ci.ExpireIndeterminate, FirstSent: ci.ExpireFirstSentAt,
+ ResendUntil: ci.ExpiresAt, ContextCurrent: true}
}
// expireIntentLocked is the one sender of an intent's expiry. The first
@@ -880,7 +901,7 @@ func (s *Server) expireIntentLocked(h billingHold, ctx context.Context, acct *Ac
if info.State != billing.CheckoutOpen {
return s.recordSessionLocked(h, ctx, acct, ci, info, now)
}
- pnow, err := s.providerNow(ctx)
+ pnow, err := s.gateProviderNow(ctx, ci.ExpireIndeterminate)
if err != nil {
return nil
}
@@ -897,8 +918,9 @@ func (s *Server) expireIntentLocked(h billingHold, ctx context.Context, acct *Ac
}
// recordExpireLocked records an expiry's answer: the expired session; a
-// refusal (the session was no longer open) or a cached 5xx is decided by a
-// read of the session; an unknown delivery or a reused key leaves the intent
+// refusal (the session was no longer open) or a cached 5xx (recorded first as
+// ExpireIndeterminate, so it is never resent) is decided by a read of the
+// session; an unknown delivery or a reused key leaves the intent
// open. An error outside every class is returned at once.
func (s *Server) recordExpireLocked(h billingHold, ctx context.Context, acct *Account, ci *checkoutIntent, res billing.Result, err error, now time.Time) error {
switch {
@@ -908,6 +930,15 @@ func (s *Server) recordExpireLocked(h billingHold, ctx context.Context, acct *Ac
log.Printf("console: billing: intent %s: the expiry answered with no session", ci.ID)
return nil
case errors.Is(err, billing.ErrRefused), errors.Is(err, billing.ErrPaymentFailed), errors.Is(err, billing.ErrIndeterminate):
+ if errors.Is(err, billing.ErrIndeterminate) {
+ // Recorded before the read, so a failed read cannot lose it: the
+ // expiry is never resent, and only a read of the session moves
+ // the intent on (expired, or complete).
+ ci.ExpireIndeterminate = true
+ if perr := s.store.PutCheckoutIntent(*ci); perr != nil {
+ return perr
+ }
+ }
info, rerr := s.billing.cfg.Provider.Checkout(ctx, ci.Session)
if rerr != nil {
log.Printf("console: billing: intent %s: reading session %s after its expiry (%v): %v", ci.ID, ci.Session, err, rerr)
@@ -1071,10 +1102,19 @@ func (s *Server) doneLocked(h billingHold, ctx context.Context, acct *Account, s
return "", "", err
}
}
- if !intentTerminal(ci) {
+ switch {
+ case !intentTerminal(ci):
if err := s.observeIntentLocked(h, ctx, acct, ci, now); err != nil {
return "", "", err
}
+ case ci.State == intentCompleted:
+ // Completed earlier (a webhook, the pass, Continue): the sync that
+ // followed may have failed, or the subscription moved since (a
+ // pending one paid). The return reads the session again and syncs
+ // its subscription; the intent stays completed.
+ if err := s.resyncCompletedLocked(h, ctx, acct, ci, now); err != nil {
+ return "", "", err
+ }
}
if ci.State != intentCompleted {
return "", "", nil
@@ -1090,6 +1130,20 @@ func (s *Server) doneLocked(h billingHold, ctx context.Context, acct *Account, s
return "ok", fmt.Sprintf(billingCopy["checkout.done"], planLabel(row.Plan)), nil
}
+// resyncCompletedLocked reads a completed intent's session and syncs the
+// subscription it made, recording nothing on the intent: a terminal intent
+// is history, and only its subscription can still move.
+func (s *Server) resyncCompletedLocked(h billingHold, ctx context.Context, acct *Account, ci *checkoutIntent, now time.Time) error {
+ info, err := s.billing.cfg.Provider.Checkout(ctx, ci.Session)
+ if err != nil {
+ return fmt.Errorf("billing: reading session %s of completed intent %s: %w", ci.Session, ci.ID, err)
+ }
+ if info.State != billing.CheckoutComplete || info.Subscription == "" {
+ return nil
+ }
+ return s.syncSubscriptionLocked(h, ctx, acct, info.Subscription, now)
+}
+
// ---- the webhook -------------------------------------------------------------------
// observeCheckoutEvent is a Checkout event for a session an intent records:
diff --git a/internal/console/billingcheckout_test.go b/internal/console/billingcheckout_test.go
index 31e24d10c..174258c83 100644
--- a/internal/console/billingcheckout_test.go
+++ b/internal/console/billingcheckout_test.go
@@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
+ "errors"
"fmt"
"io"
"net/http"
@@ -1022,6 +1023,21 @@ func TestPutCheckoutIntentGuards(t *testing.T) {
if err := st.PutCheckoutIntent(moved); err == nil {
t.Error("the expiry's first-send stamp moved")
}
+ // An indeterminate mark is never cleared (Invariant 8).
+ ci.CreateIndeterminate, ci.ExpireIndeterminate = true, true
+ if err := st.PutCheckoutIntent(ci); err != nil {
+ t.Fatal(err)
+ }
+ for name, clear := range map[string]func(c *checkoutIntent){
+ "create": func(c *checkoutIntent) { c.CreateIndeterminate = false },
+ "expiry": func(c *checkoutIntent) { c.ExpireIndeterminate = false },
+ } {
+ c := ci
+ clear(&c)
+ if err := st.PutCheckoutIntent(c); err == nil {
+ t.Errorf("the %s's indeterminate mark was cleared", name)
+ }
+ }
// Terminal is final.
ci.State = intentExpired
if err := st.PutCheckoutIntent(ci); err != nil {
@@ -1035,3 +1051,243 @@ func TestPutCheckoutIntentGuards(t *testing.T) {
t.Fatalf("stored = %+v", got)
}
}
+
+// ---- fix round 1: indeterminate requests and the return -------------------------
+
+// flakyReads wraps the Fake so chosen session reads get no answer: fail is
+// asked before each CustomerCheckouts or Checkout read, and a failed read
+// never reaches the Fake (it is not counted).
+type flakyReads struct {
+ billing.Provider
+ fail func(method string) bool
+}
+
+func (p flakyReads) CustomerCheckouts(ctx context.Context, customer string, after time.Time) ([]billing.CheckoutInfo, error) {
+ if p.fail("CustomerCheckouts") {
+ return nil, fmt.Errorf("%w: test read lost", billing.ErrNoResponse)
+ }
+ return p.Provider.CustomerCheckouts(ctx, customer, after)
+}
+
+func (p flakyReads) Checkout(ctx context.Context, id string) (billing.CheckoutInfo, error) {
+ if p.fail("Checkout") {
+ return billing.CheckoutInfo{}, fmt.Errorf("%w: test read lost", billing.ErrNoResponse)
+ }
+ return p.Provider.Checkout(ctx, id)
+}
+
+// failNext fails the next n reads of method, then lets every read through.
+func (o *opsFixture) failNext(method string, n int) {
+ left := n
+ o.srv.billing.cfg.Provider = flakyReads{Provider: o.fake, fail: func(m string) bool {
+ if m == method && left > 0 {
+ left--
+ return true
+ }
+ return false
+ }}
+}
+
+func (o *opsFixture) sentKeys() []string {
+ var keys []string
+ for _, p := range o.sent() {
+ keys = append(keys, p.Key)
+ }
+ return keys
+}
+
+// TestCheckoutIndeterminateCreateNeverResent: a cached 5xx on the create,
+// and the session list after it gets no answer. The create stays creating
+// but indeterminate, so no later request resends it: the next observation
+// decides (not found: abandoned; found: recorded).
+func TestCheckoutIndeterminateCreateNeverResent(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ after bool
+ later func(o *opsFixture, t *testing.T)
+ want string
+ calls map[string]int
+ }{
+ {"before applying, then Confirm now", false, func(o *opsFixture, t *testing.T) { o.confirm(t) }, intentAbandoned,
+ map[string]int{"CustomerCheckouts": 1}},
+ {"before applying, then the pass", false, func(o *opsFixture, t *testing.T) { o.pass(billingNow) }, intentCreating,
+ map[string]int{"ClockProbe": 1, "LiveSubscriptions": 1}},
+ {"after applying, then Confirm now", true, func(o *opsFixture, t *testing.T) { o.confirm(t) }, intentOpen,
+ map[string]int{"CustomerCheckouts": 1}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ o := newCheckoutFixture(t, true)
+ if tc.after {
+ o.fake.Cached500After = true
+ } else {
+ o.fake.Cached500Before = true
+ }
+ o.failNext("CustomerCheckouts", 1)
+ o.wantRefused(t, o.checkout(t, "plan", "personal", "currency", "usd"), billingCopy["checkout.uncertain"])
+ ci := o.intent(t)
+ if ci.State != intentCreating || !ci.CreateIndeterminate {
+ t.Fatalf("intent after the cached 5xx = %+v", ci)
+ }
+ o.srv.billing.cfg.Provider = o.fake
+ o.reset()
+ tc.later(o, t)
+ wantCounts(t, o.counts(), tc.calls)
+ if got := o.intent(t); got.ID != ci.ID || got.State != tc.want {
+ t.Fatalf("intent = %+v, want %s", got, tc.want)
+ }
+ })
+ }
+ // A later Checkout POST abandons the indeterminate create by observation
+ // and starts a new intent: the old key is never sent again.
+ t.Run("a later Checkout", func(t *testing.T) {
+ o := newCheckoutFixture(t, true)
+ o.fake.Cached500Before = true
+ o.failNext("CustomerCheckouts", 1)
+ o.wantRefused(t, o.checkout(t, "plan", "personal", "currency", "usd"), billingCopy["checkout.uncertain"])
+ old := o.intent(t)
+ o.srv.billing.cfg.Provider = o.fake
+ o.reset()
+ wantSession(t, o.checkout(t, "plan", "personal", "currency", "usd"))
+ if keys := o.sentKeys(); len(keys) != 1 || keys[0] == old.Prepared.Key {
+ t.Fatalf("sent %v: the indeterminate create %s was resent", keys, old.Prepared.Key)
+ }
+ })
+}
+
+// TestCheckoutIndeterminateExpiryNeverResent: Start over's expiry gets a
+// cached 5xx and the read after it gets no answer; a later Start over reads
+// the session (still open) and does not resend the expiry.
+func TestCheckoutIndeterminateExpiryNeverResent(t *testing.T) {
+ o := newCheckoutFixture(t, true)
+ wantSession(t, o.checkout(t, "plan", "personal", "currency", "usd"))
+ old := o.intent(t)
+ o.fake.Cached500Before = true
+ reads := 0
+ o.srv.billing.cfg.Provider = flakyReads{Provider: o.fake, fail: func(m string) bool {
+ if m != "Checkout" {
+ return false
+ }
+ reads++
+ return reads == 2 // the read after the expiry's answer
+ }}
+ o.wantRefused(t, o.checkout(t, "plan", "personal", "currency", "usd", "start_over", "1"), billingCopy["checkout.uncertain"])
+ if ci := o.intent(t); ci.ID != old.ID || ci.State != intentOpen || !ci.ExpireIndeterminate {
+ t.Fatalf("intent after the cached 5xx = %+v", ci)
+ }
+ o.srv.billing.cfg.Provider = o.fake
+ o.reset()
+ o.wantRefused(t, o.checkout(t, "plan", "personal", "currency", "usd", "start_over", "1"), billingCopy["checkout.uncertain"])
+ // S (none) + L + the observation + the expiry's read, which shows it open:
+ // no resend.
+ wantCounts(t, o.counts(), map[string]int{"LiveSubscriptions": 1, "Checkout": 2})
+ // Once the session's own expiry shows in a read, the intent moves on.
+ o.fake.AdvanceProvider(checkoutLifetime + time.Minute)
+ o.reset()
+ wantSession(t, o.checkout(t, "plan", "personal", "currency", "usd", "start_over", "1"))
+ for _, k := range o.sentKeys() {
+ if k == "expire:"+old.ID {
+ t.Fatalf("the indeterminate expiry was resent: %v", o.sentKeys())
+ }
+ }
+}
+
+// TestCustomerCreateCached500ThenFailureNeverResendsTheKey: the first
+// attempt's cached 5xx retires it before anything else; the second attempt
+// then gets no answer at all. A later Checkout resends attempt 2, never
+// attempt 1's key (Risks R3).
+func TestCustomerCreateCached500ThenFailureNeverResendsTheKey(t *testing.T) {
+ o := newCheckoutFixture(t, false)
+ o.fake.Cached500Before = true
+ n := 0
+ o.fake.BeforeSend = func(p billing.Prepared) error {
+ if p.Kind == billing.PreparedCustomer {
+ n++
+ if n == 2 {
+ o.fake.Lock()
+ o.fake.FailBeforeDelivery = 1 + handlerRetries
+ o.fake.Unlock()
+ }
+ }
+ return nil
+ }
+ o.wantRefused(t, o.checkout(t, "plan", "personal", "currency", "usd"), billingCopy["checkout.uncertain"])
+ o.disarm()
+ k1, k2 := customerKey(o.acct.Sqid, 1), customerKey(o.acct.Sqid, 2)
+ if b, _ := o.st.BillingAccount(o.acct.ID); b.Customer != "" || b.CustomerAttempt != 2 || b.CustomerPrepared == nil || b.CustomerPrepared.Key != k2 {
+ t.Fatalf("billing row = %+v", b)
+ }
+ o.fake.Elapse(time.Minute)
+ o.reset()
+ wantSession(t, o.checkout(t, "plan", "personal", "currency", "usd"))
+ keys := o.sentKeys()
+ if len(keys) != 2 || keys[0] != k2 {
+ t.Fatalf("sent %v, want attempt 2 then the Checkout", keys)
+ }
+ for _, k := range keys {
+ if k == k1 {
+ t.Fatalf("attempt 1's key was resent: %v", keys)
+ }
+ }
+}
+
+// TestCheckoutDoneResyncsAfterFailedSync: the session completed and was
+// recorded, but the subscription sync after it failed. The return still
+// reads the session and syncs its subscription, leaving the intent completed.
+func TestCheckoutDoneResyncsAfterFailedSync(t *testing.T) {
+ o := newCheckoutFixture(t, true)
+ wantSession(t, o.checkout(t, "plan", "personal", "currency", "usd"))
+ ci := o.intent(t)
+ if _, err := o.fake.CompleteCheckout(ci.Session); err != nil {
+ t.Fatal(err)
+ }
+ o.fake.BeforeSubscription = func(string) error { return errors.New("read failed") }
+ o.request(t, http.MethodGet, o.billingBase()+"/continue", nil)
+ o.fake.BeforeSubscription = nil
+ if got := o.intent(t); got.State != intentCompleted {
+ t.Fatalf("intent = %+v", got)
+ }
+ if b, _ := o.st.BillingAccount(o.acct.ID); b.Subscription != "" {
+ t.Fatalf("the failed sync recorded %q", b.Subscription)
+ }
+ o.reset()
+ r := o.request(t, http.MethodGet, o.billingBase()+"/done?session="+ci.Session, nil)
+ if r.Flash != "ok" || r.FlashMsg != fmt.Sprintf(billingCopy["checkout.done"], "Personal") {
+ t.Fatalf("done = %+v", r)
+ }
+ wantCounts(t, o.counts(), map[string]int{"Checkout": 1, "Subscription": 1})
+ if got := o.intent(t); got.State != intentCompleted || got.ReturnedAt.IsZero() || o.plan(t) != "personal" {
+ t.Fatalf("intent %+v plan %q", got, o.plan(t))
+ }
+}
+
+// TestCheckoutDonePendingThenPaid: the pass recorded the completed session
+// while its subscription was still pending; it is paid before the owner
+// returns, and the return shows it paid.
+func TestCheckoutDonePendingThenPaid(t *testing.T) {
+ o := newCheckoutFixture(t, true)
+ wantSession(t, o.checkout(t, "plan", "personal", "currency", "usd"))
+ ci := o.intent(t)
+ subID, err := o.fake.CompleteCheckout(ci.Session)
+ if err != nil {
+ t.Fatal(err)
+ }
+ o.fake.Lock()
+ o.fake.Subs[subID].State, o.fake.Subs[subID].ProviderStatus = billing.StatePending, "incomplete"
+ o.fake.Unlock()
+ o.pass(billingNow)
+ if b, _ := o.st.BillingAccount(o.acct.ID); o.intent(t).State != intentCompleted || b.State != billing.StatePending {
+ t.Fatalf("after the pass: intent %+v billing %+v", o.intent(t), b)
+ }
+ o.fake.Lock()
+ o.fake.Subs[subID].State, o.fake.Subs[subID].ProviderStatus = billing.StatePaid, "active"
+ o.fake.Unlock()
+ o.reset()
+ r := o.request(t, http.MethodGet, o.billingBase()+"/done?session="+ci.Session, nil)
+ if r.Flash != "ok" || r.FlashMsg != fmt.Sprintf(billingCopy["checkout.done"], "Personal") {
+ t.Fatalf("done = %+v", r)
+ }
+ wantCounts(t, o.counts(), map[string]int{"Checkout": 1, "Subscription": 1})
+ if b, _ := o.st.BillingAccount(o.acct.ID); b.State != billing.StatePaid || o.plan(t) != "personal" {
+ t.Fatalf("billing %+v plan %q", b, o.plan(t))
+ }
+}
diff --git a/internal/console/billingstore.go b/internal/console/billingstore.go
index 4ee774fb3..5173fdc07 100644
--- a/internal/console/billingstore.go
+++ b/internal/console/billingstore.go
@@ -199,8 +199,14 @@ CREATE TABLE IF NOT EXISTS billing_restore_checks (
}
// The expiry's own first-send stamp (provider time, Invariant 9), for a
// store created before the column existed.
- if _, err := s.db.Exec(`ALTER TABLE billing_checkout_intents ADD COLUMN expire_first_sent_at INTEGER NOT NULL DEFAULT 0`); err != nil && !strings.Contains(err.Error(), "duplicate column") {
- return err
+ for _, col := range []string{
+ `expire_first_sent_at INTEGER NOT NULL DEFAULT 0`,
+ `create_indeterminate INTEGER NOT NULL DEFAULT 0`,
+ `expire_indeterminate INTEGER NOT NULL DEFAULT 0`,
+ } {
+ if _, err := s.db.Exec(`ALTER TABLE billing_checkout_intents ADD COLUMN ` + col); err != nil && !strings.Contains(err.Error(), "duplicate column") {
+ return err
+ }
}
return s.migrateBillingOperations()
}
@@ -710,6 +716,11 @@ type checkoutIntent struct {
// before its first send and written once, like FirstSentAt for the
// create.
ExpireFirstSentAt time.Time
+ // CreateIndeterminate and ExpireIndeterminate record that the create or
+ // the expiry got a cached 5xx (fact 5): written before any observation
+ // is attempted, never cleared, so no later request resends it
+ // (Invariant 8). Only an observation moves the intent on.
+ CreateIndeterminate, ExpireIndeterminate bool
}
// intentTerminal is an intent nothing more will happen to: completed,
@@ -723,17 +734,21 @@ func intentTerminal(ci *checkoutIntent) bool {
}
const checkoutIntentColumns = `account_id, intent_id, session, url, book, plan, currency, seats, packs, prepared, expire_prepared,
- state, created_at, expires_at, first_sent_at, returned_at, resolved_at, expire_first_sent_at`
+ state, created_at, expires_at, first_sent_at, returned_at, resolved_at, expire_first_sent_at,
+ create_indeterminate, expire_indeterminate`
func scanCheckoutIntent(sc interface{ Scan(...any) error }) (*checkoutIntent, error) {
var ci checkoutIntent
var packs string
var prepared, expire []byte
var created, expires, firstSent, returned, resolved, expireSent int64
+ var createIndeterminate, expireIndeterminate int
if err := sc.Scan(&ci.AccountID, &ci.ID, &ci.Session, &ci.URL, &ci.Book, &ci.Plan, &ci.Currency, &ci.Seats, &packs,
- &prepared, &expire, &ci.State, &created, &expires, &firstSent, &returned, &resolved, &expireSent); err != nil {
+ &prepared, &expire, &ci.State, &created, &expires, &firstSent, &returned, &resolved, &expireSent,
+ &createIndeterminate, &expireIndeterminate); err != nil {
return nil, err
}
+ ci.CreateIndeterminate, ci.ExpireIndeterminate = createIndeterminate != 0, expireIndeterminate != 0
ci.ExpireFirstSentAt = timeOrZero(expireSent)
if err := json.Unmarshal([]byte(packs), &ci.Packs); err != nil {
return nil, err
@@ -757,8 +772,9 @@ func scanCheckoutIntent(sc interface{ Scan(...any) error }) (*checkoutIntent, er
// updated in place, but its prepared requests are never edited (Invariant
// 1): a create whose bytes differ, or an expiry other than the one already
// stored, is refused. So is a change to what it buys (book, plan,
-// currency, seats, packs), to a first-send stamp already written, and a
-// terminal intent made non-terminal again: a terminal intent is history.
+// currency, seats, packs), to a first-send stamp already written, clearing
+// an indeterminate mark (Invariant 8), and a terminal intent made
+// non-terminal again: a terminal intent is history.
// Another intent replaces the account's only when the stored one is
// terminal, so an outstanding create is never lost.
func (s *Store) PutCheckoutIntent(ci checkoutIntent) error {
@@ -808,20 +824,25 @@ func (s *Store) PutCheckoutIntent(ci checkoutIntent) error {
if !writeOnce(cur.FirstSentAt, ci.FirstSentAt) || !writeOnce(cur.ExpireFirstSentAt, ci.ExpireFirstSentAt) {
return fmt.Errorf("billing: checkout intent %s: a first-send stamp is written once", ci.ID)
}
+ if (cur.CreateIndeterminate && !ci.CreateIndeterminate) || (cur.ExpireIndeterminate && !ci.ExpireIndeterminate) {
+ return fmt.Errorf("billing: checkout intent %s: an indeterminate request stays indeterminate", ci.ID)
+ }
if intentTerminal(cur) && !intentTerminal(&ci) {
return fmt.Errorf("billing: checkout intent %s is %s, which is final", ci.ID, cur.State)
}
}
if _, err := tx.Exec(`INSERT INTO billing_checkout_intents (`+checkoutIntentColumns+`)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(account_id) DO UPDATE SET intent_id = excluded.intent_id, session = excluded.session, url = excluded.url,
book = excluded.book, plan = excluded.plan, currency = excluded.currency, seats = excluded.seats, packs = excluded.packs,
prepared = excluded.prepared, expire_prepared = excluded.expire_prepared, state = excluded.state,
created_at = excluded.created_at, expires_at = excluded.expires_at, first_sent_at = excluded.first_sent_at,
- returned_at = excluded.returned_at, resolved_at = excluded.resolved_at, expire_first_sent_at = excluded.expire_first_sent_at`,
+ returned_at = excluded.returned_at, resolved_at = excluded.resolved_at, expire_first_sent_at = excluded.expire_first_sent_at,
+ create_indeterminate = excluded.create_indeterminate, expire_indeterminate = excluded.expire_indeterminate`,
ci.AccountID, ci.ID, ci.Session, ci.URL, ci.Book, ci.Plan, ci.Currency, ci.Seats, packs, prepared, expire,
ci.State, unixOrZero(ci.CreatedAt), unixOrZero(ci.ExpiresAt), unixOrZero(ci.FirstSentAt),
- unixOrZero(ci.ReturnedAt), unixOrZero(ci.ResolvedAt), unixOrZero(ci.ExpireFirstSentAt)); err != nil {
+ unixOrZero(ci.ReturnedAt), unixOrZero(ci.ResolvedAt), unixOrZero(ci.ExpireFirstSentAt),
+ boolInt(ci.CreateIndeterminate), boolInt(ci.ExpireIndeterminate)); err != nil {
return err
}
return tx.Commit()