console: a join charges at most one consented seat and never for uncovered members; no billing write while billing isn't ready; expiry recovery spends one resend (plans 6b branch review)
P1 consent quantity (Invariant 2, Call 11): seatJoinTarget is the one decision of a join's restore and charge. When the members before the join are already billed above max(cur, paid), it refuses (errSeatsUncovered): admission opens seats_unpaid under the hold and answers admitNeedsConsent with nothing sent. Otherwise a charge is at most one seat over max(cur, paid). Guards: TestSeatJoinTargetChargesAtMostOneCoveredSeat and TestSeatChargeTargetIsTheOnlyQuantityPlanInSeats. P1 readiness (6a): sendPreparedLocked is the one place a prepared request reaches the provider and asks requireBillingReady first (errBillingNotReady, notice.not_ready). sendOpLocked, finishOpLocked, the customer, Checkout create and expiry senders all go through it, and refuse before storing a request they could not send. The invite's paid-seat step refuses while not ready; the retirement gate refuses with delete.unverified. Guard: TestProviderWritesOnlyThroughTheReadyGate. P2 budget F: a stored expiry's recovery makes no in-handler retries.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
9 files changed,
+621
−31
internal/console/billingcheckout.go+24 −9internal/console/billingcheckout_test.go+27 −0internal/console/billinghold.go+31 −0internal/console/billinglint_test.go+128 −8internal/console/billingops.go+13 −5internal/console/billingready_test.go+239 −0internal/console/billingretire.go+9 −3internal/console/billingseats.go+58 −6internal/console/billingseats_test.go+92 −0
diff --git a/internal/console/billingcheckout.go b/internal/console/billingcheckout.go| index 60e207066..1c0d9846f 100644 |
| --- a/internal/console/billingcheckout.go |
| +++ b/internal/console/billingcheckout.go |
| @@ -476,6 +476,9 @@ func (s *Server) ensureCustomerLocked(h billingHold, ctx context.Context, acct * |
| // the billing row with its provider-time stamp, before anything is sent. |
| func (s *Server) startCustomerLocked(h billingHold, ctx context.Context, acct *Account, b *billingAccount) error { |
| _ = h |
| + if err := s.requireBillingReady(); err != nil { |
| + return err |
| + } |
| pnow, err := s.providerNow(ctx) |
| if err != nil { |
| return errNoProviderTimeRefusal |
| @@ -507,7 +510,6 @@ func customerResendState(b *billingAccount) resendState { |
| // the resend is the check, and provider time comes from the request's |
| // recorder or one probe. |
| func (s *Server) sendCustomerLocked(h billingHold, ctx context.Context, acct *Account, b *billingAccount, recovering bool, retries int, now time.Time) (customerOutcome, error) { |
| - cfg := s.billing.cfg |
| for attempt := 0; ; attempt++ { |
| if recovering || attempt > 0 { |
| if attempt > 0 { |
| @@ -526,7 +528,7 @@ func (s *Server) sendCustomerLocked(h billingHold, ctx context.Context, acct *Ac |
| return customerUnknown, nil |
| } |
| } |
| - res, err := cfg.Provider.Send(ctx, *b.CustomerPrepared) |
| + res, err := s.sendPreparedLocked(h, ctx, *b.CustomerPrepared) |
| if !retryableSend(err) || attempt == retries { |
| return s.recordCustomerLocked(h, acct, b, res, err, now) |
| } |
| @@ -615,6 +617,9 @@ func (s *Server) createSessionLocked(h billingHold, ctx context.Context, acct *A |
| if b == nil || b.Customer == "" { |
| return fmt.Errorf("billing: account %s has no customer for a Checkout", acct.Sqid) |
| } |
| + if err := s.requireBillingReady(); err != nil { |
| + return err // before the intent: nothing stored that cannot be sent |
| + } |
| coupon, err := s.houseCoupon(acct) |
| if err != nil { |
| return err |
| @@ -663,7 +668,6 @@ func (s *Server) finishCreateLocked(h billingHold, ctx context.Context, acct *Ac |
| // when the intent id is there, then resends the same bytes only while |
| // recoveryEligible. A recovery sends at most once. |
| func (s *Server) sendCreateLocked(h billingHold, ctx context.Context, acct *Account, ci *checkoutIntent, recovering bool, now time.Time) error { |
| - cfg := s.billing.cfg |
| retries := handlerRetries |
| if recovering { |
| retries = 0 |
| @@ -693,7 +697,7 @@ func (s *Server) sendCreateLocked(h billingHold, ctx context.Context, acct *Acco |
| return nil |
| } |
| } |
| - res, err := cfg.Provider.Send(ctx, ci.Prepared) |
| + res, err := s.sendPreparedLocked(h, ctx, ci.Prepared) |
| if !retryableSend(err) || attempt == retries { |
| return s.recordCreateLocked(h, ctx, acct, ci, res, err, now) |
| } |
| @@ -866,12 +870,23 @@ func expireResendState(ci *checkoutIntent) resendState { |
| // expireIntentLocked is the one sender of an intent's expiry. The first |
| // time, the expiry is prepared and stored on the intent with its |
| // provider-time stamp before it is sent. A stored one is a recovery, read |
| -// first. An unknown delivery is retried after the backoff with a read of the |
| -// session, which decides when it is no longer open, then the same bytes only |
| -// while recoveryEligible. |
| +// first, and sends at most once (budget F). An unknown delivery on a first |
| +// send is retried after the backoff with a read of the session, which |
| +// decides when it is no longer open, then the same bytes only while |
| +// recoveryEligible. While billing is not ready nothing is stored, read or |
| +// sent (errBillingNotReady). |
| func (s *Server) expireIntentLocked(h billingHold, ctx context.Context, acct *Account, ci *checkoutIntent, now time.Time) error { |
| cfg := s.billing.cfg |
| recovering := ci.ExpirePrepared != nil |
| + // A recovery is F: one read and at most one resend, no in-handler |
| + // retries (as sendCreateLocked). |
| + retries := handlerRetries |
| + if recovering { |
| + retries = 0 |
| + } |
| + if err := s.requireBillingReady(); err != nil { |
| + return err // before the expiry is stored or anything read or sent |
| + } |
| if !recovering { |
| pnow, err := s.providerNow(ctx) |
| if err != nil { |
| @@ -910,8 +925,8 @@ func (s *Server) expireIntentLocked(h billingHold, ctx context.Context, acct *Ac |
| return nil |
| } |
| } |
| - res, err := cfg.Provider.Send(ctx, *ci.ExpirePrepared) |
| - if !retryableSend(err) || attempt == handlerRetries { |
| + res, err := s.sendPreparedLocked(h, ctx, *ci.ExpirePrepared) |
| + if !retryableSend(err) || attempt == retries { |
| return s.recordExpireLocked(h, ctx, acct, ci, res, err, now) |
| } |
| } |
diff --git a/internal/console/billingcheckout_test.go b/internal/console/billingcheckout_test.go| index 174258c83..667ef5c35 100644 |
| --- a/internal/console/billingcheckout_test.go |
| +++ b/internal/console/billingcheckout_test.go |
| @@ -732,6 +732,33 @@ func TestExpiryNoResponseResent(t *testing.T) { |
| } |
| } |
| +// TestExpiryRecoverySpendsOneResend: an expiry left without an answer is |
| +// recovered by a later Start over with one read of the session and at most |
| +// one resend of the stored bytes (budget F), however many times that resend |
| +// gets no answer: no in-handler retries on a recovery. |
| +func TestExpiryRecoverySpendsOneResend(t *testing.T) { |
| + o := newCheckoutFixture(t, true) |
| + wantSession(t, o.checkout(t, "plan", "personal", "currency", "usd")) |
| + old := o.intent(t) |
| + o.fake.FailBeforeDelivery = handlerRetries + 1 |
| + o.wantRefused(t, o.checkout(t, "plan", "personal", "currency", "usd", "start_over", "1"), billingCopy["checkout.uncertain"]) |
| + stored := o.intent(t) |
| + if stored.ID != old.ID || stored.State != intentOpen || stored.ExpirePrepared == nil { |
| + t.Fatalf("intent = %+v, want open with its expiry stored", stored) |
| + } |
| + o.reset() |
| + o.fake.FailBeforeDelivery = 10 |
| + o.wantRefused(t, o.checkout(t, "plan", "personal", "currency", "usd", "start_over", "1"), billingCopy["checkout.uncertain"]) |
| + // L + the observation's session read, then F: the recovery's read and |
| + // one resend. |
| + wantCounts(t, o.counts(), map[string]int{"LiveSubscriptions": 1, "Checkout": 2, "Send": 1}) |
| + for _, p := range o.sent() { |
| + if p.Key != stored.ExpirePrepared.Key { |
| + t.Fatalf("sent %q, want only the stored expiry", p.Key) |
| + } |
| + } |
| +} |
| + |
| // TestCheckoutExpiryNotResentPastItsWindow: the provider still shows the |
| // session open after the intent's provider-time ExpiresAt (its own expiry |
| // lags); an expiry whose first send got no answer is not resent outside its |
diff --git a/internal/console/billinghold.go b/internal/console/billinghold.go| index 8b8649a5d..717bb6075 100644 |
| --- a/internal/console/billinghold.go |
| +++ b/internal/console/billinghold.go |
| @@ -135,3 +135,34 @@ var ( |
| errNoProviderTimeRefusal = billingRefusal{Key: "change.clock"} |
| errRestoreNearRenewal = billingRefusal{Key: "change.near_renewal"} |
| ) |
| + |
| +// errBillingNotReady refuses a billing write while billing is not ready |
| +// (notice.not_ready): the readiness check has not passed, so the provider's |
| +// prices and account may not be what the configuration says. |
| +var errBillingNotReady = billingRefusal{Key: "notice.not_ready"} |
| + |
| +// requireBillingReady is the readiness rule for billing writes (6a's |
| +// readiness, plans 6b branch review): nil only once billing is ready. |
| +// sendPreparedLocked asks it before every send; a sender that stores a |
| +// prepared request before its first send asks it before storing, so nothing |
| +// is stored for a send that would be refused. |
| +func (s *Server) requireBillingReady() error { |
| + if s.billing == nil || !s.billing.ready.Load() { |
| + return errBillingNotReady |
| + } |
| + return nil |
| +} |
| + |
| +// sendPreparedLocked is the one place a prepared request reaches the |
| +// provider: every operation, recovery resend, customer create, Checkout |
| +// create and expiry goes through it. While billing is not ready it sends |
| +// nothing and answers errBillingNotReady, which is outside every outcome |
| +// class, so the caller records nothing more |
| +// (TestProviderWritesOnlyThroughTheReadyGate). |
| +func (s *Server) sendPreparedLocked(h billingHold, ctx context.Context, p billing.Prepared) (billing.Result, error) { |
| + _ = h |
| + if err := s.requireBillingReady(); err != nil { |
| + return billing.Result{}, err |
| + } |
| + return s.billing.cfg.Provider.Send(ctx, p) |
| +} |
diff --git a/internal/console/billinglint_test.go b/internal/console/billinglint_test.go| index c4e343c1e..e30e13c4b 100644 |
| --- a/internal/console/billinglint_test.go |
| +++ b/internal/console/billinglint_test.go |
| @@ -330,9 +330,12 @@ func TestOpOutstandingMatchesIndex(t *testing.T) { |
| } |
| } |
| -// sendGateFindings: in billing files, every function that calls Provider.Send |
| -// also calls recoveryEligible, and calls Send once, so no resend site exists |
| -// outside the gate (Invariant 8). |
| +// sendGateFindings: in billing files, every function that sends (calls |
| +// Provider.Send, or sendPreparedLocked, the one place a prepared request |
| +// reaches the provider) also calls recoveryEligible, and sends from one call |
| +// site, so no resend site exists outside the gate (Invariant 8). |
| +// sendPreparedLocked itself is the send primitive, pinned by |
| +// TestProviderWritesOnlyThroughTheReadyGate. |
| func sendGateFindings(fset *token.FileSet, files map[string]*ast.File) []string { |
| var findings []string |
| for name, f := range files { |
| @@ -341,7 +344,7 @@ func sendGateFindings(fset *token.FileSet, files map[string]*ast.File) []string |
| } |
| for _, d := range f.Decls { |
| fd, ok := d.(*ast.FuncDecl) |
| - if !ok || fd.Body == nil { |
| + if !ok || fd.Body == nil || fd.Name.Name == "sendPreparedLocked" { |
| continue |
| } |
| sends, gated := 0, false |
| @@ -352,7 +355,7 @@ func sendGateFindings(fset *token.FileSet, files map[string]*ast.File) []string |
| } |
| switch fun := call.Fun.(type) { |
| case *ast.SelectorExpr: |
| - if fun.Sel.Name == "Send" { |
| + if fun.Sel.Name == "Send" || fun.Sel.Name == "sendPreparedLocked" { |
| sends++ |
| } |
| if fun.Sel.Name == "recoveryEligible" { |
| @@ -392,9 +395,10 @@ func TestRecoveryEligibleIsTheOnlyGate(t *testing.T) { |
| planted := parsePlanted(t, fset, "billingplanted.go", ` |
| func (s *Server) resendAnyway(p int) { s.billing.cfg.Provider.Send(nil, p) } |
| func (s *Server) twice(p int) { recoveryEligible(p, p); s.billing.cfg.Provider.Send(nil, p); s.billing.cfg.Provider.Send(nil, p) } |
| +func (s *Server) throughTheHelper(p int) { s.sendPreparedLocked(h, nil, p) } |
| `) |
| - if got := sendGateFindings(fset, planted); len(got) != 2 { |
| - t.Fatalf("planted findings = %v, want an ungated send and a double send", got) |
| + if got := sendGateFindings(fset, planted); len(got) != 3 { |
| + t.Fatalf("planted findings = %v, want an ungated send, a double send and an ungated helper send", got) |
| } |
| // The gate is called by the code that sends: at least sendOpLocked and |
| // finishOpLocked. |
| @@ -426,7 +430,7 @@ func passSourceWrites(t *testing.T) []string { |
| } |
| ast.Inspect(f, func(n ast.Node) bool { |
| if call, ok := n.(*ast.CallExpr); ok { |
| - if sel, ok := call.Fun.(*ast.SelectorExpr); ok && (sel.Sel.Name == "Send" || sel.Sel.Name == "PortalURL") { |
| + if sel, ok := call.Fun.(*ast.SelectorExpr); ok && (sel.Sel.Name == "Send" || sel.Sel.Name == "sendPreparedLocked" || sel.Sel.Name == "PortalURL") { |
| found = append(found, fset.Position(call.Pos()).String()+": "+sel.Sel.Name) |
| } |
| } |
| @@ -435,3 +439,119 @@ func passSourceWrites(t *testing.T) []string { |
| } |
| return found |
| } |
| + |
| +// providerWriteFindings: every provider Send in the package, and every Send |
| +// call in a billing file, is inside sendPreparedLocked, and |
| +// sendPreparedLocked asks requireBillingReady before its one Send. So no |
| +// billing write (an operation, a recovery's resend, a customer create, a |
| +// Checkout create or expiry) reaches the provider while billing isn't ready, |
| +// whichever handler or helper started it (plans 6b branch review; 6a's |
| +// readiness). It answers the findings and how many sendPreparedLocked it |
| +// saw. |
| +func providerWriteFindings(fset *token.FileSet, files map[string]*ast.File) (findings []string, gates int) { |
| + for name, f := range files { |
| + for _, d := range f.Decls { |
| + fd, ok := d.(*ast.FuncDecl) |
| + if !ok || fd.Body == nil { |
| + continue |
| + } |
| + var sends []token.Pos |
| + ready := token.NoPos |
| + ast.Inspect(fd.Body, func(n ast.Node) bool { |
| + call, ok := n.(*ast.CallExpr) |
| + if !ok { |
| + return true |
| + } |
| + sel, ok := call.Fun.(*ast.SelectorExpr) |
| + if !ok { |
| + return true |
| + } |
| + switch sel.Sel.Name { |
| + case "Send": |
| + if billingSourceFile(name) || strings.HasSuffix(exprText(sel.X), "Provider") { |
| + sends = append(sends, call.Pos()) |
| + } |
| + case "requireBillingReady": |
| + if ready == token.NoPos { |
| + ready = call.Pos() |
| + } |
| + } |
| + return true |
| + }) |
| + pos := fset.Position(fd.Pos()).String() |
| + if fd.Name.Name == "sendPreparedLocked" { |
| + gates++ |
| + if len(sends) != 1 || ready == token.NoPos || ready > sends[0] { |
| + findings = append(findings, pos+": sendPreparedLocked must call requireBillingReady before its one Send") |
| + } |
| + continue |
| + } |
| + for _, p := range sends { |
| + findings = append(findings, fset.Position(p).String()+": "+fd.Name.Name+" sends to the provider outside sendPreparedLocked") |
| + } |
| + } |
| + } |
| + sort.Strings(findings) |
| + return findings, gates |
| +} |
| + |
| +// TestProviderWritesOnlyThroughTheReadyGate is the readiness guard's |
| +// structural half; the WhileNotReady tests in billingready_test.go are its |
| +// behaviour. |
| +func TestProviderWritesOnlyThroughTheReadyGate(t *testing.T) { |
| + fset, files := parsePackageSources(t) |
| + findings, gates := providerWriteFindings(fset, files) |
| + for _, f := range findings { |
| + t.Error(f) |
| + } |
| + if gates != 1 { |
| + t.Fatalf("sendPreparedLocked: found %d, want 1", gates) |
| + } |
| + for _, c := range []struct{ name, file, src string }{ |
| + {"a billing-file Send", "billingplanted.go", `func (s *Server) direct(p int) { s.billing.cfg.Provider.Send(nil, p) }`}, |
| + {"a provider Send elsewhere", "planted.go", `func (s *Server) elsewhere(p int) { cfg.Provider.Send(nil, p) }`}, |
| + {"a gate that does not ask", "billingplanted.go", `func (s *Server) sendPreparedLocked(h billingHold, p int) { s.billing.cfg.Provider.Send(nil, p) }`}, |
| + {"a gate that asks too late", "billingplanted.go", `func (s *Server) sendPreparedLocked(h billingHold, p int) { s.billing.cfg.Provider.Send(nil, p); s.requireBillingReady() }`}, |
| + } { |
| + if got, _ := providerWriteFindings(fset, parsePlanted(t, fset, c.file, c.src)); len(got) != 1 { |
| + t.Errorf("%s: findings = %v, want one", c.name, got) |
| + } |
| + } |
| + ok := parsePlanted(t, fset, "billingplanted.go", ` |
| +func (s *Server) sendPreparedLocked(h billingHold, p int) { if err := s.requireBillingReady(); err != nil { return }; s.billing.cfg.Provider.Send(nil, p) } |
| +`) |
| + ok["delivery.go"] = parsePlanted(t, fset, "delivery.go", `func (s *Server) mail() { s.consoleMail.Send(nil, "", "", "") }`)["delivery.go"] |
| + if got, n := providerWriteFindings(fset, ok); len(got) != 0 || n != 1 { |
| + t.Errorf("a well-formed gate and a mailer's Send: findings %v gates %d", got, n) |
| + } |
| +} |
| + |
| +// TestSeatChargeTargetIsTheOnlyQuantityPlanInSeats: the seat code computes a |
| +// join's restore and charge only through seatJoinTarget, which refuses a |
| +// charge for uncovered members (plans 6b branch review, Invariant 2, Call |
| +// 11), so no second calculation in billingseats.go can charge past consent. |
| +func TestSeatChargeTargetIsTheOnlyQuantityPlanInSeats(t *testing.T) { |
| + _, files := parsePackageSources(t) |
| + f, ok := files["billingseats.go"] |
| + if !ok { |
| + t.Fatal("billingseats.go not parsed") |
| + } |
| + var callers []string |
| + for _, d := range f.Decls { |
| + fd, ok := d.(*ast.FuncDecl) |
| + if !ok || fd.Body == nil { |
| + continue |
| + } |
| + ast.Inspect(fd.Body, func(n ast.Node) bool { |
| + if call, ok := n.(*ast.CallExpr); ok { |
| + if id, ok := call.Fun.(*ast.Ident); ok && id.Name == "quantityPlan" { |
| + callers = append(callers, fd.Name.Name) |
| + } |
| + } |
| + return true |
| + }) |
| + } |
| + if !slices.Equal(callers, []string{"seatJoinTarget"}) { |
| + t.Fatalf("quantityPlan callers in billingseats.go = %v, want [seatJoinTarget]", callers) |
| + } |
| +} |
diff --git a/internal/console/billingops.go b/internal/console/billingops.go| index e2ff43631..98525c99b 100644 |
| --- a/internal/console/billingops.go |
| +++ b/internal/console/billingops.go |
| @@ -519,7 +519,9 @@ func (s *Server) recordSendOutcome(op *billingOp, res billing.Result, err error, |
| } |
| // sendOpLocked writes the operation (sending, with its prepared request and |
| -// FirstSentAt from the request's provider time) and sends it. An unknown |
| +// FirstSentAt from the request's provider time) and sends it through |
| +// sendPreparedLocked. While billing is not ready nothing is written or sent |
| +// (errBillingNotReady). An unknown |
| // delivery is retried up to handlerRetries times, each after a backoff and a |
| // read of the subscription, which settles on positive evidence; the same |
| // bytes are resent only while recoveryEligible. The outcome is recorded as |
| @@ -532,7 +534,9 @@ func (s *Server) recordSendOutcome(op *billingOp, res billing.Result, err error, |
| // sendOpLocked is the only writer of an operation |
| // (TestBeginBillingOpOnlyFromSend), so no caller can skip that. |
| func (s *Server) sendOpLocked(h billingHold, ctx context.Context, op billingOp, now time.Time) (opOutcome, *billing.Subscription, error) { |
| - _ = h |
| + if err := s.requireBillingReady(); err != nil { |
| + return opOutcome{}, nil, err // before the row: nothing stored that cannot be sent |
| + } |
| if len(op.Target.Quantities) > 0 && op.StartQuantity == nil { |
| return opOutcome{}, nil, errStartUnknown |
| } |
| @@ -549,7 +553,7 @@ func (s *Server) sendOpLocked(h billingHold, ctx context.Context, op billingOp, |
| return opOutcome{}, nil, err |
| } |
| for attempt := 0; ; attempt++ { |
| - res, err := cfg.Provider.Send(ctx, op.Prepared) |
| + res, err := s.sendPreparedLocked(h, ctx, op.Prepared) |
| if !retryableSend(err) || attempt == handlerRetries { |
| return s.recordSendOutcome(&op, res, err, now) |
| } |
| @@ -581,7 +585,8 @@ func (s *Server) sendOpLocked(h billingHold, ctx context.Context, op billingOp, |
| // finishOpLocked is a user's request finishing an operation left sending or |
| // unresolved: an orphaned sending row is adopted as unresolved, the |
| // subscription is read and applied, the read settles on positive evidence, |
| -// and otherwise the same bytes are sent once more while recoveryEligible. |
| +// and otherwise the same bytes are sent once more while recoveryEligible |
| +// and billing is ready (errBillingNotReady, with nothing sent, when not). |
| // It runs only inside an owner's or invitee's request (Invariant 5). |
| func (s *Server) finishOpLocked(h billingHold, ctx context.Context, acct *Account, op *billingOp, now time.Time) (opOutcome, error) { |
| if op.State != opSending && op.State != opUnresolved { |
| @@ -636,10 +641,13 @@ func (s *Server) finishOpLocked(h billingHold, ctx context.Context, acct *Accoun |
| log.Printf("console: billing: operation %s: not resent (%s)", op.ID, reason) |
| return opOutcome{State: opUnresolved, Indeterminate: op.Indeterminate}, nil |
| } |
| + if err := s.requireBillingReady(); err != nil { |
| + return opOutcome{State: opUnresolved, Indeterminate: op.Indeterminate}, err |
| + } |
| if err := s.store.NoteOpSent(op.ID, pnow); err != nil { |
| return opOutcome{}, err |
| } |
| - res, err := cfg.Provider.Send(ctx, op.Prepared) |
| + res, err := s.sendPreparedLocked(h, ctx, op.Prepared) |
| out, _, err := s.recordSendOutcome(op, res, err, now) |
| return out, err |
| } |
diff --git a/internal/console/billingready_test.go b/internal/console/billingready_test.go| new file mode 100644 |
| index 000000000..e4e4abe30 |
| --- /dev/null |
| +++ b/internal/console/billingready_test.go |
| @@ -0,0 +1,239 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "net/http" |
| + "net/url" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// No billing write while billing isn't ready (plans 6b branch review, P1; |
| +// 6a's readiness). Readiness has failed, so the provider's prices may not be |
| +// what the configured book says; subscriptions stay readable and the Fake |
| +// would accept every write. Nothing reaches the provider's Send, no seat |
| +// authorisation is recorded against the unverified price, and deletion is |
| +// refused. Reads, and a join that needs no write, still go through. |
| + |
| +// notReady marks billing not ready on the fixture's server and resets the |
| +// counters. |
| +func (o *opsFixture) notReady() { |
| + o.srv.billing.ready.Store(false) |
| + o.reset() |
| +} |
| + |
| +func (o *opsFixture) wantNoSend(t *testing.T) { |
| + t.Helper() |
| + if c := o.counts(); c["Send"] != 0 { |
| + t.Fatalf("counts %v: a provider write while billing isn't ready", c) |
| + } |
| + if n := len(o.sent()); n != 0 { |
| + t.Fatalf("%d prepared requests sent while billing isn't ready", n) |
| + } |
| +} |
| + |
| +func TestInviteRecordsNoSeatAuthorisationWhileNotReady(t *testing.T) { |
| + o := newSeatsFixture(t, 10, 10) |
| + o.stepUp(t) |
| + o.notReady() |
| + for _, confirmed := range []bool{false, true} { |
| + form := url.Values{"address": {"new@example.com"}} |
| + if confirmed { |
| + form.Set("confirmed", "1") |
| + } |
| + r := o.request(t, http.MethodPost, o.teamPath("/invite"), form) |
| + if r.Status != http.StatusSeeOther || r.Flash != "err" || r.FlashMsg != billingCopy["notice.not_ready"] { |
| + t.Fatalf("confirmed=%v: invite = %d %q flash %s:%q, want the not-ready refusal", confirmed, r.Status, r.Loc, r.Flash, r.FlashMsg) |
| + } |
| + if inv, _ := o.st.PendingInvites(o.acct.ID); len(inv) != 0 { |
| + t.Fatalf("confirmed=%v: an invite needing a paid seat was created while billing isn't ready: %+v", confirmed, inv) |
| + } |
| + } |
| + o.wantNoSend(t) |
| + // An invite that needs no new seat is not billing's business. |
| + o.srv.billing.ready.Store(true) |
| + o.setSeats(t, 12) |
| + o.notReady() |
| + if r := o.request(t, http.MethodPost, o.teamPath("/invite"), url.Values{"address": {"spare@example.com"}}); r.Status != http.StatusSeeOther || r.Loc != o.teamPath("/team") { |
| + t.Fatalf("spare-seat invite = %+v", r) |
| + } |
| +} |
| + |
| +func TestJoinNeedingAChargeSendsNothingWhileNotReady(t *testing.T) { |
| + o := newSeatsFixture(t, 10, 10) |
| + in := o.invitee(t, "kim@example.com") |
| + tok := o.authorisedInvite(t, in.addr) |
| + o.notReady() |
| + wantAdmit(t, o.accept(in, tok), "seats.join_uncertain") |
| + o.wantNoSend(t) |
| + if o.members(t) != 10 || o.seatQty(t) != 10 || len(o.ops(t)) != 0 || !o.pendingInvite(t, tok) { |
| + t.Fatalf("members %d seats %d ops %d pending %v", o.members(t), o.seatQty(t), len(o.ops(t)), o.pendingInvite(t, tok)) |
| + } |
| + if a := o.authorisation(t, tok); a == nil || !a.ConsumedAt.IsZero() { |
| + t.Fatalf("authorisation = %+v, want unspent", a) |
| + } |
| + // Once ready, the same accept charges and joins. |
| + o.srv.billing.ready.Store(true) |
| + o.wantJoined(t, o.accept(in, tok)) |
| +} |
| + |
| +func TestFreeJoinGoesThroughWhileNotReady(t *testing.T) { |
| + o := newSeatsFixture(t, 10, 11) |
| + in := o.invitee(t, "kim@example.com") |
| + tok := o.plainInvite(t, in.addr) |
| + o.notReady() |
| + o.wantJoined(t, o.accept(in, tok)) |
| + o.wantNoSend(t) |
| + if o.members(t) != 11 { |
| + t.Fatalf("members %d", o.members(t)) |
| + } |
| +} |
| + |
| +func TestRecoveryResendsNothingWhileNotReady(t *testing.T) { |
| + o := newSeatsFixture(t, 10, 10) |
| + in := o.invitee(t, "kim@example.com") |
| + o.unresolvedSeat(t, in) |
| + opID := o.lastOp(t).ID |
| + o.notReady() |
| + // Confirm now. |
| + if status, _ := o.confirm(t); status != http.StatusSeeOther { |
| + t.Fatalf("confirm = %d", status) |
| + } |
| + o.wantNoSend(t) |
| + // finishOpLocked itself, as admission, removal, Match seats and the |
| + // retirement gate reach it. |
| + o.fresh() |
| + if _, err := o.finish(t, opID); !errors.Is(err, errBillingNotReady) { |
| + t.Fatalf("finish = %v, want errBillingNotReady", err) |
| + } |
| + o.wantNoSend(t) |
| + if op := o.op(t, opID); op.State != opUnresolved { |
| + t.Fatalf("op = %+v, want still unresolved", op) |
| + } |
| +} |
| + |
| +func TestMatchSeatsSendsNothingWhileNotReady(t *testing.T) { |
| + o := newSeatsFixture(t, 10, 13) |
| + o.notReady() |
| + o.request(t, http.MethodPost, o.billingBase()+"/seats", nil) |
| + o.wantNoSend(t) |
| + // The reduction itself, as a removal reaches it. |
| + o.fresh() |
| + h, release := o.hold() |
| + _, err := o.srv.reconcileSeatsLocked(h, o.ctx, o.acct, 10, time.Now()) |
| + release() |
| + if !errors.Is(err, errBillingNotReady) { |
| + t.Fatalf("reconcile = %v, want errBillingNotReady", err) |
| + } |
| + o.wantNoSend(t) |
| + if o.seatQty(t) != 13 || len(o.ops(t)) != 0 { |
| + t.Fatalf("seats %d ops %d", o.seatQty(t), len(o.ops(t))) |
| + } |
| +} |
| + |
| +func TestRemovalWhileNotReadyRemovesAndSendsNothing(t *testing.T) { |
| + o := newSeatsFixture(t, 11, 11) |
| + o.notReady() |
| + if r := o.removeMember(t, "m100@example.com"); r.Status != http.StatusSeeOther || r.Flash != "ok" { |
| + t.Fatalf("remove = %+v", r) |
| + } |
| + o.wantNoSend(t) |
| + if o.members(t) != 10 || o.seatQty(t) != 11 || len(o.ops(t)) != 0 { |
| + t.Fatalf("members %d seats %d ops %d", o.members(t), o.seatQty(t), len(o.ops(t))) |
| + } |
| + // Once ready, the pass marks the drift, so the page offers Match seats. |
| + o.srv.billing.ready.Store(true) |
| + o.pass(time.Now()) |
| + if b := o.billingRow(t); b.SeatDriftAt.IsZero() || b.SeatDriftMembers != 10 { |
| + t.Fatalf("drift not recorded after the skipped reduction: %+v", b) |
| + } |
| +} |
| + |
| +func TestDeleteRefusedWhileNotReady(t *testing.T) { |
| + o := newDeleteFixture(t, nil, false) |
| + o.stepUp(t) |
| + o.notReady() |
| + o.wantDeleteRefused(t, o.deleteAccount(t), billingCopy["delete.unverified"]) |
| + o.wantNoSend(t) |
| + // Ready again, the same deletion goes through. |
| + o.srv.billing.ready.Store(true) |
| + o.stepUp(t) |
| + r := o.deleteAccount(t) |
| + o.wantDeleted(t, r.Status, r.FlashMsg) |
| +} |
| + |
| +// TestCheckoutSendersSendNothingWhileNotReady: the customer create, the |
| +// Checkout create and the expiry refuse before anything is stored or sent. |
| +func TestCheckoutSendersSendNothingWhileNotReady(t *testing.T) { |
| + t.Run("customer", func(t *testing.T) { |
| + o := newCheckoutFixture(t, false) |
| + o.notReady() |
| + o.fresh() |
| + o.observe() |
| + h, release := o.hold() |
| + _, err := o.srv.ensureCustomerLocked(h, o.ctx, o.acct, billingNow) |
| + release() |
| + if !errors.Is(err, errBillingNotReady) { |
| + t.Fatalf("customer = %v, want errBillingNotReady", err) |
| + } |
| + o.wantNoSend(t) |
| + if b, _ := o.st.BillingAccount(o.acct.ID); b != nil && b.CustomerPrepared != nil { |
| + t.Fatalf("a customer create was stored while billing isn't ready: %+v", b) |
| + } |
| + }) |
| + t.Run("create", func(t *testing.T) { |
| + o := newCheckoutFixture(t, true) |
| + o.notReady() |
| + o.fresh() |
| + o.observe() |
| + ci := &checkoutIntent{ID: "ci_ready", Book: o.srv.billing.cfg.Book.Version, Plan: "personal", Currency: "usd"} |
| + h, release := o.hold() |
| + err := o.srv.createSessionLocked(h, o.ctx, o.acct, ci, billingNow) |
| + release() |
| + if !errors.Is(err, errBillingNotReady) { |
| + t.Fatalf("create = %v, want errBillingNotReady", err) |
| + } |
| + o.wantNoSend(t) |
| + if got := o.intent(t); got != nil { |
| + t.Fatalf("an intent was stored while billing isn't ready: %+v", got) |
| + } |
| + }) |
| + t.Run("expiry", func(t *testing.T) { |
| + o := newCheckoutFixture(t, true) |
| + wantSession(t, o.checkout(t, "plan", "personal", "currency", "usd")) |
| + o.notReady() |
| + o.fresh() |
| + o.observe() |
| + ci := o.intent(t) |
| + h, release := o.hold() |
| + err := o.srv.expireIntentLocked(h, o.ctx, o.acct, ci, billingNow) |
| + release() |
| + if !errors.Is(err, errBillingNotReady) { |
| + t.Fatalf("expiry = %v, want errBillingNotReady", err) |
| + } |
| + o.wantNoSend(t) |
| + if got := o.intent(t); got.ExpirePrepared != nil || got.State != intentOpen { |
| + t.Fatalf("intent = %+v, want open with no expiry stored", got) |
| + } |
| + }) |
| + t.Run("the gate itself", func(t *testing.T) { |
| + o := newCheckoutFixture(t, true) |
| + o.notReady() |
| + p, err := o.fake.PrepareRenewal("sub_x", true, "op:x") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + h, release := o.hold() |
| + _, err = o.srv.sendPreparedLocked(h, context.Background(), p) |
| + release() |
| + if !errors.Is(err, errBillingNotReady) { |
| + t.Fatalf("sendPreparedLocked = %v, want errBillingNotReady", err) |
| + } |
| + o.wantNoSend(t) |
| + var ref billingRefusal |
| + if !errors.As(err, &ref) || billingCopy[ref.Key] == "" { |
| + t.Fatalf("the refusal %v has no copy", err) |
| + } |
| + }) |
| +} |
diff --git a/internal/console/billingretire.go b/internal/console/billingretire.go| index 0ccaa2e7c..9302bd66c 100644 |
| --- a/internal/console/billingretire.go |
| +++ b/internal/console/billingretire.go |
| @@ -59,9 +59,10 @@ func (s *Store) OutstandingOpsForAccount(accountID int64) ([]billingOp, error) { |
| } |
| // retireGateLocked decides, under the hold, whether the account may be |
| -// deleted. The order is load-bearing: the only provider writes are steps 1 |
| -// and 2, and step 3 always runs after them, so what is judged is what those |
| -// writes left. |
| +// deleted. While billing is not ready it makes no request and refuses |
| +// (delete.unverified). The order is load-bearing: the only provider writes |
| +// are steps 1 and 2, and step 3 always runs after them, so what is judged is |
| +// what those writes left. |
| // |
| // 1. Outstanding work is finished: every operation left sending or |
| // unresolved gets finishOpLocked (a read, and at most one resend of its |
| @@ -78,6 +79,11 @@ func (s *Store) OutstandingOpsForAccount(accountID int64) ([]billingOp, error) { |
| // to end at its period end (delete.renewing) with nothing being |
| // collected and no change waiting for payment (delete.collecting). |
| func (s *Server) retireGateLocked(h billingHold, ctx context.Context, acct *Account, now time.Time) error { |
| + // Not ready: the gate can neither finish work at the provider nor trust |
| + // what it would judge, so nothing is checked and deletion is refused. |
| + if err := s.requireBillingReady(); err != nil { |
| + return errDeleteUnverified |
| + } |
| // 1. Outstanding work. |
| ops, err := s.store.OutstandingOpsForAccount(acct.ID) |
| if err != nil { |
diff --git a/internal/console/billingseats.go b/internal/console/billingseats.go| index 085c6f26b..5e00acc53 100644 |
| --- a/internal/console/billingseats.go |
| +++ b/internal/console/billingseats.go |
| @@ -250,16 +250,22 @@ func (s *Server) admitMember(ctx context.Context, acct *Account, token, addr str |
| // pending one refreshed); still outstanding is admitWaitPayment for this |
| // invite's pending or declined seat, admitUncertain for this invite's seat |
| // with no answer yet, and admitOutstanding for anything else; then the |
| -// allowance read, and capacity: need is the billed seats with one more |
| -// member, cur the plan item's quantity, paid the period's paid seats. |
| +// allowance read, and capacity from seatJoinTarget: need is the billed |
| +// seats with one more member, cur the plan item's quantity, paid the |
| +// period's paid seats. |
| // |
| // - need <= cur: free, no write (a seat an earlier charge left, even inside |
| // the renewal margin); |
| +// - members already billed above max(cur, paid) (an operator's add): |
| +// seats_unpaid opens and admitNeedsConsent, nothing charged (Call 11); |
| // - cur < need <= paid: a restore to need, only outside the margin; |
| // - need > paid: covered by the invite's authorisation or admitNeedsConsent; |
| // then a restore to paid if paid > cur (margin rules), and the charge to |
| // need only after a definite restore applied in the same period. |
| // |
| +// No write while billing is not ready: sendOpLocked refuses it, which is |
| +// admitUncertain (a free join still goes through). |
| +// |
| // An open problem refuses before anything is prepared. After a send the |
| // membership is written, then the subscription refreshed; then the seat |
| // observation runs on members+1, never reducing. |
| @@ -289,14 +295,27 @@ func (s *Server) admitSeatLocked(h billingHold, ctx context.Context, acct *Accou |
| if err != nil { |
| return admitUncertain, err |
| } |
| - need, cur, paid := int64(team.Billed(members+1)), item.Quantity, int64(b.PaidSeats) |
| - if need <= cur { |
| + cur, paid := item.Quantity, int64(b.PaidSeats) |
| + restoreTo, chargeTo, err := seatJoinTarget(team, members, cur, paid) |
| + if errors.Is(err, errSeatsUncovered) { |
| + // Members nobody paid for are already here (an operator's add, Call |
| + // 11): this invite's consent covers one seat, not theirs. Nothing is |
| + // charged; the owners see seats_unpaid now, not at the next pass. |
| + if err := s.openBillingProblem(acct.ID, acct.Sqid, b.Subscription, problemSeatsUnpaid, |
| + fmt.Sprintf("%d members, %d paid seats", members, b.PaidSeats), now); err != nil { |
| + return admitUncertain, err |
| + } |
| + return admitNeedsConsent, nil |
| + } |
| + if err != nil { |
| + return admitUncertain, err |
| + } |
| + if restoreTo == 0 && chargeTo == 0 { |
| if err := join(); err != nil { |
| return admitUncertain, err |
| } |
| return admitJoined, s.observeSeatsLocked(h, acct, members+1, false, now) |
| } |
| - restoreTo, chargeTo := quantityPlan(cur, need, paid) |
| if chargeTo > 0 { |
| a, err := s.store.InviteSeatAuthorisation(token) |
| if err != nil { |
| @@ -353,6 +372,32 @@ func (s *Server) admitSeatLocked(h billingHold, ctx context.Context, acct *Accou |
| return admitUncertain, nil |
| } |
| +// errSeatsUncovered is a join whose members before it are already billed |
| +// above the seats paid for: one invite's consent cannot cover them. |
| +var errSeatsUncovered = errors.New("console: seats: members before the join exceed the paid seats") |
| + |
| +// seatJoinTarget is the one decision of what a join changes on the plan |
| +// item (Invariant 2, Call 11; plans 6b branch review), given members before |
| +// the join, cur the item's quantity and paid the period's paid seats. A join |
| +// that needs no seat beyond cur plans nothing. When the members before the |
| +// join are already billed above max(cur, paid), it refuses with |
| +// errSeatsUncovered and plans nothing: a seat authorisation is consent to |
| +// one seat, never to members nobody paid for. Otherwise it is quantityPlan's |
| +// restore and charge to the billed seats with one more member, so a charge |
| +// raises the paid seats by at most one over max(cur, paid) |
| +// (TestSeatJoinTargetChargesAtMostOneCoveredSeat). |
| +func seatJoinTarget(team *plans.Team, members int, cur, paid int64) (restoreTo, chargeTo int64, err error) { |
| + need := int64(team.Billed(members + 1)) |
| + if need <= cur { |
| + return 0, 0, nil |
| + } |
| + if int64(team.Billed(members)) > max(cur, paid) { |
| + return 0, 0, errSeatsUncovered |
| + } |
| + restoreTo, chargeTo = quantityPlan(cur, need, paid) |
| + return restoreTo, chargeTo, nil |
| +} |
| + |
| // finishSeatOpsLocked finishes the operation outstanding on the account's |
| // subscription, if any, and answers admitJoined when nothing is outstanding |
| // afterwards (admission goes on), or the outcome that refuses it. A failed |
| @@ -576,7 +621,9 @@ type seatQuote struct { |
| // item's quantity and the period's paid seats, the invite needs a new paid |
| // seat. Unconfirmed, that is a quote; confirmed (after a fresh sign-in |
| // proof), the seat authorisation to record: the subscription's plan, book, |
| -// currency and per-seat price now. No seat needed is neither. |
| +// currency and per-seat price now. No seat needed is neither. A new paid |
| +// seat while billing is not ready is refused (notice.not_ready): neither a |
| +// quote nor an authorisation. |
| func (s *Server) inviteSeatLocked(h billingHold, ctx context.Context, acct *Account, pending int, to, by string, confirmed bool, now time.Time) (*seatQuote, *seatAuthorisation, error) { |
| if retiring, err := s.store.BillingRetiring(acct.ID, now); err != nil { |
| return nil, nil, err |
| @@ -600,6 +647,11 @@ func (s *Server) inviteSeatLocked(h billingHold, ctx context.Context, acct *Acco |
| if int64(team.Billed(members+pending+1)) <= max(item.Quantity, int64(b.PaidSeats)) { |
| return nil, nil, nil |
| } |
| + // The quote and the authorisation name the configured price, which only |
| + // a passed readiness check has matched with the provider's. |
| + if err := s.requireBillingReady(); err != nil { |
| + return nil, nil, err |
| + } |
| if err := s.refuseOnProblemLocked(h, acct); err != nil { |
| return nil, nil, err |
| } |
diff --git a/internal/console/billingseats_test.go b/internal/console/billingseats_test.go| index a284cbd61..d91389050 100644 |
| --- a/internal/console/billingseats_test.go |
| +++ b/internal/console/billingseats_test.go |
| @@ -2,6 +2,7 @@ package console |
| import ( |
| "context" |
| + "errors" |
| "fmt" |
| "html" |
| "net/http" |
| @@ -1073,3 +1074,94 @@ func TestSeatCovered(t *testing.T) { |
| t.Error("an authorisation off the configured book covered a seat") |
| } |
| } |
| + |
| +// ---- consent quantity (plans 6b branch review, P1) ------------------------------ |
| + |
| +// operatorAdds adds a member the way the console CLI does (cmd/console |
| +// member add): a membership transition with no billing step. Call 11: such a |
| +// member is never charged. |
| +func (o *opsFixture) operatorAdds(t *testing.T, addr string) { |
| + t.Helper() |
| + old, err := o.st.AccountPlan(o.acct.ID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := o.st.MembershipTransition(o.acct.ID, o.srv.cfg.PlanCatalog, old, AddMemberWrite(o.acct.ID, addr, RoleMember, time.Now()), time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// TestJoinNeverChargesForUncoveredMembers is the review's scenario: ten |
| +// members and ten paid seats, one authorised invite, then an operator adds a |
| +// member, then the invitee accepts before any pass has run. One |
| +// authorisation must not pay for two seats: nothing is charged, seats_unpaid |
| +// opens in the same request, and the invitee is told an owner must act. |
| +func TestJoinNeverChargesForUncoveredMembers(t *testing.T) { |
| + o := newSeatsFixture(t, 10, 10) |
| + in := o.invitee(t, "kim@example.com") |
| + tok := o.authorisedInvite(t, in.addr) |
| + o.operatorAdds(t, "added@example.com") |
| + if o.seatsUnpaidOpen(t) { |
| + t.Fatal("seats_unpaid open before the accept: the scenario needs no pass to have run") |
| + } |
| + o.reset() |
| + wantAdmit(t, o.accept(in, tok), "seats.join_consent") |
| + if c := o.counts(); c["Send"] != 0 { |
| + t.Fatalf("counts %v: a join charged for a member nobody authorised", c) |
| + } |
| + if !o.seatsUnpaidOpen(t) { |
| + t.Fatalf("problems = %v, want seats_unpaid opened by the accept", o.openProblems(t)) |
| + } |
| + if o.members(t) != 11 || o.seatQty(t) != 10 || len(o.ops(t)) != 0 || !o.pendingInvite(t, tok) { |
| + t.Fatalf("members %d seats %d ops %d pending %v", o.members(t), o.seatQty(t), len(o.ops(t)), o.pendingInvite(t, tok)) |
| + } |
| + if a := o.authorisation(t, tok); a == nil || !a.ConsumedAt.IsZero() { |
| + t.Fatalf("authorisation = %+v, want unspent", a) |
| + } |
| +} |
| + |
| +// TestSeatJoinTargetChargesAtMostOneCoveredSeat is the guard on the one |
| +// function that decides a join's seat change: a charge raises the paid seats |
| +// by at most one over max(cur, paid), and only when the members before the |
| +// join are covered (billed at or below max(cur, paid)); otherwise it refuses |
| +// with errSeatsUncovered and plans nothing. |
| +func TestSeatJoinTargetChargesAtMostOneCoveredSeat(t *testing.T) { |
| + for _, minMembers := range []int{1, 3, 10} { |
| + team := &plans.Team{MinMembers: minMembers} |
| + for members := 0; members <= 16; members++ { |
| + for cur := int64(0); cur <= 16; cur++ { |
| + for paid := int64(0); paid <= 16; paid++ { |
| + restoreTo, chargeTo, err := seatJoinTarget(team, members, cur, paid) |
| + capacity := max(cur, paid) |
| + need := int64(team.Billed(members + 1)) |
| + covered := int64(team.Billed(members)) <= capacity |
| + name := fmt.Sprintf("min %d members %d cur %d paid %d", minMembers, members, cur, paid) |
| + switch { |
| + case need <= cur: |
| + if err != nil || restoreTo != 0 || chargeTo != 0 { |
| + t.Fatalf("%s: free join = %d %d %v, want nothing", name, restoreTo, chargeTo, err) |
| + } |
| + case !covered: |
| + if !errors.Is(err, errSeatsUncovered) || restoreTo != 0 || chargeTo != 0 { |
| + t.Fatalf("%s: uncovered members = %d %d %v, want errSeatsUncovered and nothing", name, restoreTo, chargeTo, err) |
| + } |
| + default: |
| + wr, wc := quantityPlan(cur, need, paid) |
| + if err != nil || restoreTo != wr || chargeTo != wc { |
| + t.Fatalf("%s: = %d %d %v, want %d %d", name, restoreTo, chargeTo, err, wr, wc) |
| + } |
| + } |
| + if chargeTo > capacity+1 { |
| + t.Fatalf("%s: charge to %d, more than one seat over %d", name, chargeTo, capacity) |
| + } |
| + if chargeTo > 0 && !covered { |
| + t.Fatalf("%s: a charge with uncovered members", name) |
| + } |
| + if restoreTo > paid { |
| + t.Fatalf("%s: restore to %d above the paid %d", name, restoreTo, paid) |
| + } |
| + } |
| + } |
| + } |
| + } |
| +} |