console: billing webhook and hourly sync pass, not ready until the provider check passes (plans 6a)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
12 files changed,
+560
−18
cmd/console/main.go+3 −0internal/console/billingpass.go+95 −0internal/console/billingpass_test.go+85 −0internal/console/billingsync_test.go+36 −18internal/console/billingwebhook.go+81 −0internal/console/billingwebhook_test.go+179 −0internal/console/claim_invariant_fixtures_test.go+5 −0internal/console/claim_invariant_probes_nonapp_test.go+61 −0internal/console/claim_invariant_probes_worker_test.go+7 −0internal/console/claim_workers.go+1 −0internal/console/server.go+5 −0internal/console/testdata/claim-routes.txt+2 −0
diff --git a/cmd/console/main.go b/cmd/console/main.go| index fdf6414ed..423201609 100644 |
| --- a/cmd/console/main.go |
| +++ b/cmd/console/main.go |
| @@ -622,6 +622,9 @@ func serve() { |
| // account's limits record. A no-op with CARLOS_PLAN_CATALOG unset. |
| go srv.RunClaimWorker(context.Background(), "StartPlanLimitsPass") |
| go srv.RunClaimWorker(context.Background(), "StartPlanGracePass") |
| + // The billing sync (internal/console/billingpass.go, plans 6a): returns |
| + // at once with CARLOS_BILLING off. |
| + go srv.RunClaimWorker(context.Background(), "StartBillingSyncPass") |
| // The plans deployment marker (internal/console/plansmarker.go): once per |
| // start. Writes nothing on a deployment that never set a catalog. |
| go srv.RunClaimWorker(context.Background(), "PublishPlansMarker") |
diff --git a/internal/console/billingpass.go b/internal/console/billingpass.go| new file mode 100644 |
| index 000000000..6e99e0be9 |
| --- /dev/null |
| +++ b/internal/console/billingpass.go |
| @@ -0,0 +1,95 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "log" |
| + "time" |
| +) |
| + |
| +const ( |
| + // billingSyncInterval is how often every live subscription is re-read: |
| + // the net under a lost webhook. |
| + billingSyncInterval = time.Hour |
| + // billingCheckRetry is how often a failed readiness check is retried. |
| + billingCheckRetry = time.Minute |
| +) |
| + |
| +// billingSyncBatch is the hourly pass's page size; a test shrinks it. |
| +var billingSyncBatch = 200 |
| + |
| +// billingReadyCheck runs the provider's readiness check against the |
| +// configured book and price map, and marks billing ready when it passes. |
| +// Until then the webhook answers 503 and nothing syncs. |
| +func (s *Server) billingReadyCheck(ctx context.Context) error { |
| + cfg := s.billing.cfg |
| + if err := cfg.Provider.Check(ctx, cfg.Book, cfg.Prices); err != nil { |
| + return err |
| + } |
| + s.billing.ready.Store(true) |
| + return nil |
| +} |
| + |
| +// StartBillingSyncPass is the billing worker (plans 6a). With billing off |
| +// it returns at once. Otherwise it retries the readiness check every |
| +// billingCheckRetry until it passes, logging a failure only when its text |
| +// changes, then syncs every live subscription now and every |
| +// billingSyncInterval. |
| +func (s *Server) StartBillingSyncPass(ctx context.Context) { |
| + if s.billing == nil { |
| + return |
| + } |
| + last := "" |
| + for { |
| + err := s.billingReadyCheck(ctx) |
| + if err == nil { |
| + if last != "" { |
| + log.Printf("console: billing is ready") |
| + } |
| + break |
| + } |
| + if err.Error() != last { |
| + last = err.Error() |
| + log.Printf("console: billing not ready: %v", err) |
| + } |
| + select { |
| + case <-ctx.Done(): |
| + return |
| + case <-time.After(billingCheckRetry): |
| + } |
| + } |
| + t := time.NewTicker(billingSyncInterval) |
| + defer t.Stop() |
| + for { |
| + s.billingSyncPass(ctx, time.Now()) |
| + select { |
| + case <-ctx.Done(): |
| + return |
| + case <-t.C: |
| + } |
| + } |
| +} |
| + |
| +// billingSyncPass re-reads every live subscription, serially, paging by |
| +// account id. One account's error never stops the others. |
| +func (s *Server) billingSyncPass(ctx context.Context, now time.Time) { |
| + if s.billing == nil || !s.billing.ready.Load() { |
| + return |
| + } |
| + var after int64 |
| + for ctx.Err() == nil { |
| + page, err := s.store.LiveBillingAccounts(after, billingSyncBatch) |
| + if err != nil { |
| + log.Printf("console: billing sync pass: %v", err) |
| + return |
| + } |
| + for _, b := range page { |
| + after = b.AccountID |
| + if err := s.syncSubscription(ctx, b.Subscription, now); err != nil { |
| + log.Printf("console: billing sync pass: account %d: %v", b.AccountID, err) |
| + } |
| + } |
| + if len(page) < billingSyncBatch { |
| + return |
| + } |
| + } |
| +} |
diff --git a/internal/console/billingpass_test.go b/internal/console/billingpass_test.go| new file mode 100644 |
| index 000000000..c875d9dc2 |
| --- /dev/null |
| +++ b/internal/console/billingpass_test.go |
| @@ -0,0 +1,85 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func TestBillingSyncPassCatchesMissedEvents(t *testing.T) { |
| + bf := newBillingFixture(t) |
| + bf.ready(t) |
| + bf.put(bf.personalSub("sub_1", "active", map[string]int64{"apps": 1})) |
| + if err := bf.srv.syncSubscription(context.Background(), "sub_1", billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + // The quantity changes at the provider and the event is lost. |
| + bf.put(bf.personalSub("sub_1", "active", map[string]int64{"apps": 4})) |
| + bf.srv.billingSyncPass(context.Background(), billingNow.Add(time.Hour)) |
| + row, _ := bf.st.AccountPlan(bf.acct.ID) |
| + if row.Packs["apps"] != 4 { |
| + t.Fatalf("packs = %v, want apps 4", row.Packs) |
| + } |
| +} |
| + |
| +func TestBillingSyncPassPagesPastErrors(t *testing.T) { |
| + bf := newBillingFixture(t) |
| + bf.ready(t) |
| + old := billingSyncBatch |
| + billingSyncBatch = 1 |
| + t.Cleanup(func() { billingSyncBatch = old }) |
| + |
| + second := planAccount(t, bf.consoleFixture, 502) |
| + if err := bf.st.SetBillingCustomer(second.ID, "cus_2", billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + // The first account records a subscription the provider no longer has. |
| + if err := bf.st.PutBillingState(billingAccount{AccountID: bf.acct.ID, Subscription: "sub_gone", State: "paid", PaidPacks: map[string]int{}}); err != nil { |
| + t.Fatal(err) |
| + } |
| + sub := bf.personalSub("sub_2", "active", nil) |
| + sub.Customer, sub.Account = "cus_2", second.Sqid |
| + bf.put(sub) |
| + if err := bf.st.PutBillingState(billingAccount{AccountID: second.ID, Subscription: "sub_2", State: "pending", PaidPacks: map[string]int{}}); err != nil { |
| + t.Fatal(err) |
| + } |
| + bf.srv.billingSyncPass(context.Background(), billingNow) |
| + row, _ := bf.st.AccountPlan(second.ID) |
| + if row == nil || row.Plan != "personal" { |
| + t.Fatalf("second account not synced: %+v", row) |
| + } |
| +} |
| + |
| +func TestStartBillingSyncPassOffReturns(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + done := make(chan struct{}) |
| + go func() { fx.srv.StartBillingSyncPass(context.Background()); close(done) }() |
| + select { |
| + case <-done: |
| + case <-time.After(5 * time.Second): |
| + t.Fatal("StartBillingSyncPass with billing off did not return") |
| + } |
| +} |
| + |
| +func TestStartBillingSyncPassChecksThenSyncs(t *testing.T) { |
| + bf := newBillingFixture(t) |
| + bf.put(bf.personalSub("sub_1", "active", nil)) |
| + if err := bf.st.PutBillingState(billingAccount{AccountID: bf.acct.ID, Subscription: "sub_1", State: "pending", PaidPacks: map[string]int{}}); err != nil { |
| + t.Fatal(err) |
| + } |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + done := make(chan struct{}) |
| + go func() { bf.srv.StartBillingSyncPass(ctx); close(done) }() |
| + deadline := time.Now().Add(10 * time.Second) |
| + for bf.plan(t) != "personal" { |
| + if time.Now().After(deadline) { |
| + t.Fatal("the pass never synced") |
| + } |
| + time.Sleep(20 * time.Millisecond) |
| + } |
| + if !bf.srv.billing.ready.Load() { |
| + t.Error("synced without being ready") |
| + } |
| + cancel() |
| + <-done |
| +} |
diff --git a/internal/console/billingsync_test.go b/internal/console/billingsync_test.go| index 742ee4ecc..d307fa0be 100644 |
| --- a/internal/console/billingsync_test.go |
| +++ b/internal/console/billingsync_test.go |
| @@ -193,13 +193,10 @@ type billingFixture struct { |
| acct *Account |
| } |
| -// newBillingFixture is a console with the example catalog, the example |
| -// book, a full price map and a Fake provider, and one account bound to |
| -// customer cus_1. |
| -func newBillingFixture(t *testing.T) *billingFixture { |
| +// testBillingConfig is the example book over the example catalog, a full |
| +// price map and a Fake provider. |
| +func testBillingConfig(t *testing.T, cat *plans.Catalog) (*BillingConfig, *billingtest.Fake) { |
| t.Helper() |
| - fx := newConsoleFixture(t) |
| - cat := examplePlanCatalog(t) |
| book, err := plans.LoadPriceBook("../plans/testdata/example-pricebook.json", cat) |
| if err != nil { |
| t.Fatal(err) |
| @@ -223,10 +220,37 @@ func newBillingFixture(t *testing.T) *billingFixture { |
| t.Fatal(err) |
| } |
| fake := billingtest.New() |
| - cfg := &BillingConfig{Book: book, Prices: prices, Provider: fake} |
| - fx.srv.cfg.PlanCatalog = cat |
| - fx.srv.cfg.Billing = cfg |
| - fx.srv.billing = newBillingRuntime(cfg) |
| + return &BillingConfig{Book: book, Prices: prices, Provider: fake}, fake |
| +} |
| + |
| +// enableBilling switches billing on for srv over the example catalog. |
| +func enableBilling(t *testing.T, srv *Server) *billingtest.Fake { |
| + t.Helper() |
| + cat := examplePlanCatalog(t) |
| + cfg, fake := testBillingConfig(t, cat) |
| + srv.cfg.PlanCatalog = cat |
| + srv.cfg.Billing = cfg |
| + srv.billing = newBillingRuntime(cfg) |
| + return fake |
| +} |
| + |
| +// testPersonalSub is a Personal subscription on customer for account |
| +// sqid, in usd, with the given packs. |
| +func testPersonalSub(id, customer, sqid, status string, packs map[string]int64) *billing.Subscription { |
| + items := []billing.Item{{PriceID: testPriceID("example-v1/personal/usd"), Quantity: 1, Currency: "usd"}} |
| + for name, q := range packs { |
| + 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} |
| +} |
| + |
| +// newBillingFixture is a console with billing on (enableBilling) and one |
| +// account bound to customer cus_1. |
| +func newBillingFixture(t *testing.T) *billingFixture { |
| + t.Helper() |
| + fx := newConsoleFixture(t) |
| + fake := enableBilling(t, fx.srv) |
| acct := planAccount(t, fx, 501) |
| if err := fx.st.SetBillingCustomer(acct.ID, "cus_1", billingNow); err != nil { |
| t.Fatal(err) |
| @@ -234,15 +258,9 @@ func newBillingFixture(t *testing.T) *billingFixture { |
| return &billingFixture{consoleFixture: fx, fake: fake, acct: acct} |
| } |
| -// personalSub is an active Personal subscription on cus_1 for the |
| -// fixture's account, with the given packs. |
| +// personalSub is testPersonalSub on cus_1 for the fixture's account. |
| func (bf *billingFixture) personalSub(id, status string, packs map[string]int64) *billing.Subscription { |
| - items := []billing.Item{{PriceID: testPriceID("example-v1/personal/usd"), Quantity: 1, Currency: "usd"}} |
| - for name, q := range packs { |
| - items = append(items, billing.Item{PriceID: testPriceID("example-v1/pack/" + name + "/usd"), Quantity: q, Currency: "usd"}) |
| - } |
| - return &billing.Subscription{ID: id, Customer: "cus_1", Account: bf.acct.Sqid, ProviderStatus: status, State: billingStateFor(status), |
| - Currency: "usd", PeriodEnd: periodEnd, ItemsComplete: true, Items: items} |
| + return testPersonalSub(id, "cus_1", bf.acct.Sqid, status, packs) |
| } |
| func (bf *billingFixture) put(sub *billing.Subscription) { |
diff --git a/internal/console/billingwebhook.go b/internal/console/billingwebhook.go| new file mode 100644 |
| index 000000000..4d1f5ce6b |
| --- /dev/null |
| +++ b/internal/console/billingwebhook.go |
| @@ -0,0 +1,81 @@ |
| +package console |
| + |
| +import ( |
| + "errors" |
| + "io" |
| + "log" |
| + "net/http" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/billing" |
| +) |
| + |
| +// billingWebhookMaxBody bounds a delivery. |
| +const billingWebhookMaxBody = 1 << 20 |
| + |
| +// handleBillingWebhook is POST /billing/webhook (plans 6a). It is |
| +// unauthenticated like /api/ses/events: the provider's signature, checked |
| +// by Provider.ParseEvent, is its whole security model. The event only names |
| +// what to read; the plan follows the fresh read. The answer body is always |
| +// empty: the sender is the provider, not a person. |
| +// |
| +// - billing off: 404; |
| +// - not ready (the readiness check has not passed): 503, and the provider |
| +// redelivers; |
| +// - a body over 1 MiB, a refused signature or shape, or the other mode: 400; |
| +// - an ignored kind, or a checkout that made no subscription: 204; |
| +// - a subscription (or a checkout's subscription) synced: 204, or 503 on |
| +// a transient error. |
| +func (s *Server) handleBillingWebhook(w http.ResponseWriter, r *http.Request) { |
| + if s.billing == nil { |
| + w.WriteHeader(http.StatusNotFound) |
| + return |
| + } |
| + if !s.billing.ready.Load() { |
| + w.WriteHeader(http.StatusServiceUnavailable) |
| + return |
| + } |
| + r.Body = http.MaxBytesReader(w, r.Body, billingWebhookMaxBody) |
| + raw, err := io.ReadAll(r.Body) |
| + if err != nil { |
| + w.WriteHeader(http.StatusBadRequest) |
| + return |
| + } |
| + cfg := s.billing.cfg |
| + now := time.Now() |
| + ev, err := cfg.Provider.ParseEvent(raw, r.Header, now) |
| + if err != nil { |
| + w.WriteHeader(http.StatusBadRequest) |
| + return |
| + } |
| + if ev.LiveMode != cfg.LiveMode { |
| + log.Printf("console: billing webhook: event %s is in the other mode; refused", ev.ID) |
| + w.WriteHeader(http.StatusBadRequest) |
| + return |
| + } |
| + subscription := "" |
| + switch ev.Kind { |
| + case billing.EventSubscription: |
| + subscription = ev.Object |
| + case billing.EventCheckout: |
| + subscription, err = cfg.Provider.CheckoutSubscription(r.Context(), ev.Object) |
| + if errors.Is(err, billing.ErrNotFound) { |
| + subscription, err = "", nil |
| + } |
| + if err != nil { |
| + log.Printf("console: billing webhook: event %s: reading checkout: %v", ev.ID, err) |
| + w.WriteHeader(http.StatusServiceUnavailable) |
| + return |
| + } |
| + } |
| + if subscription == "" { |
| + w.WriteHeader(http.StatusNoContent) |
| + return |
| + } |
| + if err := s.syncSubscription(r.Context(), subscription, now); err != nil { |
| + log.Printf("console: billing webhook: event %s: %v", ev.ID, err) |
| + w.WriteHeader(http.StatusServiceUnavailable) |
| + return |
| + } |
| + w.WriteHeader(http.StatusNoContent) |
| +} |
diff --git a/internal/console/billingwebhook_test.go b/internal/console/billingwebhook_test.go| new file mode 100644 |
| index 000000000..36f06ce9f |
| --- /dev/null |
| +++ b/internal/console/billingwebhook_test.go |
| @@ -0,0 +1,179 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "net/http" |
| + "strings" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/billing" |
| +) |
| + |
| +func billingPost(t *testing.T, fx *consoleFixture, body string, signed bool) *http.Response { |
| + t.Helper() |
| + req, err := http.NewRequest(http.MethodPost, fx.ts.URL+"/billing/webhook", strings.NewReader(body)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + req.Header.Set("Content-Type", "application/json") |
| + if signed { |
| + req.Header.Set("Fake-Signature", "ok") |
| + } |
| + resp, err := fx.ts.Client().Do(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return resp |
| +} |
| + |
| +// billingDeliver posts one Fake event and returns the status, checking the |
| +// answer body is empty: the sender is the provider, not a person. |
| +func billingDeliver(t *testing.T, fx *consoleFixture, kind, object string, live bool) int { |
| + t.Helper() |
| + resp := billingPost(t, fx, fmt.Sprintf(`{"id":"evt_1","kind":%q,"object":%q,"live":%v}`, kind, object, live), true) |
| + defer resp.Body.Close() |
| + if b, _ := io.ReadAll(resp.Body); len(b) != 0 { |
| + t.Errorf("webhook answered a body: %q", b) |
| + } |
| + return resp.StatusCode |
| +} |
| + |
| +func (bf *billingFixture) ready(t *testing.T) { |
| + t.Helper() |
| + if err := bf.srv.billingReadyCheck(context.Background()); err != nil { |
| + t.Fatalf("ready check: %v", err) |
| + } |
| +} |
| + |
| +func (bf *billingFixture) plan(t *testing.T) string { |
| + t.Helper() |
| + row, err := bf.st.AccountPlan(bf.acct.ID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if row == nil { |
| + return "" |
| + } |
| + return row.Plan |
| +} |
| + |
| +func TestBillingWebhookOff(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + if got := billingDeliver(t, fx, "subscription", "sub_1", false); got != http.StatusNotFound { |
| + t.Fatalf("billing off: %d, want 404", got) |
| + } |
| + var n int |
| + if err := fx.st.db.QueryRow(`SELECT (SELECT COUNT(*) FROM billing_accounts) + (SELECT COUNT(*) FROM billing_problems) + (SELECT COUNT(*) FROM billing_price_books)`).Scan(&n); err != nil || n != 0 { |
| + t.Fatalf("billing rows with billing off: %d, %v", n, err) |
| + } |
| +} |
| + |
| +func TestBillingNotReadyAnswers503ThenRecovers(t *testing.T) { |
| + bf := newBillingFixture(t) |
| + bf.put(bf.personalSub("sub_1", "active", nil)) |
| + bf.fake.CheckErr = errors.New("stripe unreachable") |
| + if err := bf.srv.billingReadyCheck(context.Background()); err == nil { |
| + t.Fatal("ready check passed with the provider failing") |
| + } |
| + if got := billingDeliver(t, bf.consoleFixture, "subscription", "sub_1", false); got != http.StatusServiceUnavailable { |
| + t.Fatalf("not ready: %d, want 503", got) |
| + } |
| + if p := bf.plan(t); p != "" { |
| + t.Fatalf("plan changed while not ready: %q", p) |
| + } |
| + bf.fake.CheckErr = nil |
| + bf.ready(t) |
| + if got := billingDeliver(t, bf.consoleFixture, "subscription", "sub_1", false); got != http.StatusNoContent { |
| + t.Fatalf("ready: %d, want 204", got) |
| + } |
| + if p := bf.plan(t); p != "personal" { |
| + t.Fatalf("plan = %q, want personal", p) |
| + } |
| +} |
| + |
| +func TestBillingWebhookRefusesBadEvents(t *testing.T) { |
| + bf := newBillingFixture(t) |
| + bf.ready(t) |
| + resp := billingPost(t, bf.consoleFixture, `{"id":"evt_1","kind":"subscription","object":"sub_1","live":false}`, false) |
| + resp.Body.Close() |
| + if resp.StatusCode != http.StatusBadRequest { |
| + t.Errorf("unsigned: %d, want 400", resp.StatusCode) |
| + } |
| + if got := billingDeliver(t, bf.consoleFixture, "subscription", "sub_1", true); got != http.StatusBadRequest { |
| + t.Errorf("live event on a test console: %d, want 400", got) |
| + } |
| + big := `{"id":"evt_1","kind":"ignored","object":"","live":false,"pad":"` + strings.Repeat("a", 1<<20) + `"}` |
| + resp = billingPost(t, bf.consoleFixture, big, true) |
| + resp.Body.Close() |
| + if resp.StatusCode != http.StatusBadRequest { |
| + t.Errorf("over 1 MiB: %d, want 400", resp.StatusCode) |
| + } |
| +} |
| + |
| +func TestBillingWebhookIgnoredKinds(t *testing.T) { |
| + bf := newBillingFixture(t) |
| + bf.ready(t) |
| + bf.fake.Calls = 0 |
| + if got := billingDeliver(t, bf.consoleFixture, "ignored", "", false); got != http.StatusNoContent { |
| + t.Fatalf("ignored: %d, want 204", got) |
| + } |
| + if bf.fake.Calls != 0 { |
| + t.Fatalf("ignored event made %d provider calls", bf.fake.Calls) |
| + } |
| +} |
| + |
| +func TestBillingWebhookCheckoutSyncsItsSubscription(t *testing.T) { |
| + bf := newBillingFixture(t) |
| + bf.ready(t) |
| + bf.put(bf.personalSub("sub_1", "active", nil)) |
| + bf.fake.Checkouts["cs_1"] = "sub_1" |
| + if got := billingDeliver(t, bf.consoleFixture, "checkout", "cs_1", false); got != http.StatusNoContent { |
| + t.Fatalf("checkout: %d, want 204", got) |
| + } |
| + if p := bf.plan(t); p != "personal" { |
| + t.Fatalf("plan = %q", p) |
| + } |
| + // A checkout that made no subscription, or that the provider does |
| + // not know: nothing to do. |
| + for _, cs := range []string{"cs_none"} { |
| + if got := billingDeliver(t, bf.consoleFixture, "checkout", cs, false); got != http.StatusNoContent { |
| + t.Errorf("%s: %d, want 204", cs, got) |
| + } |
| + } |
| +} |
| + |
| +func TestBillingWebhookTransientIs503(t *testing.T) { |
| + bf := newBillingFixture(t) |
| + bf.ready(t) |
| + bf.put(bf.personalSub("sub_1", "active", nil)) |
| + bf.fake.Err = errors.New("timeout") |
| + if got := billingDeliver(t, bf.consoleFixture, "subscription", "sub_1", false); got != http.StatusServiceUnavailable { |
| + t.Fatalf("transient: %d, want 503", got) |
| + } |
| +} |
| + |
| +func TestStaleEventAppliesTheFreshRead(t *testing.T) { |
| + bf := newBillingFixture(t) |
| + bf.ready(t) |
| + bf.put(bf.personalSub("sub_1", "active", nil)) |
| + if got := billingDeliver(t, bf.consoleFixture, "subscription", "sub_1", false); got != http.StatusNoContent { |
| + t.Fatal(got) |
| + } |
| + if p := bf.plan(t); p != "personal" { |
| + t.Fatalf("plan = %q", p) |
| + } |
| + bf.put(bf.personalSub("sub_1", "canceled", nil)) |
| + // The old "updated" event, delivered again late: the fresh read wins. |
| + if got := billingDeliver(t, bf.consoleFixture, "subscription", "sub_1", false); got != http.StatusNoContent { |
| + t.Fatal(got) |
| + } |
| + if p := bf.plan(t); p != "free" { |
| + t.Fatalf("plan = %q, want free", p) |
| + } |
| + if b, _ := bf.st.BillingAccount(bf.acct.ID); b.State != billing.StateEnded { |
| + t.Errorf("billing state = %q", b.State) |
| + } |
| +} |
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go| index ef1c6e510..11a85aec0 100644 |
| --- a/internal/console/claim_invariant_fixtures_test.go |
| +++ b/internal/console/claim_invariant_fixtures_test.go |
| @@ -1249,6 +1249,10 @@ var claimFixtures = map[string]claimFixture{ |
| }, |
| }}, |
| + // The billing webhook re-reads a subscription and writes the account's |
| + // plan row and billing state (plans 6a). |
| + "route POST /billing/webhook": claimNonApp("re-reads a billing subscription and writes the account's plan row, billing state and billing problems; names no app"), |
| + |
| // ---- POST: CLI, account and deployment level ---- |
| "route POST /accounts/new": claimNonApp("creates an account and its owner membership"), |
| "route POST /api/cli/accounts/{account}/store/apply": claimNonApp("applies for the account's storage entitlement"), |
| @@ -1972,6 +1976,7 @@ var claimFixtures = map[string]claimFixture{ |
| "worker StartHostReports": claimNonApp("this console's census report (status/consoles) and roster activation release"), |
| "worker StartInfraPass": claimNonApp("the deployment's infrastructure inventory snapshot"), |
| "worker StartPlanGracePass": claimNonApp("an account's plan cap warnings and grace clocks in plan_cap_state, keyed by account; names no app"), |
| + "worker StartBillingSyncPass": claimNonApp("checks the billing provider, then re-reads live subscriptions and writes account plan rows and billing state; names no app"), |
| "worker StartPlanLimitsPass": claimNonApp("account plan rows and their limits records under accounts/<sqid>/limits.json; names no app"), |
| "worker PublishPlansMarker": claimNonApp("the plans deployment marker (control/plans.json): whether boxes read limits; names no app"), |
| "worker StartClaimRecoveryPass": {door: &claimDoor{ |
diff --git a/internal/console/claim_invariant_probes_nonapp_test.go b/internal/console/claim_invariant_probes_nonapp_test.go| index 7bd9fda53..78cddd8cf 100644 |
| --- a/internal/console/claim_invariant_probes_nonapp_test.go |
| +++ b/internal/console/claim_invariant_probes_nonapp_test.go |
| @@ -9,6 +9,7 @@ import ( |
| "context" |
| "encoding/json" |
| "errors" |
| + "fmt" |
| "github.com/carlosframework/platform/internal/hostactors" |
| "net/http" |
| "net/url" |
| @@ -16,6 +17,7 @@ import ( |
| "testing" |
| "time" |
| + "github.com/carlosframework/platform/internal/billing" |
| "github.com/carlosframework/platform/internal/economics" |
| "github.com/carlosframework/platform/internal/geoip" |
| "github.com/carlosframework/platform/internal/infraview" |
| @@ -680,6 +682,14 @@ var claimNonAppProbes = map[string]claimProbe{ |
| return "" |
| }, |
| }, |
| + "route POST /billing/webhook": { |
| + setup: claimBillingWorld, |
| + do: claimBillingWebhookReply, |
| + status: http.StatusNoContent, |
| + effect: func(t *testing.T, cx *claimCase, r claimReply) string { |
| + return claimBillingPlanIs(t, cx, "personal") |
| + }, |
| + }, |
| "route POST /api/cli/accounts/{account}/plan": { |
| setup: func(t *testing.T, cx *claimCase) { cx.srv.cfg.PlanCatalog = examplePlanCatalog(t) }, |
| do: claimAPIReply(http.MethodPost, "/api/cli/accounts/bab/plan", `{"plan":"personal","reason":"census"}`), |
| @@ -944,3 +954,54 @@ var claimNonAppProbes = map[string]claimProbe{ |
| }, |
| }, |
| } |
| + |
| +// claimBillingWorld switches billing on with a Fake provider, binds bab to |
| +// customer cus_claim, gives it an active Personal subscription the sync |
| +// pass will find, and marks billing ready. |
| +func claimBillingWorld(t *testing.T, cx *claimCase) { |
| + t.Helper() |
| + fake := enableBilling(t, cx.srv) |
| + acct, err := cx.srv.store.AccountBySqid("bab") |
| + if err != nil || acct == nil { |
| + t.Fatalf("bab: %v", err) |
| + } |
| + if err := cx.srv.store.SetBillingCustomer(acct.ID, "cus_claim", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := cx.srv.store.PutBillingState(billingAccount{AccountID: acct.ID, Subscription: "sub_claim", State: billing.StatePending, PaidPacks: map[string]int{}}); err != nil { |
| + t.Fatal(err) |
| + } |
| + fake.Subs["sub_claim"] = testPersonalSub("sub_claim", "cus_claim", "bab", "active", nil) |
| + cx.srv.billing.ready.Store(true) |
| +} |
| + |
| +// claimBillingWebhookReply delivers a signed Fake event for sub_claim. |
| +func claimBillingWebhookReply(t *testing.T, cx *claimCase) claimReply { |
| + t.Helper() |
| + req, err := http.NewRequest(http.MethodPost, cx.ts.URL+"/billing/webhook", |
| + strings.NewReader(`{"id":"evt_claim","kind":"subscription","object":"sub_claim","live":false}`)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + req.Header.Set("Fake-Signature", "ok") |
| + resp, err := cx.ts.Client().Do(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer resp.Body.Close() |
| + return claimReply{Status: resp.StatusCode} |
| +} |
| + |
| +// claimBillingPlanIs reports "" when bab's plan row says plan, written by |
| +// billing. |
| +func claimBillingPlanIs(t *testing.T, cx *claimCase, plan string) string { |
| + acct, err := cx.srv.store.AccountBySqid("bab") |
| + if err != nil || acct == nil { |
| + return "no bab account" |
| + } |
| + row, err := cx.srv.store.AccountPlan(acct.ID) |
| + if err != nil || row == nil || row.Plan != plan || row.Source != PlanSourceBilling { |
| + return fmt.Sprintf("bab's plan row is not %s from billing: %+v", plan, row) |
| + } |
| + return "" |
| +} |
diff --git a/internal/console/claim_invariant_probes_worker_test.go b/internal/console/claim_invariant_probes_worker_test.go| index 65f1ef5d9..128a935ff 100644 |
| --- a/internal/console/claim_invariant_probes_worker_test.go |
| +++ b/internal/console/claim_invariant_probes_worker_test.go |
| @@ -219,6 +219,13 @@ var claimWorkerProbes = map[string]claimProbe{ |
| return "" |
| }, |
| }, |
| + "worker StartBillingSyncPass": { |
| + setup: claimBillingWorld, |
| + do: claimWorkerReply("StartBillingSyncPass"), |
| + effect: func(t *testing.T, cx *claimCase, r claimReply) string { |
| + return claimBillingPlanIs(t, cx, "personal") |
| + }, |
| + }, |
| "worker StartPlanLimitsPass": { |
| setup: func(t *testing.T, cx *claimCase) { cx.srv.cfg.PlanCatalog = examplePlanCatalog(t) }, |
| do: claimWorkerReply("StartPlanLimitsPass"), |
diff --git a/internal/console/claim_workers.go b/internal/console/claim_workers.go| index 1f4c6d7d6..67c74a07c 100644 |
| --- a/internal/console/claim_workers.go |
| +++ b/internal/console/claim_workers.go |
| @@ -16,6 +16,7 @@ func (s *Server) registerClaimWorkers() { |
| "StartExpiryPass": s.StartExpiryPass, |
| "StartPlanLimitsPass": s.StartPlanLimitsPass, |
| "StartPlanGracePass": s.StartPlanGracePass, |
| + "StartBillingSyncPass": s.StartBillingSyncPass, |
| "PublishPlansMarker": s.PublishPlansMarker, |
| "StartRunSweep": s.StartRunSweep, |
| "StartSeedsPass": s.StartSeedsPass, |
diff --git a/internal/console/server.go b/internal/console/server.go| index 39d814427..95e0d5501 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -1666,6 +1666,11 @@ func NewServer(cfg Config, st *Store) (*Server, error) { |
| // label-aware SigningCertURL host check, and a verified signature, |
| // all run before any field of the message is trusted. |
| s.registerRoute("POST /api/ses/events", s.handleSESEvents) |
| + // Billing webhook (billingwebhook.go, plans 6a): UNAUTHENTICATED for |
| + // the same reason; the provider's signature is checked before anything |
| + // in the body is used, and the body only names what to re-read. Always |
| + // registered: with billing off it answers 404. |
| + s.registerRoute("POST /billing/webhook", s.handleBillingWebhook) |
| // Catch up on accounts minted outside this database — `carlos accounts |
| // create` writes the bucket manifest and the registry row and never opens |
| // console state. Startup is the natural place: the account switcher, the |
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt| index a526dc00c..40f23e091 100644 |
| --- a/internal/console/testdata/claim-routes.txt |
| +++ b/internal/console/testdata/claim-routes.txt |
| @@ -266,6 +266,7 @@ route POST /api/cli/system/rollback |
| route POST /api/cli/system/seeds-floor |
| route POST /api/cli/system/update |
| route POST /api/ses/events |
| +route POST /billing/webhook |
| route POST /auth/cli/accounts |
| route POST /auth/cli/approve |
| route POST /auth/cli/poll |
| @@ -297,6 +298,7 @@ worker PublishMovesConsole |
| worker PublishPlansMarker |
| worker ReportApexSquats |
| worker StartAlertWatcher |
| +worker StartBillingSyncPass |
| worker StartClaimRecoveryPass |
| worker StartDoorKeyResign |
| worker StartEconomicsPass |