billing: background sync for the Billing pages, with a syncing state
Every Billing visit re-read last month's usage costs from the bucket (1,302 reads on the flagship, 3.9 s) plus six bill reads. A background billing sync now gathers those inputs; the pages read only its stored result and the local database. Pages show when they last synced, a Sync now button, and start a sync themselves when the figures are over 10 minutes old, with a progress line. Single-flight, debounced, time-limited; the "Not available yet" gate is unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Squashed from billing-overview-speed into main.
27 files changed,
+1,146
−44
approved_billing_dashboard_copy_test.go+6 −6docs/parity.md+1 −1docs/superpowers/plans/2026-11-09-billing-dashboard-2-copy.md+19 −0internal/console/billingmoneypass.go+3 −0internal/console/billingpass.go+5 −5internal/console/claim_invariant_fixtures_test.go+2 −0internal/console/claim_invariant_probes_nonapp_test.go+18 −0internal/console/claim_invariant_probes_read_test.go+6 −5internal/console/opbilling.go+28 −16internal/console/opbilling_copy.go+29 −0internal/console/opbilling_money.go+13 −5internal/console/opbilling_money_test.go+10 −1internal/console/opbilling_sync.go+464 −0internal/console/opbilling_sync_test.go+422 −0internal/console/opbilling_test.go+3 −3internal/console/platformcost.go+2 −0internal/console/routedecls.go+5 −0internal/console/server.go+7 −0internal/console/static/ops.css+7 −0internal/console/templates/ops_billing.html+66 −0internal/console/templates/ops_billing_accounts.html+1 −0internal/console/templates/ops_billing_payments.html+1 −0internal/console/testdata/claim-routes.txt+2 −0internal/console/testdata/perf-budgets.txt+2 −0internal/provision/billing_overview_speed_census_test.go+22 −0internal/provision/plan9_b8_census_test.go+1 −1parity/parity.tsv+1 −1
CI failed — run details
diff --git a/approved_billing_dashboard_copy_test.go b/approved_billing_dashboard_copy_test.go| index cd35a4fb8..bb2405de1 100644 |
| --- a/approved_billing_dashboard_copy_test.go |
| +++ b/approved_billing_dashboard_copy_test.go |
| @@ -101,7 +101,7 @@ func TestApprovedBillingDashboardCopy(t *testing.T) { |
| // The copy gate of the billing dashboard plan 2, the operator Billing pages. |
| // The record is docs/superpowers/plans/2026-11-09-billing-dashboard-2-copy.md: |
| -// BDP-1 to BDP-150, whose files are relative to internal/console/, and the |
| +// BDP-1 to BDP-162, whose files are relative to internal/console/, and the |
| // two Plan 1 rows it carried to review again (BDC-20, BDC-36). |
| // |
| // - TestBillingPagesCopyInventory: the record names exactly |
| @@ -118,11 +118,11 @@ const billingPagesCopyRoot = "internal/console" |
| var billingPagesCopyIDPattern = regexp.MustCompile(`^(BDP|BDC)-[0-9]+$`) |
| -// billingPagesCopyIDs is the record's inventory, pinned: BDP-1 to BDP-150, |
| +// billingPagesCopyIDs is the record's inventory, pinned: BDP-1 to BDP-162, |
| // then BDC-20 and BDC-36. |
| var billingPagesCopyIDs = func() []string { |
| - ids := make([]string, 0, 152) |
| - for i := 1; i <= 150; i++ { |
| + ids := make([]string, 0, 164) |
| + for i := 1; i <= 162; i++ { |
| ids = append(ids, "BDP-"+strconv.Itoa(i)) |
| } |
| return append(ids, "BDC-20", "BDC-36") |
| @@ -132,8 +132,8 @@ var billingPagesCopyIDs = func() []string { |
| // since Task 2 wrote each row's constant in opbilling_copy.go. Later tasks |
| // only use the constants. |
| var billingPagesCopyBuilt = func() []string { |
| - ids := make([]string, 0, 150) |
| - for i := 1; i <= 150; i++ { |
| + ids := make([]string, 0, 162) |
| + for i := 1; i <= 162; i++ { |
| ids = append(ids, "BDP-"+strconv.Itoa(i)) |
| } |
| return ids |
diff --git a/docs/parity.md b/docs/parity.md| index d2f91631a..7e830ca70 100644 |
| --- a/docs/parity.md |
| +++ b/docs/parity.md |
| @@ -394,7 +394,7 @@ Discussion #742. |
| | op-accounts-plan | operator | `accounts plan` | `GET /fleet/economics/accounts`<br>`/fleet/economics/tier` | The console sets the pool tier only. | |
| | op-accounts-migrate | operator | `accounts migrate` | | A one-off migration of an app's objects. | |
| | op-billing | operator | `billing problems`<br>`billing close`<br>`billing house` | | Billing problems and house accounts. | |
| -| op-billing-pages | operator | | `/fleet/billing`<br>`/fleet/billing/accounts`<br>`/fleet/billing/payments` | The operator Billing pages: the overview, paying accounts and payments. | |
| +| op-billing-pages | operator | | `/fleet/billing`<br>`/fleet/billing/accounts`<br>`/fleet/billing/payments`<br>`/fleet/billing/sync`<br>`/fleet/billing/sync/status` | The operator Billing pages: the overview, paying accounts and payments, and their background sync. | |
| | op-instance-policy | operator | `apps set [--egress-allow,--size]`<br>`instances set [--size]` | | Instance policy is set by an operator. | |
| | op-upstreams | operator | `instances set-upstreams`<br>`instances create [--addr]` | | TCP backends are set by an operator. | |
| | op-digests | operator | `channels digests [on, off]` | | The digest signing switch. | |
diff --git a/docs/superpowers/plans/2026-11-09-billing-dashboard-2-copy.md b/docs/superpowers/plans/2026-11-09-billing-dashboard-2-copy.md| index e07667d40..5a21e2876 100644 |
| --- a/docs/superpowers/plans/2026-11-09-billing-dashboard-2-copy.md |
| +++ b/docs/superpowers/plans/2026-11-09-billing-dashboard-2-copy.md |
| @@ -244,6 +244,25 @@ BDP-80 to BDP-82 follow the plan's name and a comma (`Personal, first year`) and |
| | BDP-149 | opbilling_copy.go (overview and accounts page, under the plan name) | %s seats | approved | |
| | BDP-150 | opbilling_copy.go (overview and accounts page, under the plan name, after BDP-149 joined by a comma) | %s packs | approved | |
| +## Billing sync line |
| + |
| +Added on branch `billing-overview-speed` (2026-11-10): the Billing pages render from what the background billing sync stored and say when it ran. Approved unchanged by Paul in copy review `7pxsdmchqyyn6haqatm7nx3o6a`. |
| + |
| +| id | file | text | status | |
| +|---|---|---|---| |
| +| BDP-151 | opbilling_copy.go (every billing page, under the subhead, beside a spinner while a sync runs, before its first step) | Syncing billing… | approved | |
| +| BDP-152 | opbilling_copy.go (every billing page, the same line once a step runs: the step name, then step n of total) | Syncing billing… %s · %s of %s | approved | |
| +| BDP-153 | opbilling_copy.go (the sync line's step name: re-reading every subscription (hourly sync only)) | Subscriptions | approved | |
| +| BDP-154 | opbilling_copy.go (the sync line's step name: recording payments, refunds and fees) | Payments | approved | |
| +| BDP-155 | opbilling_copy.go (the sync line's step name: fetching the ECB euro rates) | Exchange rates | approved | |
| +| BDP-156 | opbilling_copy.go (the sync line's step name: writing today's daily record) | Daily record | approved | |
| +| BDP-157 | opbilling_copy.go (the sync line's step name: last month's usage costs and the AWS bills) | Costs | approved | |
| +| BDP-158 | opbilling_copy.go (the sync progress bar's accessible name, not shown) | Billing sync progress | approved | |
| +| BDP-159 | opbilling_copy.go (every billing page, under the subhead when no sync runs; %s is the age, like 12m ago) | Synced %s | approved | |
| +| BDP-160 | opbilling_copy.go (every billing page, under the subhead before the console's first sync) | Not synced since the console started. | approved | |
| +| BDP-161 | opbilling_copy.go (every billing page, the button beside the Synced line) | Sync now | approved | |
| +| BDP-162 | opbilling_copy.go (beside Not available yet on cost figures before the first sync) | Costs show after the first billing sync. | approved | |
| + |
| ## Plan 1 follow-ups |
| Two rows of Plan 1's record (`2026-11-09-billing-dashboard-1-copy.md`), parked by Plan 1's controller for this review. They keep their ids; files are from the repo root. When approved, the new text replaces the row in Plan 1's record. |
diff --git a/internal/console/billingmoneypass.go b/internal/console/billingmoneypass.go| index 08a6363ed..54670e2fd 100644 |
| --- a/internal/console/billingmoneypass.go |
| +++ b/internal/console/billingmoneypass.go |
| @@ -40,14 +40,17 @@ func (s *Server) billingMoneyPass(ctx context.Context, now time.Time) { |
| return |
| } |
| ctx = s.billingClock(ctx) |
| + s.billingSync.enter(billingStepPayments) |
| if err := s.reconcilePayments(ctx, now); err != nil { |
| log.Printf("console: billing money pass: payments: %v", err) |
| jobFailed(ctx, fmt.Errorf("billing money pass: payments: %w", err)) |
| } |
| + s.billingSync.enter(billingStepRates) |
| if err := s.billingRatesPass(ctx, now); err != nil { |
| log.Printf("console: billing money pass: euro rates: %v", err) |
| jobFailed(ctx, fmt.Errorf("billing money pass: euro rates: %w", err)) |
| } |
| + s.billingSync.enter(billingStepSnapshot) |
| if err := s.billingSnapshotPass(ctx, now); err != nil { |
| log.Printf("console: billing money pass: daily snapshot: %v", err) |
| jobFailed(ctx, fmt.Errorf("billing money pass: daily snapshot: %w", err)) |
diff --git a/internal/console/billingpass.go b/internal/console/billingpass.go| index 10dc234b3..12c15dd02 100644 |
| --- a/internal/console/billingpass.go |
| +++ b/internal/console/billingpass.go |
| @@ -99,12 +99,12 @@ func (s *Server) StartBillingSyncPass(ctx context.Context) { |
| } |
| } |
| -// billingRound is one run of the billing worker: the subscription sync, |
| -// then the money pass, whose failures fail the job but never undo or stop |
| -// the sync. |
| +// billingRound is one run of the billing worker, as one billing sync |
| +// (opbilling_sync.go): the subscription sync, then the money pass, whose |
| +// failures fail the job but never undo or stop the sync, then the Billing |
| +// pages' cost inputs when they need it. It waits for a sync a page started. |
| func (s *Server) billingRound(ctx context.Context, now time.Time) error { |
| - s.billingSyncPass(ctx, now) |
| - s.billingMoneyPass(ctx, now) |
| + s.billingSyncHourly(ctx, now) |
| return nil |
| } |
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go| index a1af3c39c..e6282e05d 100644 |
| --- a/internal/console/claim_invariant_fixtures_test.go |
| +++ b/internal/console/claim_invariant_fixtures_test.go |
| @@ -743,6 +743,8 @@ var claimFixtures = map[string]claimFixture{ |
| "route /fleet/billing": claimRead("operator billing view; reads billing records; names no app"), |
| "route /fleet/billing/accounts": claimRead("operator billing view; reads billing records; names no app"), |
| "route /fleet/billing/payments": claimRead("operator billing view; reads billing records; names no app"), |
| + "route /fleet/billing/sync": claimNonApp("starts the operator billing sync: Stripe money records and the cost inputs; names no app"), |
| + "route /fleet/billing/sync/status": claimRead("operator billing sync status from memory; writes nothing; names no app"), |
| "route /fleet/architecture/refresh": claimNonApp("rebuilds the deployment map snapshot from box and edge files; no app object or row"), |
| "route /fleet/economics/bill": claimNonApp("operator bill form, stored under economics/"), |
| "route /fleet/economics/scenarios": claimNonApp("operator pricing scenarios, stored under economics/"), |
diff --git a/internal/console/claim_invariant_probes_nonapp_test.go b/internal/console/claim_invariant_probes_nonapp_test.go| index 09d9e3fe5..fabae867d 100644 |
| --- a/internal/console/claim_invariant_probes_nonapp_test.go |
| +++ b/internal/console/claim_invariant_probes_nonapp_test.go |
| @@ -486,6 +486,24 @@ var claimNonAppProbes = map[string]claimProbe{ |
| return "" |
| }, |
| }, |
| + "route /fleet/billing/sync": { |
| + setup: claimBillingWorld, |
| + do: claimFormReply("/fleet/billing/sync"), |
| + status: http.StatusSeeOther, loc: "/fleet/billing", |
| + effect: func(t *testing.T, cx *claimCase, r claimReply) string { |
| + deadline := time.Now().Add(30 * time.Second) |
| + for cx.srv.billingSync.now().Running && time.Now().Before(deadline) { |
| + time.Sleep(5 * time.Millisecond) |
| + } |
| + if n := cx.srv.billingSync.now(); n.Running || n.Finished.IsZero() { |
| + return "no billing sync ran" |
| + } |
| + if cx.srv.billingSync.storedCosts() == nil { |
| + return "the sync stored no cost inputs" |
| + } |
| + return "" |
| + }, |
| + }, |
| "route /fleet/economics/tier": { |
| do: claimFormReply("/fleet/economics/tier", "account", "bab", "tier", "pool"), |
| status: http.StatusSeeOther, loc: "/fleet/economics/accounts", |
diff --git a/internal/console/claim_invariant_probes_read_test.go b/internal/console/claim_invariant_probes_read_test.go| index c52400b38..f07a4431f 100644 |
| --- a/internal/console/claim_invariant_probes_read_test.go |
| +++ b/internal/console/claim_invariant_probes_read_test.go |
| @@ -177,11 +177,12 @@ func claimInvitePageProbe() claimProbe { |
| var claimReadProbes = map[string]claimProbe{ |
| "route GET /accounts": claimPageRead(nil, "/accounts", `id="index-title">Accounts</h1>`), |
| // ---- methodless ---- |
| - "route /api/economics/backhaul": claimAPIRead(nil, "/api/economics/backhaul", `"period"`, `"accounts"`), |
| - "route /fleet/architecture": claimPageRead(nil, "/fleet/architecture", "<h1>Architecture</h1>"), |
| - "route /fleet/billing": claimPageRead(claimBillingWorld, "/fleet/billing", "<h1>"+billCopyRail+"</h1>"), |
| - "route /fleet/billing/accounts": claimPageRead(claimBillingWorld, "/fleet/billing/accounts", "<h1>"+billCopyAccounts+"</h1>"), |
| - "route /fleet/billing/payments": claimPageRead(claimBillingWorld, "/fleet/billing/payments", "<h1>"+billCopyPaymentsTitle+"</h1>"), |
| + "route /api/economics/backhaul": claimAPIRead(nil, "/api/economics/backhaul", `"period"`, `"accounts"`), |
| + "route /fleet/architecture": claimPageRead(nil, "/fleet/architecture", "<h1>Architecture</h1>"), |
| + "route /fleet/billing": claimPageRead(claimBillingWorld, "/fleet/billing", "<h1>"+billCopyRail+"</h1>"), |
| + "route /fleet/billing/accounts": claimPageRead(claimBillingWorld, "/fleet/billing/accounts", "<h1>"+billCopyAccounts+"</h1>"), |
| + "route /fleet/billing/payments": claimPageRead(claimBillingWorld, "/fleet/billing/payments", "<h1>"+billCopyPaymentsTitle+"</h1>"), |
| + "route /fleet/billing/sync/status": claimPageRead(claimBillingWorld, "/fleet/billing/sync/status", `"syncing":`), |
| // ---- browser pages ---- |
| "route GET /a/{sqid}/apps/new": claimPageRead(nil, "/a/bab/apps/new", `action="/a/bab/apps/new"`), |
diff --git a/internal/console/opbilling.go b/internal/console/opbilling.go| index 4132f6dcb..e099a8e74 100644 |
| --- a/internal/console/opbilling.go |
| +++ b/internal/console/opbilling.go |
| @@ -471,9 +471,15 @@ func (s *Server) billingTestMode() bool { return !s.billing.cfg.LiveMode } |
| // billingPage is the page a billing page renders with: under the Billing |
| // rail item, titled title. |
| -func (s *Server) billingPage(addr, raw, title string) page { |
| +// |
| +// sync is the billing sync as the handler saw it BEFORE reading any of the |
| +// page's inputs, so the sync line (and its generation, which the page's |
| +// script compares) never claims a sync whose results the page missed. |
| +func (s *Server) billingPage(addr, raw, title string, sync billingSyncNow) page { |
| p := s.opPage(addr, raw, "billing") |
| p.Title = title |
| + view := billingSyncViewOf(sync, time.Now()) |
| + p.BillingSync = &view |
| return p |
| } |
| @@ -483,13 +489,14 @@ func (s *Server) handleOpBilling(w http.ResponseWriter, r *http.Request) { |
| if !ok { |
| return |
| } |
| + sync := s.billingSync.now() // before any input: see billingPage |
| in, err := s.opBillingInputs(r.Context(), s.now()) |
| if err != nil { |
| log.Printf("console: billing overview: %v", err) |
| http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) |
| return |
| } |
| - p := s.billingPage(addr, raw, billCopyRail) |
| + p := s.billingPage(addr, raw, billCopyRail, sync) |
| v := buildOpBillingView(in) |
| v.Header = opHeader{Title: billCopyRail, Sub: fmt.Sprintf(billCopyOverviewSub, s.brandName())} |
| v.TestMode = s.billingTestMode() |
| @@ -502,7 +509,8 @@ func (s *Server) handleOpBilling(w http.ResponseWriter, r *http.Request) { |
| // snapshots for the ARR chart), each month's platform cost, six months of |
| // payments with fee rows (the money table and this month), the newest |
| // payments and the funnel. The gate is Rev.Inputs with the cost inputs |
| -// filled in. |
| +// filled in. The cost inputs are the last billing sync's; nothing here |
| +// reads the bucket. |
| func (s *Server) opBillingInputs(ctx context.Context, now time.Time) (opBillingInput, error) { |
| today := opMidnight(now) |
| in, err := s.opBillingAccountInputs(ctx, now, today.AddDate(0, 0, -(opBillingChartDays-1))) |
| @@ -510,14 +518,12 @@ func (s *Server) opBillingInputs(ctx context.Context, now time.Time) (opBillingI |
| return opBillingInput{}, err |
| } |
| monthStart := today.AddDate(0, 0, 1-today.Day()) |
| - months := make([]string, 6) |
| - for i := range months { |
| - months[i] = monthStart.AddDate(0, -i, 0).Format("2006-01") |
| - } |
| + months := billingCostMonthsAt(now) |
| + costs := s.billingSync.storedCosts() |
| in.Gate.PlatformOK = map[string]bool{} |
| in.Platform = map[string]platformCost{} |
| for _, m := range months { |
| - pc := s.platformCostEUR(ctx, m, in.Rates) |
| + pc := s.platformCostEUR(costs, m, in.Rates) |
| in.Platform[m], in.Gate.PlatformOK[m] = pc, pc.OK |
| } |
| all, _, err := s.store.Payments(paymentFilter{From: monthStart.AddDate(0, -5, 0), To: now, Kind: "all"}) |
| @@ -543,9 +549,9 @@ func (s *Server) opBillingInputs(ctx context.Context, now time.Time) (opBillingI |
| // stored snapshots from snapsFrom to today, that month's payments (Kind |
| // "": no fee rows, for once-offs) and account rows (Earned and Covered |
| // through accountEarnings, which needs the month's snapshots: snapsFrom is |
| -// at or before its first day), its Economics read (an error is logged; |
| -// econComplete decides whether costs show, and only a view of |
| -// in.LastMonth can) and the nearest caps. The gate is Rev.Inputs with |
| +// at or before its first day), its Economics view as the last billing sync |
| +// gathered it (econComplete decides whether costs show, and only a view of |
| +// in.LastMonth can; before the first sync it refuses) and the nearest caps. The gate is Rev.Inputs with |
| // EconomicsComplete. |
| func (s *Server) opBillingAccountInputs(ctx context.Context, now, snapsFrom time.Time) (opBillingInput, error) { |
| rev, facts, err := s.billingRevenueNow(now) |
| @@ -571,9 +577,11 @@ func (s *Server) opBillingAccountInputs(ctx context.Context, now, snapsFrom time |
| return opBillingInput{}, err |
| } |
| in.Earned, in.Covered = accountEarnings(in.LastMonth, days, in.Snaps) |
| - econ, econErr := s.LoadEconomics(ctx, "last") |
| - if econErr != nil { |
| - log.Printf("console: billing: economics: %v", econErr) |
| + // Last month's Economics view as the last billing sync gathered it |
| + // (opbilling_sync.go): a page view never reads the bucket. |
| + econ, econErr := (*EconomicsView)(nil), errBillingNotSynced |
| + if c := s.billingSync.storedCosts(); c != nil { |
| + econ, econErr = c.Econ, c.EconErr |
| } |
| in.Gate.EconomicsComplete = econComplete(econ, econErr, in.LastMonth) |
| in.CostUSD = map[string]float64{} |
| @@ -594,6 +602,7 @@ func (s *Server) handleOpBillingAccounts(w http.ResponseWriter, r *http.Request) |
| if !ok { |
| return |
| } |
| + sync := s.billingSync.now() // before any input: see billingPage |
| now := s.now() |
| today := opMidnight(now) |
| in, err := s.opBillingAccountInputs(r.Context(), now, today.AddDate(0, -1, 1-today.Day())) |
| @@ -609,7 +618,8 @@ func (s *Server) handleOpBillingAccounts(w http.ResponseWriter, r *http.Request) |
| v.Header = opHeader{Title: billCopyAccounts, Sub: billCopyAccountsSub} |
| v.TestMode = s.billingTestMode() |
| v.HistoryNote = opBillingHistoryNote(in.FirstDay, in.LastMonth) |
| - p := s.billingPage(addr, raw, billCopyAccounts) |
| + p := s.billingPage(addr, raw, billCopyAccounts, sync) |
| + p.BillingSync.Back = opBillingAccountsPath |
| p.OpBillingAccounts = &v |
| s.render(w, http.StatusOK, "ops_billing_accounts", p) |
| } |
| @@ -620,6 +630,7 @@ func (s *Server) handleOpBillingPayments(w http.ResponseWriter, r *http.Request) |
| if !ok { |
| return |
| } |
| + sync := s.billingSync.now() // before any input: see billingPage |
| rev, facts, err := s.billingRevenueNow(s.now()) |
| if err != nil { |
| log.Printf("console: billing payments: %v", err) |
| @@ -650,7 +661,8 @@ func (s *Server) handleOpBillingPayments(w http.ResponseWriter, r *http.Request) |
| v := buildOpBillingPayments(rows, facts, total, rev.Inputs, rev.Inputs.Rates, month, kind, page, q) |
| v.Header = opHeader{Title: billCopyPaymentsTitle, Sub: billCopyPaymentsSub} |
| v.TestMode = s.billingTestMode() |
| - p := s.billingPage(addr, raw, billCopyPaymentsTitle) |
| + p := s.billingPage(addr, raw, billCopyPaymentsTitle, sync) |
| + p.BillingSync.Back = opBillingPaymentsPath |
| p.OpBillingPayments = &v |
| s.render(w, http.StatusOK, "ops_billing_payments", p) |
| } |
diff --git a/internal/console/opbilling_copy.go b/internal/console/opbilling_copy.go| index b5d4569df..a38c85f76 100644 |
| --- a/internal/console/opbilling_copy.go |
| +++ b/internal/console/opbilling_copy.go |
| @@ -369,3 +369,32 @@ const ( |
| // BDP-150: overview and accounts page, under the plan name, after BDP-149 joined by a comma. |
| billCopyPacks = "%s packs" |
| ) |
| + |
| +// The billing sync line (opbilling_sync.go), every billing page; approved |
| +// unchanged by Paul in copy review 7pxsdmchqyyn6haqatm7nx3o6a (2026-11-10). |
| +const ( |
| + // BDP-151: every billing page, under the subhead, beside a spinner while a sync runs, before its first step. |
| + billCopySyncing = "Syncing billing…" |
| + // BDP-152: every billing page, the same line once a step runs: the step name, then step n of total. |
| + billCopySyncingStep = "Syncing billing… %s · %s of %s" |
| + // BDP-153: the sync line's step name: re-reading every subscription (hourly sync only). |
| + billCopySyncStepSubscriptions = "Subscriptions" |
| + // BDP-154: the sync line's step name: recording payments, refunds and fees. |
| + billCopySyncStepPayments = "Payments" |
| + // BDP-155: the sync line's step name: fetching the ECB euro rates. |
| + billCopySyncStepRates = "Exchange rates" |
| + // BDP-156: the sync line's step name: writing today's daily record. |
| + billCopySyncStepSnapshot = "Daily record" |
| + // BDP-157: the sync line's step name: last month's usage costs and the AWS bills. |
| + billCopySyncStepCosts = "Costs" |
| + // BDP-158: the sync progress bar's accessible name, not shown. |
| + billCopySyncBar = "Billing sync progress" |
| + // BDP-159: every billing page, under the subhead when no sync runs; %s is the age, like 12m ago. |
| + billCopySynced = "Synced %s" |
| + // BDP-160: every billing page, under the subhead before the console's first sync. |
| + billCopyNotSynced = "Not synced since the console started." |
| + // BDP-161: every billing page, the button beside the Synced line. |
| + billCopySyncNow = "Sync now" |
| + // BDP-162: beside Not available yet on cost figures before the first sync. |
| + billCopyWhyNotSynced = "Costs show after the first billing sync." |
| +) |
diff --git a/internal/console/opbilling_money.go b/internal/console/opbilling_money.go| index b63175188..0b655f0a9 100644 |
| --- a/internal/console/opbilling_money.go |
| +++ b/internal/console/opbilling_money.go |
| @@ -1,7 +1,6 @@ |
| package console |
| import ( |
| - "context" |
| "fmt" |
| "maps" |
| "math" |
| @@ -46,10 +45,19 @@ type platformCost struct { |
| } |
| // platformCostEUR is the month's ("2006-01") platform cost: Plan 3's |
| -// carlosPlatformCostUSD, converted with r (eurCents of round(usd × 100), |
| -// "usd"). Every page reads platform cost through this function only. |
| -func (s *Server) platformCostEUR(ctx context.Context, month string, r eurRates) platformCost { |
| - usd, basis, ok := s.carlosPlatformCostUSD(ctx, month) |
| +// carlosPlatformCostUSD as the billing sync that gathered c read it, |
| +// converted with r (eurCents of round(usd × 100), "usd"). A month c does |
| +// not hold (or no sync yet, c nil) is costBasisPending, not shown. Every |
| +// page reads platform cost through this function only. |
| +func (s *Server) platformCostEUR(c *billingCosts, month string, r eurRates) platformCost { |
| + p, read := platformUSD{}, false |
| + if c != nil { |
| + p, read = c.Platform[month] |
| + } |
| + usd, basis, ok := p.USD, p.Basis, p.OK |
| + if !read { |
| + basis = costBasisPending |
| + } |
| pc := platformCost{Basis: basis, Label: costBasisLabel(basis, "")} |
| if !ok { |
| pc.Hint = costBasisHint(s.cfg.CostScope, basis, month) |
diff --git a/internal/console/opbilling_money_test.go b/internal/console/opbilling_money_test.go| index 08033b7f6..dfa3b1727 100644 |
| --- a/internal/console/opbilling_money_test.go |
| +++ b/internal/console/opbilling_money_test.go |
| @@ -533,9 +533,18 @@ func TestPlatformCostEUR(t *testing.T) { |
| if tc.bill != nil { |
| putStoreJSON(t, fx.rel, economics.BillKey(month), *tc.bill) |
| } |
| - if got := fx.srv.platformCostEUR(context.Background(), month, tc.rates); got != tc.want { |
| + fx.srv.gatherBillingCosts(context.Background(), time.Date(2026, 11, 10, 12, 0, 0, 0, time.UTC)) |
| + if got := fx.srv.platformCostEUR(fx.srv.billingSync.storedCosts(), month, tc.rates); got != tc.want { |
| t.Errorf("platformCostEUR = %+v, want %+v", got, tc.want) |
| } |
| }) |
| } |
| + // Before any sync gathered the cost inputs: pending, never shown, |
| + // whatever the bucket holds. |
| + fx := newConsoleFixture(t) |
| + putStoreJSON(t, fx.rel, economics.BillKey(month), bill("account", economics.SourceCostExplorer, 110)) |
| + want := platformCost{Basis: costBasisPending, Label: costLabelOther, Hint: billCopyWhyNotSynced} |
| + if got := fx.srv.platformCostEUR(nil, month, r); got != want { |
| + t.Errorf("before a sync: platformCostEUR = %+v, want %+v", got, want) |
| + } |
| } |
diff --git a/internal/console/opbilling_sync.go b/internal/console/opbilling_sync.go| new file mode 100644 |
| index 000000000..82152059d |
| --- /dev/null |
| +++ b/internal/console/opbilling_sync.go |
| @@ -0,0 +1,464 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "log" |
| + "net/http" |
| + "sync" |
| + "time" |
| +) |
| + |
| +// The billing sync. The Billing pages used to gather their slow inputs on |
| +// every view: last month's Economics view (a cold one reads every usage day |
| +// object of the month, about 1,300 bucket reads on the flagship in November |
| +// 2026, some 4 s) and six months of bills, one bucket read each. Now a sync |
| +// gathers them in the background and keeps them here, and a page view only |
| +// reads what the last sync kept, with SQLite for the rest. |
| +// |
| +// A sync is the billing worker's money pass (the payment reconcile, the |
| +// euro rates, today's snapshot) and then the cost inputs. The hourly round |
| +// runs one after the subscription sync, as before. A Billing page whose |
| +// figures are older than billingSyncFresh starts one from its script |
| +// (POST /fleet/billing/sync, so the GET stays free of side effects), and so |
| +// does the Sync now button. One runs at a time: a page's start while one |
| +// runs joins it, and the hourly round waits for it and then runs its own. |
| +// |
| +// Request budget. A sync reads no more of the bucket than a page view did |
| +// before: the cost inputs are one LoadEconomics("last") (through its own |
| +// cache and the settled-day cache) and the six bills. The hourly round |
| +// gathers the cost inputs only when they are missing, incomplete, of |
| +// another month or older than billingCostsMaxAge, so a console nobody |
| +// visits re-reads last month's usage once a day; a visit's sync gathers |
| +// them when they are older than billingSyncFresh. Visits start at most one |
| +// sync per billingSyncFresh (the Sync now button, per billingSyncManualGap). |
| + |
| +const ( |
| + // billingSyncFresh is how old a sync may be before a Billing page |
| + // view starts another. |
| + billingSyncFresh = 10 * time.Minute |
| + // billingSyncManualGap is the least time from the end of one sync to |
| + // a Sync now press starting another. |
| + billingSyncManualGap = time.Minute |
| + // billingCostsMaxAge is how old the cost inputs may be before the |
| + // hourly round gathers them again when nothing else asks it to. |
| + billingCostsMaxAge = 24 * time.Hour |
| + // billingCostsRetry is how old cost inputs the gate refuses (a failed |
| + // or incomplete Economics view) may be before the hourly round tries |
| + // again: a month whose coverage never completes is re-read four times a |
| + // day, not every hour. |
| + billingCostsRetry = 6 * time.Hour |
| + // billingCostMonths is how many months of platform cost a sync reads: |
| + // the overview's money table's months. |
| + billingCostMonths = 6 |
| +) |
| + |
| +// billingSyncTimeout bounds a sync a page started. The hourly round runs |
| +// under the worker's own context, as it always has. A variable so a test |
| +// can shorten it. |
| +var billingSyncTimeout = 2 * time.Minute |
| + |
| +// The steps of a sync, in order. The display names are billingSyncSteps. |
| +const ( |
| + billingStepSubscriptions = "subscriptions" |
| + billingStepPayments = "payments" |
| + billingStepRates = "rates" |
| + billingStepSnapshot = "snapshot" |
| + billingStepCosts = "costs" |
| +) |
| + |
| +// billingSyncSteps names each step for the syncing line. |
| +var billingSyncSteps = map[string]string{ |
| + billingStepSubscriptions: billCopySyncStepSubscriptions, |
| + billingStepPayments: billCopySyncStepPayments, |
| + billingStepRates: billCopySyncStepRates, |
| + billingStepSnapshot: billCopySyncStepSnapshot, |
| + billingStepCosts: billCopySyncStepCosts, |
| +} |
| + |
| +// errBillingNotSynced is the Economics error of a console with no cost |
| +// inputs yet: econComplete refuses it, as it refuses any error. |
| +var errBillingNotSynced = errors.New("billing: no sync has gathered the cost inputs yet") |
| + |
| +// costBasisPending is the basis of a month the last sync did not read (or |
| +// no sync yet). Like costBasisMissing, it is never stored on a bill. |
| +const costBasisPending = "pending" |
| + |
| +// platformUSD is one month's carlosPlatformCostUSD as a sync read it. |
| +type platformUSD struct { |
| + USD float64 |
| + Basis string |
| + OK bool |
| +} |
| + |
| +// billingCosts is the cost inputs one sync gathered at At: last month's |
| +// Economics view (Econ and EconErr as LoadEconomics returned them) and each |
| +// of the six months' platform cost. Read-only once stored. |
| +type billingCosts struct { |
| + At time.Time |
| + Econ *EconomicsView |
| + EconErr error |
| + Platform map[string]platformUSD |
| +} |
| + |
| +// billingSyncState is the sync in flight (Running, its Step of Total, done |
| +// closed when it ends) and what the syncs left: when the last one ended |
| +// and the last cost inputs gathered. The zero value is a console that has |
| +// not synced since it started. |
| +type billingSyncState struct { |
| + mu sync.Mutex |
| + running bool |
| + done chan struct{} |
| + step string |
| + stepN int |
| + total int |
| + finished time.Time |
| + gen int // syncs ended since the console started |
| + costs *billingCosts |
| +} |
| + |
| +// billingSyncNow is one look at the sync: whether one runs, its step, and |
| +// when the last one ended (zero: none since the console started) and how |
| +// many have ended (Gen). |
| +type billingSyncNow struct { |
| + Running bool |
| + Step string |
| + Done, Total int |
| + Finished time.Time |
| + Gen int |
| +} |
| + |
| +func (st *billingSyncState) now() billingSyncNow { |
| + st.mu.Lock() |
| + defer st.mu.Unlock() |
| + return billingSyncNow{Running: st.running, Step: st.step, Done: st.stepN, Total: st.total, Finished: st.finished, Gen: st.gen} |
| +} |
| + |
| +// storedCosts is the last cost inputs gathered, nil before the first. |
| +func (st *billingSyncState) storedCosts() *billingCosts { |
| + st.mu.Lock() |
| + defer st.mu.Unlock() |
| + return st.costs |
| +} |
| + |
| +// begin marks a sync of total steps running and returns its done channel. |
| +// Must be called with st.mu held and no sync running. |
| +func (st *billingSyncState) begin(total int) chan struct{} { |
| + st.running, st.step, st.stepN, st.total = true, "", 0, total |
| + st.done = make(chan struct{}) |
| + return st.done |
| +} |
| + |
| +// end marks the sync over at now and wakes everyone waiting on it. |
| +func (st *billingSyncState) end(now time.Time) { |
| + st.mu.Lock() |
| + defer st.mu.Unlock() |
| + st.running, st.step = false, "" |
| + st.finished = now |
| + st.gen++ |
| + close(st.done) |
| +} |
| + |
| +// enter records that the sync in flight started step. |
| +func (st *billingSyncState) enter(step string) { |
| + st.mu.Lock() |
| + defer st.mu.Unlock() |
| + if !st.running { |
| + return |
| + } |
| + st.step = step |
| + st.stepN = min(st.stepN+1, st.total) |
| +} |
| + |
| +// startBillingSync starts a sync on its own goroutine, bounded by |
| +// billingSyncTimeout, unless one is running (true: the caller joins it) or |
| +// one ended less than gap ago (false: nothing starts). It reports whether a |
| +// sync is running when it returns. |
| +func (s *Server) startBillingSync(gap time.Duration) bool { |
| + st := &s.billingSync |
| + st.mu.Lock() |
| + defer st.mu.Unlock() |
| + if st.running { |
| + return true |
| + } |
| + if !st.finished.IsZero() && time.Since(st.finished) < gap { |
| + return false |
| + } |
| + st.begin(s.billingSyncTotal(false)) |
| + go func() { |
| + defer func() { |
| + if rec := recover(); rec != nil { |
| + log.Printf("console: billing sync panic: %v", rec) |
| + } |
| + st.end(time.Now()) |
| + }() |
| + ctx, cancel := context.WithTimeout(context.Background(), billingSyncTimeout) |
| + defer cancel() |
| + s.billingSyncBody(ctx, time.Now(), false) |
| + }() |
| + return true |
| +} |
| + |
| +// billingSyncHourly is the billing worker's round as one sync: it waits for |
| +// a sync in flight to end, then runs the subscription sync, the money pass |
| +// and, when they need it, the cost inputs, under ctx. |
| +func (s *Server) billingSyncHourly(ctx context.Context, now time.Time) { |
| + st := &s.billingSync |
| + for { |
| + st.mu.Lock() |
| + if !st.running { |
| + st.begin(s.billingSyncTotal(true)) |
| + st.mu.Unlock() |
| + break |
| + } |
| + wait := st.done |
| + st.mu.Unlock() |
| + select { |
| + case <-wait: |
| + case <-ctx.Done(): |
| + return |
| + } |
| + } |
| + defer func() { st.end(time.Now()) }() |
| + s.billingSyncBody(ctx, now, true) |
| +} |
| + |
| +// billingSyncTotal is how many steps a sync runs: the money pass's three |
| +// only when billing is ready (billingMoneyPass does nothing otherwise), |
| +// the subscription sync's on the hourly round, and the cost inputs. |
| +func (s *Server) billingSyncTotal(hourly bool) int { |
| + n := 1 |
| + if s.billing != nil && s.billing.ready.Load() { |
| + n += 3 |
| + if hourly { |
| + n++ |
| + } |
| + } |
| + return n |
| +} |
| + |
| +// billingSyncBody is one sync's work. The hourly round also re-reads the |
| +// subscriptions first, and gathers the cost inputs only when they need it |
| +// (billingCostsDue); a page's sync gathers them when older than |
| +// billingSyncFresh. |
| +func (s *Server) billingSyncBody(ctx context.Context, now time.Time, hourly bool) { |
| + st := &s.billingSync |
| + ready := s.billing != nil && s.billing.ready.Load() |
| + if hourly && ready { |
| + st.enter(billingStepSubscriptions) |
| + s.billingSyncPass(ctx, now) |
| + } |
| + s.billingMoneyPass(ctx, now) |
| + st.enter(billingStepCosts) |
| + maxAge := billingSyncFresh |
| + if hourly { |
| + maxAge = billingCostsMaxAge |
| + } |
| + if !billingCostsDue(st.storedCosts(), now, maxAge) { |
| + return |
| + } |
| + // The Economics sweep runs detached under its own economicsSweepTimeout |
| + // (buildEconomicsView), so it starts only when the sync's deadline |
| + // leaves room for all of it. |
| + if d, ok := ctx.Deadline(); ctx.Err() != nil || ok && time.Until(d) < economicsSweepTimeout { |
| + log.Printf("console: billing sync: no time left for the cost inputs; the next sync gathers them") |
| + return |
| + } |
| + s.gatherBillingCosts(ctx, now) |
| +} |
| + |
| +// billingCostsDue is whether cost inputs c, at now, should be gathered |
| +// again: none yet, of a month that is no longer this one, older than |
| +// maxAge, or with an Economics view the gate refuses and older than |
| +// billingCostsRetry (a page's sync, maxAge billingSyncFresh, retries |
| +// sooner). |
| +func billingCostsDue(c *billingCosts, now time.Time, maxAge time.Duration) bool { |
| + if c == nil { |
| + return true |
| + } |
| + if _, ok := c.Platform[now.UTC().Format("2006-01")]; !ok { |
| + return true |
| + } |
| + age := now.Sub(c.At) |
| + if age >= maxAge { |
| + return true |
| + } |
| + return age >= billingCostsRetry && !econComplete(c.Econ, c.EconErr, lastCompleteMonth(now)) |
| +} |
| + |
| +// gatherBillingCosts reads last month's Economics view and the six months' |
| +// bills, and stores them as read, replacing the last: a failed Economics |
| +// read is stored with its error (econComplete refuses it, as a page view's |
| +// own failed read was refused), never covered by an older view; a failed |
| +// bill read is costBasisMissing, as carlosPlatformCostUSD says. |
| +// |
| +// The sync's deadline is enforced here, in one place: LoadEconomics may |
| +// wait for another caller's sweep and then start its own, detached under |
| +// economicsSweepTimeout, so the sync waits for it only until ctx is done. |
| +// Then it gives up and stores nothing (the previous inputs stand, and the |
| +// gate judges them as before); the abandoned sweep ends within its own |
| +// timeout and still fills the Economics cache. |
| +func (s *Server) gatherBillingCosts(ctx context.Context, now time.Time) { |
| + type econRead struct { |
| + v *EconomicsView |
| + err error |
| + } |
| + read := make(chan econRead, 1) |
| + go func() { |
| + defer func() { |
| + if rec := recover(); rec != nil { |
| + read <- econRead{err: fmt.Errorf("economics sweep panic: %v", rec)} |
| + } |
| + }() |
| + v, err := s.LoadEconomics(ctx, "last") |
| + read <- econRead{v, err} |
| + }() |
| + var econ *EconomicsView |
| + var econErr error |
| + select { |
| + case r := <-read: |
| + econ, econErr = r.v, r.err |
| + case <-ctx.Done(): |
| + } |
| + if ctx.Err() != nil { |
| + log.Printf("console: billing sync: cost inputs abandoned at the sync's deadline: %v", ctx.Err()) |
| + return |
| + } |
| + if econErr != nil { |
| + log.Printf("console: billing sync: economics: %v", econErr) |
| + } |
| + plat := make(map[string]platformUSD, billingCostMonths) |
| + for _, m := range billingCostMonthsAt(now) { |
| + usd, basis, ok := s.carlosPlatformCostUSD(ctx, m) |
| + plat[m] = platformUSD{USD: usd, Basis: basis, OK: ok} |
| + } |
| + if ctx.Err() != nil { // a bill read cut off is no "missing" bill |
| + log.Printf("console: billing sync: cost inputs abandoned at the sync's deadline: %v", ctx.Err()) |
| + return |
| + } |
| + c := &billingCosts{At: now, Econ: econ, EconErr: econErr, Platform: plat} |
| + st := &s.billingSync |
| + st.mu.Lock() |
| + defer st.mu.Unlock() |
| + st.costs = c |
| +} |
| + |
| +// billingCostMonthsAt is the six months ("2006-01") whose platform cost |
| +// the overview shows at now, this month first. |
| +func billingCostMonthsAt(now time.Time) []string { |
| + today := opMidnight(now) |
| + monthStart := today.AddDate(0, 0, 1-today.Day()) |
| + months := make([]string, billingCostMonths) |
| + for i := range months { |
| + months[i] = monthStart.AddDate(0, -i, 0).Format("2006-01") |
| + } |
| + return months |
| +} |
| + |
| +// billingSyncView is what a Billing page says about the sync: the syncing |
| +// line (Label, with Done of Total for the bar) while one runs, otherwise |
| +// when the last one ended (Synced) and the Sync now button. Auto tells the |
| +// page's script to start one: the figures are older than billingSyncFresh. |
| +// Every word is chosen here; the page's script only sets textContent. |
| +type billingSyncView struct { |
| + Syncing bool |
| + Label string |
| + Done, Total int |
| + Synced string |
| + Auto bool |
| + BarLabel string |
| + Button string |
| + Back string // the page Sync now returns to; "" is the overview |
| + // Gen is how many syncs had ended when the page rendered: the script |
| + // reloads once the status reports more, whether or not it saw one run. |
| + Gen int |
| +} |
| + |
| +// billingSyncViewOf is the view of n at now. |
| +func billingSyncViewOf(n billingSyncNow, now time.Time) billingSyncView { |
| + v := billingSyncView{BarLabel: billCopySyncBar, Button: billCopySyncNow, Gen: n.Gen} |
| + if n.Running { |
| + v.Syncing, v.Label, v.Done, v.Total = true, billCopySyncing, n.Done, n.Total |
| + if name, ok := billingSyncSteps[n.Step]; ok && n.Total > 0 { |
| + v.Label = fmt.Sprintf(billCopySyncingStep, name, opNumber(n.Done), opNumber(n.Total)) |
| + } |
| + return v |
| + } |
| + if n.Finished.IsZero() { |
| + v.Synced, v.Auto = billCopyNotSynced, true |
| + return v |
| + } |
| + v.Synced = fmt.Sprintf(billCopySynced, humanAge(now.Sub(n.Finished))+" ago") |
| + v.Auto = now.Sub(n.Finished) >= billingSyncFresh |
| + return v |
| +} |
| + |
| +// billingSyncGate admits an operator on a console with billing on, for |
| +// method, like billingPageGate: everyone else gets the missing-route 404. |
| +func (s *Server) billingSyncGate(w http.ResponseWriter, r *http.Request, method string) (raw string, ok bool) { |
| + _, raw, ok = s.operatorOnly(w, r) |
| + if !ok { |
| + return "", false |
| + } |
| + if r.Method != method || s.billing == nil { |
| + http.NotFound(w, r) |
| + return "", false |
| + } |
| + return raw, true |
| +} |
| + |
| +// handleOpBillingSync is POST /fleet/billing/sync: start a sync. The page's |
| +// script sends auto=1 when its figures are stale (a sync starts only if |
| +// none ended within billingSyncFresh) and answers with the status; the Sync |
| +// now button sends nothing (billingSyncManualGap) and is sent back to the |
| +// page it was pressed on. |
| +func (s *Server) handleOpBillingSync(w http.ResponseWriter, r *http.Request) { |
| + raw, ok := s.billingSyncGate(w, r, http.MethodPost) |
| + if !ok { |
| + return |
| + } |
| + if !s.storeFormCSRF(w, r, raw) { |
| + return |
| + } |
| + gap := billingSyncManualGap |
| + if r.FormValue("auto") == "1" { |
| + gap = billingSyncFresh |
| + } |
| + s.startBillingSync(gap) |
| + if r.FormValue("auto") == "1" { |
| + s.writeBillingSyncStatus(w) |
| + return |
| + } |
| + back := "/fleet/billing" |
| + switch r.FormValue("back") { |
| + case opBillingAccountsPath, opBillingPaymentsPath: |
| + back = r.FormValue("back") |
| + } |
| + http.Redirect(w, r, back, http.StatusSeeOther) |
| +} |
| + |
| +// handleOpBillingSyncStatus is GET /fleet/billing/sync/status: the syncing |
| +// line for the page's script to poll. It has no side effect and carries no |
| +// figure: a label, a step count, a boolean and how many syncs have ended. |
| +func (s *Server) handleOpBillingSyncStatus(w http.ResponseWriter, r *http.Request) { |
| + if _, ok := s.billingSyncGate(w, r, http.MethodGet); !ok { |
| + return |
| + } |
| + s.writeBillingSyncStatus(w) |
| +} |
| + |
| +// writeBillingSyncStatus writes the sync's status as JSON, never cached. |
| +func (s *Server) writeBillingSyncStatus(w http.ResponseWriter) { |
| + v := billingSyncViewOf(s.billingSync.now(), time.Now()) |
| + w.Header().Set("Cache-Control", "no-store") |
| + w.Header().Set("Content-Type", "application/json; charset=utf-8") |
| + _ = json.NewEncoder(w).Encode(struct { |
| + Syncing bool `json:"syncing"` |
| + Label string `json:"label"` |
| + Done int `json:"done"` |
| + Total int `json:"total"` |
| + Gen int `json:"gen"` |
| + }{v.Syncing, v.Label, v.Done, v.Total, v.Gen}) |
| +} |
diff --git a/internal/console/opbilling_sync_test.go b/internal/console/opbilling_sync_test.go| new file mode 100644 |
| index 000000000..df8b20403 |
| --- /dev/null |
| +++ b/internal/console/opbilling_sync_test.go |
| @@ -0,0 +1,422 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "html" |
| + "io" |
| + "net/http" |
| + "net/url" |
| + "regexp" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/economics" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// readCountStore counts every bucket read the console makes through it. It |
| +// wraps the fixture's store and passes on only the optional listings that |
| +// store has (ListMod, ListSizes); everything else falls back to Get and |
| +// List, which it counts. |
| +type readCountStore struct { |
| + release.Store |
| + reads atomic.Int64 |
| + // failing, when set, fails every Get and ListDirs: a bucket outage. |
| + failing atomic.Bool |
| +} |
| + |
| +var errReadCountOutage = errors.New("test: bucket outage") |
| + |
| +func (c *readCountStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + c.reads.Add(1) |
| + if c.failing.Load() { |
| + return nil, "", errReadCountOutage |
| + } |
| + return c.Store.Get(ctx, key) |
| +} |
| + |
| +func (c *readCountStore) List(ctx context.Context, prefix string) ([]string, error) { |
| + c.reads.Add(1) |
| + return c.Store.List(ctx, prefix) |
| +} |
| + |
| +func (c *readCountStore) ListDirs(ctx context.Context, prefix string) ([]string, error) { |
| + c.reads.Add(1) |
| + if c.failing.Load() { |
| + return nil, errReadCountOutage |
| + } |
| + return c.Store.ListDirs(ctx, prefix) |
| +} |
| + |
| +func (c *readCountStore) ListMod(ctx context.Context, prefix string) ([]release.KeyMod, error) { |
| + c.reads.Add(1) |
| + return c.Store.(interface { |
| + ListMod(context.Context, string) ([]release.KeyMod, error) |
| + }).ListMod(ctx, prefix) |
| +} |
| + |
| +func (c *readCountStore) ListSizes(ctx context.Context, prefix string) ([]release.KeySize, error) { |
| + c.reads.Add(1) |
| + return c.Store.(interface { |
| + ListSizes(context.Context, string) ([]release.KeySize, error) |
| + }).ListSizes(ctx, prefix) |
| +} |
| + |
| +// billingSyncFixture is overviewFixture's console on a store that counts |
| +// the console's bucket reads, with October's bill on file as CARLOS-only. |
| +func billingSyncFixture(t *testing.T) (*consoleFixture, *readCountStore) { |
| + t.Helper() |
| + var counter *readCountStore |
| + fx := newConsoleFixtureWith(t, consoleFixtureOptions{WrapReleases: func(st release.Store) release.Store { |
| + counter = &readCountStore{Store: st} |
| + return counter |
| + }}) |
| + enableBilling(t, fx.srv) |
| + fx.srv.opNow = func() time.Time { return overviewNow } |
| + fx.srv.cfg.CostScope = CostScope{AccountCarlosOnly: true} |
| + putStoreJSON(t, fx.rel, economics.BillKey("2026-10"), economics.Bill{Schema: 1, Month: "2026-10", TotalUSD: 112, |
| + Services: map[string]float64{"AmazonEC2": 112}, Source: economics.SourceCostExplorer, Basis: economics.BasisAccount}) |
| + return fx, counter |
| +} |
| + |
| +// waitBillingSync waits for the sync in flight to end. |
| +func waitBillingSync(t *testing.T, srv *Server) { |
| + t.Helper() |
| + deadline := time.Now().Add(30 * time.Second) |
| + for srv.billingSync.now().Running { |
| + if time.Now().After(deadline) { |
| + t.Fatal("billing sync still running after 30 s") |
| + } |
| + time.Sleep(5 * time.Millisecond) |
| + } |
| +} |
| + |
| +var csrfField = regexp.MustCompile(`name="csrf" value="([^"]+)"`) |
| + |
| +// TestBillingPagesReadNoBucket pins the speed property: a Billing page view |
| +// reads nothing from the bucket, before the first sync and after it, and a |
| +// GET never starts a sync. The costs come from what the sync stored. |
| +func TestBillingPagesReadNoBucket(t *testing.T) { |
| + fx, counter := billingSyncFixture(t) |
| + c := signInOperator(t, fx) |
| + pages := []string{"/fleet/billing", opBillingAccountsPath, opBillingPaymentsPath} |
| + |
| + view := func(when string) { |
| + for _, p := range pages { |
| + before := counter.reads.Load() |
| + status, _, body := get(t, c, fx.ts.URL+p) |
| + if status != http.StatusOK { |
| + t.Fatalf("%s %s = %d", when, p, status) |
| + } |
| + if n := counter.reads.Load() - before; n != 0 { |
| + t.Errorf("%s: GET %s read the bucket %d times, want 0", when, p, n) |
| + } |
| + if !strings.Contains(body, "data-billing-sync") { |
| + t.Errorf("%s: GET %s has no sync line", when, p) |
| + } |
| + } |
| + } |
| + |
| + view("before a sync") |
| + if n := fx.srv.billingSync.now(); n.Running || !n.Finished.IsZero() { |
| + t.Fatalf("a GET started a sync: %+v", n) |
| + } |
| + in, err := fx.srv.opBillingInputs(context.Background(), overviewNow) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if in.Gate.PlatformOK["2026-10"] || in.Platform["2026-10"].Hint != billCopyWhyNotSynced || in.Gate.EconomicsComplete { |
| + t.Errorf("before a sync: platform %+v, economics complete %v; want refused, not synced", in.Platform["2026-10"], in.Gate.EconomicsComplete) |
| + } |
| + |
| + if !fx.srv.startBillingSync(billingSyncFresh) { |
| + t.Fatal("no sync started") |
| + } |
| + waitBillingSync(t, fx.srv) |
| + if counter.reads.Load() == 0 { |
| + t.Fatal("the sync read nothing: the costs did not come from the bucket") |
| + } |
| + in, err = fx.srv.opBillingInputs(context.Background(), overviewNow) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if pc := in.Platform["2026-10"]; !in.Gate.PlatformOK["2026-10"] || pc.USD != 11200 { |
| + t.Errorf("after a sync: October platform cost %+v, want the bill's $112 shown", pc) |
| + } |
| + view("after a sync") |
| +} |
| + |
| +// TestBillingSyncDebouncedAndSingleFlight: a page's sync does not start |
| +// again within billingSyncFresh (no bucket read), Sync now waits |
| +// billingSyncManualGap, a start while one runs joins it, and the hourly |
| +// round with fresh, complete cost inputs reads no bucket for them. |
| +func TestBillingSyncDebouncedAndSingleFlight(t *testing.T) { |
| + fx, counter := billingSyncFixture(t) |
| + fx.srv.startBillingSync(billingSyncFresh) |
| + waitBillingSync(t, fx.srv) |
| + |
| + before := counter.reads.Load() |
| + if fx.srv.startBillingSync(billingSyncFresh) { |
| + t.Error("a page's sync started again within billingSyncFresh") |
| + } |
| + if fx.srv.startBillingSync(billingSyncManualGap) { |
| + t.Error("Sync now started again within billingSyncManualGap") |
| + } |
| + if n := counter.reads.Load() - before; n != 0 { |
| + t.Errorf("debounced starts read the bucket %d times", n) |
| + } |
| + |
| + // A start while one runs joins it: nothing new begins. |
| + st := &fx.srv.billingSync |
| + st.mu.Lock() |
| + done := st.begin(3) |
| + st.mu.Unlock() |
| + if !fx.srv.startBillingSync(0) { |
| + t.Error("a start while a sync runs did not join it") |
| + } |
| + if n := st.now(); n.Total != 3 { |
| + t.Errorf("the start replaced the sync in flight: %+v", n) |
| + } |
| + // The hourly round waits for it. |
| + hourly := make(chan struct{}) |
| + go func() { fx.srv.billingSyncHourly(context.Background(), time.Now()); close(hourly) }() |
| + select { |
| + case <-hourly: |
| + t.Fatal("the hourly round ran while a sync was in flight") |
| + case <-time.After(50 * time.Millisecond): |
| + } |
| + st.end(time.Now()) |
| + <-done |
| + <-hourly |
| + |
| + // Fresh, complete cost inputs: the hourly round leaves them alone. |
| + now := time.Now() |
| + st.mu.Lock() |
| + st.costs = &billingCosts{At: now, |
| + Econ: &EconomicsView{Period: "last", GeneratedAt: now, CoveredDays: 31, PeriodDays: 31}, |
| + Platform: map[string]platformUSD{now.UTC().Format("2006-01"): {Basis: costBasisMissing}}} |
| + st.mu.Unlock() |
| + before = counter.reads.Load() |
| + fx.srv.billingSyncHourly(context.Background(), now) |
| + if n := counter.reads.Load() - before; n != 0 { |
| + t.Errorf("the hourly round re-read complete, fresh cost inputs: %d bucket reads", n) |
| + } |
| + // A day later it reads them again. |
| + if !billingCostsDue(st.storedCosts(), now.Add(billingCostsMaxAge), billingCostsMaxAge) { |
| + t.Error("cost inputs a day old are not due") |
| + } |
| + if !billingCostsDue(st.storedCosts(), now.AddDate(0, 1, 0), billingCostsMaxAge) { |
| + t.Error("cost inputs of another month are not due") |
| + } |
| +} |
| + |
| +// TestBillingSyncDoors: both doors answer the missing-route 404 to anyone |
| +// but an operator and to a wrong method; the start needs the CSRF token; |
| +// the status is JSON, no-store, with no figure; the page's script start |
| +// answers with the status and Sync now goes back to its page. |
| +func TestBillingSyncDoors(t *testing.T) { |
| + fx, _ := billingSyncFixture(t) |
| + anon := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} |
| + if status, _, _ := get(t, anon, fx.ts.URL+"/fleet/billing/sync/status"); status != http.StatusNotFound { |
| + t.Errorf("anonymous status = %d, want 404", status) |
| + } |
| + if status, _, _ := postForm(t, anon, fx.ts.URL+"/fleet/billing/sync", url.Values{}); status != http.StatusNotFound { |
| + t.Errorf("anonymous start = %d, want 404", status) |
| + } |
| + c := signInOperator(t, fx) |
| + if status, _, _ := get(t, c, fx.ts.URL+"/fleet/billing/sync"); status != http.StatusNotFound { |
| + t.Errorf("GET of the start = %d, want 404", status) |
| + } |
| + if status, _, _ := postForm(t, c, fx.ts.URL+"/fleet/billing/sync", url.Values{"auto": {"1"}}); status != http.StatusForbidden { |
| + t.Errorf("start without CSRF = %d, want 403", status) |
| + } |
| + if n := fx.srv.billingSync.now(); n.Running || !n.Finished.IsZero() { |
| + t.Fatalf("a refused start started a sync: %+v", n) |
| + } |
| + |
| + _, _, page := get(t, c, fx.ts.URL+"/fleet/billing/payments") |
| + m := csrfField.FindStringSubmatch(page) |
| + if m == nil { |
| + t.Fatal("no CSRF field on the page") |
| + } |
| + if !strings.Contains(page, "data-gen=\"0\" data-auto") || !strings.Contains(page, html.EscapeString(billCopyNotSynced)) { |
| + t.Error("an unsynced page does not ask its script to start a sync") |
| + } |
| + status, _, body := postForm(t, c, fx.ts.URL+"/fleet/billing/sync", url.Values{"csrf": {m[1]}, "auto": {"1"}}) |
| + var got struct { |
| + Syncing bool `json:"syncing"` |
| + Label string `json:"label"` |
| + Done int `json:"done"` |
| + Total int `json:"total"` |
| + } |
| + if status != http.StatusOK || json.Unmarshal([]byte(body), &got) != nil || !strings.HasPrefix(got.Label, billCopySyncing) && got.Syncing { |
| + t.Errorf("script start = %d %q", status, body) |
| + } |
| + waitBillingSync(t, fx.srv) |
| + |
| + res, err := c.Get(fx.ts.URL + "/fleet/billing/sync/status") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + raw, _ := io.ReadAll(res.Body) |
| + res.Body.Close() |
| + if res.StatusCode != http.StatusOK || res.Header.Get("Cache-Control") != "no-store" || |
| + !strings.HasPrefix(res.Header.Get("Content-Type"), "application/json") { |
| + t.Errorf("status = %d, %v", res.StatusCode, res.Header) |
| + } |
| + var keys map[string]any |
| + if err := json.Unmarshal(raw, &keys); err != nil || len(keys) != 5 || keys["syncing"] != false { |
| + t.Errorf("status body = %s", raw) |
| + } |
| + |
| + // Sync now goes back to its page; the page says when it synced. |
| + fx.srv.billingSync.mu.Lock() |
| + fx.srv.billingSync.finished = time.Now().Add(-2 * billingSyncManualGap) |
| + fx.srv.billingSync.mu.Unlock() |
| + status, loc, _ := postForm(t, c, fx.ts.URL+"/fleet/billing/sync", url.Values{"csrf": {m[1]}, "back": {opBillingPaymentsPath}}) |
| + if status != http.StatusSeeOther || loc != opBillingPaymentsPath { |
| + t.Errorf("Sync now = %d to %q", status, loc) |
| + } |
| + waitBillingSync(t, fx.srv) |
| + _, _, page = get(t, c, fx.ts.URL+"/fleet/billing") |
| + if !strings.Contains(page, "Synced 0m ago") || regexp.MustCompile(`data-gen="\d+" data-auto`).MatchString(page) { |
| + t.Error("a fresh sync is not shown as fresh") |
| + } |
| +} |
| + |
| +// completeCosts is cost inputs gathered at at whose Economics view the gate |
| +// accepts for last month. |
| +func completeCosts(at time.Time) *billingCosts { |
| + return &billingCosts{At: at, |
| + Econ: &EconomicsView{Period: "last", GeneratedAt: at, CoveredDays: 31, PeriodDays: 31}, |
| + Platform: map[string]platformUSD{at.UTC().Format("2006-01"): {Basis: costBasisMissing}}} |
| +} |
| + |
| +// TestBillingSyncFailedRefreshRefuses (Astra R1 P1): after a complete |
| +// view, a refresh whose Economics read fails stores the failure, and the |
| +// gate refuses last month's costs; no older view stands in for it. |
| +func TestBillingSyncFailedRefreshRefuses(t *testing.T) { |
| + fx, counter := billingSyncFixture(t) |
| + now := time.Now() |
| + fx.srv.billingSync.mu.Lock() |
| + fx.srv.billingSync.costs = completeCosts(now.Add(-time.Hour)) |
| + fx.srv.billingSync.mu.Unlock() |
| + if c := fx.srv.billingSync.storedCosts(); !econComplete(c.Econ, c.EconErr, lastCompleteMonth(now)) { |
| + t.Fatal("the seeded view is not complete") |
| + } |
| + counter.failing.Store(true) |
| + fx.srv.gatherBillingCosts(context.Background(), now) |
| + c := fx.srv.billingSync.storedCosts() |
| + if c.EconErr == nil || econComplete(c.Econ, c.EconErr, lastCompleteMonth(now)) { |
| + t.Errorf("after a failed refresh: econ %+v, err %v; want the failure stored and refused", c.Econ, c.EconErr) |
| + } |
| +} |
| + |
| +// TestBillingCostsDueRetry (Astra R1 P3): the hourly round retries cost |
| +// inputs the gate refuses only every billingCostsRetry, not every hour; a |
| +// page's sync retries them once they are older than billingSyncFresh. |
| +func TestBillingCostsDueRetry(t *testing.T) { |
| + now := time.Now() |
| + incomplete := completeCosts(now) |
| + incomplete.Econ.CoveredDays = 30 |
| + for _, tc := range []struct { |
| + name string |
| + age time.Duration |
| + maxAge time.Duration |
| + want bool |
| + }{ |
| + {"hourly, an hour old", time.Hour, billingCostsMaxAge, false}, |
| + {"hourly, five hours old", 5 * time.Hour, billingCostsMaxAge, false}, |
| + {"hourly, six hours old", billingCostsRetry, billingCostsMaxAge, true}, |
| + {"page, five minutes old", 5 * time.Minute, billingSyncFresh, false}, |
| + {"page, ten minutes old", billingSyncFresh, billingSyncFresh, true}, |
| + } { |
| + c := *incomplete |
| + c.At = now.Add(-tc.age) |
| + if got := billingCostsDue(&c, now, tc.maxAge); got != tc.want { |
| + t.Errorf("%s: due = %v, want %v", tc.name, got, tc.want) |
| + } |
| + } |
| + if c := completeCosts(now.Add(-5 * time.Hour)); billingCostsDue(c, now, billingCostsMaxAge) { |
| + t.Error("complete inputs five hours old are due on the hourly round") |
| + } |
| +} |
| + |
| +// TestBillingSyncDeadlineSkipsCosts (Astra R1 P4): a sync whose deadline |
| +// has passed, or leaves less than the Economics sweep's own timeout, does |
| +// not start the cost inputs. |
| +func TestBillingSyncDeadlineSkipsCosts(t *testing.T) { |
| + fx, counter := billingSyncFixture(t) |
| + for _, left := range []time.Duration{-time.Second, economicsSweepTimeout / 2} { |
| + ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(left)) |
| + before := counter.reads.Load() |
| + fx.srv.billingSyncBody(ctx, time.Now(), false) |
| + cancel() |
| + if n := counter.reads.Load() - before; n != 0 || fx.srv.billingSync.storedCosts() != nil { |
| + t.Errorf("%v left: %d bucket reads, costs %+v; want none", left, n, fx.srv.billingSync.storedCosts()) |
| + } |
| + } |
| +} |
| + |
| +// TestBillingSyncGenReloads (Astra R1 P2): the page renders how many syncs |
| +// had ended, and the status reports more once one ends, so the script |
| +// reloads even when it never saw the sync run. |
| +func TestBillingSyncGenReloads(t *testing.T) { |
| + fx, _ := billingSyncFixture(t) |
| + c := signInOperator(t, fx) |
| + _, _, page := get(t, c, fx.ts.URL+"/fleet/billing") |
| + if !strings.Contains(page, `data-billing-sync data-gen="0"`) { |
| + t.Fatal("the page does not render the sync generation") |
| + } |
| + fx.srv.startBillingSync(billingSyncFresh) |
| + waitBillingSync(t, fx.srv) |
| + _, _, body := get(t, c, fx.ts.URL+"/fleet/billing/sync/status") |
| + var st struct { |
| + Syncing bool `json:"syncing"` |
| + Gen int `json:"gen"` |
| + } |
| + if err := json.Unmarshal([]byte(body), &st); err != nil || st.Syncing || st.Gen != 1 { |
| + t.Errorf("status after one sync = %s", body) |
| + } |
| +} |
| + |
| +// TestBillingSyncDeadlineWhileWaitingForASweep (Astra R2 P2): a sync whose |
| +// Economics read waits on another caller's sweep gives up at its own |
| +// deadline and stores nothing. |
| +func TestBillingSyncDeadlineWhileWaitingForASweep(t *testing.T) { |
| + fx, _ := billingSyncFixture(t) |
| + c := fx.srv.economicsCacheEntry("last") |
| + c.mu.Lock() |
| + c.sweeping, c.done = true, make(chan struct{}) // a sweep that never ends |
| + c.mu.Unlock() |
| + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) |
| + defer cancel() |
| + start := time.Now() |
| + fx.srv.gatherBillingCosts(ctx, time.Now()) |
| + if took := time.Since(start); took > 2*time.Second { |
| + t.Errorf("gatherBillingCosts outlived its deadline by %v", took) |
| + } |
| + if got := fx.srv.billingSync.storedCosts(); got != nil { |
| + t.Errorf("abandoned cost inputs were stored: %+v", got) |
| + } |
| +} |
| + |
| +// TestBillingPageSyncIsTheHandlersSnapshot (Astra R2 P2): the sync line |
| +// is the state the handler captured before its inputs, not a later one, so |
| +// its generation never acknowledges a sync the page's figures missed. |
| +func TestBillingPageSyncIsTheHandlersSnapshot(t *testing.T) { |
| + fx, _ := billingSyncFixture(t) |
| + fx.srv.startBillingSync(billingSyncFresh) |
| + waitBillingSync(t, fx.srv) |
| + if fx.srv.billingSync.now().Gen != 1 { |
| + t.Fatal("no sync ended") |
| + } |
| + p := fx.srv.billingPage("paul@keymail.dev", "", billCopyRail, billingSyncNow{}) |
| + if p.BillingSync.Gen != 0 || !p.BillingSync.Auto { |
| + t.Errorf("sync line = %+v; want the captured state (generation 0, never synced)", p.BillingSync) |
| + } |
| +} |
diff --git a/internal/console/opbilling_test.go b/internal/console/opbilling_test.go| index 1bf25d04c..938027825 100644 |
| --- a/internal/console/opbilling_test.go |
| +++ b/internal/console/opbilling_test.go |
| @@ -567,7 +567,7 @@ func TestOverviewARRChart(t *testing.T) { |
| func renderOverview(t *testing.T, fx *consoleFixture, v *opBillingView) string { |
| t.Helper() |
| rec := httptest.NewRecorder() |
| - p := fx.srv.billingPage("paul@keymail.dev", "", billCopyRail) |
| + p := fx.srv.billingPage("paul@keymail.dev", "", billCopyRail, billingSyncNow{}) |
| p.OpBilling = v |
| fx.srv.render(rec, http.StatusOK, "ops_billing", p) |
| if rec.Code != http.StatusOK { |
| @@ -1154,7 +1154,7 @@ func TestBillingAccountsRender(t *testing.T) { |
| t.Helper() |
| v.Header = opHeader{Title: billCopyAccounts, Sub: billCopyAccountsSub} |
| rec := httptest.NewRecorder() |
| - p := fx.srv.billingPage("paul@keymail.dev", "", billCopyAccounts) |
| + p := fx.srv.billingPage("paul@keymail.dev", "", billCopyAccounts, billingSyncNow{}) |
| p.OpBillingAccounts = &v |
| fx.srv.render(rec, http.StatusOK, "ops_billing_accounts", p) |
| if rec.Code != http.StatusOK { |
| @@ -1469,7 +1469,7 @@ func renderPayments(t *testing.T, v opBillingPaymentsView) string { |
| enableBilling(t, fx.srv) |
| v.Header = opHeader{Title: billCopyPaymentsTitle, Sub: billCopyPaymentsSub} |
| rec := httptest.NewRecorder() |
| - p := fx.srv.billingPage("paul@keymail.dev", "", billCopyPaymentsTitle) |
| + p := fx.srv.billingPage("paul@keymail.dev", "", billCopyPaymentsTitle, billingSyncNow{}) |
| p.OpBillingPayments = &v |
| fx.srv.render(rec, http.StatusOK, "ops_billing_payments", p) |
| if rec.Code != http.StatusOK { |
diff --git a/internal/console/platformcost.go b/internal/console/platformcost.go| index 72ad60eac..46af54c3d 100644 |
| --- a/internal/console/platformcost.go |
| +++ b/internal/console/platformcost.go |
| @@ -84,6 +84,8 @@ func costBasisHint(scope CostScope, basis, month string) string { |
| return costHintUnstated |
| case costBasisMissing: |
| return fmt.Sprintf(costHintNoBillFmt, month) |
| + case costBasisPending: |
| + return billCopyWhyNotSynced |
| default: |
| return costHintWhole |
| } |
diff --git a/internal/console/routedecls.go b/internal/console/routedecls.go| index 31407c2d1..c7eb06a09 100644 |
| --- a/internal/console/routedecls.go |
| +++ b/internal/console/routedecls.go |
| @@ -165,6 +165,11 @@ var routeDecls = []routeDecl{ |
| {Pattern: "/fleet/billing", Handler: (*Server).handleOpBilling}, |
| {Pattern: "/fleet/billing/accounts", Handler: (*Server).handleOpBillingAccounts}, |
| {Pattern: "/fleet/billing/payments", Handler: (*Server).handleOpBillingPayments}, |
| + // The billing sync (opbilling_sync.go): the pages' script and Sync now |
| + // POST the start (CSRF); the script polls the status. Same bare |
| + // registration: billingSyncGate answers the missing-route 404. |
| + {Pattern: "/fleet/billing/sync", Handler: (*Server).handleOpBillingSync}, |
| + {Pattern: "/fleet/billing/sync/status", Handler: (*Server).handleOpBillingSyncStatus}, |
| // Account-scoped and explicit: /a/<sqid>/apps/<app> rather than |
| // account-by-session, so a link a teammate opens lands where you meant. |
| {Pattern: "GET /a/{sqid}/{$}", Handler: (*Server).handleAccountHome}, |
diff --git a/internal/console/server.go b/internal/console/server.go| index 4de2ddd72..a9d2c1df9 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -1301,6 +1301,10 @@ type Server struct { |
| // reads (usagedays.go), so a cold view reads only today and yesterday; |
| // the hourly economics pass fills it as it reads. |
| usageDays usageDayCache |
| + // billingSync is the billing sync in flight and the cost inputs the |
| + // last one gathered (opbilling_sync.go): the Billing pages read them |
| + // and never the bucket. |
| + billingSync billingSyncState |
| // trafficMemo holds the Overview traffic card's counts for a minute |
| // (analyticsview.go, analyticsMemo). |
| trafficMemo analyticsMemo |
| @@ -2480,6 +2484,9 @@ type page struct { |
| OpBilling *opBillingView |
| OpBillingAccounts *opBillingAccountsView |
| OpBillingPayments *opBillingPaymentsView |
| + // BillingSync is the Billing pages' sync line (opbilling_sync.go); nil |
| + // on every other page. |
| + BillingSync *billingSyncView |
| // App page, "Resources": this app's OWN instances' unit readings (Task |
| // 12), one row per route host. Nil renders no section at all — metrics |
diff --git a/internal/console/static/ops.css b/internal/console/static/ops.css| index 0c317ccca..5cb8b80f9 100644 |
| --- a/internal/console/static/ops.css |
| +++ b/internal/console/static/ops.css |
| @@ -313,3 +313,10 @@ a[rst-stat]:hover [co-statlink] { text-decoration: underline; } |
| [co-cols="billaccounts"] > [rst-lrow] > :is(:nth-child(n+2):nth-child(-n+4), :nth-child(n+6)) { display: none; } |
| [co-cols="billpaymentlist"] > [rst-lrow] > :is(:nth-child(1), :nth-child(3), :nth-child(4), :nth-child(n+6)) { display: none; } |
| } |
| + |
| +/* The Billing pages' sync line (ops_billing.html op_billing_sync). */ |
| +[co-billsync], [co-billsync-run], [co-billsync-idle] { align-items: center; display: flex; flex-wrap: wrap; gap: 0.75rem; } |
| +[co-billsync] { margin-block: 0.25rem 1rem; } |
| +[co-billsync] [co-note] { margin: 0; } |
| +[co-billsync] progress { inline-size: 12rem; } |
| +[co-billsync] [hidden] { display: none; } |
diff --git a/internal/console/templates/ops_billing.html b/internal/console/templates/ops_billing.html| index 457660586..b5bad4ce5 100644 |
| --- a/internal/console/templates/ops_billing.html |
| +++ b/internal/console/templates/ops_billing.html |
| @@ -5,6 +5,7 @@ |
| with a link is co-rowlink: its first rst-nm link covers the row. */}} |
| {{define "ops_billing"}}{{template "op_top" .}} |
| {{template "op_billing_head" .OpBilling}} |
| +{{template "op_billing_sync" .}} |
| {{with .OpBilling}}{{$w := .W}} |
| {{with .RateLine}}<p co-note>{{.}}</p>{{end}} |
| <div rst-stats rst-card co-billstats> |
| @@ -146,3 +147,68 @@ |
| {{/* op_bill_whys is a section's refusal reasons, one line each. */}} |
| {{define "op_bill_whys"}}{{range .}}<p co-note>{{.}}</p>{{end}}{{end}} |
| + |
| +{{/* op_billing_sync is every billing page's sync line (opbilling_sync.go): |
| + while a sync runs, a spinner, its line and a progress bar; otherwise |
| + when the last one ended and Sync now. Its data is the page (CSRF and |
| + .BillingSync). Every word is chosen in Go. The script is enhancement |
| + only: it starts a sync when the figures are stale (Auto), swaps in the |
| + syncing line, polls the status and reloads once more syncs have ended |
| + than when the page rendered (data-gen), even one it never saw run. It sets |
| + textContent and two numbers, and composes no markup. Without it the |
| + page and Sync now work as they are. */}} |
| +{{define "op_billing_sync"}}{{with .BillingSync}}<div co-billsync data-billing-sync data-gen="{{.Gen}}"{{if .Auto}} data-auto{{end}}{{if .Syncing}} data-syncing{{end}}> |
| + <div co-billsync-run{{if not .Syncing}} hidden{{end}}> |
| + <span class="rst-spin" aria-hidden="true"></span> |
| + <p co-note role="status" data-billing-sync-label>{{.Label}}</p> |
| + <progress data-billing-sync-bar max="{{if .Total}}{{.Total}}{{else}}1{{end}}" value="{{.Done}}" aria-label="{{.BarLabel}}"{{if not .Total}} hidden{{end}}></progress> |
| + </div> |
| + {{if not .Syncing}}<form co-billsync-idle method="post" action="/fleet/billing/sync"> |
| + <input type="hidden" name="csrf" value="{{$.CSRF}}"> |
| + {{with .Back}}<input type="hidden" name="back" value="{{.}}">{{end}} |
| + <p co-note>{{.Synced}}</p> |
| + <button type="submit" class="rst-btn rst-btn--ghost rst-btn--sm" data-busy>{{.Button}}</button> |
| + </form>{{end}} |
| +</div> |
| +<script> |
| +(function () { |
| + "use strict"; |
| + var root = document.querySelector("[data-billing-sync]"); |
| + if (!root) return; |
| + var run = root.querySelector("[co-billsync-run]"); |
| + var idle = root.querySelector("[co-billsync-idle]"); |
| + var label = root.querySelector("[data-billing-sync-label]"); |
| + var bar = root.querySelector("[data-billing-sync-bar]"); |
| + var gen = Number(root.getAttribute("data-gen")); |
| + var EVERY = 1500, deadline = Date.now() + 10 * 60 * 1000, timer = null; |
| + function json(res) { |
| + if (!res.ok || (res.headers.get("Content-Type") || "").indexOf("json") === -1) return null; |
| + return res.json(); |
| + } |
| + function apply(d) { |
| + if (!d) return; |
| + if (!d.syncing) { |
| + if (typeof d.gen === "number" && d.gen > gen) window.location.reload(); |
| + return; |
| + } |
| + root.setAttribute("data-syncing", ""); |
| + if (idle) idle.hidden = true; |
| + run.hidden = false; |
| + if (typeof d.label === "string") label.textContent = d.label; |
| + if (d.total > 0) { bar.max = d.total; bar.value = d.done; bar.hidden = false; } |
| + if (Date.now() < deadline) timer = setTimeout(poll, EVERY); |
| + } |
| + function poll() { |
| + fetch("/fleet/billing/sync/status", { headers: { "Accept": "application/json" }, credentials: "same-origin" }) |
| + .then(json).then(apply) |
| + .catch(function () { if (Date.now() < deadline) timer = setTimeout(poll, EVERY); }); |
| + } |
| + if (root.hasAttribute("data-syncing")) { timer = setTimeout(poll, EVERY); return; } |
| + if (!root.hasAttribute("data-auto") || !idle) return; |
| + var body = new URLSearchParams(); |
| + body.set("csrf", idle.querySelector("[name=csrf]").value); |
| + body.set("auto", "1"); |
| + fetch("/fleet/billing/sync", { method: "POST", body: body, headers: { "Accept": "application/json" }, credentials: "same-origin" }) |
| + .then(json).then(apply).catch(function () {}); |
| +})(); |
| +</script>{{end}}{{end}} |
diff --git a/internal/console/templates/ops_billing_accounts.html b/internal/console/templates/ops_billing_accounts.html| index 47ec9d370..bdb5ac4d6 100644 |
| --- a/internal/console/templates/ops_billing_accounts.html |
| +++ b/internal/console/templates/ops_billing_accounts.html |
| @@ -6,6 +6,7 @@ |
| link opens the account and covers the row. */}} |
| {{define "ops_billing_accounts"}}{{template "op_top" .}} |
| {{template "op_billing_head" .OpBillingAccounts}} |
| +{{template "op_billing_sync" .}} |
| {{with .OpBillingAccounts}}{{$w := .W}} |
| {{with .RateNote}}<p co-note>{{.}}</p>{{end}} |
| <div co-billbar> |
diff --git a/internal/console/templates/ops_billing_payments.html b/internal/console/templates/ops_billing_payments.html| index e094db707..5966836d3 100644 |
| --- a/internal/console/templates/ops_billing_payments.html |
| +++ b/internal/console/templates/ops_billing_payments.html |
| @@ -7,6 +7,7 @@ |
| deleted account's row is plain. */}} |
| {{define "ops_billing_payments"}}{{template "op_top" .}} |
| {{template "op_billing_head" .OpBillingPayments}} |
| +{{template "op_billing_sync" .}} |
| {{with .OpBillingPayments}}{{$w := .W}} |
| {{with .RateNote}}<p co-note>{{.}}</p>{{end}} |
| <div co-billbar> |
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt| index 333f6d525..62ea96268 100644 |
| --- a/internal/console/testdata/claim-routes.txt |
| +++ b/internal/console/testdata/claim-routes.txt |
| @@ -10,6 +10,8 @@ route /fleet/architecture/refresh |
| route /fleet/billing |
| route /fleet/billing/accounts |
| route /fleet/billing/payments |
| +route /fleet/billing/sync |
| +route /fleet/billing/sync/status |
| route /fleet/economics/bill |
| route /fleet/economics/scenarios |
| route /fleet/economics/tier |
diff --git a/internal/console/testdata/perf-budgets.txt b/internal/console/testdata/perf-budgets.txt| index d277fb8ba..1c4ce2efa 100644 |
| --- a/internal/console/testdata/perf-budgets.txt |
| +++ b/internal/console/testdata/perf-budgets.txt |
| @@ -42,6 +42,8 @@ GET /static/{hash}/{file...} skip: static asset, not a screen; consolePerfSkip l |
| /fleet/economics/bill skip: POST-only door; a GET answers 404 on its first line by design (economicspass.go) |
| /fleet/economics/scenarios skip: POST-only door; a GET answers 404 on its first line by design (economicspass.go) |
| /fleet/economics/tier skip: POST-only door; a GET answers 404 on its first line by design (economicspass.go) |
| +/fleet/billing/sync skip: POST-only door; a GET answers 404 on its first line by design (opbilling_sync.go) |
| +/fleet/billing/sync/status skip: the Billing pages' sync status JSON door, not a screen; it reads memory only (opbilling_sync.go) |
| /fleet/alerts/connectors skip: POST-only door; a GET answers 404 on its first line by design (alertpages.go) |
| /fleet/alerts/connectors/{id}/confirm-link skip: POST-only door; a GET answers 404 on its first line by design (alertpages.go) |
| /fleet/alerts/connectors/{id}/delete skip: POST-only door; a GET answers 404 on its first line by design (alertpages.go) |
diff --git a/internal/provision/billing_overview_speed_census_test.go b/internal/provision/billing_overview_speed_census_test.go| new file mode 100644 |
| index 000000000..f624b704e |
| --- /dev/null |
| +++ b/internal/provision/billing_overview_speed_census_test.go |
| @@ -0,0 +1,22 @@ |
| +package provision |
| + |
| +// billingOverviewSpeedWriteCensusInventory is the billing-overview-speed |
| +// review of the record-write census, layered on |
| +// groupRollVerbWriteCensusInventory. The console's route table (var |
| +// routeDecls) gains two methodless declarations for the Billing pages' |
| +// background sync: /fleet/billing/sync (start, operator + CSRF) and |
| +// /fleet/billing/sync/status (JSON status). Their handlers |
| +// (opbilling_sync.go) write no record: the sync runs the existing billing |
| +// money pass and reads Economics and the bills. Its kinds and class are |
| +// unchanged; only the digest moves. |
| +func billingOverviewSpeedWriteCensusInventory() []censusEntry { |
| + entries := append([]censusEntry(nil), groupRollVerbWriteCensusInventory()...) |
| + r := censusEntry{"internal/console/routedecls.go", "var routeDecls", "key-site", "lit:instances,lit:sidecars", "d2fb2693d88d5c4701a900f646d6a8bfb6ad0852a58cb170d96463345a0e01c6"} |
| + for i, e := range entries { |
| + if e.File == r.File && e.Unit == r.Unit { |
| + entries[i] = r |
| + return entries |
| + } |
| + } |
| + return append(entries, r) |
| +} |
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go| index 9965b5636..796626fa5 100644 |
| --- a/internal/provision/plan9_b8_census_test.go |
| +++ b/internal/provision/plan9_b8_census_test.go |
| @@ -366,7 +366,7 @@ func TestPlan9B8RecordWriteCensus(t *testing.T) { |
| if len(got) < 100 { |
| t.Fatalf("census found only %d units under %s; the walk is broken", len(got), root) |
| } |
| - inventory := groupRollVerbWriteCensusInventory() |
| + inventory := billingOverviewSpeedWriteCensusInventory() |
| problems := append(censusDiff(inventory, got), censusPolicy(inventory)...) |
| if len(problems) > 0 { |
| t.Fatalf("record-write census rejected %d site(s); update the explicit inventory only after reviewing the source:\n %s", len(problems), strings.Join(problems, "\n ")) |
diff --git a/parity/parity.tsv b/parity/parity.tsv| index 812083d88..cf2743a10 100644 |
| --- a/parity/parity.tsv |
| +++ b/parity/parity.tsv |
| @@ -195,7 +195,7 @@ op-economics operator operator economics bill ; economics backhaul GET /fleet/ec |
| op-accounts-plan operator operator accounts plan GET /fleet/economics/accounts ; /fleet/economics/tier The console sets the pool tier only. |
| op-accounts-migrate operator operator accounts migrate A one-off migration of an app's objects. |
| op-billing operator operator billing problems ; billing close ; billing house Billing problems and house accounts. |
| -op-billing-pages operator operator /fleet/billing ; /fleet/billing/accounts ; /fleet/billing/payments The operator Billing pages: the overview, paying accounts and payments. |
| +op-billing-pages operator operator /fleet/billing ; /fleet/billing/accounts ; /fleet/billing/payments ; /fleet/billing/sync ; /fleet/billing/sync/status The operator Billing pages: the overview, paying accounts and payments, and their background sync. |
| op-instance-policy operator operator apps set [--egress-allow,--size] ; instances set [--size] Instance policy is set by an operator. |
| op-upstreams operator operator instances set-upstreams ; instances create [--addr] TCP backends are set by an operator. |
| op-digests operator operator channels digests [on, off] The digest signing switch. |