Merge origin/main into held-floor-capability
main c2083896 (#810 WAL test fix), 3a8eabde (#802 quiet litestream logs) and later. Census: main's litestream-quiet-802 overlay chains before this branch's, which is re-proposed last with the same claims.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
42 files changed,
+1,462
−62
approved_billing_dashboard_copy_test.go+6 −6docs/parity.md+1 −1docs/site/plans.md+1 −1docs/superpowers/notes/census-proposal-held-floor-capability.md+1 −1docs/superpowers/notes/census-proposal-litestream-quiet-802.md+19 −0docs/superpowers/plans/2026-11-09-billing-dashboard-1-copy.md+1 −1docs/superpowers/plans/2026-11-09-billing-dashboard-1-data.md+6 −3docs/superpowers/plans/2026-11-09-billing-dashboard-2-copy.md+19 −0internal/billingstripe/client.go+82 −9internal/billingstripe/client_test.go+73 −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/host/units/carlos-litestream.service+6 −0internal/host/units_isolation_test.go+14 −0internal/lease/lease.go+1 −0internal/lease/quietlog.go+41 −0internal/lease/quietlog_test.go+50 −0internal/lease/release_snapshot_test.go+13 −2internal/provision/billing_overview_speed_census_test.go+22 −0internal/provision/plan9_b8_census_test.go+1 −1internal/provision/testdata/plan14-root-reads-chain.tsv+2 −1internal/provision/testdata/plan14-root-reads-litestream-quiet-802.tsv+6 −0parity/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/site/plans.md b/docs/site/plans.md| index adf32abd9..26df09a02 100644 |
| --- a/docs/site/plans.md |
| +++ b/docs/site/plans.md |
| @@ -157,7 +157,7 @@ Every billing setting lives in the console's EnvironmentFile. None of them is a |
| If any of them is wrong, the console refuses to start and names the variable, never its value. |
| -The restricted key also needs read access to Balance, Charges and Refunds, and the webhook also needs `charge.succeeded`, `charge.captured` and `charge.refunded`, so the console can record the money it receives. |
| +So the console can record the money it receives, the restricted key also needs read access to Balance, Balance Transaction Sources, Charges and Refunds, and Invoices. The webhook also needs `charge.succeeded`, `charge.captured` and `charge.refunded`. |
| Point Stripe's webhook at `https://<console>/billing/webhook`. When the console starts, it checks the account, every price in the book, the portal configuration and the house coupon (if you set one) against Stripe before it accepts a webhook. Until that check passes, the webhook answers 503 and Stripe tries again later, so a console that starts while Stripe is unreachable catches up by itself. |
diff --git a/docs/superpowers/notes/census-proposal-held-floor-capability.md b/docs/superpowers/notes/census-proposal-held-floor-capability.md| index e85cc2c79..cbacab8ac 100644 |
| --- a/docs/superpowers/notes/census-proposal-held-floor-capability.md |
| +++ b/docs/superpowers/notes/census-proposal-held-floor-capability.md |
| @@ -28,6 +28,6 @@ New dispositions, which census-propose wrote and the reviewer checks against the |
| - new `internal/edge/hadrain.go:Edge.AskDrainSeen`: reads +file:Read; written legacy, accepted-legacy, frozen |
| -Seal: `837f27a6b7b6ed272f8c68aca07650fa32cf3ec92ce28bf9d812a4282eeb0b58` → `acef53b35eaa775cd2e32a9c5a0684a313def0425cd2c5c910d53c61b3a6cbf1`. |
| +Seal: `6d3ea7fccce1a7f4bc507b6eb8d368ed0b62f83022504aa04c7684c72c93aa9a` → `b60c83f8ba4311222174284420b5327e92002882b4a1c6f291e74e69234c6f59`. |
| Overlay: `internal/provision/testdata/plan14-root-reads-held-floor-capability.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/docs/superpowers/notes/census-proposal-litestream-quiet-802.md b/docs/superpowers/notes/census-proposal-litestream-quiet-802.md| new file mode 100644 |
| index 000000000..76d8ab119 |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-litestream-quiet-802.md |
| @@ -0,0 +1,19 @@ |
| +# Census approval: litestream-quiet-802 |
| + |
| +Ruling `census-ruling-litestream-quiet-802`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| + |
| +| unit | change | read sites | what changed | |
| +|---|---|---|---| |
| +| `internal/host/units/carlos-litestream.service` `external` | body | unchanged (1) | adds Environment=LOG_LEVEL=warn (litestream logs warnings and errors only, #802); ExecStart, user, sandboxing, EnvironmentFile and the config path it reads are unchanged; no new read | |
| + |
| +Envelopes re-pinned: `internal/host/units`, `internal/lease`. |
| + |
| +Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner. |
| + |
| +Recorded dispositions, which each change must still satisfy: |
| + |
| +- `internal/host/units/carlos-litestream.service` `external`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-ls284;basis=MemoryMax 256M -> 512M, adds Environment=GOMEMLIMIT=384MiB and RestartSteps=5/RestartMaxDelaySec=60 backoff; ExecStart, user, sandboxing and the config path it reads are unchanged; no new read |
| + |
| +Seal: `837f27a6b7b6ed272f8c68aca07650fa32cf3ec92ce28bf9d812a4282eeb0b58` → `6d3ea7fccce1a7f4bc507b6eb8d368ed0b62f83022504aa04c7684c72c93aa9a`. |
| + |
| +Overlay: `internal/provision/testdata/plan14-root-reads-litestream-quiet-802.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/docs/superpowers/plans/2026-11-09-billing-dashboard-1-copy.md b/docs/superpowers/plans/2026-11-09-billing-dashboard-1-copy.md| index f2bbdd863..ace39f50d 100644 |
| --- a/docs/superpowers/plans/2026-11-09-billing-dashboard-1-copy.md |
| +++ b/docs/superpowers/plans/2026-11-09-billing-dashboard-1-copy.md |
| @@ -80,7 +80,7 @@ BDC-32 to BDC-34 are new lines in the section's `sh` block, after `carlos billin |
| | id | file | text | status | |
| |---|---|---|---| |
| -| BDC-37 | docs/site/plans.md | The restricted key also needs read access to Balance, Charges and Refunds, and the webhook also needs `charge.succeeded`, `charge.captured` and `charge.refunded`, so the console can record the money it receives. | approved | |
| +| BDC-37 | docs/site/plans.md | So the console can record the money it receives, the restricted key also needs read access to Balance, Balance Transaction Sources, Charges and Refunds, and Invoices. The webhook also needs `charge.succeeded`, `charge.captured` and `charge.refunded`. | approved | |
| BDC-37 goes straight after the paragraph that starts "If any of them is wrong", which follows the variables table. |
diff --git a/docs/superpowers/plans/2026-11-09-billing-dashboard-1-data.md b/docs/superpowers/plans/2026-11-09-billing-dashboard-1-data.md| index ed53f6716..8b5a05ea2 100644 |
| --- a/docs/superpowers/plans/2026-11-09-billing-dashboard-1-data.md |
| +++ b/docs/superpowers/plans/2026-11-09-billing-dashboard-1-data.md |
| @@ -874,7 +874,8 @@ and §5; Plan 3 (written separately) covers §4.5. |
| - `docs/site/cli.md` `### carlos billing`: one paragraph for the two verbs |
| and their example lines. |
| - `docs/site/plans.md`: one sentence after the variables table saying the |
| - key also needs read access to balance, charges and refunds, and that |
| + key also needs read access to Balance, Balance Transaction Sources, |
| + Charges and Refunds, and Invoices (corrected 2026-11-10), and that |
| Stripe's webhook also sends `charge.succeeded`, `charge.captured` and |
| `charge.refunded`. |
| - `scripts/stripe-setup.sh`: the `WEBHOOK_PROBLEM` line that says "the six". |
| @@ -977,8 +978,10 @@ and §5; Plan 3 (written separately) covers §4.5. |
| ## After the plan |
| -- Before the first roll that carries this, Paul adds Balance, Charges and |
| - Refunds read to the dev and flagship restricted keys, and the three |
| +- Before the first roll that carries this, Paul adds Balance, Balance |
| + Transaction Sources (for `expand[]=data.source` on balance transactions), |
| + Charges and Refunds, and Invoices read to the dev and flagship restricted |
| + keys (Sources corrected 2026-11-10), and the three |
| charge events to both webhook endpoints. Without them the money pass |
| fails its job and nothing else changes; once added, the next hourly pass |
| backfills everything. |
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/billingstripe/client.go b/internal/billingstripe/client.go| index 55521e8d5..68dfe3d1b 100644 |
| --- a/internal/billingstripe/client.go |
| +++ b/internal/billingstripe/client.go |
| @@ -23,6 +23,7 @@ import ( |
| "strconv" |
| "strings" |
| "time" |
| + "unicode/utf8" |
| "github.com/carlosframework/platform/internal/billing" |
| ) |
| @@ -42,10 +43,13 @@ const ( |
| requestTimeout = 15 * time.Second |
| ) |
| -// Stable, sanitized error codes. Error never carries a response body, |
| -// a Stripe error "message" (which can echo request parameters back) or |
| -// any request secret — only these codes plus the HTTP status and, for a |
| -// parsed Stripe API error, Stripe's own "type" and "code" enum values. |
| +// Stable, sanitized error codes. Error never carries a response body or |
| +// any request secret: only these codes plus the HTTP status and, for a |
| +// parsed Stripe API error, Stripe's own "type", "code" and "param" values. |
| +// Stripe's "message" (which can echo request parameters back) travels only |
| +// on a 401 or 403, where it describes the key, not the request: it names |
| +// the permission a restricted key lacks. Any key-shaped token in it is |
| +// redacted. |
| const ( |
| CodeInvalidParams = "invalid_params" |
| CodeInvalidID = "invalid_id" |
| @@ -72,6 +76,10 @@ type Error struct { |
| // StripeParam is Stripe's error "param" field: the request parameter |
| // the refusal is about. Present only for CodeAPIError. |
| StripeParam string |
| + // StripeMessage is Stripe's error "message", present only for a |
| + // CodeAPIError on a 401 or 403 (see stripeKeyMessage): control |
| + // characters dropped, key-shaped tokens redacted, length capped. |
| + StripeMessage string |
| // Replayed reports that the provider answered from its memory of an |
| // earlier request under the same idempotency key (its |
| // Idempotent-Replayed header), and ran nothing now. |
| @@ -101,6 +109,12 @@ func (e *Error) Error() string { |
| if e.StripeCode != "" { |
| parts = append(parts, "stripe_code="+e.StripeCode) |
| } |
| + if e.StripeParam != "" { |
| + parts = append(parts, "stripe_param="+e.StripeParam) |
| + } |
| + if e.StripeMessage != "" { |
| + parts = append(parts, "stripe_message="+strconv.Quote(e.StripeMessage)) |
| + } |
| if e.Cause != nil { |
| parts = append(parts, "cause="+e.Cause.Error()) |
| } |
| @@ -201,13 +215,62 @@ type stripeErrorEnvelope struct { |
| Type string `json:"type"` |
| Code string `json:"code"` |
| Param string `json:"param"` |
| - // message and param are deliberately not decoded: Stripe's message |
| - // text can interpolate request parameters (card numbers' last four, |
| - // email addresses, free-text fields), and this package promises |
| - // never to surface response-body content in an error. |
| + // Message is kept only for a 401 or 403 (stripeKeyMessage): on |
| + // other statuses Stripe's text can interpolate request parameters |
| + // (card numbers' last four, email addresses, free-text fields). |
| + Message string `json:"message"` |
| } `json:"error"` |
| } |
| +// maxStripeMessage caps the message an Error carries, in bytes. |
| +const maxStripeMessage = 400 |
| + |
| +// keyToken matches a whole word holding anything shaped like a Stripe key |
| +// or signing secret, masked or not, wherever in the word it starts |
| +// ("x_rk_live_..." too): Stripe masks keys in its messages, but redact |
| +// anyway. A plain word that happens to hold "sk_" ("desk_top") is |
| +// redacted as well; over-redacting a log line is the safe side. |
| +var keyToken = regexp.MustCompile(`(?i)[A-Za-z0-9_*.\-]*(?:rk|sk|pk|whsec)_[A-Za-z0-9_*.\-]*`) |
| + |
| +// stripeKeyMessage is a 401 or 403 message made safe to log: control |
| +// characters dropped first, so dropping one cannot rejoin a key the |
| +// redaction already passed over, then key-shaped tokens redacted, then |
| +// capped at maxStripeMessage bytes on a rune boundary. |
| +func stripeKeyMessage(msg string) string { |
| + msg = strings.Map(func(r rune) rune { |
| + if r == '\n' || r == '\t' { |
| + return ' ' |
| + } |
| + if r < 0x20 || r == 0x7f || (r >= 0x80 && r < 0xa0) || r == '\u2028' || r == '\u2029' || r == utf8.RuneError { |
| + return -1 |
| + } |
| + return r |
| + }, msg) |
| + msg = keyToken.ReplaceAllString(msg, "[redacted]") |
| + msg = strings.TrimSpace(msg) |
| + if len(msg) > maxStripeMessage { |
| + cut := maxStripeMessage |
| + for cut > 0 && !utf8.RuneStart(msg[cut]) { |
| + cut-- |
| + } |
| + msg = msg[:cut] + "..." |
| + } |
| + return msg |
| +} |
| + |
| +// keyWord matches a Stripe error code or param name: a short word of |
| +// lowercase letters, digits, underscores, dots and brackets. |
| +var keyWord = regexp.MustCompile(`^[a-z0-9_.\[\]]{1,64}$`) |
| + |
| +// stripeKeyWord keeps a 401 or 403 error's code or param when it is |
| +// word-shaped and not key-shaped, and drops it otherwise. |
| +func stripeKeyWord(v string) string { |
| + if !keyWord.MatchString(v) || keyToken.MatchString(v) { |
| + return "" |
| + } |
| + return v |
| +} |
| + |
| // response is what every answer carries besides its body. |
| type response struct { |
| Status int |
| @@ -308,7 +371,7 @@ func (c *Client) exchange(ctx context.Context, method, path, query string, body |
| if resp.StatusCode < 200 || resp.StatusCode >= 300 { |
| var env stripeErrorEnvelope |
| _ = json.Unmarshal(respBody, &env) // best-effort; body itself never leaves this function |
| - return meta, &Error{ |
| + apiErr := &Error{ |
| Code: CodeAPIError, |
| HTTPStatus: resp.StatusCode, |
| StripeType: safeErrorEnum(env.Error.Type), |
| @@ -316,6 +379,16 @@ func (c *Client) exchange(ctx context.Context, method, path, query string, body |
| StripeParam: safeErrorParam(env.Error.Param), |
| Replayed: meta.Replayed, |
| } |
| + if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden { |
| + apiErr.StripeMessage = stripeKeyMessage(env.Error.Message) |
| + if apiErr.StripeCode == "" { |
| + apiErr.StripeCode = stripeKeyWord(env.Error.Code) |
| + } |
| + if apiErr.StripeParam == "" { |
| + apiErr.StripeParam = stripeKeyWord(env.Error.Param) |
| + } |
| + } |
| + return meta, apiErr |
| } |
| if out == nil { |
diff --git a/internal/billingstripe/client_test.go b/internal/billingstripe/client_test.go| index d9b575d32..6a8a4df0e 100644 |
| --- a/internal/billingstripe/client_test.go |
| +++ b/internal/billingstripe/client_test.go |
| @@ -11,6 +11,7 @@ import ( |
| "strings" |
| "testing" |
| "time" |
| + "unicode/utf8" |
| ) |
| func testClient(t *testing.T, base string) *Client { |
| @@ -448,6 +449,78 @@ func TestDo_APIErrorSanitized(t *testing.T) { |
| } |
| } |
| +// A restricted key missing a permission gets a 403 whose message names |
| +// the permission. The error carries that message, so the log says what to |
| +// grant, with every key-shaped token redacted. |
| +func TestDo_PermissionErrorCarriesMessage(t *testing.T) { |
| + const message = "The provided key 'rk_live_51AbCdEfGhIjKlMnOpQrStUv' does not have the required permissions for this endpoint on account 'acct_1'. Having the 'rak_balance_transaction_source_read' permission would allow this request to continue." |
| + for _, status := range []int{http.StatusForbidden, http.StatusUnauthorized} { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + w.WriteHeader(status) |
| + _ = json.NewEncoder(w).Encode(map[string]any{ |
| + "error": map[string]any{ |
| + "type": "invalid_request_error", |
| + "code": "secret_key_required", |
| + "param": "expand[0]", |
| + "message": message, |
| + }, |
| + }) |
| + })) |
| + c := testClient(t, srv.URL) |
| + _, err := c.GetSubscription(context.Background(), "sub_1") |
| + srv.Close() |
| + e, ok := err.(*Error) |
| + if !ok || e.Code != CodeAPIError || e.HTTPStatus != status { |
| + t.Fatalf("%d: err = %v, want CodeAPIError", status, err) |
| + } |
| + msg := e.Error() |
| + for _, want := range []string{ |
| + "stripe_type=invalid_request_error", |
| + "stripe_code=secret_key_required", |
| + "stripe_param=expand[0]", |
| + "does not have the required permissions", |
| + "Having the 'rak_balance_transaction_source_read' permission would allow this request to continue.", |
| + "'[redacted]'", |
| + } { |
| + if !strings.Contains(msg, want) { |
| + t.Errorf("%d: Error() lacks %q: %s", status, want, msg) |
| + } |
| + } |
| + if strings.Contains(msg, "rk_live") || strings.Contains(msg, "51AbCdEf") { |
| + t.Errorf("%d: Error() leaked the key: %s", status, msg) |
| + } |
| + } |
| +} |
| + |
| +func TestStripeKeyMessage(t *testing.T) { |
| + for _, tc := range []struct{ in, want string }{ |
| + {"key rk_live_abc123 bad", "key [redacted] bad"}, |
| + {"key 'sk_test_****************4242' bad", "key '[redacted]' bad"}, |
| + {"pk_live_x, RK_TEST_Y and whsec_z", "[redacted], [redacted] and [redacted]"}, |
| + {"line one\nline two\x1b[31m\u2028end", "line one line two[31mend"}, |
| + {" padded ", "padded"}, |
| + {"chunk_size stays", "chunk_size stays"}, |
| + {"key x_rk_live_abc123 glued", "key [redacted] glued"}, |
| + {"key sk\u2028_live_abc123 split", "key [redacted] split"}, |
| + {"key sk_\x00live_abc123 split", "key [redacted] split"}, |
| + {"key r\u0085k_live_abc123 split", "key [redacted] split"}, |
| + } { |
| + if got := stripeKeyMessage(tc.in); got != tc.want { |
| + t.Errorf("stripeKeyMessage(%q) = %q, want %q", tc.in, got, tc.want) |
| + } |
| + } |
| + long := strings.Repeat("é", maxStripeMessage) |
| + got := stripeKeyMessage(long) |
| + if len(got) > maxStripeMessage+len("...") || !strings.HasSuffix(got, "...") || !utf8.ValidString(got) { |
| + t.Errorf("long message not capped on a rune boundary: %d bytes", len(got)) |
| + } |
| + for in, want := range map[string]string{"secret_key_required": "secret_key_required", "expand[0]": "expand[0]", "rk_live_x": "", "x_sk_test_y": "", "has space": "", "": ""} { |
| + if got := stripeKeyWord(in); got != want { |
| + t.Errorf("stripeKeyWord(%q) = %q, want %q", in, got, want) |
| + } |
| + } |
| +} |
| + |
| // --- Strict decode: Session/Subscription reject null / missing / invalid id / missing livemode --- |
| func TestSessionUnmarshalJSON_Strictness(t *testing.T) { |
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/host/units/carlos-litestream.service b/internal/host/units/carlos-litestream.service| index 89472b450..235421d3b 100644 |
| --- a/internal/host/units/carlos-litestream.service |
| +++ b/internal/host/units/carlos-litestream.service |
| @@ -15,6 +15,12 @@ Wants=network-online.target |
| [Service] |
| ExecStart=/usr/local/bin/litestream replicate -config /etc/litestream.yml |
| EnvironmentFile=/data/litestream.env |
| +# Warnings and errors only. At INFO litestream logs one "replica sync" line |
| +# per database per sync, about 220k lines an hour on a box with a few dozen |
| +# databases, which pushed everything else out of a 256M journal after two |
| +# hours (discussion #802). LogLevelMax= is no substitute: journald stamps |
| +# every stdout line of this unit as info, so it would drop the errors too. |
| +Environment=LOG_LEVEL=warn |
| User=carlos |
| Group=carlos |
| CapabilityBoundingSet= |
diff --git a/internal/host/units_isolation_test.go b/internal/host/units_isolation_test.go| index 9b7d8b114..3b1b98f09 100644 |
| --- a/internal/host/units_isolation_test.go |
| +++ b/internal/host/units_isolation_test.go |
| @@ -635,3 +635,17 @@ func TestGenerationTemplateKeysNothingByItsInstanceString(t *testing.T) { |
| } |
| } |
| } |
| + |
| +// Litestream at INFO logs a line per database per sync and pushes everything |
| +// else out of a capped journal (#802). LOG_LEVEL holds it to warnings; a |
| +// LogLevelMax= would also drop its errors, since journald stamps every stdout |
| +// line of the unit as info. |
| +func TestLitestreamUnitLogsWarningsOnly(t *testing.T) { |
| + l := readUnit(t, "carlos-litestream.service") |
| + if !strings.Contains(l, "\nEnvironment=LOG_LEVEL=warn\n") { |
| + t.Error("carlos-litestream.service does not set LOG_LEVEL=warn") |
| + } |
| + if strings.Contains(l, "\nLogLevelMax=") { |
| + t.Error("carlos-litestream.service sets LogLevelMax=, which would drop litestream's errors") |
| + } |
| +} |
diff --git a/internal/lease/lease.go b/internal/lease/lease.go| index 389bf4804..e3d9bb2bc 100644 |
| --- a/internal/lease/lease.go |
| +++ b/internal/lease/lease.go |
| @@ -457,6 +457,7 @@ func (h *Held) newStore(dbPath string, syncInterval time.Duration) (*litestream. |
| db.Replica.SyncInterval = syncInterval |
| } |
| store := litestream.NewStore([]*litestream.DB{db}, compactionLevels) |
| + quietStoreLogs(store, db) |
| store.SnapshotInterval = SnapshotInterval |
| store.SnapshotRetention = SnapshotRetention |
| if h.generationPrefix != "" { |
diff --git a/internal/lease/quietlog.go b/internal/lease/quietlog.go| new file mode 100644 |
| index 000000000..315b56757 |
| --- /dev/null |
| +++ b/internal/lease/quietlog.go |
| @@ -0,0 +1,41 @@ |
| +package lease |
| + |
| +import ( |
| + "context" |
| + "log/slog" |
| + "path/filepath" |
| + |
| + "github.com/benbjohnson/litestream" |
| +) |
| + |
| +// Litestream logs one INFO "replica sync" line per database on every sync. |
| +// The box-wide binary is held to WARN by LOG_LEVEL in its unit; this is the |
| +// same floor for the replicator embedded here, whose lines would otherwise |
| +// land in carlos's own journal through slog.Default(). On a capped journal |
| +// those lines are what pushed everything else out after about two hours |
| +// (discussion #802). Warnings and errors still come through. |
| + |
| +// warnFloor passes on only records at WARN or above. |
| +type warnFloor struct{ slog.Handler } |
| + |
| +func (h warnFloor) Enabled(ctx context.Context, l slog.Level) bool { |
| + return l >= slog.LevelWarn && h.Handler.Enabled(ctx, l) |
| +} |
| + |
| +func (h warnFloor) WithAttrs(attrs []slog.Attr) slog.Handler { |
| + return warnFloor{h.Handler.WithAttrs(attrs)} |
| +} |
| + |
| +func (h warnFloor) WithGroup(name string) slog.Handler { |
| + return warnFloor{h.Handler.WithGroup(name)} |
| +} |
| + |
| +// quietStoreLogs replaces the loggers litestream.NewStore gave the store and |
| +// its database with the same ones held to WARN. Call it after NewStore and |
| +// before Open: NewStore sets the database's logger, Open starts the work |
| +// that logs. |
| +func quietStoreLogs(store *litestream.Store, db *litestream.DB) { |
| + quiet := slog.New(warnFloor{slog.Default().Handler()}).With(litestream.LogKeySystem, litestream.LogSystemStore) |
| + store.Logger = quiet |
| + db.SetLogger(quiet.With(litestream.LogKeyDB, filepath.Base(db.Path()))) |
| +} |
diff --git a/internal/lease/quietlog_test.go b/internal/lease/quietlog_test.go| new file mode 100644 |
| index 000000000..ad6ef9d3a |
| --- /dev/null |
| +++ b/internal/lease/quietlog_test.go |
| @@ -0,0 +1,50 @@ |
| +package lease |
| + |
| +import ( |
| + "bytes" |
| + "log/slog" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + lss3 "github.com/benbjohnson/litestream/s3" |
| +) |
| + |
| +// The embedded replicator's per-sync INFO lines stay out of carlos's journal |
| +// (#802); its warnings still reach it, labelled as litestream labels them. |
| +func TestNewStoreHoldsLitestreamToWarn(t *testing.T) { |
| + var buf bytes.Buffer |
| + prev := slog.Default() |
| + slog.SetDefault(slog.New(slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelDebug}))) |
| + t.Cleanup(func() { slog.SetDefault(prev) }) |
| + |
| + l := lss3.NewLeaser() |
| + l.Path = "instances/x.example/inc" |
| + h := &Held{leaser: l, replicaClient: &generationFake{}} |
| + store, db, err := h.newStore(filepath.Join(t.TempDir(), "app.db"), time.Second) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + db.Replica.Logger().Info("replica sync") |
| + db.Logger.Info("db info") |
| + store.Logger.Info("starting compaction monitor") |
| + db.Replica.Logger().Warn("replica sync warn") |
| + db.Logger.Error("compaction failed") |
| + |
| + got := buf.String() |
| + for _, quiet := range []string{"msg=\"replica sync\"", "db info", "starting compaction monitor"} { |
| + if strings.Contains(got, quiet) { |
| + t.Errorf("INFO line %s reached the log:\n%s", quiet, got) |
| + } |
| + } |
| + for _, loud := range []string{"replica sync warn", "compaction failed"} { |
| + if !strings.Contains(got, loud) { |
| + t.Errorf("%q did not reach the log:\n%s", loud, got) |
| + } |
| + } |
| + if !strings.Contains(got, "system=store") || !strings.Contains(got, "db=app.db") { |
| + t.Errorf("warnings lost litestream's labels:\n%s", got) |
| + } |
| +} |
diff --git a/internal/lease/release_snapshot_test.go b/internal/lease/release_snapshot_test.go| index a0228bc3c..3b2cafd61 100644 |
| --- a/internal/lease/release_snapshot_test.go |
| +++ b/internal/lease/release_snapshot_test.go |
| @@ -29,6 +29,10 @@ import ( |
| // countingReplica is a replica client that counts the LTX files opened |
| // (a restore's reads, one GET each on S3) and records the levels written, |
| // and can refuse snapshot writes. |
| +// drainSnapshotOnly marks the context of the drain release's own snapshot, |
| +// so a refusing fake can refuse that snapshot and no other. |
| +type drainSnapshotOnly struct{} |
| + |
| type countingReplica struct { |
| litestream.ReplicaClient |
| mu sync.Mutex |
| @@ -52,7 +56,12 @@ func (c *countingReplica) WriteLTXFile(ctx context.Context, level int, minTXID, |
| c.mu.Lock() |
| c.writes = append(c.writes, level) |
| fail := c.failSnapshot && level == litestream.SnapshotLevel |
| - early := c.refuseEarly && level == litestream.SnapshotLevel |
| + // Only the drain's own snapshot is refused: the test marks its context |
| + // (drainSnapshotOnly). The store monitor's snapshots run on the store's |
| + // context and are never refused, so litestream's DB.Snapshot, which |
| + // leaves its reader and the WAL open when an upload fails (#810, #811), |
| + // never runs into this fake's refusal. |
| + early := c.refuseEarly && level == litestream.SnapshotLevel && ctx.Value(drainSnapshotOnly{}) != nil |
| if level == litestream.SnapshotLevel { |
| c.snapshotTXID = maxTXID |
| } |
| @@ -230,7 +239,9 @@ func TestDrainReleaseSnapshotEarlyRefusalReleasesTheWAL(t *testing.T) { |
| dir := t.TempDir() |
| rc := &countingReplica{ReplicaClient: lsfile.NewReplicaClient(dir), refuseEarly: true} |
| r, path := manyL0(t, fx, "instances/h", rc, 5) |
| - txid, snapErr, err := r.FinishSnapshot(ctx) |
| + // The refusal applies to the drain's own snapshot only (#810): its |
| + // context carries drainSnapshotOnly, the store monitor's does not. |
| + txid, snapErr, err := r.FinishSnapshot(context.WithValue(ctx, drainSnapshotOnly{}, true)) |
| if err != nil || snapErr == nil { |
| t.Fatalf("FinishSnapshot: txid %d, snapshot %v, %v; want the snapshot's failure alone", txid, snapErr, err) |
| } |
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/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index 93ee503c9..d017240d7 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -154,4 +154,5 @@ plan14-root-reads-warm-set-published-724.tsv 158a30344d45448de74c9d6fbcc46eeab1e |
| plan14-root-reads-gvisor-probe-diag.tsv a9ae6b238b6b2e177be1f9c7ae06ea0f24477e4eb0e58abda63f4b7337dbe3ee |
| plan14-root-reads-deploy-happy-path.tsv a9ae6b238b6b2e177be1f9c7ae06ea0f24477e4eb0e58abda63f4b7337dbe3ee |
| plan14-root-reads-held-move-speed.tsv 837f27a6b7b6ed272f8c68aca07650fa32cf3ec92ce28bf9d812a4282eeb0b58 |
| -plan14-root-reads-held-floor-capability.tsv acef53b35eaa775cd2e32a9c5a0684a313def0425cd2c5c910d53c61b3a6cbf1 |
| +plan14-root-reads-litestream-quiet-802.tsv 6d3ea7fccce1a7f4bc507b6eb8d368ed0b62f83022504aa04c7684c72c93aa9a |
| +plan14-root-reads-held-floor-capability.tsv b60c83f8ba4311222174284420b5327e92002882b4a1c6f291e74e69234c6f59 |
diff --git a/internal/provision/testdata/plan14-root-reads-litestream-quiet-802.tsv b/internal/provision/testdata/plan14-root-reads-litestream-quiet-802.tsv| new file mode 100644 |
| index 000000000..34005d4fc |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-litestream-quiet-802.tsv |
| @@ -0,0 +1,6 @@ |
| +# Census overlay litestream-quiet-802, written by census-propose (#369). census-ruling-litestream-quiet-802, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-litestream-quiet-802.md. |
| +# 1 body, 0 sites, 2 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +@legacy 1c221b073d38eec62bf1995804256125ea66ba141a0cd32af975e6915d1ab1e4 internal/host/units/carlos-litestream.service external legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-ls284;basis=MemoryMax 256M -> 512M, adds Environment=GOMEMLIMIT=384MiB and RestartSteps=5/RestartMaxDelaySec=60 backoff; ExecStart, user, sandboxing and the config path it reads are unchanged; no new read;rev3=census-ruling-litestream-quiet-802;basis=adds Environment=LOG_LEVEL=warn (litestream logs warnings and errors only, #802); ExecStart, user, sandboxing, EnvironmentFile and the config path it reads are unchanged; no new read file:external@0 c6b8a0aacef922143bc21c52b4c22bca98f90e6b7d3dbf8629dc7040f2a00664 |
| +internal/host/units/carlos-litestream.service external legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-ls284;basis=MemoryMax 256M -> 512M, adds Environment=GOMEMLIMIT=384MiB and RestartSteps=5/RestartMaxDelaySec=60 backoff; ExecStart, user, sandboxing and the config path it reads are unchanged; no new read;rev3=census-ruling-litestream-quiet-802;basis=adds Environment=LOG_LEVEL=warn (litestream logs warnings and errors only, #802); ExecStart, user, sandboxing, EnvironmentFile and the config path it reads are unchanged; no new read file:external@0 c6b8a0aacef922143bc21c52b4c22bca98f90e6b7d3dbf8629dc7040f2a00664 |
| +@coverage internal/host/units 429984217ca0fccd69aa739521fb2d7fc7851f050145c06ffaab8afc391d981e |
| +@coverage internal/lease f6505e89d92b6146c3394f2a61718e349da9b57649b50742d3ef71b5ae8a07de |
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. |