carlos / platform Public

billingtest: outages are no-response, checkouts listed at or after the bound, keys age from the first request (plans 6b)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 740badead9da89cf285801673e93df4b9f74af91 parent 66d7919
2 files changed, +112 −9
  • internal/billing/billingtest/fake.go +24 −9
  • internal/billing/billingtest/fake_test.go +88 −0
diff --git a/internal/billing/billingtest/fake.go b/internal/billing/billingtest/fake.go
index fa69267ab..71a6a6f1d 100644
--- a/internal/billing/billingtest/fake.go
+++ b/internal/billing/billingtest/fake.go
@@ -116,6 +116,7 @@ type Fake struct {
// CheckoutSubscription); Sessions is consulted when absent.
Checkouts map[string]string
// Err fails every call (no Date): a provider that cannot be reached.
+ // Reads return it as it is; Send wraps it in billing.ErrNoResponse.
Err error
// CheckErr fails only the readiness check.
CheckErr error
@@ -202,7 +203,9 @@ type Fake struct {
// BeforeSend, when set, runs at the start of every Send, outside the
// Fake's lock, after CrashBeforeSend is checked: something that happens
// at the provider just before the request arrives (a buyer completing a
- // session, say). A non-nil error is returned as the Send's answer.
+ // session, say). A non-nil error is returned as the Send's answer,
+ // raw: unless it wraps an outcome class, the console treats it like
+ // ErrCrash.
BeforeSend func(p billing.Prepared) error
keys map[string]*keyEntry
@@ -320,8 +323,8 @@ func (f *Fake) AdvanceConsole(d time.Duration) {
f.console = f.console.Add(d)
}
-// ConsoleNow reads the console's wall clock: a func(time.Time) a test
-// injects as the console's now.
+// ConsoleNow reads the console's wall clock. The method value f.ConsoleNow
+// is a func() time.Time a test injects as the console's now.
func (f *Fake) ConsoleNow() time.Time {
f.cmu.Lock()
defer f.cmu.Unlock()
@@ -622,6 +625,9 @@ func (f *Fake) Check(ctx context.Context, _ *plans.PriceBook, _ billing.PriceMap
if f.Err != nil {
return f.Err
}
+ if f.timedOut() {
+ return fmt.Errorf("%w: timed out before headers", billing.ErrNoResponse)
+ }
f.respond(ctx)
return f.CheckErr
}
@@ -646,12 +652,13 @@ func (f *Fake) LiveSubscriptions(ctx context.Context, customer string) ([]string
return out, nil
}
-// CustomerCheckouts pages through customer's sessions created after
-// createdAfter, in id order.
+// CustomerCheckouts pages through customer's sessions created at or after
+// createdAfter, in id order. The bound is inclusive: with whole-second
+// clocks, a session created in the same second as the bound is listed.
func (f *Fake) CustomerCheckouts(ctx context.Context, customer string, createdAfter time.Time) ([]billing.CheckoutInfo, error) {
f.mu.Lock()
defer f.mu.Unlock()
- ids := sortedKeys(f.Sessions, func(s *Session) bool { return s.Customer == customer && s.Created.After(createdAfter) })
+ ids := sortedKeys(f.Sessions, func(s *Session) bool { return s.Customer == customer && !s.Created.Before(createdAfter) })
out := []billing.CheckoutInfo{}
err := f.list(ctx, "CustomerCheckouts", ids, func(id string) {
if s := f.Sessions[id]; s != nil {
@@ -981,7 +988,9 @@ func (f *Fake) Send(ctx context.Context, p billing.Prepared) (billing.Result, er
func (f *Fake) send(ctx context.Context, p billing.Prepared) (billing.Result, error) {
if f.Err != nil {
- return billing.Result{}, f.Err
+ // An unreachable provider: delivery unknown, so no response, never
+ // a raw error (which the console treats as a crash).
+ return billing.Result{}, fmt.Errorf("%w: %w", billing.ErrNoResponse, f.Err)
}
if f.timedOut() {
return billing.Result{}, fmt.Errorf("%w: timed out before headers", billing.ErrNoResponse)
@@ -1065,7 +1074,9 @@ func (f *Fake) send(ctx context.Context, p billing.Prepared) (billing.Result, er
func (f *Fake) land(l *lateSend) {
r, err := f.execute(l.body)
if e, ok := f.keys[l.p.Key]; ok && e.executing {
- e.executing, e.result, e.err, e.storedAt = false, cloneResult(r), err, f.ProviderClock
+ // storedAt stays when execution began: the provider ages a key from
+ // the original request (fact 6).
+ e.executing, e.result, e.err = false, cloneResult(r), err
}
}
@@ -1251,7 +1262,8 @@ func (f *Fake) InvoiceReadFails(n int) {
f.invoiceErr = n
}
-// Renew is the subscription reaching its period end. A renewing
+// Renew is the subscription reaching its period end: ProviderClock moves up
+// to the old period end if it is behind (never back). A renewing
// subscription moves its period a year on, keeps its items, drops any
// pending update, and gets a renewal invoice (ReasonCycle, PeriodStart the
// old period end) of its items' quantities. One set to cancel at period
@@ -1267,6 +1279,9 @@ func (f *Fake) Renew(subscription string) error {
return fmt.Errorf("billingtest: %s is not a live subscription", subscription)
}
f.dropPending(s)
+ if f.ProviderClock.Before(s.PeriodEnd) {
+ f.ProviderClock = s.PeriodEnd
+ }
if s.CancelAtPeriodEnd {
s.Live, s.State, s.ProviderStatus = false, billing.StateEnded, "canceled"
} else {
diff --git a/internal/billing/billingtest/fake_test.go b/internal/billing/billingtest/fake_test.go
index cae636738..7e3c2170f 100644
--- a/internal/billing/billingtest/fake_test.go
+++ b/internal/billing/billingtest/fake_test.go
@@ -901,3 +901,91 @@ func TestFakeAssignsItemIDs(t *testing.T) {
t.Fatal("a read shares its items with the Fake")
}
}
+
+// Review fix round 1.
+
+// An unreachable provider is no response on Send, never a crash-like raw
+// error; reads keep returning Err as it is.
+func TestFakeErrOnSendIsNoResponse(t *testing.T) {
+ f := newFake(t)
+ seedSub(f, "sub_1", "cus_1")
+ down := errors.New("network down")
+ f.Err = down
+ _, err := f.Send(context.Background(), prepareApps(t, f, "sub_1", 3, billing.ProrateNone, "op:1"))
+ if !errors.Is(err, billing.ErrNoResponse) || !errors.Is(err, down) || errors.Is(err, ErrCrash) {
+ t.Fatalf("Send under Err: err = %v, want ErrNoResponse wrapping Err", err)
+ }
+ if _, err := f.Subscription(context.Background(), "sub_1"); err != down {
+ t.Fatalf("read under Err: err = %v, want Err itself", err)
+ }
+}
+
+// A session created at exactly the bound is listed: whole-second clocks
+// make equality the common case.
+func TestFakeCustomerCheckoutsInclusiveBound(t *testing.T) {
+ f := newFake(t)
+ f.AddSession(&Session{CheckoutInfo: billing.CheckoutInfo{Customer: "cus_1", IntentID: "in_eq", State: billing.CheckoutOpen}, Created: t0})
+ f.AddSession(&Session{CheckoutInfo: billing.CheckoutInfo{Customer: "cus_1", IntentID: "in_before", State: billing.CheckoutOpen}, Created: t0.Add(-time.Second)})
+ got, err := f.CustomerCheckouts(context.Background(), "cus_1", t0)
+ if err != nil || len(got) != 1 || got[0].IntentID != "in_eq" {
+ t.Fatalf("CustomerCheckouts at the bound = %+v, %v", got, err)
+ }
+}
+
+// A key ages from the request that began execution, not from when a late
+// request landed (fact 6).
+func TestFakeLateKeyAgesFromFirstRequest(t *testing.T) {
+ f := newFake(t)
+ seedSub(f, "sub_1", "cus_1")
+ ctx := context.Background()
+ f.CompleteLater(1)
+ p := prepareApps(t, f, "sub_1", 3, billing.ProrateNone, "op:1")
+ if _, err := f.Send(ctx, p); !errors.Is(err, billing.ErrNoResponse) {
+ t.Fatal(err)
+ }
+ f.AdvanceProvider(2 * time.Hour)
+ if _, err := f.Subscription(ctx, "sub_1"); err != nil { // it lands now, 2 h later
+ t.Fatal(err)
+ }
+ f.AdvanceProvider(23 * time.Hour) // 25 h after the first request, 23 h after landing
+ f.PruneKeysOlderThan(24 * time.Hour)
+ f.Lock()
+ f.Subs["sub_1"].Items[1].Quantity = 5
+ f.Unlock()
+ if r, err := f.Send(ctx, p); err != nil || r.Replayed || appsQty(t, f, "sub_1") != 3 {
+ t.Fatalf("resend 25 h after the first request = %+v, %v; want the key pruned and a new execution", r, err)
+ }
+}
+
+// Renew brings the provider clock up to the old period end.
+func TestFakeRenewAdvancesProviderClock(t *testing.T) {
+ f := newFake(t)
+ s := seedSub(f, "sub_1", "cus_1")
+ oldEnd := s.PeriodEnd
+ if err := f.Renew("sub_1"); err != nil {
+ t.Fatal(err)
+ }
+ if !f.ProviderClock.Equal(oldEnd) {
+ t.Fatalf("ProviderClock = %v, want the old period end %v", f.ProviderClock, oldEnd)
+ }
+ // A clock already past the period end is not moved back.
+ later := f.ProviderClock.AddDate(2, 0, 0)
+ f.SetProviderClock(later)
+ if err := f.Renew("sub_1"); err != nil {
+ t.Fatal(err)
+ }
+ if !f.ProviderClock.Equal(later) {
+ t.Fatalf("Renew moved the clock back: %v", f.ProviderClock)
+ }
+}
+
+func TestFakeCheckHonoursHeaderlessTimeout(t *testing.T) {
+ f := newFake(t)
+ f.HeaderlessTimeout = 1
+ if err := f.Check(context.Background(), nil, billing.PriceMap{}); !errors.Is(err, billing.ErrNoResponse) {
+ t.Fatalf("Check under HeaderlessTimeout: err = %v", err)
+ }
+ if err := f.Check(context.Background(), nil, billing.PriceMap{}); err != nil {
+ t.Fatalf("Check after: %v", err)
+ }
+}