carlos / platform Public

plans 6a: Astra fix pass. Operator billing doors join the empty-role allowlist (CI); a replacement subscription re-reads the recorded one before refusing it; billing state and plan change commit together; bounded discovery finds a missed first purchase; a vanished subscription opens a problem whose close ends it; unpaid blocks problem closure; request budget restated. Finding 5 deferred to after Plan 4d-1 merges

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 03428600dc5610adf2f91408e29a57e071fea641 parent 7826d2e
17 files changed, +718 −53
  • docs/site/plans.md +2 −1
  • docs/superpowers/plans/2026-10-25-plans-6a-checkout.md +8 −1
  • docs/superpowers/specs/CODEX-FINDINGS-PLANS-6A-CODE.md +123 −0
  • internal/billing/billing.go +17 −4
  • internal/billing/billingtest/fake.go +30 −0
  • internal/billingstripe/adapter.go +27 −0
  • internal/billingstripe/adapter_test.go +40 −1
  • internal/billingstripe/client.go +26 −0
  • internal/console/accountplans.go +15 −4
  • internal/console/apibilling.go +10 −2
  • internal/console/apibilling_test.go +22 −0
  • internal/console/billingpass.go +38 −0
  • internal/console/billingrecovery_test.go +172 −0
  • internal/console/billingstore.go +83 −11
  • internal/console/billingsync.go +88 −26
  • internal/console/billingsync_test.go +10 −1
  • internal/console/svcroutes_test.go +7 −2
diff --git a/docs/site/plans.md b/docs/site/plans.md
index a6403de15..8a90ce2a9 100644
--- a/docs/site/plans.md
+++ b/docs/site/plans.md
@@ -135,7 +135,7 @@ carlos billing problems -all # closed ones too
carlos billing close -id 12 -note "refunded and cancelled in the dashboard"
```
-The console can't close a problem while Stripe still shows the subscription as live, and it can't see refunds, so your note is the record of what you did.
+The console can't close a problem while Stripe can still charge the subscription, an unpaid one included, and it can't see refunds, so your note is the record of what you did.
| Reason | What it means | What to do in Stripe |
| --- | --- | --- |
@@ -145,3 +145,4 @@ The console can't close a problem while Stripe still shows the subscription as l
| `unknown_customer` | A subscription on a Stripe customer the console never created. | Find out where it came from, then refund and cancel. |
| `account_mismatch` | The subscription's metadata names a different account from its customer's. | Check both accounts, then refund and cancel. |
| `mode_mismatch` | A test-mode subscription reached a live console, or the other way round. | Check the webhook endpoints in each mode. |
+| `subscription_missing` | Stripe has no record of the account's current subscription. The account keeps its paid limits while the problem is open. | Find out what happened to it. Closing the problem while Stripe still has no such subscription ends it in the console and moves the account to the default plan. |
diff --git a/docs/superpowers/plans/2026-10-25-plans-6a-checkout.md b/docs/superpowers/plans/2026-10-25-plans-6a-checkout.md
index 1498e7bcc..a8b12c9f3 100644
--- a/docs/superpowers/plans/2026-10-25-plans-6a-checkout.md
+++ b/docs/superpowers/plans/2026-10-25-plans-6a-checkout.md
@@ -91,7 +91,10 @@ Each has a recommendation. Decisions 1 to 8 and 15 are the old `DECISIONS-FOR-PA
It publishes through the operator door's best-effort `publishPlanNow`. The limits pass retries anything that misses.
- **One console serves billing.** The per-account lock is in-process: the console runs as one process per deployment.
- **Request budget.**
- - Stripe: one `GET /v1/subscriptions/{id}` per event and per live subscription per hourly pass, plus at most 16 reads (prices, products, account) per readiness check.
+ - Stripe, as built (Astra finding 7 reconciled, 2026-10-25):
+ - per sync (an event, or one live subscription in the hourly pass): two `GET /v1/subscriptions/{id}`, one to learn the customer and one fresh read under the account's lock, plus a third only when another subscription of the account is recorded as live (finding 1);
+ - per hourly pass, additionally one `GET /v1/subscriptions?customer=…&status=all&limit=10` for each customer bound in the last seven days with no subscription recorded (finding 3), then a sync per subscription it names;
+ - per readiness check, until it passes: one account read, one read per price in the book (18 with the example book) and one per distinct product (6), so 25 for the example book: at most 1 + 2 × the price count.
- S3: nothing new. A plan change is the existing single limits-record PUT.
- **No product name** in code, tests, copy or example data. Examples use neutral names (shop, example.com).
- **Names:** no helper or type name containing `Record` (the record-write census matches on it).
@@ -687,6 +690,10 @@ Plan 7 (the pricing page, written in parallel) builds the slim book as its Task
- [ ] **Cross-compile:** run `GOOS=darwin go build ./...` and `GOOS=windows go build ./...`. Nothing here is Linux-only.
- [ ] **Finish:** merge main, push, wait for green CI, then Astra's whole-branch review.
+## Astra review (2026-10-25, at 7826d2e0)
+
+Findings in `docs/superpowers/specs/CODEX-FINDINGS-PLANS-6A-CODE.md`. Fixed in one pass: 1, 2, 3, 4, 6, 7 and the CI failure (the operator billing doors join the empty-role allowlist). Finding 5, routing billing's plan change through Plan 4d-1's `applyAccountPlan` with a transaction-aware ownership guard: deferred to after 4d-1 merges: billing activation is blocked until then.
+
## Done when
- Every task's tests pass, and Review Focus 1 to 5 are pinned.
diff --git a/docs/superpowers/specs/CODEX-FINDINGS-PLANS-6A-CODE.md b/docs/superpowers/specs/CODEX-FINDINGS-PLANS-6A-CODE.md
new file mode 100644
index 000000000..cb42a92d4
--- /dev/null
+++ b/docs/superpowers/specs/CODEX-FINDINGS-PLANS-6A-CODE.md
@@ -0,0 +1,123 @@
+**Verdict: changes required** at `7826d2e04b64d3ab8dd81cc36ebbc7a4333bcce2`, reviewed against `c743efeafef23567c9e2c37d29d351043690e1e4`.
+
+No Critical findings. Six Important findings and one Minor finding follow. These are static findings: Go tests could not start because the read-only filesystem blocked creation of Go’s build directory. No network calls or repository changes were made.
+
+1. **Important — out-of-order events can reject a valid replacement subscription.**
+ [billingsync.go:72](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingsync.go:72) treats the *stored* previous subscription state as proof that it remains live. Suppose A has ended at Stripe, but B’s successful purchase events arrive before A’s cancellation event. B is recorded as a `second_subscription` problem and acknowledged with 204. A’s later event drops the account to free. The hourly pass never revisits B, so a paying account remains free until another event or operator intervention.
+
+ Re-read the previously bound subscription under the account lock before declaring a second live subscription. Preserve retryable work for B until that comparison is settled.
+
+2. **Important — a partially completed sync can leave paid access permanently active after cancellation.**
+ [billingsync.go:196](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingsync.go:196) commits `PutBillingState` before `SetBillingPlan`. If an hourly sync records `ended` and the process crashes—or the plan write fails—the plan remains paid. [billingstore.go:210](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingstore.go:210) excludes that account from all subsequent hourly passes.
+
+ Commit billing state and the guarded plan change together, or persist outstanding reconciliation work that survives the transition to `ended`. Add a failure-between-writes regression test.
+
+3. **Important — readiness recovery cannot recover a missed first purchase.**
+ [billingstore.go:210](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingstore.go:210) requires an already recorded subscription and a paid/pending state. A bound customer starts with neither. If readiness remains unavailable until the initial webhook retries expire, the eventual successful check scans past that customer forever. The provider interface has no discovery operation to recover the subscription.
+
+ Persist purchase reconciliation work or provide bounded discovery by bound customer. The existing missed-event test covers changes to an already discovered subscription only.
+
+4. **Important — the unknown-subscription ruling leaves unpaid access without an actionable problem.**
+ [billingsync.go:141](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingsync.go:141) and its second-read equivalent return success on `ErrNotFound`, retaining paid limits and acknowledging the webhook. Hourly retries produce the same log but never open a billing problem. Thus the executor’s “until an operator acts” outcome has no entry in the operator’s billing-problem workflow and no bounded resolution.
+
+ Retaining limits while investigating an ambiguous 404 is reasonable. Silently retaining them indefinitely is not. Open a deduplicated problem for a previously bound subscription and provide an explicit resolution path.
+
+5. **Important — billing bypasses Plan 4d’s lapse transition.**
+ [accountplans.go:206](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/accountplans.go:206) shares the upsert SQL, but does not share the lifecycle operation. The local `plans-4d-lapse` branch’s `internal/console/planlapse.go:74` confirms that `applyAccountPlan` takes the lapse lock, reads the previous assignment, marks a fall, resets grace, reconverges, and publishes.
+
+ Combining the branches without integration lets a billing cancellation or pack reduction lower limits without starting the lapse lifecycle. Repayment also misses immediate reconvergence. A fall processed before integration loses the previous assignment needed to detect it later.
+
+ Dormant code can land before 4d, but billing activation needs this integration. It requires a shared server-level transition with a transaction-aware ownership guard, unchanged-write suppression, consistent lock ordering, and durable lapse bookkeeping. Calling the existing server function from inside `billingSetPlan`’s transaction is not a safe one-line swap.
+
+6. **Important — an `unpaid` subscription’s problem can be closed prematurely.**
+ [apibilling.go:136](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/apibilling.go:136) uses `liveState(sub.State)` to decide whether closure is allowed. The adapter maps `unpaid` to `StateEnded`, so closure succeeds without cancellation. Paul’s accepted Call 2 explicitly requires refusal while the subscription is `unpaid`; Call 12 separately ends its paid entitlement.
+
+ Separate settlement eligibility from entitlement state at the provider boundary. Test that `unpaid` loses paid limits but still prevents problem closure.
+
+7. **Minor — the stated provider-request budget is exceeded.**
+ [adapter.go:198](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/billingstripe/adapter.go:198) reads all 18 prices, their products, and the merchant account: ordinarily 25 requests with six shared products, exceeding the stated maximum of 16. [billingsync.go:140](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingsync.go:140) also makes two subscription reads per sync, rather than the promised one. This increases startup readiness time and ongoing provider traffic.
+
+ Reconcile the budget and implementation explicitly. Preserve the fresh read under the account lock.
+
+The five Review Focus checks are accounted for:
+
+| Focus | Assessment |
+|---|---|
+| Unchanged subscription | Plan revision, publication and throttle are preserved. Billing bookkeeping still updates `synced_at`. |
+| Sponsored/operator ownership | The transactional source guard prevents overwrites. |
+| Out-of-order events | Same-subscription updates use fresh state correctly; replacement subscriptions fail as described above. |
+| Pack reductions | Highest quantities persist within the period; reductions apply when the period changes. |
+| Startup provider outage | The console serves, webhook returns 503, and readiness retries. Recovery lacks first-purchase discovery. |
+
+The remaining requested checks look sound on inspection: billing activation is explicit and independent of hostname; off mode ignores billing configuration and writes no billing rows; live mode refuses drafts; version digests prevent edits under an existing book version; price identifiers remain outside the book and public export; the schema-2 exporter follows the documented ordering and shape. Restricted-key configuration errors omit values, client errors are sanitized, and formatted client/provider values redact secrets. Webhook verification bounds the body, verifies signatures before interpretation, supports rotation, and rejects timestamps outside tolerance. Duplicate deliveries do not repeat plan changes. The console uses the provider interface rather than importing Stripe.
+
+**Census verdicts:** approve each listed unit for its stated census disposition. These approvals concern privileged reads and authority; they do not waive the billing defects above.
+
+| Existing unit | Verdict and evidence |
+|---|---|
+| [serve, main.go:300](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/cmd/console/main.go:300) | **Approve.** Operator configuration, console-store bookkeeping and a claim worker; existing data-path literals remain unchanged. |
+| [Store.SetAccountPlan, accountplans.go:92](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/accountplans.go:92) | **Approve.** Same parameterized upsert, now shared as SQL and arguments. |
+| [NewServer, server.go:1367](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/server.go:1367) | **Approve.** Configuration validation and route/runtime wiring introduce no privileged filesystem reader. |
+| [Store.migrate, store.go:138](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/store.go:138) | **Approve.** Adds console-owned billing schema through `migrateBilling`. |
+
+For the handwritten `plans-6a-units` decision overlay:
+
+| New unit | Verdict and evidence |
+|---|---|
+| [Client.do, client.go:175](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/billingstripe/client.go:175) | **Approve.** Bounded response read; fixed production API destination; redirects refused. |
+| [Store.SetBillingPlan, accountplans.go:157](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/accountplans.go:157) | **Approve.** Console-owned SQL, transactional ownership guard and deleted-account check. |
+| [billingSetPlan, accountplans.go:206](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/accountplans.go:206) | **Approve.** Parameterized existing plan upsert within that transaction. |
+| [Server.handleAPIBillingProblems, apibilling.go:72](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/apibilling.go:72) | **Approve.** Operator gate precedes listing; `URL.Query` is not a filesystem read. |
+| [Store.BillingProblem, billingstore.go:285](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingstore.go:285) | **Approve.** Parameterized lookup in the console’s problem table. |
+| [Store.BillingProblems, billingstore.go:263](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingstore.go:263) | **Approve.** Fixed query variants over that table. |
+| [Store.CloseBillingProblem, billingstore.go:298](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingstore.go:298) | **Approve.** Parameterized update restricted to an open problem. |
+| [Store.LiveBillingAccounts, billingstore.go:208](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingstore.go:208) | **Approve.** Console-owned account/billing query. |
+| [Store.NotePriceBook, billingstore.go:34](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingstore.go:34) | **Approve.** Parameterized version/digest bookkeeping. |
+| [Store.OpenBillingProblem, billingstore.go:250](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingstore.go:250) | **Approve.** Parameterized, deduplicated problem insertion. |
+| [Store.PutBillingState, billingstore.go:184](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingstore.go:184) | **Approve.** Parameterized billing-state upsert; customer binding remains unchanged. |
+| [Store.SetBillingCustomer, billingstore.go:159](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingstore.go:159) | **Approve.** Binding is parameterized and refuses reassignment. |
+| [Store.billingAccountWhere, billingstore.go:134](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingstore.go:134) | **Approve.** Both callers supply fixed SQL predicates; values are bound arguments. |
+| [Store.migrateBilling, billingstore.go:17](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingstore.go:17) | **Approve.** Fixed console-owned schema creation. |
+| [Store.migrateBillingAccounts, billingstore.go:63](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingstore.go:63) | **Approve.** Fixed tables and uniqueness indexes. |
+| [Server.handleBillingWebhook, billingwebhook.go:29](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/console/billingwebhook.go:29) | **Approve.** Bounded request body; verified event identifies a provider reread, never a filesystem path. |
+| [LoadPriceBook, pricebook.go:59](/home/paulca/.cache/tmp/claude-1001/plans-6-checkout/internal/plans/pricebook.go:59) | **Approve.** Path comes from operator configuration or the operator-run exporter. |
+
+Each re-pinned envelope is also **approved**:
+
+| Envelope | Basis |
+|---|---|
+| `.` | Billing CLI dispatch and API requests; no new privileged local reader. |
+| `cmd/console` | Explicit environment configuration and console worker wiring. |
+| `cmd/pricebook-export` | Operator-selected input/output paths; no service or tenant-controlled path. |
+| `internal/billing` | Provider-neutral types, parsing and purchase recognition. |
+| `internal/billing/billingtest` | In-memory fake provider. |
+| `internal/billingstripe` | Validated API identifiers, bounded responses, refused redirects and authenticated webhooks. |
+| `internal/console` | Console-owned SQL and existing limits publication; no new root reader or weakened root-input validation. |
+| `internal/plans` | Operator-loaded book, validation and deterministic export. |
+
+Direct recomputation matched all 21 unit source digests, legacy fingerprints, eight package envelopes and three updated record-write digests. Both seals match:
+
+- `plans-6a-units`: `291e567c156ae95916ea1a1425788ac2ee6bbb71a1829cc722f4dc24fa3a82f0`
+- `plans-6-checkout`: `31b160764c5b171d0549cb9b07a500b0fcfd90beb4a9f6198d61237e59370094`
+
+This does not substitute for running the full census scanner. No verdict was posted to #280 under the no-network instruction; the handwritten new-unit classifications still require the owner’s decision record.
+
+---
+
+**FIRST PROMPT:**
+“Follow the brief docs/superpowers/specs/CODEX-REVIEW-BRIEF-PLANS-6A-CODE.md exactly, at the branch's current HEAD.”
+
+**WHAT:**
+Review Plans 6a code and census at the pinned HEAD.
+
+**STATUS:**
+Review complete: changes required. Hash checks passed; Go tests were blocked by filesystem permissions.
+
+**NEEDED:**
+Owner decision on the new census classifications.
+
+**RECOMMENDED:**
+Fix the billing recovery defects, integrate the lapse transition, then rerun targeted tests and review.
+
+**SESSION:**
+Safe to close. Working tree and HEAD unchanged; nothing running.
\ No newline at end of file
diff --git a/internal/billing/billing.go b/internal/billing/billing.go
index 4cfc58dee..9d064e4bf 100644
--- a/internal/billing/billing.go
+++ b/internal/billing/billing.go
@@ -39,10 +39,16 @@ type Item struct {
// Subscription is a fresh read of one subscription at the provider.
type Subscription struct {
- ID, Customer string
- Account string // the account sqid the purchase metadata names
- ProviderStatus string // the provider's own word, for operators
- State State // the adapter's mapping
+ ID, Customer string
+ Account string // the account sqid the purchase metadata names
+ ProviderStatus string // the provider's own word, for operators
+ State State // the adapter's mapping: what the plan does with it
+ // Live is settlement, separate from entitlement: true while the
+ // provider may still charge or collect on the subscription (active,
+ // trialing, past due, incomplete, unpaid). An unpaid subscription has
+ // lost paid limits (State ended) but is still live, so a billing problem
+ // on it cannot be closed until it is cancelled at the provider.
+ Live bool
Currency string
LiveMode bool
PeriodEnd time.Time
@@ -68,6 +74,9 @@ type Event struct {
LiveMode bool
}
+// MaxCustomerSubscriptions bounds CustomerSubscriptions.
+const MaxCustomerSubscriptions = 10
+
var (
// ErrBadEvent is any signature or shape failure on an event.
ErrBadEvent = errors.New("billing: event refused")
@@ -86,6 +95,10 @@ type Provider interface {
// CheckoutSubscription is the subscription a checkout made, "" when it
// made none.
CheckoutSubscription(ctx context.Context, checkoutID string) (string, error)
+ // CustomerSubscriptions names a customer's subscriptions, newest
+ // first, at most MaxCustomerSubscriptions: the hourly pass's discovery
+ // of a first purchase whose events were all missed. One request.
+ CustomerSubscriptions(ctx context.Context, customer string) ([]string, error)
// Check is the readiness check: the provider account and every price
// of the book agree with the configuration.
Check(ctx context.Context, book *plans.PriceBook, prices PriceMap) error
diff --git a/internal/billing/billingtest/fake.go b/internal/billing/billingtest/fake.go
index 2c8b000c9..c161f311e 100644
--- a/internal/billing/billingtest/fake.go
+++ b/internal/billing/billingtest/fake.go
@@ -5,6 +5,7 @@ import (
"context"
"encoding/json"
"net/http"
+ "sort"
"sync"
"time"
@@ -22,6 +23,10 @@ type Fake struct {
Err error
CheckErr error
Calls int
+ // SubErr fails Subscription for one id only.
+ SubErr map[string]error
+ // CustomerCalls counts CustomerSubscriptions calls.
+ CustomerCalls int
}
// New is an empty Fake.
@@ -65,6 +70,9 @@ func (f *Fake) Subscription(_ context.Context, id string) (*billing.Subscription
if f.Err != nil {
return nil, f.Err
}
+ if err := f.SubErr[id]; err != nil {
+ return nil, err
+ }
s, ok := f.Subs[id]
if !ok {
return nil, billing.ErrNotFound
@@ -74,6 +82,28 @@ func (f *Fake) Subscription(_ context.Context, id string) (*billing.Subscription
return &c, nil
}
+// CustomerSubscriptions returns the ids of Subs on customer, in id order.
+func (f *Fake) CustomerSubscriptions(_ context.Context, customer string) ([]string, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.Calls++
+ f.CustomerCalls++
+ if f.Err != nil {
+ return nil, f.Err
+ }
+ var ids []string
+ for id, s := range f.Subs {
+ if s.Customer == customer {
+ ids = append(ids, id)
+ }
+ }
+ sort.Strings(ids)
+ if len(ids) > billing.MaxCustomerSubscriptions {
+ ids = ids[:billing.MaxCustomerSubscriptions]
+ }
+ return ids, nil
+}
+
// CheckoutSubscription returns Checkouts[id], "" when absent.
func (f *Fake) CheckoutSubscription(_ context.Context, id string) (string, error) {
f.mu.Lock()
diff --git a/internal/billingstripe/adapter.go b/internal/billingstripe/adapter.go
index e4dfcadfd..683b7ad4c 100644
--- a/internal/billingstripe/adapter.go
+++ b/internal/billingstripe/adapter.go
@@ -95,6 +95,19 @@ func stateOf(status string) billing.State {
}
}
+// liveOf is settlement, separate from stateOf's entitlement: whether Stripe
+// may still charge or collect on a subscription in this status. Unpaid has
+// lost paid limits but is still live (Call 2: a problem on it cannot be
+// closed until it is cancelled).
+func liveOf(status string) bool {
+ switch status {
+ case "active", "trialing", "past_due", "incomplete", "unpaid":
+ return true
+ default:
+ return false
+ }
+}
+
// ParseEvent verifies a delivery's signature and reduces it to what to
// read. Nothing else from the body is used.
func (p *Provider) ParseEvent(raw []byte, header http.Header, now time.Time) (billing.Event, error) {
@@ -155,6 +168,7 @@ func (p *Provider) Subscription(ctx context.Context, id string) (*billing.Subscr
Account: s.Metadata["account_sqid"],
ProviderStatus: s.Status,
State: stateOf(s.Status),
+ Live: liveOf(s.Status),
Currency: s.Currency,
LiveMode: s.LiveMode,
PeriodEnd: s.CurrentPeriodEnd,
@@ -167,6 +181,19 @@ func (p *Provider) Subscription(ctx context.Context, id string) (*billing.Subscr
return out, nil
}
+// CustomerSubscriptions lists a customer's subscriptions, newest first.
+func (p *Provider) CustomerSubscriptions(ctx context.Context, customer string) ([]string, error) {
+ subs, err := p.client.ListCustomerSubscriptions(ctx, customer, billing.MaxCustomerSubscriptions)
+ if err != nil {
+ return nil, err
+ }
+ ids := make([]string, 0, len(subs))
+ for _, s := range subs {
+ ids = append(ids, s.ID)
+ }
+ return ids, nil
+}
+
// CheckoutSubscription is the subscription a checkout session made.
func (p *Provider) CheckoutSubscription(ctx context.Context, checkoutID string) (string, error) {
s, err := p.client.GetCheckout(ctx, checkoutID)
diff --git a/internal/billingstripe/adapter_test.go b/internal/billingstripe/adapter_test.go
index 0bc74714b..0334737bd 100644
--- a/internal/billingstripe/adapter_test.go
+++ b/internal/billingstripe/adapter_test.go
@@ -30,6 +30,19 @@ func TestStateOf(t *testing.T) {
}
}
+// Settlement is not entitlement: unpaid has ended paid limits but Stripe
+// can still collect on it (Call 2).
+func TestLiveOf(t *testing.T) {
+ for status, want := range map[string]bool{
+ "active": true, "trialing": true, "past_due": true, "incomplete": true, "unpaid": true,
+ "canceled": false, "incomplete_expired": false, "paused": false, "weird": false,
+ } {
+ if got := liveOf(status); got != want {
+ t.Errorf("liveOf(%q) = %v, want %v", status, got, want)
+ }
+ }
+}
+
func testProvider(t *testing.T, base string, live bool, secrets ...string) *Provider {
t.Helper()
key := "rk_test_abc"
@@ -183,7 +196,7 @@ func TestSubscriptionMapsFields(t *testing.T) {
t.Fatal(err)
}
want := billing.Subscription{
- ID: "sub_1", Customer: "cus_1", Account: "bab", ProviderStatus: "past_due", State: billing.StatePaid,
+ ID: "sub_1", Customer: "cus_1", Account: "bab", ProviderStatus: "past_due", State: billing.StatePaid, Live: true,
Currency: "usd", LiveMode: false, PeriodEnd: end, CancelAtPeriodEnd: true, ItemsComplete: true,
Items: []billing.Item{{PriceID: "price_p", Quantity: 1, Currency: "usd"}, {PriceID: "price_a", Quantity: 3, Currency: "usd"}},
}
@@ -425,3 +438,29 @@ func TestCreateCheckoutSendsItems(t *testing.T) {
}
}
}
+
+func TestCustomerSubscriptionsLists(t *testing.T) {
+ var query string
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/v1/subscriptions" {
+ w.WriteHeader(http.StatusNotFound)
+ return
+ }
+ query = r.URL.RawQuery
+ fmt.Fprint(w, `{"has_more":false,"data":[{"id":"sub_2","livemode":false},{"id":"sub_1","livemode":false}]}`)
+ }))
+ defer srv.Close()
+ p := testProvider(t, srv.URL, false)
+ ids, err := p.CustomerSubscriptions(context.Background(), "cus_1")
+ if err != nil || len(ids) != 2 || ids[0] != "sub_2" || ids[1] != "sub_1" {
+ t.Fatalf("ids = %v, %v", ids, err)
+ }
+ for _, want := range []string{"customer=cus_1", "status=all", "limit=10"} {
+ if !strings.Contains(query, want) {
+ t.Errorf("query %q lacks %s", query, want)
+ }
+ }
+ if _, err := p.CustomerSubscriptions(context.Background(), "../x"); err == nil {
+ t.Error("bad customer id accepted")
+ }
+}
diff --git a/internal/billingstripe/client.go b/internal/billingstripe/client.go
index 59cc8a38f..ddb5e648e 100644
--- a/internal/billingstripe/client.go
+++ b/internal/billingstripe/client.go
@@ -817,6 +817,32 @@ func (c *Client) FenceQuantityKey(ctx context.Context, itemID string, generation
return "", err
}
+// ListCustomerSubscriptions reads one page of a customer's subscriptions in
+// every status, newest first (Stripe's list order), at most limit. One
+// request; it never pages.
+func (c *Client) ListCustomerSubscriptions(ctx context.Context, customerID string, limit int) ([]Subscription, error) {
+ if !validID(customerID) {
+ return nil, &Error{Code: CodeInvalidID}
+ }
+ if limit < 1 || limit > listPageLimit {
+ return nil, &Error{Code: CodeInvalidParams}
+ }
+ form := url.Values{}
+ form.Set("customer", customerID)
+ form.Set("status", "all")
+ form.Set("limit", strconv.Itoa(limit))
+ var page subscriptionListResponse
+ if err := c.do(ctx, http.MethodGet, "/v1/subscriptions", form, "", &page); err != nil {
+ return nil, err
+ }
+ for _, s := range page.Data {
+ if !validID(s.ID) {
+ return nil, &Error{Code: CodeDecodeError}
+ }
+ }
+ return page.Data, nil
+}
+
type subscriptionListResponse struct {
Data []Subscription `json:"data"`
HasMore bool `json:"has_more"`
diff --git a/internal/console/accountplans.go b/internal/console/accountplans.go
index 85a16e617..31dc96a40 100644
--- a/internal/console/accountplans.go
+++ b/internal/console/accountplans.go
@@ -155,15 +155,26 @@ const planBilling = "billing"
// never touched (not written, not owned). A deleted account is
// ErrAccountGone.
func (s *Store) SetBillingPlan(accountID int64, plan string, packs map[string]int, reason string, now time.Time) (written, owned bool, err error) {
- want, err := canonicalPacks(packs)
+ tx, err := s.db.Begin()
if err != nil {
return false, false, err
}
- tx, err := s.db.Begin()
+ defer tx.Rollback()
+ written, owned, err = setBillingPlanTx(tx, accountID, plan, packs, reason, now)
+ if err != nil || !written {
+ return written, owned, err
+ }
+ return written, owned, tx.Commit()
+}
+
+// setBillingPlanTx is SetBillingPlan inside the caller's transaction: the
+// ownership guard, the unchanged-write check and the write. It never
+// commits.
+func setBillingPlanTx(tx *sql.Tx, accountID int64, plan string, packs map[string]int, reason string, now time.Time) (written, owned bool, err error) {
+ want, err := canonicalPacks(packs)
if err != nil {
return false, false, err
}
- defer tx.Rollback()
var live int
if err := tx.QueryRow(`SELECT COUNT(*) FROM accounts WHERE id = ? AND deleted_at = 0`, accountID).Scan(&live); err != nil {
return false, false, err
@@ -195,7 +206,7 @@ func (s *Store) SetBillingPlan(accountID int64, plan string, packs map[string]in
if err := billingSetPlan(tx, accountID, plan, packs, reason, now); err != nil {
return false, true, err
}
- return true, true, tx.Commit()
+ return true, true, nil
}
// billingSetPlan is the one place billing changes a plan row. It switches
diff --git a/internal/console/apibilling.go b/internal/console/apibilling.go
index e4e426aad..47b6fb9dd 100644
--- a/internal/console/apibilling.go
+++ b/internal/console/apibilling.go
@@ -125,20 +125,28 @@ func (s *Server) handleAPIBillingProblemClose(w http.ResponseWriter, r *http.Req
jsonError(w, http.StatusConflict, billingCopyClosed)
return
}
+ now := time.Now()
if p.Subscription != "" {
sub, err := s.billing.cfg.Provider.Subscription(r.Context(), p.Subscription)
switch {
case errors.Is(err, billing.ErrNotFound):
+ if p.Reason == problemSubscriptionMissing {
+ // The resolution: still unknown to the provider, so it ends here.
+ if err := s.endMissingSubscription(r.Context(), p.AccountID, p.Subscription, now); err != nil {
+ log.Printf("console: api billing close %d: ending the missing subscription: %v", id, err)
+ jsonError(w, http.StatusInternalServerError, billingCopyFailed)
+ return
+ }
+ }
case err != nil:
log.Printf("console: api billing close %d: reading subscription: %v", id, err)
jsonError(w, http.StatusServiceUnavailable, billingCopyProviderDown)
return
- case liveState(sub.State):
+ case sub.Live:
jsonError(w, http.StatusConflict, billingCopyStillLive)
return
}
}
- now := time.Now()
if err := s.store.CloseBillingProblem(id, addr, note, now); err != nil {
if errors.Is(err, errBillingProblemClosed) {
jsonError(w, http.StatusConflict, billingCopyClosed)
diff --git a/internal/console/apibilling_test.go b/internal/console/apibilling_test.go
index 147790088..94d1487aa 100644
--- a/internal/console/apibilling_test.go
+++ b/internal/console/apibilling_test.go
@@ -1,6 +1,7 @@
package console
import (
+ "context"
"encoding/json"
"net/http"
"strconv"
@@ -102,3 +103,24 @@ func TestCloseNeedsANote(t *testing.T) {
}
}
}
+
+// Call 2: unpaid has lost paid limits (Call 12) but Stripe can still collect
+// on it, so its problem cannot be closed until it is cancelled there.
+func TestCloseRefusedWhileUnpaid(t *testing.T) {
+ bf := newBillingFixture(t)
+ bf.put(bf.personalSub("sub_1", "unpaid", nil))
+ if err := bf.srv.syncSubscription(context.Background(), "sub_1", billingNow); err != nil {
+ t.Fatal(err)
+ }
+ if p := bf.plan(t); p != "free" {
+ t.Fatalf("unpaid kept paid limits: plan %q", p)
+ }
+ if _, err := bf.st.OpenBillingProblem(bf.acct.ID, "sub_1", problemUnrecognised, "", billingNow); err != nil {
+ t.Fatal(err)
+ }
+ open, _ := bf.st.BillingProblems(false)
+ op := planOperatorToken(t, bf.consoleFixture, "ops@keymail.dev", "code-billing-unpaid")
+ if status, out := postJSON(t, billingCloseURL(bf.consoleFixture, open[0].ID), map[string]any{"note": "x"}, op); status != http.StatusConflict || out["error"] != billingCopyStillLive {
+ t.Fatalf("unpaid: %d %v, want 409", status, out)
+ }
+}
diff --git a/internal/console/billingpass.go b/internal/console/billingpass.go
index 6e99e0be9..35ca3d5af 100644
--- a/internal/console/billingpass.go
+++ b/internal/console/billingpass.go
@@ -14,6 +14,11 @@ const (
billingCheckRetry = time.Minute
)
+// billingDiscoveryWindow is how long after binding a customer the pass
+// asks the provider for its subscriptions, when none is recorded: longer
+// than the provider's three days of webhook retries.
+const billingDiscoveryWindow = 7 * 24 * time.Hour
+
// billingSyncBatch is the hourly pass's page size; a test shrinks it.
var billingSyncBatch = 200
@@ -88,6 +93,39 @@ func (s *Server) billingSyncPass(ctx context.Context, now time.Time) {
log.Printf("console: billing sync pass: account %d: %v", b.AccountID, err)
}
}
+ if len(page) < billingSyncBatch {
+ break
+ }
+ }
+ s.billingDiscoveryPass(ctx, now)
+}
+
+// billingDiscoveryPass asks the provider for the subscriptions of each
+// customer bound within billingDiscoveryWindow that has none recorded, and
+// syncs each one (Astra finding 3): a first purchase whose every event was
+// missed, because billing was not ready while the provider retried, is
+// still found. One list request per such customer per pass.
+func (s *Server) billingDiscoveryPass(ctx context.Context, now time.Time) {
+ var after int64
+ for ctx.Err() == nil {
+ page, err := s.store.DiscoverableBillingAccounts(now.Add(-billingDiscoveryWindow), after, billingSyncBatch)
+ if err != nil {
+ log.Printf("console: billing discovery: %v", err)
+ return
+ }
+ for _, b := range page {
+ after = b.AccountID
+ ids, err := s.billing.cfg.Provider.CustomerSubscriptions(ctx, b.Customer)
+ if err != nil {
+ log.Printf("console: billing discovery: account %d: %v", b.AccountID, err)
+ continue
+ }
+ for _, id := range ids {
+ if err := s.syncSubscription(ctx, id, now); err != nil {
+ log.Printf("console: billing discovery: account %d: %v", b.AccountID, err)
+ }
+ }
+ }
if len(page) < billingSyncBatch {
return
}
diff --git a/internal/console/billingrecovery_test.go b/internal/console/billingrecovery_test.go
new file mode 100644
index 000000000..8489b3256
--- /dev/null
+++ b/internal/console/billingrecovery_test.go
@@ -0,0 +1,172 @@
+package console
+
+import (
+ "context"
+ "errors"
+ "net/http"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/billing"
+)
+
+// Astra finding 1: B's purchase events arrive before A's cancellation. The
+// stored state says A is paid, but a fresh read under the lock says it has
+// ended, so B is adopted rather than refused as a second subscription.
+func TestReplacementSubscriptionBeforeOldCancellation(t *testing.T) {
+ bf := newBillingFixture(t)
+ bf.put(bf.personalSub("sub_a", "active", nil))
+ if err := bf.srv.syncSubscription(context.Background(), "sub_a", billingNow); err != nil {
+ t.Fatal(err)
+ }
+ bf.put(bf.personalSub("sub_a", "canceled", nil))
+ bf.put(bf.personalSub("sub_b", "active", map[string]int64{"apps": 1}))
+ if err := bf.srv.syncSubscription(context.Background(), "sub_b", billingNow); err != nil {
+ t.Fatal(err)
+ }
+ b, _ := bf.st.BillingAccount(bf.acct.ID)
+ row, _ := bf.st.AccountPlan(bf.acct.ID)
+ if b.Subscription != "sub_b" || row.Plan != "personal" || row.Packs["apps"] != 1 {
+ t.Fatalf("replacement not adopted: billing %+v plan %+v", b, row)
+ }
+ if open, _ := bf.st.BillingProblems(false); len(open) != 0 {
+ t.Fatalf("problems opened: %+v", open)
+ }
+ // A's cancellation arrives late: an old subscription ending changes nothing.
+ if err := bf.srv.syncSubscription(context.Background(), "sub_a", billingNow); err != nil {
+ t.Fatal(err)
+ }
+ if p := bf.plan(t); p != "personal" {
+ t.Fatalf("late cancellation of the old subscription dropped the plan to %q", p)
+ }
+}
+
+// The old subscription cannot be read just now: B stays retryable (an
+// error, so the webhook answers 503 and the provider redelivers), and
+// nothing is recorded or refused.
+func TestReplacementWaitsForTheOldRead(t *testing.T) {
+ bf := newBillingFixture(t)
+ bf.put(bf.personalSub("sub_a", "active", nil))
+ if err := bf.srv.syncSubscription(context.Background(), "sub_a", billingNow); err != nil {
+ t.Fatal(err)
+ }
+ bf.put(bf.personalSub("sub_b", "active", nil))
+ bf.fake.SubErr = map[string]error{"sub_a": errors.New("timeout")}
+ if err := bf.srv.syncSubscription(context.Background(), "sub_b", billingNow); err == nil {
+ t.Fatal("sync of B succeeded without settling A")
+ }
+ b, _ := bf.st.BillingAccount(bf.acct.ID)
+ if b.Subscription != "sub_a" {
+ t.Fatalf("billing row = %+v", b)
+ }
+ if open, _ := bf.st.BillingProblems(false); len(open) != 0 {
+ t.Fatalf("problems opened: %+v", open)
+ }
+ // A really is still live: a second subscription, refused.
+ bf.fake.SubErr = nil
+ if err := bf.srv.syncSubscription(context.Background(), "sub_b", billingNow); err != nil {
+ t.Fatal(err)
+ }
+ if open, _ := bf.st.BillingProblems(false); len(open) != 1 || open[0].Reason != problemSecondSubscription {
+ t.Fatalf("problems = %+v", open)
+ }
+}
+
+// Astra finding 2: the billing state and the plan change commit together.
+// A plan write that fails leaves the billing row as it was, so the account
+// stays on the hourly pass and the next pass finishes the change.
+func TestSyncFailureBetweenWritesIsRetried(t *testing.T) {
+ bf := newBillingFixture(t)
+ bf.ready(t)
+ bf.put(bf.personalSub("sub_1", "active", nil))
+ if err := bf.srv.syncSubscription(context.Background(), "sub_1", billingNow); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := bf.st.db.Exec(`CREATE TRIGGER fail_plan BEFORE UPDATE ON account_plans BEGIN SELECT RAISE(ABORT, 'injected'); END`); err != nil {
+ t.Fatal(err)
+ }
+ bf.put(bf.personalSub("sub_1", "canceled", nil))
+ if err := bf.srv.syncSubscription(context.Background(), "sub_1", billingNow.Add(time.Hour)); err == nil {
+ t.Fatal("a failed plan write was reported as success")
+ }
+ b, _ := bf.st.BillingAccount(bf.acct.ID)
+ if b.State != billing.StatePaid || !b.SyncedAt.Equal(billingNow) {
+ t.Fatalf("billing state committed without the plan change: %+v", b)
+ }
+ if _, err := bf.st.db.Exec(`DROP TRIGGER fail_plan`); err != nil {
+ t.Fatal(err)
+ }
+ bf.srv.billingSyncPass(context.Background(), billingNow.Add(2*time.Hour))
+ if p := bf.plan(t); p != "free" {
+ t.Fatalf("the next pass did not finish the change: plan %q", p)
+ }
+}
+
+// Astra finding 3: the first purchase's events were all missed (billing
+// was not ready while the provider retried). The pass finds the bound
+// customer's subscription through the provider.
+func TestSyncPassDiscoversAMissedFirstPurchase(t *testing.T) {
+ bf := newBillingFixture(t)
+ bf.ready(t)
+ bf.put(bf.personalSub("sub_1", "active", nil))
+ bf.srv.billingSyncPass(context.Background(), billingNow.Add(time.Hour))
+ if p := bf.plan(t); p != "personal" {
+ t.Fatalf("missed first purchase not found: plan %q", p)
+ }
+ // A customer bound longer ago than the discovery window is not asked about.
+ old := planAccount(t, bf.consoleFixture, 502)
+ if err := bf.st.SetBillingCustomer(old.ID, "cus_old", billingNow); err != nil {
+ t.Fatal(err)
+ }
+ bf.fake.CustomerCalls = 0
+ bf.srv.billingSyncPass(context.Background(), billingNow.Add(billingDiscoveryWindow+time.Hour))
+ if bf.fake.CustomerCalls != 0 {
+ t.Fatalf("discovery asked about %d customers past the window", bf.fake.CustomerCalls)
+ }
+}
+
+// Astra finding 4: the provider no longer knows a bound subscription. Paid
+// limits are kept while an operator looks, through one deduplicated
+// problem; closing it (the provider still answers not found) ends the
+// subscription in the console and drops the account to the default plan.
+func TestMissingSubscriptionOpensAProblemThenCloses(t *testing.T) {
+ bf := newBillingFixture(t)
+ bf.ready(t)
+ bf.put(bf.personalSub("sub_1", "active", nil))
+ if err := bf.srv.syncSubscription(context.Background(), "sub_1", billingNow); err != nil {
+ t.Fatal(err)
+ }
+ bf.fake.Lock()
+ delete(bf.fake.Subs, "sub_1")
+ bf.fake.Unlock()
+ for i := 0; i < 2; i++ {
+ if err := bf.srv.syncSubscription(context.Background(), "sub_1", billingNow); err != nil {
+ t.Fatal(err)
+ }
+ }
+ bf.srv.billingSyncPass(context.Background(), billingNow.Add(time.Hour))
+ open, _ := bf.st.BillingProblems(false)
+ if len(open) != 1 || open[0].Reason != problemSubscriptionMissing || open[0].AccountID != bf.acct.ID || open[0].Subscription != "sub_1" {
+ t.Fatalf("problems = %+v", open)
+ }
+ if p := bf.plan(t); p != "personal" {
+ t.Fatalf("limits not kept while the problem is open: %q", p)
+ }
+ op := planOperatorToken(t, bf.consoleFixture, "ops@keymail.dev", "code-billing-missing")
+ if status, out := postJSON(t, billingCloseURL(bf.consoleFixture, open[0].ID), map[string]any{"note": "deleted in the dashboard by mistake; refunded"}, op); status != http.StatusOK {
+ t.Fatalf("close: %d %v", status, out)
+ }
+ if p := bf.plan(t); p != "free" {
+ t.Fatalf("closing the missing-subscription problem left plan %q", p)
+ }
+ if b, _ := bf.st.BillingAccount(bf.acct.ID); b.State != billing.StateEnded {
+ t.Fatalf("billing state = %+v", b)
+ }
+ // A subscription the console never bound is only logged.
+ if err := bf.srv.syncSubscription(context.Background(), "sub_stranger", billingNow); err != nil {
+ t.Fatal(err)
+ }
+ if open, _ := bf.st.BillingProblems(false); len(open) != 0 {
+ t.Fatalf("problems = %+v", open)
+ }
+}
diff --git a/internal/console/billingstore.go b/internal/console/billingstore.go
index da04e24e9..7ff4d9dea 100644
--- a/internal/console/billingstore.go
+++ b/internal/console/billingstore.go
@@ -52,12 +52,13 @@ func (s *Store) NotePriceBook(version, digest, status string, now time.Time) err
// The reasons a billing problem is opened for (plans 6a Calls 1 to 3, 11).
const (
- problemUnknownCustomer = "unknown_customer"
- problemAccountMismatch = "account_mismatch"
- problemModeMismatch = "mode_mismatch"
- problemSecondSubscription = "second_subscription"
- problemUnrecognised = "unrecognised"
- problemNotBillingOwned = "not_billing_owned"
+ problemUnknownCustomer = "unknown_customer"
+ problemAccountMismatch = "account_mismatch"
+ problemModeMismatch = "mode_mismatch"
+ problemSecondSubscription = "second_subscription"
+ problemUnrecognised = "unrecognised"
+ problemNotBillingOwned = "not_billing_owned"
+ problemSubscriptionMissing = "subscription_missing"
)
func (s *Store) migrateBillingAccounts() error {
@@ -73,7 +74,8 @@ func (s *Store) migrateBillingAccounts() error {
cancel_at_period_end INTEGER NOT NULL DEFAULT 0,
paid_packs TEXT NOT NULL DEFAULT '{}',
paid_period_end INTEGER NOT NULL DEFAULT 0,
- synced_at INTEGER NOT NULL DEFAULT 0
+ synced_at INTEGER NOT NULL DEFAULT 0,
+ bound_at INTEGER NOT NULL DEFAULT 0
);
CREATE UNIQUE INDEX IF NOT EXISTS billing_accounts_customer ON billing_accounts(customer) WHERE customer != '';
CREATE UNIQUE INDEX IF NOT EXISTS billing_accounts_subscription ON billing_accounts(subscription) WHERE subscription != '';
@@ -160,9 +162,9 @@ func (s *Store) SetBillingCustomer(accountID int64, customer string, now time.Ti
if customer == "" {
return errors.New("billing: empty customer")
}
- res, err := s.db.Exec(`INSERT INTO billing_accounts (account_id, customer, synced_at) VALUES (?, ?, ?)
- ON CONFLICT(account_id) DO UPDATE SET customer = excluded.customer WHERE billing_accounts.customer = ''`,
- accountID, customer, now.Unix())
+ res, err := s.db.Exec(`INSERT INTO billing_accounts (account_id, customer, synced_at, bound_at) VALUES (?, ?, ?, ?)
+ ON CONFLICT(account_id) DO UPDATE SET customer = excluded.customer, bound_at = excluded.bound_at WHERE billing_accounts.customer = ''`,
+ accountID, customer, now.Unix(), now.Unix())
if err != nil {
return err
}
@@ -182,6 +184,15 @@ func (s *Store) SetBillingCustomer(accountID int64, customer string, now time.Ti
// PutBillingState writes every column of the account's billing row but the
// customer, creating the row if needed.
func (s *Store) PutBillingState(b billingAccount) error {
+ return putBillingState(s.db, b)
+}
+
+// sqlExecer is a store handle or a transaction.
+type sqlExecer interface {
+ Exec(query string, args ...any) (sql.Result, error)
+}
+
+func putBillingState(e sqlExecer, b billingAccount) error {
packs, err := canonicalPacks(b.PaidPacks)
if err != nil {
return err
@@ -190,7 +201,7 @@ func (s *Store) PutBillingState(b billingAccount) error {
if b.CancelAtPeriodEnd {
cancel = 1
}
- _, err = s.db.Exec(`INSERT INTO billing_accounts
+ _, err = e.Exec(`INSERT INTO billing_accounts
(account_id, subscription, provider_status, state, book, currency, period_end, cancel_at_period_end, paid_packs, paid_period_end, synced_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(account_id) DO UPDATE SET subscription = excluded.subscription, provider_status = excluded.provider_status,
@@ -306,3 +317,64 @@ func (s *Store) CloseBillingProblem(id int64, by, note string, now time.Time) er
}
return errBillingProblemClosed
}
+
+// SaveBillingSync commits one sync's outcome in one transaction: the
+// billing row (when next is not nil) and billing's guarded plan change
+// (when plan is not nil). A failure leaves both as they were, so an
+// account whose plan write failed keeps its old billing state and stays
+// on the hourly pass until the change lands (Astra finding 2). A deleted
+// account writes nothing and is not an error.
+func (s *Store) SaveBillingSync(next *billingAccount, accountID int64, plan *planChange, now time.Time) (written, owned bool, err error) {
+ tx, err := s.db.Begin()
+ if err != nil {
+ return false, false, err
+ }
+ defer tx.Rollback()
+ if next != nil {
+ if err := putBillingState(tx, *next); err != nil {
+ return false, false, err
+ }
+ }
+ if plan != nil {
+ written, owned, err = setBillingPlanTx(tx, accountID, plan.Plan, plan.Packs, plan.Reason, now)
+ if errors.Is(err, ErrAccountGone) {
+ return false, false, nil
+ }
+ if err != nil {
+ return false, false, err
+ }
+ }
+ return written, owned, tx.Commit()
+}
+
+// BillingAccountBySubscription is the row whose recorded subscription is
+// id, nil when none.
+func (s *Store) BillingAccountBySubscription(id string) (*billingAccount, error) {
+ if id == "" {
+ return nil, nil
+ }
+ return s.billingAccountWhere(`b.subscription = ?`, id)
+}
+
+// DiscoverableBillingAccounts pages, in account order after afterAccountID,
+// the live accounts with a bound customer and no subscription recorded,
+// bound at or after boundAfter: the pass asks the provider about these, so
+// a first purchase whose every event was missed is still found.
+func (s *Store) DiscoverableBillingAccounts(boundAfter time.Time, afterAccountID int64, limit int) ([]billingAccount, error) {
+ rows, err := s.db.Query(`SELECT `+billingAccountColumns+` FROM billing_accounts b JOIN accounts a ON a.id = b.account_id
+ WHERE a.deleted_at = 0 AND b.account_id > ? AND b.customer != '' AND b.subscription = '' AND b.bound_at >= ?
+ ORDER BY b.account_id LIMIT ?`, afterAccountID, boundAfter.Unix(), limit)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ var out []billingAccount
+ for rows.Next() {
+ b, err := scanBillingAccount(rows)
+ if err != nil {
+ return nil, err
+ }
+ out = append(out, *b)
+ }
+ return out, rows.Err()
+}
diff --git a/internal/console/billingsync.go b/internal/console/billingsync.go
index c6ed14bf8..d7b5d9c3a 100644
--- a/internal/console/billingsync.go
+++ b/internal/console/billingsync.go
@@ -129,9 +129,16 @@ func decideBilling(in billingInput) billingDecision {
// syncSubscription reads one subscription and applies the decision. It
// returns nil when a problem was opened, when the provider has no such
-// subscription, and when the account is gone; a transient provider or
-// store error is returned so the caller can retry (the webhook answers
-// 503 and the provider redelivers).
+// subscription (subscriptionMissing), and when the account is gone; a
+// transient provider or store error is returned so the caller can retry
+// (the webhook answers 503 and the provider redelivers).
+//
+// It reads the subscription twice: once to learn its customer and so its
+// account, and again under that account's lock, so the read that decides
+// is the latest. When another subscription of the account is recorded as
+// live, that one is re-read too before this one is refused as a second
+// subscription (Astra finding 1): events arrive out of order, and the
+// stored state may be older than the provider's.
func (s *Server) syncSubscription(ctx context.Context, subscriptionID string, now time.Time) error {
if s.billing == nil {
return nil
@@ -139,8 +146,7 @@ func (s *Server) syncSubscription(ctx context.Context, subscriptionID string, no
cfg := s.billing.cfg
first, err := cfg.Provider.Subscription(ctx, subscriptionID)
if errors.Is(err, billing.ErrNotFound) {
- log.Printf("console: billing: subscription %s not found at the provider; nothing changed", subscriptionID)
- return nil
+ return s.subscriptionMissing(subscriptionID, now)
}
if err != nil {
return fmt.Errorf("billing: reading subscription %s: %w", subscriptionID, err)
@@ -171,11 +177,9 @@ func (s *Server) syncSubscription(ctx context.Context, subscriptionID string, no
}
defer s.billing.locks.lock(acct.Sqid)()
- // Re-read under the lock: the read that decides is the latest one.
sub, err := cfg.Provider.Subscription(ctx, subscriptionID)
if errors.Is(err, billing.ErrNotFound) {
- log.Printf("console: billing: subscription %s not found at the provider; nothing changed", subscriptionID)
- return nil
+ return s.subscriptionMissing(subscriptionID, now)
}
if err != nil {
return fmt.Errorf("billing: reading subscription %s: %w", subscriptionID, err)
@@ -188,34 +192,48 @@ func (s *Server) syncSubscription(ctx context.Context, subscriptionID string, no
// The customer changed between the two reads: settle it next time.
return fmt.Errorf("billing: subscription %s changed customer during the sync", subscriptionID)
}
+ if prev.Subscription != "" && prev.Subscription != sub.ID && liveState(prev.State) && liveState(sub.State) {
+ old, err := cfg.Provider.Subscription(ctx, prev.Subscription)
+ switch {
+ case errors.Is(err, billing.ErrNotFound):
+ // The recorded one is unknown to the provider: it is not shown
+ // to have ended, so this one is still a second subscription.
+ case err != nil:
+ return fmt.Errorf("billing: reading the recorded subscription %s before adopting %s: %w", prev.Subscription, subscriptionID, err)
+ default:
+ prev.State, prev.ProviderStatus = old.State, old.ProviderStatus
+ }
+ }
+ return s.applyBillingRead(ctx, acct, prev, sub, now)
+}
+
+// applyBillingRead decides on one fresh read and commits the billing row
+// and the plan change together (SaveBillingSync). The caller holds the
+// account's lock.
+func (s *Server) applyBillingRead(ctx context.Context, acct *Account, prev *billingAccount, sub *billing.Subscription, now time.Time) error {
+ cfg := s.billing.cfg
purchase, unrecognised := billing.Recognise(sub, cfg.Prices, s.cfg.PlanCatalog)
d := decideBilling(billingInput{
Prev: prev, Sub: sub, Purchase: purchase, Unrecognised: unrecognised,
AccountSqid: acct.Sqid, LiveMode: cfg.LiveMode, DefaultPlan: s.cfg.PlanCatalog.DefaultPlan,
})
+ var next *billingAccount
if d.Save {
d.Next.SyncedAt = now
- if err := s.store.PutBillingState(d.Next); err != nil {
- return err
- }
+ next = &d.Next
}
- if d.Plan != nil {
- written, owned, err := s.store.SetBillingPlan(acct.ID, d.Plan.Plan, d.Plan.Packs, d.Plan.Reason, now)
- if errors.Is(err, ErrAccountGone) {
- return nil
- }
- if err != nil {
+ written, owned, err := s.store.SaveBillingSync(next, acct.ID, d.Plan, now)
+ if err != nil {
+ return err
+ }
+ if written {
+ s.publishPlanNow(ctx, acct.ID, now)
+ }
+ if d.Plan != nil && !owned && sub.State == billing.StatePaid {
+ if err := s.openBillingProblem(acct.ID, acct.Sqid, sub.ID, problemNotBillingOwned,
+ "the account's plan was set by an operator; billing leaves it alone", now); err != nil {
return err
}
- if written {
- s.publishPlanNow(ctx, acct.ID, now)
- }
- if !owned && sub.State == billing.StatePaid {
- if err := s.openBillingProblem(acct.ID, acct.Sqid, sub.ID, problemNotBillingOwned,
- "the account's plan was set by an operator; billing leaves it alone", now); err != nil {
- return err
- }
- }
}
if d.Problem != nil {
return s.openBillingProblem(acct.ID, acct.Sqid, sub.ID, d.Problem.Reason, d.Problem.Detail, now)
@@ -223,6 +241,50 @@ func (s *Server) syncSubscription(ctx context.Context, subscriptionID string, no
return nil
}
+// subscriptionMissing handles the provider answering not found for a
+// subscription (Astra finding 4). One the console never recorded is only
+// logged. For an account's current, live subscription it opens one
+// deduplicated subscription_missing problem and keeps the paid limits
+// while an operator looks; closing that problem, with the provider still
+// answering not found, ends the subscription (endMissingSubscription).
+func (s *Server) subscriptionMissing(subscriptionID string, now time.Time) error {
+ b, err := s.store.BillingAccountBySubscription(subscriptionID)
+ if err != nil {
+ return err
+ }
+ if b == nil || !liveState(b.State) {
+ log.Printf("console: billing: subscription %s not found at the provider; nothing changed", subscriptionID)
+ return nil
+ }
+ sqid := ""
+ if a, err := s.store.AccountByID(b.AccountID); err == nil && a != nil {
+ sqid = a.Sqid
+ }
+ return s.openBillingProblem(b.AccountID, sqid, subscriptionID, problemSubscriptionMissing,
+ "the provider has no such subscription; paid limits are kept until this problem is closed", now)
+}
+
+// endMissingSubscription is the resolution of a subscription_missing
+// problem: the provider still has no such subscription, so the console
+// treats it as ended and drops the account to the default plan, through
+// the same decision and commit as any ended subscription. A subscription
+// the account has since replaced is left alone.
+func (s *Server) endMissingSubscription(ctx context.Context, accountID int64, subscriptionID string, now time.Time) error {
+ acct, err := s.store.AccountByID(accountID)
+ if err != nil || acct == nil {
+ return err
+ }
+ defer s.billing.locks.lock(acct.Sqid)()
+ prev, err := s.store.BillingAccount(acct.ID)
+ if err != nil || prev == nil || prev.Subscription != subscriptionID {
+ return err
+ }
+ ended := &billing.Subscription{ID: subscriptionID, Customer: prev.Customer, Account: acct.Sqid,
+ ProviderStatus: "missing", State: billing.StateEnded, LiveMode: s.billing.cfg.LiveMode,
+ Currency: prev.Currency, PeriodEnd: prev.PeriodEnd, ItemsComplete: true}
+ return s.applyBillingRead(ctx, acct, prev, ended, now)
+}
+
// openBillingProblem opens a problem and logs it once, when it opens.
func (s *Server) openBillingProblem(accountID int64, sqid, subscription, reason, detail string, now time.Time) error {
opened, err := s.store.OpenBillingProblem(accountID, subscription, reason, detail, now)
diff --git a/internal/console/billingsync_test.go b/internal/console/billingsync_test.go
index d307fa0be..e9c535f13 100644
--- a/internal/console/billingsync_test.go
+++ b/internal/console/billingsync_test.go
@@ -21,6 +21,15 @@ func paidSub(id, status string, packs map[string]int64) *billing.Subscription {
Currency: "usd", PeriodEnd: periodEnd, ItemsComplete: true}
}
+// billingLiveFor mirrors the Stripe adapter's settlement mapping.
+func billingLiveFor(status string) bool {
+ switch status {
+ case "active", "trialing", "past_due", "incomplete", "unpaid":
+ return true
+ }
+ return false
+}
+
// billingStateFor mirrors the Stripe adapter's mapping for test fixtures.
func billingStateFor(status string) billing.State {
switch status {
@@ -242,7 +251,7 @@ func testPersonalSub(id, customer, sqid, status string, packs map[string]int64)
items = append(items, billing.Item{PriceID: testPriceID("example-v1/pack/" + name + "/usd"), Quantity: q, Currency: "usd"})
}
return &billing.Subscription{ID: id, Customer: customer, Account: sqid, ProviderStatus: status, State: billingStateFor(status),
- Currency: "usd", PeriodEnd: periodEnd, ItemsComplete: true, Items: items}
+ Live: billingLiveFor(status), Currency: "usd", PeriodEnd: periodEnd, ItemsComplete: true, Items: items}
}
// newBillingFixture is a console with billing on (enableBilling) and one
diff --git a/internal/console/svcroutes_test.go b/internal/console/svcroutes_test.go
index 6f24f6db4..8dd3d07c7 100644
--- a/internal/console/svcroutes_test.go
+++ b/internal/console/svcroutes_test.go
@@ -195,6 +195,11 @@ var closedDoors = []string{
// or sets them.
"GET /api/cli/accounts/{account}/plan",
"POST /api/cli/accounts/{account}/plan",
+ // Billing problems are settled by a fleet operator in the provider's
+ // dashboard (plans 6a, Calls 1 and 2); no machine credential lists or
+ // closes them.
+ "GET /api/cli/billing/problems",
+ "POST /api/cli/billing/problems/{id}/close",
// Moving a route between channels decides what that route SERVES, which
// is release authority wearing a config-shaped hat: a credential the app
// itself holds must not be able to walk its own route onto a channel
@@ -1078,8 +1083,8 @@ func TestEveryClosedDoorRefusesAServiceCredential(t *testing.T) {
}
seen++
}
- if seen != len(closedDoors) || seen != 59 {
- t.Errorf("walked %d closed doors, want all %d (and 59 today: instance-token, three door-key doors, the routes door, instances-manifest, the app update policy, sidecars-manifest, the route-channel move, three instance update settings doors, two db replica doors, the forwarded db read, six fleets, four services, two email credentials, email pause, the build probe, the swap policy, the live tenancy read, the layout read, the activation-cancel door, nine system doors, three deployment-wide antivirus, three platform geoip doors, two pointer digest doors, the channel resign, two release authorize doors, four store-entitlement doors, and two account plan doors)",
+ if seen != len(closedDoors) || seen != 61 {
+ t.Errorf("walked %d closed doors, want all %d (and 61 today: instance-token, three door-key doors, the routes door, instances-manifest, the app update policy, sidecars-manifest, the route-channel move, three instance update settings doors, two db replica doors, the forwarded db read, six fleets, four services, two email credentials, email pause, the build probe, the swap policy, the live tenancy read, the layout read, the activation-cancel door, nine system doors, three deployment-wide antivirus, three platform geoip doors, two pointer digest doors, the channel resign, two release authorize doors, four store-entitlement doors, two account plan doors, and two billing problem doors)",
seen, len(closedDoors))
}
}