carlos / platform Public

Console 150 ms budget: quick wins

A per-app frame cache (channels, production flag, pipeline; 30 s; every console write to the app clears it before its response, per-app generations so an in-flight load can't store an old value), the account manifest checked once per process, a per-request memo so each page reads box reports, edges and instances.json once, settings sections that read only what they show, and account settings reading the account telemetry key directly. Scripted session 857 -> 320 S3 requests (ceiling lowered). Replaces the unbuilt 17-task cache plan. Reviewed by Astra (task 2 and whole branch, READY AFTER FIXES, fixed).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Prompts:

  Did we not get our Rastrillo Design system /fleet pages?

Squashed from console-perf-quick-wins into main.
claude agent, operated by paul@keymail.dev fc30b42163ac77e1505b4ab6df6125f4fd28767c parent 78c2365
42 files changed, +2,723 −180
  • docs/superpowers/plans/2026-10-26-console-perf-quick-wins.md +190 −0
  • docs/superpowers/reviews/CODEX-FINDINGS-console-perf-quick-wins-r1.md +39 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-console-perf-quick-wins.md +42 −0
  • internal/console/apiassets_test.go +1 −0
  • internal/console/apicli_test.go +3 −0
  • internal/console/apigatepass_test.go +1 −0
  • internal/console/apiinstances.go +16 −2
  • internal/console/apiinstanceschannel_test.go +2 −0
  • internal/console/apipipeline_test.go +1 −0
  • internal/console/apisystemgeoip.go +8 −4
  • internal/console/apisystemupdate.go +2 −2
  • internal/console/appframe.go +383 −0
  • internal/console/appframe_test.go +915 −0
  • internal/console/appsettings.go +54 −22
  • internal/console/appsettings_sections_test.go +15 −4
  • internal/console/appsettings_test.go +2 −1
  • internal/console/bakecontrols_test.go +4 −0
  • internal/console/claim_routes.go +10 −0
  • internal/console/deletion_test.go +2 −0
  • internal/console/deployscope_test.go +1 −0
  • internal/console/ladder_test.go +16 −1
  • internal/console/ownership.go +3 −0
  • internal/console/pendingflow_test.go +1 −0
  • internal/console/perflatency_test.go +22 −3
  • internal/console/perfquickwins_test.go +631 −0
  • internal/console/perfspeed_test.go +6 −0
  • internal/console/perfwalk_test.go +6 −2
  • internal/console/perfwiring_test.go +29 −0
  • internal/console/pipelinepage.go +4 −7
  • internal/console/regionbudget_test.go +5 −2
  • internal/console/regioncandidates.go +4 −10
  • internal/console/remoteinstances.go +11 −2
  • internal/console/remoteinstances_round4_test.go +1 −0
  • internal/console/remoteinstances_test.go +1 −0
  • internal/console/reqmemo.go +124 −0
  • internal/console/rolloutjoin_test.go +1 −0
  • internal/console/serialbump_test.go +3 −0
  • internal/console/server.go +75 −38
  • internal/console/server_test.go +1 −0
  • internal/console/testdata/perf-budgets.txt +34 −28
  • internal/console/testdata/perf-session-s3.txt +1 −1
  • internal/console/view.go +53 −51

CI failed — run details

landed from console-perf-quick-wins

diff --git a/docs/superpowers/plans/2026-10-26-console-perf-quick-wins.md b/docs/superpowers/plans/2026-10-26-console-perf-quick-wins.md
new file mode 100644
index 000000000..de1cb74d6
--- /dev/null
+++ b/docs/superpowers/plans/2026-10-26-console-perf-quick-wins.md
@@ -0,0 +1,190 @@
+# Console perf quick wins Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Cut the warm S3 requests behind the console's slowest screens, so most app tabs fit the 150 ms page budget, using small fixes each provable by the perf walk's own counts.
+
+**Architecture:** Two small caches and a handful of local fixes. The account manifest check is remembered in process once it succeeds. A per-app frame cache holds the reads every app tab makes first (channels, production flag, pipeline) for 30 s, and every console write that names an app clears that app's entry before its response goes out. A per-request memo stops the same box reports, edges and instance manifest being read twice in one page. Settings sections read only what they show, and account settings stops reading a key nothing writes.
+
+**Tech Stack:** Go, `internal/console`, `internal/release`, `internal/telemetry`, the perf walk (`internal/console/perfwalk_test.go`) over `internal/s3fake`.
+
+**Spec:** `docs/superpowers/specs/2026-10-25-console-ux-perf-design.md`, Part 2 (§2.4 C and the "read your own writes" rule of §2.4 A). This plan REPLACES `docs/superpowers/plans/2026-10-25-console-perf-2-fixes.md`: no read-set cache, no deferred parts, no restricted loaders.
+
+**Driven by:** the `over:` records in `internal/console/testdata/perf-budgets.txt` (measured 2026-10-26, 25 ms per S3 request). "The frame" below is the 7 warm S3 calls every app tab pays first: the account manifest `Get`, the channel listing plus one `Get` per channel (3 in the fixture), the production flag and the pipeline.
+
+## Global Constraints
+
+- Local tests are targeted: `go test ./internal/console/ -run '<names>' -count=1`. Never a whole package, never an empty `-run`. CI runs the full suite.
+- `gofmt -l` empty, `go vet ./internal/console/ ./internal/telemetry/`, and `GOOS=darwin go build ./... && GOOS=windows go build ./...` before each commit.
+- Leave `GOCACHE` at its default.
+- New tests go through the production wiring: `newPerfFixture` (real S3 client over `internal/s3fake`) or `newConsoleFixture`, signed in with `signInPaul`, writes made with `postForm` against the real routes.
+- Warm S3 requests only go down. No new background polling, timers or per-box reads. `TestPerfSessionS3Requests` stays at or under its ceiling after every task.
+- Security gate order (session, CSRF, owner/role) is unchanged. Caches are consulted only after a handler's gate has passed, and only on GET/HEAD view paths; write doors keep their own direct reads.
+- Cached values are immutable to callers: every read from a cache returns a deep copy.
+- No new user-facing copy. If a task finds it cannot avoid one, stop and get a Luna pass on the string first.
+- No tenant names in code, tests or fixtures.
+- Commit per task; every commit message ends with `Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>`.
+- Each task edits `internal/console/testdata/perf-budgets.txt` for the screens it fixes: a screen with 0 warm calls and under 150 ms loses its record; a screen with a few calls left and under 150 ms becomes `calls <n>: <reason>`; a screen still slow keeps `over:` with its new count in the reason.
+- AGENTS.md "Stopping rules" apply. Per rule 3, Task 2 (a cache) gets its own review; the rest are covered by one whole-branch review.
+
+## Review Focus
+
+- A person promotes, rolls back, edits a channel or canary, or saves settings, in the browser or with the CLI, and the next page view must show the change, never the pre-write value. Owned by Task 2 (`TestAppFrameOwnWriteVisible`, `TestAppFrameCLIWriteVisible`).
+- A GET that started before a write and finishes after it must not put the old value back into the cache. Owned by Task 2 (`TestAppFrameLoadDuringWriteNotStored`).
+- A failed read (S3 error on a channel or the pipeline) must not be cached: the next view retries. Owned by Task 2 (`TestAppFrameErrorNotCached`).
+- A strict reader of box reports (`loadBoxJoinComplete`) must still see "incomplete" when one box report fails, after the memo. Owned by Task 3 (`TestRequestMemoKeepsBoxCompleteness`).
+- A write door that decides placement from `liveEdges` must keep reading fresh, not a memoized view. Owned by Task 3 (`TestReqMemoOnlyOnViews`).
+
+---
+
+### Task 1: Remember the account manifest
+
+Every app tab `Get`s `accounts/<sqid>/account.json` (`ensureAccountManifest`, `internal/console/server.go:4384-4402`, called from `appPage` at `server.go:3611` and from `server.go:4686`). Once it exists it never needs checking again in this process.
+
+Screens: every app tab, frame 7 → 6.
+
+**Files:**
+- Modify: `internal/console/server.go:4384-4402` (`ensureAccountManifest`), `internal/console/server.go:892` (`Server` gains the field)
+- Test: `internal/console/perfquickwins_test.go` (create)
+
+**Interfaces:**
+- Produces: `Server.manifestSeen sync.Map` keyed by sqid (value `struct{}`). `ensureAccountManifest` returns at once for a sqid in the map; it stores the sqid after a successful `Get` or a successful `WriteAccountManifest`, never after an error. Account deletion (`handleDeleteAccount`, `ownership.go:95`) deletes the sqid from the map.
+
+- [ ] **Step 1: Write the failing test** `TestAccountManifestCheckedOncePerProcess` in `perfquickwins_test.go`: `newPerfFixture`; GET `/apps/kass/activity` twice; record request paths with `lat.Fake().OnRequest`; the key `accounts/<sqid>/account.json` is requested exactly once across both views. Second case: delete the manifest object from the fake bucket before the first view; after two views it was written once and read once.
+- [ ] **Step 2: Run** `go test ./internal/console/ -run TestAccountManifestCheckedOncePerProcess -count=1`. Expected: FAIL (two reads).
+- [ ] **Step 3: Implement** as in Interfaces.
+- [ ] **Step 4: Run** `go test ./internal/console/ -run 'TestAppPageBackfillsAccountManifest|TestBackfill|TestDeleteAccount' -count=1`. Expected: PASS.
+- [ ] **Step 5: Walk** `CI=1 go test ./internal/console/ -run 'TestConsoleScreensMeetTheBudget|TestPerfSessionS3Requests' -count=1`; update every app-tab `over:` reason from "7 S3 calls" frame to 6. Commit `console: check the account manifest once per process`.
+
+### Task 2: A per-app frame cache, cleared by every console write to the app
+
+Today `Assemble` (`internal/console/view.go:560-657`) runs `assembleChannels` (`view.go:784-832`: one listing plus one `release.Channel` per channel) and `assembleProduction` (`view.go:834`, `release.GetProduction`) for each app on every view, then `applyPipelineView` (`server.go:3687-3712`) reads the pipeline, and the Overview and Releases pending cards read it again through `pendingPipeline` (`pendinghandlers.go:473`, called from `server.go:3818` and `:3857`), as does the Pipeline settings section (`pipelinepage.go:222`).
+
+Screens, warm S3 after (from Task 1's 6): account-review 6 → 0, activity 6 → 0, settings Placement/Delete 6 → 0, settings Pipeline 7 → 0, account home `/a/{sqid}/` 5 → 0, Overview 15 → 8, Releases 13 → 6, Analytics 10 → 4, Errors and Availability 16 → 10, Logs 14 → 8, Running 23 → 17, instance page 30 → 24, Settings General 31 → 25, settings sections worst 30 → 24, errors-analytics section 8 → 2.
+
+**Files:**
+- Create: `internal/console/appframe.go`
+- Modify: `internal/console/view.go:560-657` (`Assemble` becomes a wrapper), `:784-870` (`assembleChannels`, `assembleProduction` take an `appFrame`), `AppView` gains `PipelineErr string`
+- Modify: `internal/console/remoteinstances.go:531-533` (`assembleApps` uses the cache)
+- Modify: `internal/console/server.go:3687-3712` (`applyPipelineView` reads the frame), `:3818`, `:3857` (pending cards pass `p.Detail.Pipeline`), `internal/console/pipelinepage.go:219-230` (uses `p.Detail.Pipeline` / `p.Detail.PipelineErr`)
+- Modify: `internal/console/claim_routes.go:59-69` (`registerRoute`: the write hook)
+- Test: `internal/console/appframe_test.go` (create)
+
+**Interfaces:**
+- Produces:
+ - `type frameChannel struct { Name string; Pointer *release.ChannelPointer; Err string }`
+ - `type appFrame struct { Channels []frameChannel; ChannelsErr string; Production *release.ProductionFlag; ProductionErr string; Pipeline *release.Pipeline; PipelineErr string }` and `func (f appFrame) clone() appFrame` (deep: every slice, every pointed-to struct and its slices).
+ - `func loadAppFrame(ctx context.Context, st release.Store, pub ed25519.PublicKey, acct, app string) appFrame`: today's reads, in today's order, with `pipelineStoreTimeout` on the pipeline read.
+ - `type appFrames struct { mu sync.Mutex; ttl time.Duration; now func() time.Time; ... }` whose zero value is ready (ttl 0 means `appFrameTTL`, nil `now` means `time.Now`), like `keyedLocks` (`applocks.go:5-15`), so `&Server{}` literals in tests stay safe. `func (c *appFrames) get(ctx context.Context, acct, app string, load func(context.Context) appFrame) appFrame`; `func (c *appFrames) clearApp(app string)` (every account's entry for that app name); `func (c *appFrames) clearAccount(sqid string)`. `const appFrameTTL = 30 * time.Second`. `Server.frames appFrames` (a value field).
+ - `get` records a per-app generation before loading and stores the result only if the generation is unchanged and the frame has no `*Err` set. Clears bump the generation. No single-flight, no background refresh, no size cap beyond the app count (one entry per viewed app).
+ - `func (s *Server) appFrame(ctx context.Context, acct, app string) appFrame`: `s.frames.get` with `loadAppFrame` over `s.cfg.Releases`; returns a clone.
+ - `func Assemble(...)` keeps its signature (tests call it) and calls `assembleViews(ctx, regPath, acct, apps, dns, remote, frame func(app string) appFrame)`; `assembleApps` passes `s.appFrame`.
+ - The write hook, in `registerRoute`: for a pattern whose method is not GET or HEAD (method-less patterns: when `r.Method` is not GET or HEAD), wrap `w` so that the first `WriteHeader` or `Write` first runs the clear, and run the clear again when the handler returns. The clear is `clearApp(r.PathValue("app"))` when the pattern has `{app}`; otherwise `clearAccount(r.PathValue("sqid"))` when it has `{sqid}`; otherwise nothing. This covers every browser door under `/a/{sqid}/apps/{app}/` (promote, rollback, production, fasttrack, canary, canary/retire, pipeline, pending confirm/reject, settings saves, rename, move, delete, domains, place, gate, swap, restart) and every CLI door under `/api/cli/apps/{account}/{app}/` (promote, rollback, releases, channels/resign, pipeline PUT, version-target, retention, delete, restore).
+ - Every console writer of channels, production or pipeline sits under an `{app}` door, checked 2026-10-26: `handlePromote` (`server.go:4943`, `:4994`), `handleProduction` (`:5279`), `handleNewCanary` (`:5600`), `executePendingPromote` and `executePendingPolicy` (`pendinghandlers.go:560`, `:607`, reached from `proposeThenExecute` and `handlePendingConfirm`), `handlePipelineSettingsSave` (`pipelinepage.go:202`), `ensureProductionForBakes` (`apipipeline.go:269`, from the CLI pipeline PUT), and the CLI promote/rollback doors. `claimAppWith` (`server.go:4691`) writes a new app's pipeline from `POST /a/{sqid}/apps/new` (cleared by `clearAccount`) and the CLI `new` doors (a name with no live entry). So the hook alone covers them. Two explicit clears remain: `handleAppRename` calls `clearApp(newName)` (the hook clears the old name), and the trash doors (`POST /a/{sqid}/trash/restore`, `/trash/delete`, app in the form) are covered by `clearAccount`. Any writer outside the console is bounded by the 30 s window. A refused or failed write also clears: that costs one reload, which is what every view pays today.
+- Write doors keep their direct reads (`pendinghandlers.go:401, :496, :591, :731`, `pipelinepage.go:304`, `apipipeline.go`, `channelmove.go:146`): a decision is never made on a cached value.
+
+- [ ] **Step 1: Write the failing tests** in `appframe_test.go`, all on `newPerfFixture` with `signInPaul`:
+ - `TestAppFrameWarmViewReadsNothing`: GET `/apps/kass/activity` twice; the second view makes 0 S3 requests (`lat.Calls()` before/after).
+ - `TestAppFrameOwnWriteVisible`, table-driven over promote (`POST /apps/kass/promote` stable to v2), rollback, the production switch, fasttrack, a new canary, canary retire and a pipeline settings save (the settings saves that change what the frame holds): warm the frame with a GET, make the write with `postForm`, then the very next GET of the page that shows it (Releases, Overview or the settings section) shows the new value. Uses the existing seeds (`fx.channelVersion` confirms the write landed).
+ - `TestAppFrameCLIWriteVisible`: warm the frame; promote through `POST /api/cli/apps/<sqid>/kass/promote` with the fixture's CLI token; the next browser GET of Releases shows the new version.
+ - `TestAppFrameLoadDuringWriteNotStored`: unit test on `appFrames`: start `get` with a `load` that blocks on a channel; call `clearApp`; release the load; the next `get` calls `load` again.
+ - `TestAppFrameErrorNotCached`: `lat.Fake().OnRequest` fails the pipeline key once with 500; two GETs: the second reads the pipeline again and shows it.
+ - `TestAppFrameCopiesOnRead`: `get`, mutate the returned `Channels[0].Pointer.History` and `Pipeline.Channels`, `get` again: unchanged.
+ - `TestAppFrameExpires`: `appFrames{now: clock}`; after advancing the clock 31 s the next `get` loads.
+ - `TestOverviewReadsPipelineOnce`: with one pending change seeded, a cold GET of `/apps/kass` requests the pipeline key once.
+- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestAppFrame|TestOverviewReadsPipelineOnce' -count=1`. Expected: FAIL.
+- [ ] **Step 3: Implement** as in Interfaces.
+- [ ] **Step 4: Run** Step 2's command, then `go test ./internal/console/ -run 'TestAssemble|TestView|TestLadder|TestPending|TestPipeline|TestPromote|TestRollback|TestCanary|TestProduction|TestFastTrack|TestAppSettings|TestPageHeadsOnAccountPages' -count=1`. Expected: PASS.
+- [ ] **Step 5: Walk** (Task 1's command). Delete the records for account-review, activity and `/a/{sqid}/{$}`; Analytics becomes `calls 4: both telemetry settings, the analytics day listing and one day read`; update the remaining reasons with the measured counts. Commit `console: cache the app-tab frame for 30 s; every console write to the app clears it first`.
+- [ ] **Step 6: Review.** Per stopping rule 3 (a cache), one Opus or Astra review of this task from `docs/superpowers/reviews/REVIEW-BRIEF-TEMPLATE.md`, focused on the hook's coverage and the generation check.
+
+### Task 3: Read each thing once per request
+
+A request-scoped memo for the reads one GET repeats, installed only on GET and HEAD requests. No cross-request state, and write doors (which also call `liveEdges` for placement) never see it. Inventory checked 2026-10-26:
+
+- Running (`handleAppInstances`, `server.go:3930`): `liveEdges` (`regioncandidates.go:203`, `readLiveEdgesSnapshot`: a `control/edges/` listing, a `Get` per file, then `status.LoadBoxesComplete`) runs twice, from `appDefault` (`server.go:3957` → `regiondefault.go:36`) and at `server.go:3966`. `instances.json` is read twice when the app has no rows (`appPolicy`, `regioncandidates.go:285`, and `instanceDomainFor` via `attachHint`, `server.go:3976`).
+- Instance page (`handleAppInstance`, `instancepage.go:242`): platform `status/boxes/` loaded three times, by `systemBoxes` (`instancepage.go:285` → `apisystemupdate.go:270`), `loadRolloutJoin` (`:291` → `apiinstances.go:560`) and `updatesPage` (`:294` → … → `geoipInventory`, `apisystemgeoip.go:252`); each fleet's box reports two or three times (`apisystemupdate.go:295`, `apiinstances.go:618`, `apisystemgeoip.go:299`).
+- Logs (`server.go:3995`): the host picker lists and reads every instance record through `s.listRecords` (`server.go:4045`) only for `rec.Host`, while the frame already holds the same records through the process-cached `pageRecords` (`remoteinstances.go:464`).
+- Errors, Availability and Analytics repeat nothing (one telemetry resolve, one read per window); they are left for a later round.
+
+Screens, warm S3 after (from Task 2): Running 17 → ~9, instance page 24 → ~10, Logs 8 → 3 (the log-chunk listings). The walk records the exact counts.
+
+**Files:**
+- Create: `internal/console/reqmemo.go`
+- Modify: `internal/console/claim_routes.go:59-69` (`registerRoute` installs the memo for GET and HEAD), `internal/console/regioncandidates.go:203` (`liveEdges`), `:285` (`appPolicy`'s manifest read), `instanceDomainFor` (`server.go:5636`), `internal/console/apisystemupdate.go:270`, `:295`, `internal/console/apiinstances.go:560`, `:618`, `internal/console/apisystemgeoip.go:252` (box loads go through the memo), `internal/console/server.go:4043-4054` (Logs host picker)
+- Test: `internal/console/perfquickwins_test.go`
+
+**Interfaces:**
+- Produces:
+ - `func withReqMemo(ctx context.Context) context.Context` and `func memoize[T any](ctx context.Context, key string, load func() (T, error)) (T, error)`: with no memo in `ctx`, `load` runs every time. Errors are memoized too (a retry inside one request changes nothing). Memoized values are shared within the request only; callers already treat these results as read-only.
+ - `func (s *Server) loadBoxes(ctx context.Context, st release.Store, prefix string) (boxes []status.Box, complete bool, err error)`: `status.LoadBoxesComplete` behind memo key `boxes:<prefix>` (`""` for the platform, `fleets/<name>/` per fleet). `status.LoadBoxes` callers above switch to it and drop `complete`; the status package documents that both return the same boxes (`internal/status/fleet.go:225-236`). Strict callers keep using `complete` and `err` exactly as today.
+ - `liveEdges` behind memo key `edges`; the app's `instances.json` behind `instances-manifest:<sqid>/<app>`.
+ - The Logs host picker takes its record hosts from `s.pageRecords(ctx, acct.Sqid, p.AppName)` instead of `s.listRecords`.
+
+- [ ] **Step 1: Write the failing tests** on `newPerfFixture`, keys recorded with `lat.Fake().OnRequest`:
+ - `TestInstancePageLoadsBoxesOnce`: GET `/apps/kass/instances/kass.carlosapp.dev`; the `status/boxes/` listing requested once, each fleet's once.
+ - `TestRunningTabReadsEdgesOnce`: GET `/apps/kass/instances`; `control/edges/` listed once.
+ - `TestRequestMemoKeepsBoxCompleteness`: `OnRequest` fails one box report's key; two `s.loadBoxes` calls inside one `withReqMemo` context both return `complete == false` with the same boxes, and the existing `loadBoxJoinComplete` tests stay green.
+ - `TestLogsHostPickerReadsNoRecords`: three instance records seeded; GET `/apps/kass/logs` warm; no `Get` under `apps/<sqid>/kass/instances/`; all three hosts in the picker.
+ - `TestReqMemoOnlyOnViews`: `memoize` on a context without `withReqMemo` runs `load` on every call; a test handler registered through `registerRoute` as `POST /x` sees no memo in its request context, and as `GET /x` sees one.
+- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestInstancePageLoadsBoxesOnce|TestRunningTabReadsEdgesOnce|TestRequestMemoKeepsBoxCompleteness|TestLogsHostPickerReadsNoRecords|TestReqMemoOnlyOnViews' -count=1`. Expected: FAIL.
+- [ ] **Step 3: Implement** as in Interfaces.
+- [ ] **Step 4: Run** Step 2's command, then `go test ./internal/console/ -run 'TestInstancePage|TestInstancesTab|TestRegion|TestUpdatesEnforced|TestUpdatesSection|TestSystemUpdate|TestBoxJoin|TestGeoip|TestAppLogs' -count=1`. Expected: PASS.
+- [ ] **Step 5: Walk**; Logs becomes `calls 3: the three log-chunk listings`; Running and the instance page keep `over:` with their measured counts unless they now pass. Commit `console: each remote read once per request`.
+
+### Task 4: Settings sections read only what they show
+
+`settingsSectionReadsFor` (`server.go:4294-4307`) sends General, Domains, Environments, Storage, Email and Feature flags through the whole `assembleSettings` (`appsettings.go:329-403`), which makes every read for every section: `settingsDomains` (`:343`, claims, `aliasReadings` box reports, cert-warm listing and reads), `settingsGates` (`:369`, every instance record), `appDeployEmpty` (`:374`, two full listings), `envCards` (`:384`, environments plus a store `GetIn` each at `:532`), `storeCard` (`:385`), `storeEnvCards` (`:386`, the same store records again at `:567`), `mailCard` (`:387`), `featuresCard` (`:388`). Environments and Storage each display only their own loop, so splitting by section also ends the double store read. `AppFlags`, `readyRouteHost` and the mismatch lookup are local and stay.
+
+Screens: `/settings` (General) 25 → 3 (the two one-key listings and the swap policy); `/settings/{section}`: Environments, Storage, Email, Feature flags drop to their own reads (1 to 2 + 2 per environment); Domains keeps claims, box reports, cert-warm and gates, so the record stays `over:` with Domains' measured count as the worst.
+
+**Files:**
+- Modify: `internal/console/server.go:4283-4307` (`settingsSectionReads` gains `domains, gates, deployEmpty, envs, store, mail, features bool` in place of `record`), `:4310-4318` (`populateAppSettings` passes them)
+- Modify: `internal/console/appsettings.go:329-403` (`assembleSettings` takes the flags), `:752-763` (`appDeployEmpty`)
+- Test: `internal/console/perfquickwins_test.go`
+
+**Interfaces:**
+- Produces:
+ - `func (s *Server) assembleSettings(ctx context.Context, p *page, acct *Account, reads settingsSectionReads) SettingsView`: each remote part runs only when its flag is set. Section flags: general `{deployEmpty, swap}`; domains `{domains, gates}`; environments `{envs}`; storage `{store}`; email `{mail}`; features `{features}`; placement, errors-analytics, delete, pipeline unchanged.
+ - `appDeployEmpty` asks each prefix (`release.AppPrefix`, `release.LegacyAppPrefix`) for one key: `release.PageLister.ListPage(ctx, prefix, "", 1)` (`internal/release/store.go:382-384`) when the store implements it, else `List`. Its rename callers (`appsettings.go:861`, `:916`) get the same. `S3Store` and `DirStore` implement `PageLister`; the console test store (`deletableStore`, `view_test.go:22`) does not, so the fallback is exercised by the existing settings tests.
+
+- [ ] **Step 1: Write the failing tests:**
+ - `TestSettingsSectionReadsOnlyItsOwn`, table over general, environments, storage, email, features: GET the section on `newPerfFixture`, record keys with `OnRequest`; General requests nothing under `instances/`, `status/boxes/`, `control/cert-warm/`, `stores/` or the environments prefix; Environments nothing under `status/boxes/`, `control/cert-warm/`, `instances/`; Storage, Email and Features nothing under any of those nor each other's keys.
+ - `TestSettingsStorageReadsEachStoreOnce`: two environments seeded; GET Storage; each environment's store record requested once.
+ - `TestAppDeployEmptyAsksForOneKey`: a store wrapper with `ListPage` recording `limit`: called with 1 per prefix, `List` never called; over a store without `ListPage`, falls back to `List` and gives the same answer.
+- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestSettingsSectionReadsOnlyItsOwn|TestSettingsStorageReadsEachStoreOnce|TestAppDeployEmptyAsksForOneKey' -count=1`. Expected: FAIL.
+- [ ] **Step 3: Implement** as in Interfaces.
+- [ ] **Step 4: Run** Step 2's command, then `go test ./internal/console/ -run 'TestAppSettings|TestSettings|TestDomains|TestStore|TestEnvironment|TestRename|TestAppSwap' -count=1`. Expected: PASS.
+- [ ] **Step 5: Walk**; General's record becomes `calls 3: the two one-key app listings for the rename check and the swap policy`; the sections record keeps `over:` with Domains' measured count and the others' counts in the reason. Commit `console: each settings section reads only what it shows`.
+
+### Task 5: Account settings reads the account's telemetry key, not an app key
+
+`handleAccountSettings` calls `telemetry.Resolve(ctx, s.cfg.Releases, acct.Sqid, "")` (`server.go:3522`), which reads `telemetry.AppKey(sqid, "")` = `apps/<sqid>//telemetry.json`, a key nothing writes, plus the account key. The account level is written at `telemetry.AccountKey(sqid)` (`internal/telemetry/telemetry.go:48`) by `handleAccountErrorLevel` (`errorsview.go:364`) and `handleAccountAnalyticsSetting` (`analyticsview.go:156`); `Resolve` (`telemetry.go:109-122`) reads that key and then the app key.
+
+Screens: `/a/{sqid}/settings` 3 → 2.
+
+**Files:**
+- Modify: `internal/console/server.go:3516-3527`
+- Test: `internal/console/perfquickwins_test.go`
+
+**Interfaces:**
+- Consumes: `telemetry.Read(ctx, s, telemetry.AccountKey(sqid)) (Settings, string, error)`, `telemetry.Fold(acct, appSt Settings) Resolved`.
+
+- [ ] **Step 1: Write the failing tests:** `TestAccountSettingsReadsNoAppTelemetryKey`: GET `/settings`; no requested key contains `//`. `TestAccountSettingsShowsAccountLevel`: set the account Errors level through its POST door; GET `/settings` shows it (the same assertion the existing account-settings tests make, kept green).
+- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestAccountSettingsReadsNoAppTelemetryKey|TestAccountSettingsShowsAccountLevel' -count=1`. Expected: first FAILS.
+- [ ] **Step 3: Implement:** `telemetry.Read` of the account key, folded with `telemetry.Fold(acct, telemetry.Settings{})`; a bucketless console (`s.cfg.Releases == nil`) folds defaults as `Resolve` does; a read error sets `ErrLevelUnread` as today.
+- [ ] **Step 4: Run** `go test ./internal/console/ -run 'TestAccountSettings|TestTelemetry|TestErrors|TestAnalytics' -count=1`. Expected: PASS.
+- [ ] **Step 5: Walk**: `/a/{sqid}/settings` becomes `calls 2: the account telemetry settings and the storage entitlement`. Commit `console: account settings reads the account telemetry key only`.
+
+### Task 6: Lower the session ceiling, tidy the budgets, census
+
+**Files:**
+- Modify: `internal/console/testdata/perf-session-s3.txt`, `internal/console/testdata/perf-budgets.txt`
+- Census overlay files written by `make census-propose`
+
+- [ ] **Step 1: Measure:** `go test ./internal/console/ -run TestPerfSessionS3Requests -count=1 -v`; read "the scripted session made N S3 requests".
+- [ ] **Step 2: Lower the ceiling:** set `perf-session-s3.txt` to `<N> after console-perf-quick-wins, 2026-10-26` (replacing `1000 baseline before plan 2`). Rerun Step 1's command: PASS.
+- [ ] **Step 3: Check the budgets file:** every remaining `over:` reason carries the measured warm count; the header comment says these records are deleted by the next round, not "plan 2". Expected left `over:` (out of this plan's scope, for the next round): Overview (release listing, manifests, box reports), Releases, Errors, Availability, Running and the instance page if still over 5 calls, the Domains settings section, the account fleet pages, `/a/{sqid}/plan/keep`, `/a/{sqid}/trash`, and the operator pages (Part 3). Run `CI=1 go test ./internal/console/ -run 'TestConsoleScreensMeetTheBudget|TestPerfBudgetsFileParses' -count=1`: PASS.
+- [ ] **Step 4: Gate:** `gofmt -l ./internal`, `go vet ./internal/console/ ./internal/telemetry/`, `GOOS=darwin go build ./...`, `GOOS=windows go build ./...`.
+- [ ] **Step 5: Census** (AGENTS.md "The census"): `make census-card`; write CLAIMS (one line per changed unit, "same reads, fewer calls" or the read removed); `make census-propose NAME=console-perf-quick-wins CLAIMS=<file>`; a cross-model reviewer approves `body`/`sites`/`envelope`/`removed` rows; any `reads`/`new`/`quiet`/`other` row goes to Paul as a decision.
+- [ ] **Step 6: Commit** `console perf: lower the session S3 ceiling to <N>`, then the whole-branch review.
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-console-perf-quick-wins-r1.md b/docs/superpowers/reviews/CODEX-FINDINGS-console-perf-quick-wins-r1.md
new file mode 100644
index 000000000..8f8c1f930
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-console-perf-quick-wins-r1.md
@@ -0,0 +1,39 @@
+Reviewed `origin/main..16e026f93507fa3771786241536572d558070cce`, following round 1’s brief. Found one P2; no P1 or P3 findings.
+
+**P2 — Task 2: Account-name URLs miss account-wide cache invalidation.**
+
+In [appframe.go:283](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/console-perf-quick-wins/internal/console/appframe.go:283), `frameClear` passes the raw `{sqid}` or `{account}` URL segment to `clearAccount`. Cache entries use the resolved account’s sqid. Both browser and personal CLI requests accept account names; [apicli.go:267](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/console-perf-quick-wins/internal/console/apicli.go:267) resolves that name without replacing the path value.
+
+A concrete failure occurs during `POST /api/cli/apps/<account-name>/new`:
+
+1. App creation inserts the database row at [server.go:4821](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/console-perf-quick-wins/internal/console/server.go:4821).
+2. Before creation writes the default pipeline at line 4864, a concurrent account-home or app GET can discover the row and cache a frame with no pipeline.
+3. Creation completes, but both response-time clears target the account name rather than its sqid. The next view can retain the legacy ladder for the remainder of the 30-second TTL. An unfinished load also escapes the generation bump.
+
+**Fix:** Supply the resolved `acct.Sqid` to account-wide invalidation after authorization, through request-local invalidation state or explicit handler clears. Preserve the existing gate order. Add a regression test using a named-account create route, holding the pipeline write while a GET caches the incomplete frame, then checking the first post-create view.
+
+**Invariant:** Every completed console write invalidates the affected app’s frame, including loads already in flight. This is a display-consistency defect; write authorization continues to use fresh reads.
+
+Other review checks:
+
+- Frame copying, error exclusion, expiry, and generation handling are sound when invalidation reaches the correct entry. Clearing unknown names allocates no slots. Frame loads remain behind membership/app gates, and non-GET/HEAD requests bypass the cache.
+- The request memo is request-scoped and installed only on GET/HEAD. Box completeness survives memoization; write requests retain direct reads.
+- Settings flags match the sections’ template dependencies. The one-key deployment check retains the existing `List` fallback and refusal on read errors.
+- Account telemetry reads the same account key written by both settings handlers and preserves defaults and unreadable-state handling.
+- No changed handler reorders its authorization gates.
+- Cold reset clears both new process caches. The account-settings `calls 2` allowance matches its remaining reads; app screens retain `over:` records for their cold cost. The session ceiling is 320. I could not independently reproduce the recorded timings or request total.
+
+`git diff --check` passed. Targeted tests could not start because Go’s build-directory creation failed with `read-only file system`. No full suites ran, no subagents were spawned, and no files were changed.
+
+Census verdicts apply to `16e026f93507fa3771786241536572d558070cce`:
+
+- **APPROVE — `Server.loadRolloutJoin`**, [apiinstances.go:689](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/console-perf-quick-wins/internal/console/apiinstances.go:689). The configured registry, account-filtered fleets, prefixes, and completeness decisions remain unchanged. Memoization adds no root-readable input.
+- **APPROVE — `Server.systemBoxes`**, [apisystemupdate.go:270](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/console-perf-quick-wins/internal/console/apisystemupdate.go:270). The same platform and fleet reports are read; registry-error and strict-mode behavior remain intact.
+- **APPROVE — `Server.handleAppLogs`**, [server.go:4166](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/console-perf-quick-wins/internal/console/server.go:4166). The host picker reuses the account/app-scoped records already consumed by page assembly. It introduces no new root path or authority.
+- **APPROVE — `Server.geoipInventory`**, [apisystemgeoip.go:237](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/console-perf-quick-wins/internal/console/apisystemgeoip.go:237). Prefix construction moves into the helper without changing fleet-name provenance, expected-box enumeration, or incomplete-evidence handling.
+- **APPROVE — `internal/console` envelope re-pin.** The changed functions and their callees introduce no additional root open/run/query/follow authority and weaken no root-read validation. The P2 above concerns in-memory invalidation.
+- **Decision rows match Paul’s ruling.** `handleAccountSettings` directly reads account telemetry; `assembleViews` contains the existing registry listing and account scoping; `Assemble` delegates that work and no longer performs those reads itself.
+
+Fix the P2 without reopening this review, then perform the required census checks for the resulting diff.
+
+**READY AFTER FIXES**
\ No newline at end of file
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-console-perf-quick-wins.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-console-perf-quick-wins.md
new file mode 100644
index 000000000..8265966b6
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-console-perf-quick-wins.md
@@ -0,0 +1,42 @@
+# Review brief: branch console-perf-quick-wins, round 1 of 3
+
+Repo carlos/platform, branch `console-perf-quick-wins`, commit 16e026f9 (named in the reviewer's prompt with its full sha).
+Under review: the diff `origin/main..16e026f9` (merge base: the branch merged origin/main at be785f21).
+Authorities: `docs/superpowers/specs/2026-10-25-console-ux-perf-design.md` Part 2 (on main) and the plan `docs/superpowers/plans/2026-10-26-console-perf-quick-wins.md` (on this branch; it replaces the unbuilt `2026-10-25-console-perf-2-fixes.md`).
+
+You are an independent reviewer. Read the plan, then the code, and check every claim against the code.
+
+## Fixed: do not re-argue
+
+- Paul, 2026-10-26: the 17-task read-set cache plan is replaced by these quick wins; no read-set tracking, no deferred parts in this round.
+- Paul, 2026-10-26: S3 requests must go down; the scripted session ceiling is lowered (now 320).
+- Paul, 2026-10-26: accept three census decision rows (handleAccountSettings reading the account telemetry key directly; assembleViews/Assemble registry-read relocation). Check the rows match; do not re-argue accepting them.
+- Screens that still miss 150 ms on a cold first view stay recorded as `over:` with their measured counts; that is accepted for this round.
+
+## What to check
+
+1. The per-app frame cache (`internal/console/appframe.go`, the registerRoute hook in `claim_routes.go`, rename clear in `appsettings.go`): every console write that changes an app's channels, production flag or pipeline clears that app's entry before its response; per-app generation stops an in-flight GET from storing a pre-write value; nothing unbounded grows from unauthenticated requests; cached values are copied on read; write doors never read the cache. Look for a write path that escapes the hook.
+2. The per-request memo (Task 3): request-scoped only; partial box listings stay partial; no cross-request state; memo installed only on GET/HEAD.
+3. Settings sections (Task 4): every section still renders everything it showed before for owners and members; `appDeployEmpty` one-key listing behaves the same on stores without ListPage.
+4. Account telemetry (Task 5): the account level shown matches what errorsview/analyticsview write.
+5. Security gate order (session, CSRF, owner/member 404) unchanged on every touched handler; the registerRoute hook runs nothing that changes responses.
+6. The perf walk and `perf-budgets.txt` records are truthful (cold reset clears the frame cache and manifest memo; `calls` records only where cold also fits).
+7. Census approvals (AGENTS.md "The census: an approval, not a decision"): for each unit on `docs/superpowers/notes/census-proposal-console-perf-quick-wins.md` (body: loadRolloutJoin, systemBoxes, handleAppLogs; sites: geoipInventory; the internal/console envelope re-pin) answer APPROVE or ESCALATE to the card's question (does any root read now open/run/query/follow a path or input a tenant, app or box agent can create, write or name?). Confirm the three decision rows in `internal/provision/testdata/plan14-root-reads-console-perf-quick-wins-decisions.tsv` match Paul's ruling.
+
+## Severity
+
+- **P1**: unsafe, would not compile, a test fails, or it would not work. Blocks merge.
+- **P2**: wrong or missing. Fixed without reopening this review.
+- **P3**: clarity or polish. Goes on a follow-up list; never a reason for another round.
+
+A P1 states its failure scenario and the evidence (file:line). Do not raise a P2 to P1 to keep the review open.
+
+## Output
+
+Findings ranked P1, P2, P3. Each gives the section or task, the problem, the evidence (file:line, verified), the failure scenario, a concrete fix and the invariant or trust boundary it breaks. Then the census verdict lines. End with exactly one verdict:
+
+- **READY**: no P1 and no P2.
+- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another round.
+- **NOT READY**: one or more P1s, listed.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of your own. Do not run the full test suites.
diff --git a/internal/console/apiassets_test.go b/internal/console/apiassets_test.go
index ffd86ec7c..03a629d18 100644
--- a/internal/console/apiassets_test.go
+++ b/internal/console/apiassets_test.go
@@ -542,6 +542,7 @@ func TestAssetsStatusJoinsPublishedGeneration(t *testing.T) {
if err := release.Promote(ctx, fx.rel, fx.priv, shipAssetsAccount, assetsApp, "stable", "v1"); err != nil {
t.Fatal(err)
}
+ fx.forgetFrame(assetsApp)
at := time.Date(2026, 10, 25, 9, 0, 0, 0, time.UTC)
edges := map[string]any{
"v": 1, "box": "box-a", "eip": "192.0.2.1", "region": "ie",
diff --git a/internal/console/apicli_test.go b/internal/console/apicli_test.go
index 969d668d3..ced8f9f48 100644
--- a/internal/console/apicli_test.go
+++ b/internal/console/apicli_test.go
@@ -230,6 +230,7 @@ func TestAPIChannelsErrorRow(t *testing.T) {
if _, err := fx.rel.Put(context.Background(), release.ChannelKey(release.OpsAccount, "titogo", "broken"), garbage, ""); err != nil {
t.Fatal(err)
}
+ fx.forgetFrame("titogo")
token := cliToken(t, fx, "paul@keymail.dev", "code-channels-error-row")
status, out := getJSON(t, fx.ts.URL+"/api/cli/apps/bab/titogo/channels", token)
@@ -352,6 +353,7 @@ func TestAPIChannelsPipelineUnreadableOmitsKey(t *testing.T) {
if _, err := fx.rel.Put(context.Background(), release.PipelineKey("bab", "widget"), []byte("not json"), ""); err != nil {
t.Fatal(err)
}
+ fx.forgetFrame("widget")
token := cliToken(t, fx, "paul@keymail.dev", "code-channels-pipeline-unreadable")
status, out := getJSON(t, fx.ts.URL+"/api/cli/apps/bab/widget/channels", token)
@@ -2423,6 +2425,7 @@ func TestAPITrashProductionRefused(t *testing.T) {
release.OpsAccount, "titogo", true, "paul@keymail.dev"); err != nil {
t.Fatal(err)
}
+ fx.forgetFrame("titogo")
status, body := postBody(t, fx.ts.URL+"/api/cli/apps/bab/titogo/delete", token, "")
if status != http.StatusConflict {
diff --git a/internal/console/apigatepass_test.go b/internal/console/apigatepass_test.go
index 75cfb8c6c..177a309f2 100644
--- a/internal/console/apigatepass_test.go
+++ b/internal/console/apigatepass_test.go
@@ -190,6 +190,7 @@ func TestAPIInstanceGatePassDeployScope(t *testing.T) {
[]release.PipelineChannel{{Name: "edge"}, {Name: "stable"}}, "paul@keymail.dev"); err != nil {
t.Fatal(err)
}
+ fx.forgetFrame("titogo")
if status, _, out := rawReq(t, http.MethodPost, edge, tok, ""); status != http.StatusForbidden {
t.Fatalf("deploy credential, edge host on a pipelined app = %d %s, want 403", status, out)
}
diff --git a/internal/console/apiinstances.go b/internal/console/apiinstances.go
index 2141a5baa..1e2a8fe5a 100644
--- a/internal/console/apiinstances.go
+++ b/internal/console/apiinstances.go
@@ -681,6 +681,20 @@ func loadBoxJoinComplete(ctx context.Context, s release.Store, now time.Time) (b
return joinBoxes(boxes, now), complete
}
+// platformBoxJoin is loadBoxJoinComplete on the console's release store,
+// its box reports read once per request (loadBoxes).
+func (s *Server) platformBoxJoin(ctx context.Context, now time.Time) (boxJoin, bool) {
+ if s.cfg.Releases == nil {
+ return boxJoin{}, false
+ }
+ boxes, complete, err := s.loadBoxes(ctx, s.cfg.Releases, "")
+ if err != nil {
+ log.Printf("console: api instances: could not load status boxes for the list join: %v", err)
+ return boxJoin{}, false
+ }
+ return joinBoxes(boxes, now), complete
+}
+
// loadRolloutJoin is the box join the instance list, the instance page and
// the host-retry door share (Astra plan 6 R1 #6), so the three never
// disagree about a host's rollout: the platform's boxes (status/boxes/),
@@ -708,7 +722,7 @@ func loadBoxJoinComplete(ctx context.Context, s release.Store, now time.Time) (b
// still READ, whatever relevant says: completeness is scoped, the join's
// content is not.
func (s *Server) loadRolloutJoin(ctx context.Context, acct string, now time.Time, relevant map[string]bool) (boxJoin, bool) {
- j, complete := loadBoxJoinComplete(ctx, s.cfg.Releases, now)
+ j, complete := s.platformBoxJoin(ctx, now)
if s.cfg.Releases == nil || s.cfg.Registry == "" {
return j, complete
}
@@ -731,7 +745,7 @@ func (s *Server) loadRolloutJoin(ctx context.Context, acct string, now time.Time
if f.Account != acct {
continue
}
- boxes, fleetComplete, err := status.LoadBoxesComplete(ctx, release.NewPrefixStore(s.cfg.Releases, "fleets/"+f.Name+"/"))
+ boxes, fleetComplete, err := s.loadBoxes(ctx, s.cfg.Releases, "fleets/"+f.Name+"/")
if err != nil {
log.Printf("console: rollout join %s: fleet %s boxes: %v", acct, f.Name, err)
complete = complete && !counts(f.Name)
diff --git a/internal/console/apiinstanceschannel_test.go b/internal/console/apiinstanceschannel_test.go
index bb79b4588..c0173cb62 100644
--- a/internal/console/apiinstanceschannel_test.go
+++ b/internal/console/apiinstanceschannel_test.go
@@ -201,6 +201,7 @@ func TestAPIInstanceCreateUnreadablePipelineRefuses(t *testing.T) {
release.PipelineKey(release.OpsAccount, "titogo"), []byte("not json"), ""); err != nil {
t.Fatal(err)
}
+ fx.forgetFrame("titogo")
status, _, out := rawReq(t, http.MethodPost, instancesURL(fx, "bab", "titogo"), member,
`{"host":"acme.go.tito.io","region":"ie"}`)
@@ -229,6 +230,7 @@ func TestAPIInstanceCreateExplicitChannelNeverReadsThePipeline(t *testing.T) {
release.PipelineKey(release.OpsAccount, "titogo"), []byte("not json"), ""); err != nil {
t.Fatal(err)
}
+ fx.forgetFrame("titogo")
status, _, out := rawReq(t, http.MethodPost, instancesURL(fx, "bab", "titogo"), member,
`{"host":"acme.go.tito.io","region":"ie","channel":"canary/boot-check"}`)
diff --git a/internal/console/apipipeline_test.go b/internal/console/apipipeline_test.go
index 74cdc8824..36bd5c30a 100644
--- a/internal/console/apipipeline_test.go
+++ b/internal/console/apipipeline_test.go
@@ -130,6 +130,7 @@ func TestAPIPipelineGetUnreadableIsNot502(t *testing.T) {
if _, err := fx.rel.Put(context.Background(), release.PipelineKey("bab", "widget"), []byte("not json"), ""); err != nil {
t.Fatal(err)
}
+ fx.forgetFrame("widget")
token := cliToken(t, fx, "paul@keymail.dev", "code-pipeline-unreadable")
status, out := getJSON(t, fx.ts.URL+"/api/cli/apps/bab/widget/pipeline", token)
diff --git a/internal/console/apisystemgeoip.go b/internal/console/apisystemgeoip.go
index bec97a9a6..e9f675622 100644
--- a/internal/console/apisystemgeoip.go
+++ b/internal/console/apisystemgeoip.go
@@ -248,8 +248,12 @@ func (s *Server) geoipInventory(ctx context.Context) (geoipInventoryRead, error)
inv.expected[geoipBoxKey{Label: label}] = true
}
}
- add := func(store release.Store, fleet string) error {
- boxes, complete, err := status.LoadBoxesComplete(ctx, store)
+ add := func(fleet string) error {
+ prefix := ""
+ if fleet != "" {
+ prefix = "fleets/" + fleet + "/"
+ }
+ boxes, complete, err := s.loadBoxes(ctx, s.cfg.Releases, prefix)
if err != nil {
return err
}
@@ -261,7 +265,7 @@ func (s *Server) geoipInventory(ctx context.Context) (geoipInventoryRead, error)
}
return nil
}
- if err := add(s.cfg.Releases, ""); err != nil {
+ if err := add(""); err != nil {
return inv, err
}
if s.cfg.Registry == "" {
@@ -296,7 +300,7 @@ func (s *Server) geoipInventory(ctx context.Context) (geoipInventoryRead, error)
inv.expected[geoipBoxKey{f.Name, fb.Label}] = true
}
}
- if err := add(release.NewPrefixStore(s.cfg.Releases, "fleets/"+f.Name+"/"), f.Name); err != nil {
+ if err := add(f.Name); err != nil {
// That fleet's heartbeats are unknown: its expected boxes are
// missing from boxes and block as "no heartbeat".
inv.heartbeatsComplete = false
diff --git a/internal/console/apisystemupdate.go b/internal/console/apisystemupdate.go
index 382c7973b..a96b3ce5c 100644
--- a/internal/console/apisystemupdate.go
+++ b/internal/console/apisystemupdate.go
@@ -268,7 +268,7 @@ func (s *Server) systemFeed() publicrelease.Feed {
// cannot be opened, or one whose fleets cannot be listed, is a fleet set this
// console cannot see.
func (s *Server) systemBoxes(ctx context.Context, strict bool) ([]status.Box, bool, error) {
- boxes, err := status.LoadBoxes(ctx, s.cfg.Releases)
+ boxes, _, err := s.loadBoxes(ctx, s.cfg.Releases, "")
if err != nil {
return nil, false, err
}
@@ -278,7 +278,7 @@ func (s *Server) systemBoxes(ctx context.Context, strict bool) ([]status.Box, bo
}
partial := false
for _, f := range fleets {
- fb, err := status.LoadBoxes(ctx, release.NewPrefixStore(s.cfg.Releases, "fleets/"+f.Name+"/"))
+ fb, _, err := s.loadBoxes(ctx, s.cfg.Releases, "fleets/"+f.Name+"/")
if err != nil {
if strict {
return nil, false, fmt.Errorf("fleet %s: cannot read its box heartbeats, refusing to guess which platforms to mirror: %w", f.Name, err)
diff --git a/internal/console/appframe.go b/internal/console/appframe.go
new file mode 100644
index 000000000..48ae009f4
--- /dev/null
+++ b/internal/console/appframe.go
@@ -0,0 +1,383 @@
+package console
+
+import (
+ "context"
+ "crypto/ed25519"
+ "net/http"
+ "slices"
+ "sort"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// The app-tab frame: the release-store reads every app tab makes before its
+// own part (the channel listing and each channel pointer, the production
+// flag, the pipeline), kept per app for appFrameTTL so a person moving
+// between tabs does not pay them again on every view.
+//
+// READ YOUR OWN WRITES. Every console door that writes one of these objects
+// sits under an {app} route, and registerRoute clears that app's entry
+// before the door's response goes out (frameClearingWriter), so the page a
+// write redirects to always loads fresh. A door with only {sqid} (or
+// {account}) clears the whole account: the new-app and trash doors. That
+// segment may be the account's NAME as well as its sqid (the browser and
+// the CLI both resolve either), so a slot also remembers the account name
+// its last view used and a clear matches the segment against both. Rename
+// clears the new name itself. A writer outside the console (another
+// console, a box, an operator's script) is seen within appFrameTTL.
+//
+// WRITE DOORS NEVER READ IT. A non-GET request's context carries
+// frameBypassKey (registerRoute), and appFrame loads fresh for it without
+// storing, so a write door that builds its page through appPage decides on
+// nothing older than its own request. Doors that decide on these objects
+// read them directly anyway.
+
+// appFrameTTL is how long a frame is served without asking the bucket.
+const appFrameTTL = 30 * time.Second
+
+// frameChannel is one channel pointer as read: the verified pointer, or the
+// read's error.
+type frameChannel struct {
+ Name string
+ Pointer *release.ChannelPointer
+ Err string
+}
+
+// appFrame is one app's frame. Each *Err holds the read's error text; a
+// frame with any of them set is never cached.
+type appFrame struct {
+ Channels []frameChannel
+ ChannelsErr string
+ Production *release.ProductionFlag
+ ProductionErr string
+ Pipeline *release.Pipeline
+ PipelineErr string
+}
+
+// failed reports whether any read in the frame failed.
+func (f appFrame) failed() bool {
+ if f.ChannelsErr != "" || f.ProductionErr != "" || f.PipelineErr != "" {
+ return true
+ }
+ for _, c := range f.Channels {
+ if c.Err != "" {
+ return true
+ }
+ }
+ return false
+}
+
+// clone is a deep copy: every slice, every pointed-to struct and its slices.
+// Cached frames are shared; what a caller gets is its own.
+func (f appFrame) clone() appFrame {
+ out := f
+ if f.Channels != nil {
+ out.Channels = make([]frameChannel, len(f.Channels))
+ for i, c := range f.Channels {
+ if c.Pointer != nil {
+ p := *c.Pointer
+ p.History = slices.Clone(c.Pointer.History)
+ p.HistoryDigests = slices.Clone(c.Pointer.HistoryDigests)
+ p.Audit = slices.Clone(c.Pointer.Audit)
+ c.Pointer = &p
+ }
+ out.Channels[i] = c
+ }
+ }
+ if f.Production != nil {
+ p := *f.Production
+ out.Production = &p
+ }
+ if f.Pipeline != nil {
+ p := *f.Pipeline
+ p.Channels = slices.Clone(f.Pipeline.Channels)
+ out.Pipeline = &p
+ }
+ return out
+}
+
+// loadAppFrame makes the frame's reads, in the order the app tabs have
+// always made them: the channel listing, each channel, the production flag,
+// then the pipeline (bounded by pipelineStoreTimeout, as it always was).
+func loadAppFrame(ctx context.Context, st release.Store, pub ed25519.PublicKey, acct, app string) appFrame {
+ var f appFrame
+ prefix := release.ChannelsPrefix(acct, app)
+ keys, err := st.List(ctx, prefix)
+ if err != nil {
+ f.ChannelsErr = err.Error()
+ } else {
+ var names []string
+ for _, k := range keys {
+ name := strings.TrimPrefix(k, prefix)
+ if !strings.HasSuffix(name, ".json") {
+ continue
+ }
+ names = append(names, strings.TrimSuffix(name, ".json"))
+ }
+ sort.Strings(names)
+ for _, name := range names {
+ p, err := release.Channel(ctx, st, pub, acct, app, name)
+ if err != nil {
+ f.Channels = append(f.Channels, frameChannel{Name: name, Err: err.Error()})
+ continue
+ }
+ f.Channels = append(f.Channels, frameChannel{Name: name, Pointer: p})
+ }
+ }
+ if flag, err := release.GetProduction(ctx, st, pub, acct, app); err != nil {
+ f.ProductionErr = err.Error()
+ } else {
+ f.Production = flag
+ }
+ pctx, cancel := context.WithTimeout(ctx, pipelineStoreTimeout)
+ defer cancel()
+ if pipe, err := release.GetPipeline(pctx, st, pub, acct, app); err != nil {
+ f.PipelineErr = err.Error()
+ } else {
+ f.Pipeline = pipe
+ }
+ return f
+}
+
+type frameKey struct{ acct, app string }
+
+// frameSlot is one (account, app)'s place in the cache: the stored frame,
+// if any, and the generation every clear of it bumps. A slot exists only
+// while it holds a frame or a load for it is in flight. name is the
+// account's name as the last view of the slot knew it ("" when that view
+// did not say), so an account-wide clear addressed by name finds the slot
+// without a lookup.
+type frameSlot struct {
+ name string
+ frame appFrame
+ at time.Time
+ has bool
+ gen uint64
+ loading int
+}
+
+// appFrames is the cache. The zero value is ready (ttl 0 is appFrameTTL, nil
+// now is time.Now), like keyedLocks, so &Server{} literals stay safe. It
+// holds one slot per app viewed; nothing refreshes in the background.
+//
+// The generation is what stops a view that began before a write from
+// putting the old frame back after the write's clear: get notes its slot's
+// generation before loading and stores only if no clear of that slot has
+// happened since. Generations live on the slots, so a clear only touches
+// slots that already exist: the clears run on every non-GET request before
+// any gate, and a name nobody has viewed allocates nothing. Slots are made
+// only by get, which page views reach after their gate.
+type appFrames struct {
+ mu sync.Mutex
+ ttl time.Duration
+ now func() time.Time
+ slots map[frameKey]*frameSlot
+}
+
+func (c *appFrames) clock() time.Time {
+ if c.now != nil {
+ return c.now()
+ }
+ return time.Now()
+}
+
+func (c *appFrames) lifetime() time.Duration {
+ if c.ttl > 0 {
+ return c.ttl
+ }
+ return appFrameTTL
+}
+
+// get answers acct/app's frame from the cache while it is fresh, else from
+// load, storing the result only when it has no error and no clear of this
+// app happened while it loaded. Either way the caller gets its own copy.
+func (c *appFrames) get(ctx context.Context, acct, app string, load func(context.Context) appFrame) appFrame {
+ return c.getAs(ctx, acct, "", app, load)
+}
+
+// getAs is get for a caller that knows the account's name: the slot keeps
+// it for clearAccount (see frameSlot).
+func (c *appFrames) getAs(ctx context.Context, acct, name, app string, load func(context.Context) appFrame) appFrame {
+ k := frameKey{acct, app}
+ c.mu.Lock()
+ now := c.clock()
+ sl := c.slots[k]
+ if sl != nil && name != "" {
+ sl.name = name
+ }
+ if sl != nil && sl.has && now.Before(sl.at.Add(c.lifetime())) {
+ f := sl.frame.clone()
+ c.mu.Unlock()
+ return f
+ }
+ if sl == nil {
+ if c.slots == nil {
+ c.slots = make(map[frameKey]*frameSlot)
+ }
+ sl = &frameSlot{name: name}
+ c.slots[k] = sl
+ }
+ sl.loading++
+ gen := sl.gen
+ c.mu.Unlock()
+
+ f := load(ctx)
+
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ sl.loading--
+ if sl.gen == gen && !f.failed() {
+ // Stamped with the time the load began: an entry never outlives
+ // the TTL measured from its oldest read.
+ sl.frame, sl.at, sl.has = f.clone(), now, true
+ }
+ c.dropIfIdle(k, sl)
+ return f
+}
+
+// dropIfIdle removes a slot that holds no frame and has no load in flight.
+// The slot is only removed from the map while no get holds it, so a clear
+// always reaches the slot an in-flight load will check.
+func (c *appFrames) dropIfIdle(k frameKey, sl *frameSlot) {
+ if !sl.has && sl.loading == 0 && c.slots[k] == sl {
+ delete(c.slots, k)
+ }
+}
+
+// clearWhere drops the frame of every slot match picks and bumps its
+// generation, so a load in flight for it will not store.
+func (c *appFrames) clearWhere(match func(frameKey) bool) {
+ c.clearSlots(func(k frameKey, _ *frameSlot) bool { return match(k) })
+}
+
+// clearSlots is clearWhere for a match that also reads the slot.
+func (c *appFrames) clearSlots(match func(frameKey, *frameSlot) bool) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ for k, sl := range c.slots {
+ if !match(k, sl) {
+ continue
+ }
+ sl.gen++
+ sl.frame, sl.has = appFrame{}, false
+ c.dropIfIdle(k, sl)
+ }
+}
+
+// clearApp drops app's frame in every account (app names are per account,
+// and a CLI door's account segment is not checked here).
+func (c *appFrames) clearApp(app string) {
+ c.clearWhere(func(k frameKey) bool { return k.app == app })
+}
+
+// clearAccount drops every frame of the account that seg names: seg is a
+// request's raw path segment, so it matches a slot's account sqid or its
+// account name (compared as matchAccounts does, ignoring case). It looks
+// nothing up: a segment no slot knows clears, and allocates, nothing.
+func (c *appFrames) clearAccount(seg string) {
+ c.clearSlots(func(k frameKey, sl *frameSlot) bool {
+ return k.acct == seg || (sl.name != "" && strings.EqualFold(sl.name, seg))
+ })
+}
+
+// frameBypassKey marks a non-GET request's context: appFrame loads fresh
+// for it and stores nothing.
+type frameBypassKey struct{}
+
+// appFrame is the frame for a page view: the cache over the console's
+// release store, or a fresh load for a write door's request.
+// acctName is the account's name when the caller has it (see frameSlot).
+func (s *Server) appFrame(ctx context.Context, acct, acctName, app string) appFrame {
+ load := func(ctx context.Context) appFrame {
+ return loadAppFrame(ctx, s.cfg.Releases, s.cfg.ReleasePub, acct, app)
+ }
+ if ctx.Value(frameBypassKey{}) != nil {
+ return load(ctx)
+ }
+ return s.frames.getAs(ctx, acct, acctName, app, load)
+}
+
+// frameClear is the clear registerRoute runs for a write request: the app
+// for a pattern with {app}, else the account for one with {sqid} or
+// {account}, else nothing (nil).
+func (s *Server) frameClear(pattern string) func(r *http.Request) {
+ switch {
+ case strings.Contains(pattern, "{app}"):
+ return func(r *http.Request) { s.frames.clearApp(r.PathValue("app")) }
+ case strings.Contains(pattern, "{sqid}"):
+ return func(r *http.Request) { s.frames.clearAccount(r.PathValue("sqid")) }
+ case strings.Contains(pattern, "{account}"):
+ return func(r *http.Request) { s.frames.clearAccount(r.PathValue("account")) }
+ }
+ return nil
+}
+
+// patternMethod is a mux pattern's method, "" for a method-less pattern.
+func patternMethod(pattern string) string {
+ if i := strings.IndexByte(pattern, ' '); i > 0 && !strings.Contains(pattern[:i], "/") {
+ return pattern[:i]
+ }
+ return ""
+}
+
+// readOnlyMethod reports whether a request with this method cannot write.
+func readOnlyMethod(m string) bool { return m == http.MethodGet || m == http.MethodHead }
+
+// frameClearingWriter runs clear before the first byte of the response,
+// header included, so a client that follows the response (a redirect, a
+// reload) never sees a frame from before the write. The wrapper changes
+// nothing else: Unwrap keeps http.ResponseController working.
+type frameClearingWriter struct {
+ http.ResponseWriter
+ clear func()
+ cleared bool
+}
+
+func (w *frameClearingWriter) before() {
+ if !w.cleared {
+ w.cleared = true
+ w.clear()
+ }
+}
+
+func (w *frameClearingWriter) WriteHeader(code int) {
+ w.before()
+ w.ResponseWriter.WriteHeader(code)
+}
+
+func (w *frameClearingWriter) Write(b []byte) (int, error) {
+ w.before()
+ return w.ResponseWriter.Write(b)
+}
+
+func (w *frameClearingWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter }
+
+// withFrameClear wraps h for pattern: a GET or HEAD request passes through
+// untouched; any other request is marked frameBypassKey and has its clear
+// run before its first response byte and again when h returns (for work
+// done after the response was started). Gate order is h's own: this runs
+// nothing before h but the clear itself.
+func (s *Server) withFrameClear(pattern string, h http.HandlerFunc) http.HandlerFunc {
+ method := patternMethod(pattern)
+ if readOnlyMethod(method) {
+ return h
+ }
+ clear := s.frameClear(pattern)
+ return func(w http.ResponseWriter, r *http.Request) {
+ if readOnlyMethod(r.Method) {
+ h(w, r)
+ return
+ }
+ r = r.WithContext(context.WithValue(r.Context(), frameBypassKey{}, true))
+ if clear == nil {
+ h(w, r)
+ return
+ }
+ cw := &frameClearingWriter{ResponseWriter: w, clear: func() { clear(r) }}
+ defer clear(r)
+ h(cw, r)
+ }
+}
diff --git a/internal/console/appframe_test.go b/internal/console/appframe_test.go
new file mode 100644
index 000000000..96bce6268
--- /dev/null
+++ b/internal/console/appframe_test.go
@@ -0,0 +1,915 @@
+package console
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "io/fs"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "os"
+ "path/filepath"
+ "regexp"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// ---- appFrames on its own --------------------------------------------------
+
+// testFrame is a frame with one channel and a two-channel pipeline, so a
+// caller has a slice inside a pointer to mutate.
+func testFrame(version string) appFrame {
+ return appFrame{
+ Channels: []frameChannel{{Name: "stable", Pointer: &release.ChannelPointer{
+ Version: version, History: []string{"v0"}, HistoryDigests: []string{""},
+ Audit: []release.Promotion{{Version: version}},
+ }}},
+ Production: &release.ProductionFlag{Production: true},
+ Pipeline: &release.Pipeline{Channels: []release.PipelineChannel{{Name: "beta"}, {Name: "stable"}}},
+ }
+}
+
+// countingLoad returns a load func that answers testFrame(version) and
+// counts its calls.
+func countingLoad(version string, n *int) func(context.Context) appFrame {
+ return func(context.Context) appFrame {
+ *n++
+ return testFrame(version)
+ }
+}
+
+// frameWait fails the test unless ch is ready within testWait.
+func frameWait[T any](t *testing.T, ch <-chan T, what string) T {
+ t.Helper()
+ select {
+ case v := <-ch:
+ return v
+ case <-time.After(testWait):
+ t.Fatalf("timed out after %v waiting for %s", testWait, what)
+ var zero T
+ return zero
+ }
+}
+
+const testWait = 30 * time.Second
+
+// releaseOnce returns a channel and an idempotent close for it, so a test
+// can release a blocked load early and still defer the release.
+func releaseOnce() (chan struct{}, func()) {
+ ch := make(chan struct{})
+ var once sync.Once
+ return ch, func() { once.Do(func() { close(ch) }) }
+}
+
+// TestAppFrameLoadDuringWriteNotStored: a load that started before a clear
+// of its app (or account) and finishes after it must not put its
+// (pre-write) frame into the cache. A clear of another app leaves it
+// eligible.
+func TestAppFrameLoadDuringWriteNotStored(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ clear func(c *appFrames)
+ stored bool
+ }{
+ {"clearApp", func(c *appFrames) { c.clearApp("kass") }, false},
+ {"clearAccount", func(c *appFrames) { c.clearAccount("bab") }, false},
+ {"clearApp of another app", func(c *appFrames) { c.clearApp("other") }, true},
+ {"clearAccount of another account", func(c *appFrames) { c.clearAccount("other") }, true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ var c appFrames
+ started := make(chan struct{})
+ unblock, release := releaseOnce()
+ defer release()
+ done := make(chan appFrame, 1)
+ go func() {
+ done <- c.get(context.Background(), "bab", "kass", func(context.Context) appFrame {
+ close(started)
+ <-unblock
+ return testFrame("old")
+ })
+ }()
+ frameWait(t, started, "the load to start")
+ tc.clear(&c)
+ release()
+ if f := frameWait(t, done, "the in-flight get"); f.Channels[0].Pointer.Version != "old" {
+ t.Fatalf("the in-flight get answered %q, want its own load's value", f.Channels[0].Pointer.Version)
+ }
+ n := 0
+ f := c.get(context.Background(), "bab", "kass", countingLoad("new", &n))
+ if tc.stored {
+ if n != 0 || f.Channels[0].Pointer.Version != "old" {
+ t.Fatalf("after an unrelated clear during a load: load calls %d, version %q; want 0 and \"old\" (stored)", n, f.Channels[0].Pointer.Version)
+ }
+ return
+ }
+ if n != 1 || f.Channels[0].Pointer.Version != "new" {
+ t.Fatalf("after a clear during a load: load calls %d, version %q; want 1 and \"new\"", n, f.Channels[0].Pointer.Version)
+ }
+ })
+ }
+}
+
+// TestAppFrameClearOfUnknownNameAllocatesNothing: the hook clears whatever
+// a request's path names, before any gate; a name with no slot adds none.
+func TestAppFrameClearOfUnknownNameAllocatesNothing(t *testing.T) {
+ var c appFrames
+ c.get(context.Background(), "bab", "kass", func(context.Context) appFrame { return testFrame("v1") })
+ for i := range 1000 {
+ c.clearApp(fmt.Sprintf("nobody-%d", i))
+ c.clearAccount(fmt.Sprintf("nobody-%d", i))
+ }
+ c.mu.Lock()
+ n := len(c.slots)
+ c.mu.Unlock()
+ if n != 1 {
+ t.Fatalf("slots = %d after clears of unknown names, want 1", n)
+ }
+ c.clearApp("kass")
+ c.mu.Lock()
+ n = len(c.slots)
+ c.mu.Unlock()
+ if n != 0 {
+ t.Fatalf("slots = %d after clearing the only app, want 0", n)
+ }
+}
+
+// TestAppFrameConcurrentGetsAndClears is the race detector's case: views and
+// writes on the same app at once. After the last clear, the next get loads.
+func TestAppFrameConcurrentGetsAndClears(t *testing.T) {
+ var c appFrames
+ var wg sync.WaitGroup
+ for i := range 8 {
+ wg.Add(2)
+ go func() {
+ defer wg.Done()
+ for range 50 {
+ f := c.get(context.Background(), "bab", "kass", func(context.Context) appFrame { return testFrame("v1") })
+ f.Channels[0].Pointer.History[0] = "mutated"
+ f.Pipeline.Channels[0].Name = "mutated"
+ }
+ }()
+ go func() {
+ defer wg.Done()
+ for range 50 {
+ if i%2 == 0 {
+ c.clearApp("kass")
+ } else {
+ c.clearAccount("bab")
+ }
+ }
+ }()
+ }
+ wg.Wait()
+ c.clearApp("kass")
+ n := 0
+ f := c.get(context.Background(), "bab", "kass", countingLoad("v2", &n))
+ if n != 1 || f.Channels[0].Pointer.Version != "v2" {
+ t.Fatalf("after the last clear: load calls %d, version %q; want 1 and v2", n, f.Channels[0].Pointer.Version)
+ }
+}
+
+// TestAppFrameClears: clearApp drops the app in every account, clearAccount
+// drops every app in one account, and neither touches anything else.
+func TestAppFrameClears(t *testing.T) {
+ var c appFrames
+ n := 0
+ load := countingLoad("v1", &n)
+ keys := [][2]string{{"bab", "kass"}, {"bab", "shop"}, {"other", "kass"}, {"other", "shop"}}
+ warm := func() {
+ for _, k := range keys {
+ c.get(context.Background(), k[0], k[1], load)
+ }
+ }
+ warm()
+ if n != 4 {
+ t.Fatalf("cold loads = %d, want 4", n)
+ }
+ warm()
+ if n != 4 {
+ t.Fatalf("warm loads = %d, want still 4", n)
+ }
+ c.clearApp("kass")
+ warm()
+ if n != 6 {
+ t.Fatalf("loads after clearApp(kass) = %d, want 6 (kass in both accounts)", n)
+ }
+ c.clearAccount("bab")
+ warm()
+ if n != 8 {
+ t.Fatalf("loads after clearAccount(bab) = %d, want 8 (both of bab's apps)", n)
+ }
+}
+
+// TestAppFrameCopiesOnRead: what get hands back is the caller's to change.
+func TestAppFrameCopiesOnRead(t *testing.T) {
+ var c appFrames
+ n := 0
+ load := countingLoad("v1", &n)
+ first := c.get(context.Background(), "bab", "kass", load)
+ first.Channels[0].Pointer.History[0] = "mutated"
+ first.Channels[0].Pointer.HistoryDigests[0] = "mutated"
+ first.Channels[0].Pointer.Audit[0].Version = "mutated"
+ first.Channels[0].Name = "mutated"
+ first.Production.Production = false
+ first.Pipeline.Channels[0].Name = "mutated"
+
+ second := c.get(context.Background(), "bab", "kass", load)
+ if n != 1 {
+ t.Fatalf("load calls = %d, want 1 (the second get is a hit)", n)
+ }
+ second.Pipeline.Channels = append(second.Pipeline.Channels, release.PipelineChannel{Name: "extra"})
+
+ third := c.get(context.Background(), "bab", "kass", load)
+ want := testFrame("v1")
+ if third.Channels[0].Name != want.Channels[0].Name ||
+ third.Channels[0].Pointer.History[0] != "v0" ||
+ third.Channels[0].Pointer.HistoryDigests[0] != "" ||
+ third.Channels[0].Pointer.Audit[0].Version != "v1" ||
+ !third.Production.Production ||
+ len(third.Pipeline.Channels) != 2 || third.Pipeline.Channels[0].Name != "beta" {
+ t.Fatalf("a caller's mutation reached the cache: %+v / %+v / %+v", third.Channels[0], third.Production, third.Pipeline)
+ }
+}
+
+// TestAppFrameExpires: an entry lives appFrameTTL, then the next get loads.
+func TestAppFrameExpires(t *testing.T) {
+ now := time.Unix(1_800_000_000, 0)
+ c := appFrames{now: func() time.Time { return now }}
+ n := 0
+ load := countingLoad("v1", &n)
+ c.get(context.Background(), "bab", "kass", load)
+ now = now.Add(29 * time.Second)
+ c.get(context.Background(), "bab", "kass", load)
+ if n != 1 {
+ t.Fatalf("loads at 29 s = %d, want 1", n)
+ }
+ now = now.Add(2 * time.Second)
+ c.get(context.Background(), "bab", "kass", load)
+ if n != 2 {
+ t.Fatalf("loads at 31 s = %d, want 2", n)
+ }
+}
+
+// TestAppFrameFailedLoadNotStored: a frame carrying any read error is
+// answered but never kept.
+func TestAppFrameFailedLoadNotStored(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ fail func(f *appFrame)
+ }{
+ {"channel listing", func(f *appFrame) { f.ChannelsErr = "boom" }},
+ {"one channel", func(f *appFrame) { f.Channels[0].Err = "boom" }},
+ {"production", func(f *appFrame) { f.ProductionErr = "boom" }},
+ {"pipeline", func(f *appFrame) { f.PipelineErr = "boom" }},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ var c appFrames
+ n := 0
+ load := func(context.Context) appFrame {
+ n++
+ f := testFrame("v1")
+ tc.fail(&f)
+ return f
+ }
+ c.get(context.Background(), "bab", "kass", load)
+ c.get(context.Background(), "bab", "kass", load)
+ if n != 2 {
+ t.Fatalf("loads = %d, want 2 (a failed frame is not cached)", n)
+ }
+ })
+ }
+}
+
+// ---- through the console ----------------------------------------------------
+
+// TestAppFrameWarmViewReadsNothing: the second view of an app tab makes no
+// S3 request at all.
+func TestAppFrameWarmViewReadsNothing(t *testing.T) {
+ fx, lat := newPerfFixture(t)
+ c := signInPaul(t, fx)
+ if status, _, body := get(t, c, fx.u("/apps/kass/activity")); status != http.StatusOK {
+ t.Fatalf("activity = %d:\n%s", status, body)
+ }
+ before, _ := lat.Calls()
+ if status, _, body := get(t, c, fx.u("/apps/kass/activity")); status != http.StatusOK {
+ t.Fatalf("activity = %d:\n%s", status, body)
+ }
+ if after, _ := lat.Calls(); after != before {
+ t.Fatalf("warm activity view made %d S3 requests, want 0", after-before)
+ }
+}
+
+// pipelineKeyRequests counts the S3 requests that name the app's pipeline
+// key, and fails them with a 500 while failing is set. (The SDK retries a
+// 500, so failing one request alone would not fail the read.)
+type pipelineKeyRequests struct {
+ mu sync.Mutex
+ n int
+ failing bool
+}
+
+func watchPipelineKey(lat *perfLatency, key string) *pipelineKeyRequests {
+ p := &pipelineKeyRequests{}
+ lat.Fake().OnRequest(func(r *http.Request) (int, <-chan struct{}) {
+ if !strings.HasSuffix(r.URL.Path, key) {
+ return 0, nil
+ }
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ p.n++
+ if p.failing {
+ return http.StatusInternalServerError, nil
+ }
+ return 0, nil
+ })
+ return p
+}
+
+func (p *pipelineKeyRequests) count() int {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ return p.n
+}
+
+func (p *pipelineKeyRequests) fail(on bool) {
+ p.mu.Lock()
+ p.failing = on
+ p.mu.Unlock()
+}
+
+// TestOverviewReadsPipelineOnce: with a pending change on the card, a cold
+// Overview reads the pipeline once, for the frame and the card together.
+func TestOverviewReadsPipelineOnce(t *testing.T) {
+ fx, lat := newPerfFixture(t)
+ c := signInPaul(t, fx)
+ reqs := watchPipelineKey(lat, release.PipelineKey(fx.sqid, "kass"))
+ status, _, body := get(t, c, fx.u("/apps/kass"))
+ if status != http.StatusOK {
+ t.Fatalf("overview = %d:\n%s", status, body)
+ }
+ if !strings.Contains(body, "Pending changes") || !strings.Contains(body, "promote v1 to beta") {
+ t.Fatalf("the seeded pending change is not on the Overview:\n%s", body)
+ }
+ if got := reqs.count(); got != 1 {
+ t.Fatalf("a cold Overview requested the pipeline %d times, want 1", got)
+ }
+}
+
+// TestAppFrameErrorNotCached: a pipeline read that fails is not cached; the
+// next view reads it again and shows it.
+func TestAppFrameErrorNotCached(t *testing.T) {
+ fx, lat := newPerfFixture(t)
+ c := signInPaul(t, fx)
+ reqs := watchPipelineKey(lat, release.PipelineKey(fx.sqid, "kass"))
+ reqs.fail(true)
+ status, _, body := get(t, c, fx.u("/apps/kass/settings/pipeline"))
+ if status != http.StatusOK {
+ t.Fatalf("pipeline settings = %d:\n%s", status, body)
+ }
+ if !strings.Contains(body, "Could not read the pipeline") {
+ t.Fatalf("the failed pipeline read did not reach the page:\n%s", body)
+ }
+ reqs.fail(false)
+ failed := reqs.count()
+ status, _, body = get(t, c, fx.u("/apps/kass/settings/pipeline"))
+ if status != http.StatusOK {
+ t.Fatalf("pipeline settings = %d:\n%s", status, body)
+ }
+ if got := reqs.count() - failed; got != 1 {
+ t.Fatalf("the view after a failed read requested the pipeline %d times, want 1", got)
+ }
+ if strings.Contains(body, "Could not read the pipeline") || !strings.Contains(body, `value="beta"`) {
+ t.Fatalf("the second view did not show the pipeline:\n%s", body)
+ }
+}
+
+// channelsTableVersion is the version the Releases page's Channels table
+// shows for channel, "" when the table has no row for it.
+func channelsTableVersion(body, channel string) string {
+ _, table, ok := strings.Cut(body, "<h2>Channels</h2>")
+ if !ok {
+ return ""
+ }
+ m := regexp.MustCompile(`<td>` + regexp.QuoteMeta(channel) + `</td>\s*<td><code>([^<]*)</code></td>`).FindStringSubmatch(table)
+ if m == nil {
+ return ""
+ }
+ return m[1]
+}
+
+// channelsTableRow is the Channels table's whole row for channel.
+func channelsTableRow(body, channel string) string {
+ _, table, _ := strings.Cut(body, "<h2>Channels</h2>")
+ _, row, ok := strings.Cut(table, "<td>"+channel+"</td>")
+ if !ok {
+ return ""
+ }
+ row, _, _ = strings.Cut(row, "</tr>")
+ return row
+}
+
+// TestAppFrameOwnWriteVisible: a person who changes what the frame holds
+// sees the change on the very next view, though that view's frame was warm
+// a moment before the write.
+func TestAppFrameOwnWriteVisible(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ // setup runs before the frame is warmed (straight into the bucket).
+ setup func(t *testing.T, fx *consoleFixture)
+ // page is the view that shows the change.
+ page string
+ path string
+ form url.Values
+ // landed checks the write reached the bucket.
+ landed func(t *testing.T, fx *consoleFixture)
+ // shows reports whether page's body shows the new value.
+ shows func(body string) bool
+ }{
+ {
+ name: "promote", page: "/apps/kass/releases", path: "/apps/kass/promote",
+ form: url.Values{"channel": {"stable"}, "version": {"v2"}, "confirmed": {"1"}},
+ landed: func(t *testing.T, fx *consoleFixture) { wantChannel(t, fx, "stable", "v2") },
+ shows: func(body string) bool { return channelsTableVersion(body, "stable") == "v2" },
+ },
+ {
+ name: "rollback",
+ setup: func(t *testing.T, fx *consoleFixture) {
+ seedChannel(t, fx, "kass", "beta", "v1")
+ seedChannel(t, fx, "kass", "beta", "v2")
+ },
+ page: "/apps/kass/releases", path: "/apps/kass/rollback",
+ form: url.Values{"channel": {"beta"}, "confirmed": {"1"}},
+ landed: func(t *testing.T, fx *consoleFixture) { wantChannel(t, fx, "beta", "v1") },
+ shows: func(body string) bool { return channelsTableVersion(body, "beta") == "v1" },
+ },
+ {
+ name: "production switch",
+ // The safety-delay line is the legacy ladder's: no pipeline.
+ setup: func(t *testing.T, fx *consoleFixture) { deleteKey(t, fx, release.PipelineKey(fx.sqid, "kass")) },
+ page: "/apps/kass", path: "/apps/kass/production",
+ form: url.Values{"production": {"on"}},
+ landed: func(t *testing.T, fx *consoleFixture) {
+ if f := productionFlag(t, fx, "kass"); f == nil || !f.Production {
+ t.Fatalf("production flag = %+v, want on", f)
+ }
+ },
+ shows: func(body string) bool { return strings.Contains(body, "Safety delay: <strong>on</strong>") },
+ },
+ {
+ name: "fasttrack", page: "/apps/kass/releases", path: "/apps/kass/fasttrack",
+ setup: func(t *testing.T, fx *consoleFixture) { deleteKey(t, fx, release.PipelineKey(fx.sqid, "kass")) },
+ form: url.Values{"channel": {"stable"}, "confirmed": {"1"}},
+ landed: func(t *testing.T, fx *consoleFixture) {
+ if p := fx.channelVersion(t, "kass", "stable"); !p.FastTrack {
+ t.Fatalf("stable = %+v, want fast_track set", p)
+ }
+ },
+ shows: func(body string) bool { return strings.Contains(channelsTableRow(body, "stable"), "delay skipped") },
+ },
+ {
+ name: "new canary", page: "/apps/kass/releases", path: "/apps/kass/canary",
+ form: url.Values{"name": {"rc"}, "version": {"v1"}},
+ landed: func(t *testing.T, fx *consoleFixture) { wantChannel(t, fx, "canary/rc", "v1") },
+ shows: func(body string) bool { return channelsTableVersion(body, "canary/rc") == "v1" },
+ },
+ {
+ name: "canary retire",
+ // The retire waits for an app whose records have been still
+ // for channelSettle; the walk's records were just written.
+ setup: func(t *testing.T, fx *consoleFixture) { ageAppRecords(t, fx, "kass") },
+ page: "/apps/kass/releases", path: "/apps/kass/canary/retire",
+ form: url.Values{"name": {"x"}, "confirmed": {"1"}},
+ landed: func(t *testing.T, fx *consoleFixture) {
+ if _, err := release.Channel(context.Background(), fx.rel, fx.pub, fx.sqid, "kass", "canary/x"); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("canary/x = %v after the retire, want it gone", err)
+ }
+ },
+ shows: func(body string) bool { return channelsTableRow(body, "canary/x") == "" },
+ },
+ {
+ name: "pipeline settings save", page: "/apps/kass/settings/pipeline", path: "/apps/kass/pipeline",
+ form: url.Values{"ch.0.name": {"edge"}, "ch.1.name": {"beta"}, "ch.2.name": {"stable"}},
+ landed: func(t *testing.T, fx *consoleFixture) {
+ p, err := release.GetPipeline(context.Background(), fx.rel, fx.pub, fx.sqid, "kass")
+ if err != nil || p == nil || len(p.Channels) != 3 || p.Channels[0].Name != "edge" {
+ t.Fatalf("pipeline = %+v, %v; want edge, beta, stable", p, err)
+ }
+ },
+ shows: func(body string) bool { return strings.Contains(body, `value="edge"`) },
+ },
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ fx, lat := newPerfFixture(t)
+ c := signInPaul(t, fx)
+ if tc.setup != nil {
+ tc.setup(t, fx)
+ }
+ // Warm the frame, and prove it is warm: the second view of
+ // the page reads none of the frame's keys.
+ stop := func() {}
+ for i := range 2 {
+ status, _, body := get(t, c, fx.u(tc.page))
+ if status != http.StatusOK {
+ t.Fatalf("GET %s = %d:\n%s", tc.page, status, body)
+ }
+ if tc.shows(body) {
+ t.Fatalf("GET %s shows the change before the write", tc.page)
+ }
+ if i == 0 {
+ stop = watchFrameKeys(t, lat, fx.sqid, "kass")
+ }
+ }
+ stop()
+ form := url.Values{"csrf": {sessionToken(t, fx, c)}}
+ for k, v := range tc.form {
+ form[k] = v
+ }
+ status, loc, body := postGated(t, fx, c, fx.u(tc.path), form)
+ if status != http.StatusSeeOther {
+ t.Fatalf("POST %s = %d -> %q:\n%s", tc.path, status, loc, body)
+ }
+ tc.landed(t, fx)
+ status, _, body = get(t, c, fx.u(tc.page))
+ if status != http.StatusOK {
+ t.Fatalf("GET %s after the write = %d:\n%s", tc.page, status, body)
+ }
+ if !tc.shows(body) {
+ t.Fatalf("GET %s after the write does not show it:\n%s", tc.page, body)
+ }
+ })
+ }
+}
+
+// TestAppFrameCLIWriteVisible: a promote through the CLI's door shows on the
+// person's next browser view.
+func TestAppFrameCLIWriteVisible(t *testing.T) {
+ fx, lat := newPerfFixture(t)
+ token := cliToken(t, fx, "paul@keymail.dev", "code-frame-cli")
+ c := signInPaul(t, fx)
+ stop := func() {}
+ for i := range 2 {
+ status, _, body := get(t, c, fx.u("/apps/kass/releases"))
+ if status != http.StatusOK || channelsTableVersion(body, "canary/x") != "v2" {
+ t.Fatalf("releases = %d, canary/x %q; want 200 and v2:\n%s", status, channelsTableVersion(body, "canary/x"), body)
+ }
+ if i == 0 {
+ stop = watchFrameKeys(t, lat, fx.sqid, "kass")
+ }
+ }
+ stop()
+ status, out := postJSON(t, fx.ts.URL+"/api/cli/apps/"+fx.sqid+"/kass/promote",
+ map[string]string{"version": "v1", "channel": "canary/x"}, token)
+ if status != http.StatusOK {
+ t.Fatalf("CLI promote = %d %v", status, out)
+ }
+ wantChannel(t, fx, "canary/x", "v1")
+ _, _, body := get(t, c, fx.u("/apps/kass/releases"))
+ if got := channelsTableVersion(body, "canary/x"); got != "v1" {
+ t.Fatalf("releases after a CLI promote shows canary/x at %q, want v1:\n%s", got, body)
+ }
+}
+
+func wantChannel(t *testing.T, fx *consoleFixture, channel, version string) {
+ t.Helper()
+ if p := fx.channelVersion(t, "kass", channel); p.Version != version {
+ t.Fatalf("%s = %s, want %s", channel, p.Version, version)
+ }
+}
+
+func deleteKey(t *testing.T, fx *consoleFixture, key string) {
+ t.Helper()
+ if err := fx.rel.Delete(context.Background(), key); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// watchFrameKeys fails the test if any request names one of the frame's
+// keys until the returned stop is called: the proof that a view was served
+// from a warm frame.
+func watchFrameKeys(t *testing.T, lat *perfLatency, acct, app string) (stop func()) {
+ t.Helper()
+ var mu sync.Mutex
+ armed := true
+ keys := []string{release.ChannelsPrefix(acct, app), release.ProductionKey(acct, app), release.PipelineKey(acct, app)}
+ lat.Fake().OnRequest(func(r *http.Request) (int, <-chan struct{}) {
+ mu.Lock()
+ defer mu.Unlock()
+ if !armed {
+ return 0, nil
+ }
+ where := r.URL.Path + "?" + r.URL.RawQuery
+ for _, k := range keys {
+ if strings.Contains(where, k) || strings.Contains(where, url.QueryEscape(k)) {
+ t.Errorf("a warm view requested %s", where)
+ }
+ }
+ return 0, nil
+ })
+ return func() {
+ mu.Lock()
+ armed = false
+ mu.Unlock()
+ }
+}
+
+// ageAppRecords backdates the app's instance and sidecar record files past
+// channelSettle.
+func ageAppRecords(t *testing.T, fx *consoleFixture, app string) {
+ t.Helper()
+ old := time.Now().Add(-2 * channelSettle)
+ for _, prefix := range []string{provision.RecordsPrefix(fx.sqid, app), provision.SidecarsPrefix(fx.sqid, app)} {
+ dir := filepath.Join(fx.rel.(*deletableStore).root, filepath.FromSlash(prefix))
+ err := filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+ return os.Chtimes(path, old, old)
+ })
+ if err != nil && !errors.Is(err, fs.ErrNotExist) {
+ t.Fatal(err)
+ }
+ }
+}
+
+// TestAppFrameGetDuringWrite: a view whose frame load began before a
+// promote, and whose reads come back after it, must not leave the old
+// frame in the cache. The view's read of the stable pointer is held at the
+// fake until the promote has returned.
+func TestAppFrameGetDuringWrite(t *testing.T) {
+ fx, lat := newPerfFixture(t)
+ c := signInPaul(t, fx)
+ csrf := sessionToken(t, fx, c)
+ stableKey := release.ChannelsPrefix(fx.sqid, "kass") + "stable.json"
+ var mu sync.Mutex
+ armed := true
+ reached := make(chan struct{})
+ hold, release := releaseOnce()
+ // Released however the test ends, so neither the held view nor the
+ // fake's handler outlives it.
+ defer release()
+ lat.Fake().OnRequest(func(r *http.Request) (int, <-chan struct{}) {
+ mu.Lock()
+ defer mu.Unlock()
+ if armed && r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, stableKey) {
+ armed = false
+ close(reached)
+ return 0, hold
+ }
+ return 0, nil
+ })
+ viewed := make(chan string, 1)
+ go func() {
+ res, err := c.Get(fx.u("/apps/kass/releases"))
+ if err != nil {
+ viewed <- "error: " + err.Error()
+ return
+ }
+ defer res.Body.Close()
+ b, _ := io.ReadAll(res.Body)
+ viewed <- string(b)
+ }()
+ frameWait(t, reached, "the view's read of the stable pointer")
+ status, loc, body := postForm(t, c, fx.u("/apps/kass/promote"),
+ url.Values{"csrf": {csrf}, "channel": {"stable"}, "version": {"v2"}, "confirmed": {"1"}})
+ if status != http.StatusSeeOther {
+ t.Fatalf("promote = %d -> %q:\n%s", status, loc, body)
+ }
+ wantChannel(t, fx, "stable", "v2")
+ release()
+ if got := channelsTableVersion(frameWait(t, viewed, "the held view"), "stable"); got != "v1" {
+ t.Fatalf("the view that began before the promote shows stable at %q, want v1 (its own reads)", got)
+ }
+ _, _, body = get(t, c, fx.u("/apps/kass/releases"))
+ if got := channelsTableVersion(body, "stable"); got != "v2" {
+ t.Fatalf("the next view shows stable at %q, want v2: the in-flight view stored its old frame", got)
+ }
+}
+
+// cached reports whether acct/app has a stored frame, fresh or not.
+func (c *appFrames) cached(acct, app string) bool {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ sl := c.slots[frameKey{acct, app}]
+ return sl != nil && sl.has
+}
+
+// forgetAll empties the cache: perfColdReset's cold console.
+func (c *appFrames) forgetAll() {
+ c.clearWhere(func(frameKey) bool { return true })
+}
+
+// TestAppFrameWriteHookClears: registerRoute's hook clears the app (or the
+// account) a write door names before the first byte of its response, leaves
+// GET and HEAD alone, and is a no-op for a pattern that names neither.
+func TestAppFrameWriteHookClears(t *testing.T) {
+ warm := func(s *Server) {
+ for _, k := range [][2]string{{"bab", "kass"}, {"bab", "shop"}, {"other", "kass"}} {
+ s.frames.get(context.Background(), k[0], k[1], func(context.Context) appFrame { return testFrame("v1") })
+ }
+ }
+ for _, tc := range []struct {
+ pattern, method, path string
+ gone, kept [][2]string
+ }{
+ {"POST /a/{sqid}/apps/{app}/promote", "POST", "/a/bab/apps/kass/promote",
+ [][2]string{{"bab", "kass"}, {"other", "kass"}}, [][2]string{{"bab", "shop"}}},
+ {"POST /api/cli/apps/{account}/{app}/promote", "POST", "/api/cli/apps/bab/kass/promote",
+ [][2]string{{"bab", "kass"}, {"other", "kass"}}, [][2]string{{"bab", "shop"}}},
+ {"POST /a/{sqid}/trash/restore", "POST", "/a/bab/trash/restore",
+ [][2]string{{"bab", "kass"}, {"bab", "shop"}}, [][2]string{{"other", "kass"}}},
+ {"POST /api/cli/apps/{account}/new", "POST", "/api/cli/apps/bab/new",
+ [][2]string{{"bab", "kass"}, {"bab", "shop"}}, [][2]string{{"other", "kass"}}},
+ {"POST /auth/signout", "POST", "/auth/signout",
+ nil, [][2]string{{"bab", "kass"}, {"bab", "shop"}, {"other", "kass"}}},
+ {"GET /a/{sqid}/apps/{app}", "GET", "/a/bab/apps/kass",
+ nil, [][2]string{{"bab", "kass"}, {"bab", "shop"}, {"other", "kass"}}},
+ {"GET /a/{sqid}/apps/{app}", "HEAD", "/a/bab/apps/kass",
+ nil, [][2]string{{"bab", "kass"}, {"bab", "shop"}, {"other", "kass"}}},
+ {"/a/{sqid}/apps/{app}/anything", "GET", "/a/bab/apps/kass/anything",
+ nil, [][2]string{{"bab", "kass"}, {"bab", "shop"}, {"other", "kass"}}},
+ {"/a/{sqid}/apps/{app}/anything", "POST", "/a/bab/apps/kass/anything",
+ [][2]string{{"bab", "kass"}, {"other", "kass"}}, [][2]string{{"bab", "shop"}}},
+ } {
+ t.Run(tc.method+" "+tc.pattern, func(t *testing.T) {
+ s := &Server{}
+ warm(s)
+ mux := http.NewServeMux()
+ var beforeWrite, bypass bool
+ mux.HandleFunc(tc.pattern, s.withFrameClear(tc.pattern, func(w http.ResponseWriter, r *http.Request) {
+ beforeWrite = s.frames.cached("bab", "kass")
+ bypass = r.Context().Value(frameBypassKey{}) != nil
+ w.WriteHeader(http.StatusSeeOther)
+ for _, k := range tc.gone {
+ if s.frames.cached(k[0], k[1]) {
+ t.Errorf("%s/%s still cached once the response started", k[0], k[1])
+ }
+ }
+ }))
+ mux.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(tc.method, tc.path, nil))
+ if !beforeWrite {
+ t.Error("the clear ran before the handler wrote anything; it belongs at the first write")
+ }
+ if want := !readOnlyMethod(tc.method); bypass != want {
+ t.Errorf("the request bypasses the cache: %v, want %v (a write door never reads it)", bypass, want)
+ }
+ for _, k := range tc.kept {
+ if !s.frames.cached(k[0], k[1]) {
+ t.Errorf("%s/%s was cleared, want it kept", k[0], k[1])
+ }
+ }
+ })
+ }
+}
+
+// TestAppFrameRenameClearsNewName: a rename clears the frame under the new
+// name too (the hook clears the old one).
+func TestAppFrameRenameClearsNewName(t *testing.T) {
+ fx, _ := newPerfFixture(t)
+ freshApp(t, fx, "sprout")
+ c := signInPaul(t, fx)
+ for _, app := range []string{"sprout", "sapling"} {
+ fx.srv.frames.get(context.Background(), fx.sqid, app, func(context.Context) appFrame { return testFrame("stale") })
+ }
+ status, loc, body := postForm(t, c, fx.u("/apps/sprout/rename"),
+ url.Values{"csrf": {sessionToken(t, fx, c)}, "to": {"sapling"}, "confirmed": {"1"}})
+ if status != http.StatusSeeOther || loc != fx.path("/apps/sapling/settings") {
+ t.Fatalf("rename = %d -> %q:\n%s", status, loc, body)
+ }
+ for _, app := range []string{"sprout", "sapling"} {
+ if fx.srv.frames.cached(fx.sqid, app) {
+ t.Errorf("%s's frame survived the rename", app)
+ }
+ }
+}
+
+// TestAppFrameNamedAccountWriteClears: an account-wide write door addressed
+// by the account's NAME (the browser and the CLI both accept it) clears the
+// account's frames and bumps their generations just as the sqid does. The
+// create is held after inserting the app's row and before writing its
+// default pipeline; a view in that gap caches a frame with no pipeline, and the
+// first view after the create must show the pipeline.
+func TestAppFrameNamedAccountWriteClears(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ create func(t *testing.T, fx *consoleFixture, c *http.Client, token, acctName, app string) int
+ }{
+ {"CLI POST /api/cli/apps/{account}/new", func(t *testing.T, fx *consoleFixture, c *http.Client, token, acctName, app string) int {
+ status, out := postJSON(t, fx.ts.URL+"/api/cli/apps/"+acctName+"/new", map[string]string{"name": app}, token)
+ if status != http.StatusCreated && status != http.StatusOK {
+ t.Errorf("CLI create = %d %v", status, out)
+ }
+ return status
+ }},
+ {"browser POST /a/{sqid}/apps/new", func(t *testing.T, fx *consoleFixture, c *http.Client, token, acctName, app string) int {
+ status, loc, body := postForm(t, c, fx.ts.URL+"/a/"+acctName+"/apps/new",
+ url.Values{"csrf": {sessionToken(t, fx, c)}, "name": {app}})
+ if status != http.StatusSeeOther || strings.Contains(loc, "/apps/new") {
+ t.Errorf("browser create = %d -> %q:\n%s", status, loc, body)
+ }
+ return status
+ }},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ fx, lat := newPerfFixture(t)
+ // The seeded plan allows no fourth app; the cap is not under test.
+ fx.srv.cfg.PlanCatalog = nil
+ token := cliToken(t, fx, "paul@keymail.dev", "code-frame-named")
+ c := signInPaul(t, fx)
+ accts, err := fx.st.AccountsFor("paul@keymail.dev")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var acctName string
+ for _, a := range accts {
+ if a.Sqid == fx.sqid {
+ acctName = a.Name
+ }
+ }
+ if acctName == "" || acctName == fx.sqid {
+ t.Fatalf("the fixture account has no name distinct from its sqid: %q", acctName)
+ }
+ const app = "sprout"
+ pipeKey := release.PipelineKey(fx.sqid, app)
+ var mu sync.Mutex
+ armed := true
+ reached := make(chan struct{})
+ hold, releaseHold := releaseOnce()
+ defer releaseHold()
+ lat.Fake().OnRequest(func(r *http.Request) (int, <-chan struct{}) {
+ mu.Lock()
+ defer mu.Unlock()
+ // The fake runs a held request's operation and holds only its
+ // response, so hold the create's first look at the pipeline
+ // key (SetPipeline reads it before it writes): the write is
+ // still to come.
+ if armed && strings.HasSuffix(r.URL.Path, pipeKey) {
+ armed = false
+ close(reached)
+ return 0, hold
+ }
+ return 0, nil
+ })
+ created := make(chan int, 1)
+ go func() { created <- tc.create(t, fx, c, token, acctName, app) }()
+ frameWait(t, reached, "the create's first read of the pipeline key")
+ // The row exists and the pipeline does not: this view caches
+ // the incomplete frame.
+ if status, _, body := get(t, c, fx.u("/")); status != http.StatusOK || !strings.Contains(body, app) {
+ t.Fatalf("account home during the create = %d, want 200 listing %s:\n%s", status, app, body)
+ }
+ if !fx.srv.frames.cached(fx.sqid, app) {
+ t.Fatal("the view during the create did not cache a frame; the test is not exercising the race")
+ }
+ if f := fx.srv.appFrame(context.Background(), fx.sqid, acctName, app); f.Pipeline != nil {
+ t.Fatalf("the frame cached during the create already has a pipeline: %+v", f.Pipeline)
+ }
+ releaseHold()
+ frameWait(t, created, "the create's response")
+ if fx.srv.frames.cached(fx.sqid, app) {
+ t.Error("the incomplete frame survived the create's response")
+ }
+ if status, _, body := get(t, c, fx.u("/apps/"+app)); status != http.StatusOK {
+ t.Fatalf("app page after the create = %d:\n%s", status, body)
+ }
+ if f := fx.srv.appFrame(context.Background(), fx.sqid, acctName, app); f.Pipeline == nil {
+ t.Fatal("the first view after the create has no pipeline: the name-addressed write missed the account-wide clear")
+ }
+ })
+ }
+}
+
+// TestAppFrameClearAccountByName: clearAccount matches a slot's account
+// sqid or the account name its last view gave, ignoring case, and a name no
+// slot knows allocates nothing.
+func TestAppFrameClearAccountByName(t *testing.T) {
+ var c appFrames
+ ctx := context.Background()
+ load := func(context.Context) appFrame { return testFrame("v1") }
+ c.getAs(ctx, "bab", "Ops", "kass", load)
+ c.getAs(ctx, "bab", "Ops", "shop", load)
+ c.getAs(ctx, "other", "elsewhere", "kass", load)
+ c.get(ctx, "unnamed", "kass", load)
+ c.clearAccount("ops")
+ if c.cached("bab", "kass") || c.cached("bab", "shop") {
+ t.Error("clearAccount(name) left the named account's frames")
+ }
+ if !c.cached("other", "kass") || !c.cached("unnamed", "kass") {
+ t.Error("clearAccount(name) cleared another account")
+ }
+ c.clearAccount("unnamed")
+ if c.cached("unnamed", "kass") {
+ t.Error("clearAccount(sqid) left a frame whose view gave no name")
+ }
+ c.clearAccount("nobody")
+ if n := len(c.slots); n != 1 {
+ t.Errorf("%d slots after clearing an unknown name, want the 1 that was cached", n)
+ }
+}
diff --git a/internal/console/appsettings.go b/internal/console/appsettings.go
index 77b5532b8..14279af71 100644
--- a/internal/console/appsettings.go
+++ b/internal/console/appsettings.go
@@ -327,7 +327,12 @@ type MailStandaloneView struct {
// assembleSettings fills the Settings tab's view. Best-effort by design: a
// bucket hiccup here blocks the rename form (fail closed — an unverifiable
// emptiness claim must not enable an identity change) and never the page.
-func (s *Server) assembleSettings(ctx context.Context, p *page, acct *Account) *SettingsView {
+//
+// reads names the parts to fetch (settingsSectionReads): each remote read
+// runs only when its flag is set, so a section view pays for what it shows.
+// The control-plane flag, the route-based channel question and the account
+// mismatch are local and always filled.
+func (s *Server) assembleSettings(ctx context.Context, p *page, acct *Account, reads settingsSectionReads) *SettingsView {
sv := &SettingsView{}
// Domains, its derived OnlyPlatformDomain, and NeedsChannel are all
// read-only against the registry/claims and owe nothing to the
@@ -340,7 +345,9 @@ func (s *Server) assembleSettings(ctx context.Context, p *page, acct *Account) *
} else {
sv.ControlPlane = cp
}
- sv.Domains = s.settingsDomains(ctx, acct, p.AppName, p.Detail.Domains)
+ if reads.domains {
+ sv.Domains = s.settingsDomains(ctx, acct, p.AppName, p.Detail.Domains)
+ }
sv.OnlyPlatformDomain = len(sv.Domains) > 0
for _, d := range sv.Domains {
// Prefix, not equality: domainView appends " · canary/<name>" AFTER
@@ -366,30 +373,42 @@ func (s *Server) assembleSettings(ctx context.Context, p *page, acct *Account) *
} else {
sv.NeedsChannel = route == ""
}
- sv.Gates, sv.GatesUnavailable = s.settingsGates(ctx, acct, p.AppName)
+ if reads.gates {
+ sv.Gates, sv.GatesUnavailable = s.settingsGates(ctx, acct, p.AppName)
+ }
if s.cfg.Releases == nil {
sv.NoBucket = true
sv.RenameBlocked = "No deployment bucket on this host, so the never-shipped check cannot run."
return sv
}
- switch empty, err := s.appDeployEmpty(ctx, acct.Sqid, p.AppName); {
- case err != nil:
- sv.RenameBlocked = "Could not check the deployment bucket, so renaming is off until it can be."
- case len(p.Detail.Routes) > 0:
- sv.RenameBlocked = "This app is wired to a host — its name is its address, in routes and bucket keys alike."
- case !empty:
- sv.RenameBlocked = "This app has shipped — its name is baked into its releases' bucket keys."
- default:
- sv.CanRename = true
- }
- sv.Envs, sv.EnvsUnavailable = s.envCards(ctx, acct, p.AppName, p.Detail.Routes)
- sv.Store = s.storeCard(ctx, acct, p.AppName)
- sv.StoreEnvs = s.storeEnvCards(ctx, acct, p.AppName)
- sv.Mail = s.mailCard(ctx, acct, p.AppName)
- sv.Features = s.featuresCard(ctx, acct, p.AppName)
- sv.StoreUnavailable = sv.Store == nil
- sv.MailUnavailable = sv.Mail == nil
- sv.FeaturesUnavailable = sv.Features == nil
+ if reads.deployEmpty {
+ switch empty, err := s.appDeployEmpty(ctx, acct.Sqid, p.AppName); {
+ case err != nil:
+ sv.RenameBlocked = "Could not check the deployment bucket, so renaming is off until it can be."
+ case len(p.Detail.Routes) > 0:
+ sv.RenameBlocked = "This app is wired to a host — its name is its address, in routes and bucket keys alike."
+ case !empty:
+ sv.RenameBlocked = "This app has shipped — its name is baked into its releases' bucket keys."
+ default:
+ sv.CanRename = true
+ }
+ }
+ if reads.envs {
+ sv.Envs, sv.EnvsUnavailable = s.envCards(ctx, acct, p.AppName, p.Detail.Routes)
+ }
+ if reads.store {
+ sv.Store = s.storeCard(ctx, acct, p.AppName)
+ sv.StoreEnvs = s.storeEnvCards(ctx, acct, p.AppName)
+ sv.StoreUnavailable = sv.Store == nil
+ }
+ if reads.mail {
+ sv.Mail = s.mailCard(ctx, acct, p.AppName)
+ sv.MailUnavailable = sv.Mail == nil
+ }
+ if reads.features {
+ sv.Features = s.featuresCard(ctx, acct, p.AppName)
+ sv.FeaturesUnavailable = sv.Features == nil
+ }
if ra := p.Detail.RouteAccount; ra != "" && p.Detail.AllMismatched {
sv.MismatchTarget = ra
if target, err := s.store.AccountBySqid(ra); err == nil && target != nil {
@@ -750,9 +769,19 @@ func (s *Server) settingsDomains(ctx context.Context, acct *Account, app string,
// appDeployEmpty reports whether the bucket holds ANYTHING under the app's
// prefix — account-qualified or legacy-unqualified. One key is enough to
// refuse a rename; the caller never needs the listing itself.
+//
+// It asks each prefix for a single key (release.PageLister) when the store can
+// page, and lists the prefix when not, so a long-shipped app's releases are
+// not enumerated to answer a yes or no.
func (s *Server) appDeployEmpty(ctx context.Context, acct, app string) (bool, error) {
for _, prefix := range []string{release.AppPrefix(acct, app), release.LegacyAppPrefix(app)} {
- keys, err := s.cfg.Releases.List(ctx, prefix)
+ var keys []string
+ var err error
+ if pl, ok := s.cfg.Releases.(release.PageLister); ok {
+ keys, err = pl.ListPage(ctx, prefix, "", 1)
+ } else {
+ keys, err = s.cfg.Releases.List(ctx, prefix)
+ }
if err != nil {
return false, err
}
@@ -921,6 +950,9 @@ func (s *Server) handleAppRename(w http.ResponseWriter, r *http.Request) {
back("err", renameAdvice(err, to))
return
}
+ // registerRoute's hook clears the old name; the new one is cleared
+ // here, before any response, so its first page is read fresh.
+ s.frames.clearApp(to)
// The emptiness checks above cannot join the database transaction — the
// bucket and the registry are other stores — so a `carlos ship` or
// `carlos add` racing this request can land under the old name between
diff --git a/internal/console/appsettings_sections_test.go b/internal/console/appsettings_sections_test.go
index 2d72bb064..0e2cbfbb6 100644
--- a/internal/console/appsettings_sections_test.go
+++ b/internal/console/appsettings_sections_test.go
@@ -271,7 +271,7 @@ func TestSettingsSectionsReadOnlyWhatTheyShow(t *testing.T) {
Detail: &AppView{App: "shop"},
}
setAppSettingsSection(&p, section)
- if reads.record {
+ if reads.record() {
p.Settings = &SettingsView{}
}
var buf bytes.Buffer
@@ -280,12 +280,23 @@ func TestSettingsSectionsReadOnlyWhatTheyShow(t *testing.T) {
}
}
for _, section := range []string{"placement", "errors-analytics", "delete"} {
- if settingsSectionReadsFor(section).record {
+ if settingsSectionReadsFor(section).record() {
t.Errorf("section %s builds the whole settings record it never shows", section)
}
}
- if r := settingsSectionReadsFor("general"); !r.record || !r.swap || r.telemetry {
- t.Errorf("general reads %+v, want the record and the swap policy only", r)
+ if r := settingsSectionReadsFor("general"); r != (settingsSectionReads{deployEmpty: true, swap: true}) {
+ t.Errorf("general reads %+v, want the never-shipped check and the swap policy only", r)
+ }
+ for section, want := range map[string]settingsSectionReads{
+ "domains": {domains: true, gates: true},
+ "environments": {envs: true},
+ "storage": {store: true},
+ "email": {mail: true},
+ "features": {features: true},
+ } {
+ if got := settingsSectionReadsFor(section); got != want {
+ t.Errorf("%s reads %+v, want %+v", section, got, want)
+ }
}
if r := settingsSectionReadsFor("errors-analytics"); !r.telemetry || r.swap || r.placement {
t.Errorf("errors-analytics reads %+v, want telemetry only", r)
diff --git a/internal/console/appsettings_test.go b/internal/console/appsettings_test.go
index b8f44ebcb..2934a3b2c 100644
--- a/internal/console/appsettings_test.go
+++ b/internal/console/appsettings_test.go
@@ -422,6 +422,7 @@ func TestAppDeleteRefusesAProductionApp(t *testing.T) {
release.OpsAccount, "kass", true, "test"); err != nil {
t.Fatal(err)
}
+ fx.forgetFrame("kass")
c := signInPaul(t, fx)
csrf := sessionToken(t, fx, c)
@@ -1136,7 +1137,7 @@ func TestAssembleSettingsListsRoutedDomainsWithoutABucket(t *testing.T) {
}
p := &page{AppName: "kass", Detail: detail}
- sv := fx.srv.assembleSettings(context.Background(), p, acct)
+ sv := fx.srv.assembleSettings(context.Background(), p, acct, settingsSectionReads{domains: true, gates: true, deployEmpty: true, envs: true, store: true, mail: true, features: true})
if !sv.NoBucket || sv.StoreUnavailable || sv.MailUnavailable || sv.FeaturesUnavailable {
t.Fatalf("bucketless settings flags = NoBucket %v, unavailable %v/%v/%v", sv.NoBucket,
sv.StoreUnavailable, sv.MailUnavailable, sv.FeaturesUnavailable)
diff --git a/internal/console/bakecontrols_test.go b/internal/console/bakecontrols_test.go
index e86a9b363..e8f5ea22f 100644
--- a/internal/console/bakecontrols_test.go
+++ b/internal/console/bakecontrols_test.go
@@ -98,6 +98,7 @@ func TestProductionOffIsOwnerPasskeyGated(t *testing.T) {
release.OpsAccount, "kass", true, "test"); err != nil {
t.Fatal(err)
}
+ fx.forgetFrame("kass")
// Without the passkey the flag does not move.
status, loc, _ := postForm(t, c, fx.u("/apps/kass/production"),
@@ -128,6 +129,7 @@ func TestProductionOffMemberGets404(t *testing.T) {
release.OpsAccount, "kass", true, "test"); err != nil {
t.Fatal(err)
}
+ fx.forgetFrame("kass")
if err := fx.st.AddMember(OpsAccountID, "sam@keymail.dev", RoleMember, time.Now()); err != nil {
t.Fatal(err)
}
@@ -296,6 +298,7 @@ func TestPromoteEnableBakeSaysWhenItCouldNotRead(t *testing.T) {
release.ProductionKey(release.OpsAccount, "kass"), []byte("{not a wrapper"), ""); err != nil {
t.Fatal(err)
}
+ fx.forgetFrame("kass")
postGated(t, fx, c, fx.u("/apps/kass/promote"),
url.Values{"csrf": {csrf}, "channel": {"stable"}, "version": {"v3"}, "enable_bake": {"1"}, "confirmed": {"1"}})
@@ -342,6 +345,7 @@ func TestPromoteBakeNoteFollowsTheFlag(t *testing.T) {
release.OpsAccount, "kass", true, "test"); err != nil {
t.Fatal(err)
}
+ fx.forgetFrame("kass")
shipVersion(t, fx, "kass", "v4")
seedChannel(t, fx, "kass", "edge", "v4")
if status, _, body := postForm(t, c, fx.u("/apps/kass/promote"),
diff --git a/internal/console/claim_routes.go b/internal/console/claim_routes.go
index 10107da69..91097dcdb 100644
--- a/internal/console/claim_routes.go
+++ b/internal/console/claim_routes.go
@@ -56,9 +56,19 @@ func claimHandlerName(h any) string {
// registerRoute preserves each handler's existing authorization order. It adds
// provenance for the effect-boundary audit; provenance does not grant a permit.
+//
+// Every non-GET request also clears the app-tab frame cache for the app (or
+// account) its pattern names, before its first response byte and again on
+// return (withFrameClear, appframe.go). The clear is the only thing it adds
+// ahead of the handler's own gates, and it changes no response.
+//
+// Every GET and HEAD request gets a request memo of its own (reqmemo.go),
+// so one page view reads each box report set, the edges files and the
+// app's instances.json at most once. Other requests get none.
func (s *Server) registerRoute(pattern string, h http.HandlerFunc) {
e := claimEntry{Kind: "route", Pattern: pattern, Handler: claimHandlerName(h)}
s.claimEntries.add(e)
+ h = withReqMemoOnViews(s.withFrameClear(pattern, h))
if !s.cfg.HostClaim {
s.mux.HandleFunc(pattern, h)
return
diff --git a/internal/console/deletion_test.go b/internal/console/deletion_test.go
index f96d3d1e8..3f4c043e3 100644
--- a/internal/console/deletion_test.go
+++ b/internal/console/deletion_test.go
@@ -461,6 +461,7 @@ func TestDeleteNowRefusesAProductionApp(t *testing.T) {
if err := release.SetProduction(ctx, fx.rel, fx.priv, release.OpsAccount, "kass", true, "test"); err != nil {
t.Fatal(err)
}
+ fx.forgetFrame("kass")
c := newBrowser(t)
signUp(t, fx, c, "code-trash-prod")
trashKass(t, fx, "paul@keymail.dev", time.Now())
@@ -745,6 +746,7 @@ func TestPurgeRefusesAProductionAppBeforeTouchingItsStore(t *testing.T) {
if err := release.SetProduction(ctx, fx.rel, fx.priv, release.OpsAccount, "kass", true, "test"); err != nil {
t.Fatal(err)
}
+ fx.forgetFrame("kass")
c := newBrowser(t)
signUp(t, fx, c, "code-purge-prod-store")
trashKass(t, fx, "paul@keymail.dev", time.Now())
diff --git a/internal/console/deployscope_test.go b/internal/console/deployscope_test.go
index c05fef515..3e8341877 100644
--- a/internal/console/deployscope_test.go
+++ b/internal/console/deployscope_test.go
@@ -119,6 +119,7 @@ func TestDeployScopeRefusalsAtTheDoors(t *testing.T) {
[]release.PipelineChannel{{Name: "edge"}, {Name: "stable"}}, "paul@keymail.dev"); err != nil {
t.Fatal(err)
}
+ fx.forgetFrame("hello")
for _, a := range []attempt{
{"pipelined edge", map[string]any{"version": "v1", "channel": "edge"}, "edge",
"hello has a pipeline, so deploy credential ci may move canary/<name> channels only."},
diff --git a/internal/console/ladder_test.go b/internal/console/ladder_test.go
index de333e509..9fd971154 100644
--- a/internal/console/ladder_test.go
+++ b/internal/console/ladder_test.go
@@ -39,15 +39,23 @@ func shipVersion(t *testing.T, fx *consoleFixture, app, version string) {
// seedChannel points a channel at a version through the UNCHECKED primitive.
// That is deliberate: these are arrangements of the world the console then has
-// to read and gate, not promotions under test.
+// to read and gate, not promotions under test. Like every write straight into
+// the bucket, it then forgets the app's frame (forgetFrame).
func seedChannel(t *testing.T, fx *consoleFixture, app, channel, version string, rec ...release.Promotion) {
t.Helper()
if err := release.Promote(context.Background(), fx.rel, fx.priv,
release.OpsAccount, app, channel, version, rec...); err != nil {
t.Fatal(err)
}
+ fx.forgetFrame(app)
}
+// forgetFrame drops app's app-tab frame (appframe.go). A test that writes a
+// channel, the production flag or the pipeline straight into the bucket is a
+// writer outside the console, which a running console sees within
+// appFrameTTL; this stands for that wait.
+func (fx *consoleFixture) forgetFrame(app string) { fx.srv.frames.clearApp(app) }
+
// rungBlock cuts one rung's markup out of the rendered page, so "the beta rung
// shows v4" is an assertion about the beta rung and not about the page
// containing "v4" somewhere.
@@ -596,6 +604,7 @@ func seedExpiredCanary(t *testing.T, fx *consoleFixture, app, channel, version s
release.ChannelKey(release.OpsAccount, app, channel), wrapper, ""); err != nil {
t.Fatal(err)
}
+ fx.forgetFrame(app)
}
// TestLadderPromotesOntoAnExpiredCanary pins spec §5's visibility-only
@@ -656,6 +665,7 @@ func TestLadderShowsBakeStateAndControls(t *testing.T) {
release.OpsAccount, "kass", true, "test"); err != nil {
t.Fatal(err)
}
+ fx.forgetFrame("kass")
_, _, body = get(t, c, fx.u("/apps/kass/releases"))
if !strings.Contains(body, `action="/a/bab/apps/kass/fasttrack"`) {
t.Fatalf("no fast-track control on a held head:\n%s", rungBlock(t, body, "beta"))
@@ -729,6 +739,7 @@ func TestLadderBakeControlsMemberView(t *testing.T) {
release.OpsAccount, "kass", true, "test"); err != nil {
t.Fatal(err)
}
+ fx.forgetFrame("kass")
_, _, obody := get(t, c, fx.u("/apps/kass/releases"))
if !strings.Contains(obody, `name="production" value="off"`) {
t.Fatal("owner is not offered the turn-off control once bake is eligible — the member-only checks below would be vacuous")
@@ -759,6 +770,7 @@ func TestLadderUnreadableFlagOffersRepair(t *testing.T) {
release.ProductionKey(release.OpsAccount, "kass"), []byte("{not a wrapper"), ""); err != nil {
t.Fatal(err)
}
+ fx.forgetFrame("kass")
_, _, body := get(t, c, fx.u("/apps/kass/releases"))
if !strings.Contains(body, "Safety delay: this app's setting can't be read right now, so the delay stays on.") {
t.Fatalf("no error line for an unverifiable flag:\n%s", body)
@@ -800,9 +812,11 @@ func TestLadderTurningOffOffersTurnBackOn(t *testing.T) {
if err := release.SetProduction(ctx, fx.rel, fx.priv, release.OpsAccount, "kass", true, "test"); err != nil {
t.Fatal(err)
}
+ fx.forgetFrame("kass")
if err := release.SetProduction(ctx, fx.rel, fx.priv, release.OpsAccount, "kass", false, "test"); err != nil {
t.Fatal(err)
}
+ fx.forgetFrame("kass")
_, _, body := get(t, c, fx.u("/apps/kass/releases"))
if !strings.Contains(body, "turning off") {
t.Fatalf("a fresh off-flag on a held app does not say hosts are still ratcheting:\n%s", body)
@@ -834,6 +848,7 @@ func TestLadderNudgesProdWiredBakeOff(t *testing.T) {
release.OpsAccount, "kass", true, "test"); err != nil {
t.Fatal(err)
}
+ fx.forgetFrame("kass")
if _, _, body := get(t, c, fx.u("/apps/kass/releases")); strings.Contains(body, "new versions go live immediately") {
t.Fatal("the nudge survived the flag turning on")
}
diff --git a/internal/console/ownership.go b/internal/console/ownership.go
index f776ff4a5..98af50470 100644
--- a/internal/console/ownership.go
+++ b/internal/console/ownership.go
@@ -165,6 +165,9 @@ func (s *Server) handleDeleteAccount(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/a/"+acct.Sqid+"/settings", http.StatusSeeOther)
return
}
+ // The account is retired in the bucket now: forget that its manifest was
+ // seen, so nothing in this process vouches for it any more.
+ s.manifestSeen.Delete(acct.Sqid)
if err := s.store.DeleteAccount(acct.ID, time.Now()); err != nil {
log.Printf("console: delete account: %v", err)
s.setFlash(w, "err", deletionAdvice(err))
diff --git a/internal/console/pendingflow_test.go b/internal/console/pendingflow_test.go
index 257d9a5ae..2fd8a522a 100644
--- a/internal/console/pendingflow_test.go
+++ b/internal/console/pendingflow_test.go
@@ -37,6 +37,7 @@ func setPipeline(t *testing.T, fx *consoleFixture, app string, channels ...relea
if err != nil {
t.Fatal(err)
}
+ fx.forgetFrame(app)
return p
}
diff --git a/internal/console/perflatency_test.go b/internal/console/perflatency_test.go
index 877b6e886..7ed8a30c7 100644
--- a/internal/console/perflatency_test.go
+++ b/internal/console/perflatency_test.go
@@ -159,8 +159,14 @@ func TestLatencyAppClientAnswersTheContract(t *testing.T) {
// The fixture over the S3 fake serves a real screen, and the perf sample
// for each view counts exactly the S3 requests the fake answered for it:
-// the cold view's edge-fold refresh included, the warm one's with the
+// the cold view's edge-fold refresh included, the delayed one's with the
// delays on.
+//
+// The delayed views start from an empty app-frame cache. Warm, the frame
+// cache answers an app page from memory in far less than the budget, so
+// whether the over-budget warning fired would depend on how fast the
+// page is; reading the frame afresh through the delayed fake makes the
+// view's S3 round trips the cost, whatever the cache saves.
func TestFixtureOverTheS3FakeServesAppPage(t *testing.T) {
lat := &perfLatency{S3Delay: 25 * time.Millisecond, HostDelay: 40 * time.Millisecond}
fx := newConsoleFixtureWith(t, consoleFixtureOptions{WithKey: true, S3: lat, AppClient: lat.AppClient()})
@@ -172,11 +178,22 @@ func TestFixtureOverTheS3FakeServesAppPage(t *testing.T) {
}
return 0
}
+ pageRequests := func() (n int) {
+ for _, g := range fx.srv.PerfGroups() {
+ if g.Screen == screen && g.Method == "GET" {
+ n += g.Requests
+ }
+ }
+ return n
+ }
+ coldFrames := func() { fx.srv.frames.clearWhere(func(frameKey) bool { return true }) }
view := func() (fake, sample, background, host int64) {
t.Helper()
s0, h0 := lat.Calls()
p0, b0 := pageCalls(), fx.srv.PerfBackground()["s3"]
+ r0 := pageRequests()
resp, body := perfGet(t, c, fx.u("/apps/kass"))
+ waitPerfRequests(t, fx.srv, screen, "GET", r0+1)
if resp.StatusCode != http.StatusOK {
t.Fatalf("GET app page over the S3 fake = %d:\n%s", resp.StatusCode, body)
}
@@ -209,19 +226,21 @@ func TestFixtureOverTheS3FakeServesAppPage(t *testing.T) {
}
lat.Enable(true)
+ coldFrames()
start := time.Now()
fake, sample, background, _ = view()
if fake <= 0 || sample != fake || background != 0 {
- t.Errorf("warm view: sample Calls[s3] = %d (background %d), the fake answered %d; want them equal", sample, background, fake)
+ t.Errorf("delayed view: sample Calls[s3] = %d (background %d), the fake answered %d; want them equal", sample, background, fake)
}
if took, floor := time.Since(start), time.Duration(fake)*lat.S3Delay; took < floor {
- t.Errorf("warm view with S3 delays on took %v, under %d requests at %v", took, fake, lat.S3Delay)
+ t.Errorf("delayed view with S3 delays on took %v, under %d requests at %v", took, fake, lat.S3Delay)
}
if g := findGroup(fx.srv.PerfGroups(), screen); g == nil || g.Requests != 2 {
t.Errorf("app page group = %+v, want two requests", g)
}
// The Running tab's instance report goes through Config.AppClient.
+ coldFrames()
_, h0 := lat.Calls()
if resp, body := perfGet(t, c, fx.u("/apps/kass/instances")); resp.StatusCode != http.StatusOK {
t.Fatalf("GET instances tab over the S3 fake = %d:\n%s", resp.StatusCode, body)
diff --git a/internal/console/perfquickwins_test.go b/internal/console/perfquickwins_test.go
new file mode 100644
index 000000000..a08a77e3d
--- /dev/null
+++ b/internal/console/perfquickwins_test.go
@@ -0,0 +1,631 @@
+package console
+
+import (
+ "context"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "slices"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/objstore"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/status"
+)
+
+// manifestRequests records the HTTP methods of the S3 requests that name one
+// key, from the fake's request hook.
+type manifestRequests struct {
+ mu sync.Mutex
+ methods []string
+}
+
+func recordKeyRequests(lat *perfLatency, key string) *manifestRequests {
+ m := &manifestRequests{}
+ lat.Fake().OnRequest(func(r *http.Request) (int, <-chan struct{}) {
+ if strings.Contains(r.URL.Path, key) {
+ m.mu.Lock()
+ m.methods = append(m.methods, r.Method)
+ m.mu.Unlock()
+ }
+ return 0, nil
+ })
+ return m
+}
+
+func (m *manifestRequests) count(method string) int {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ n := 0
+ for _, k := range m.methods {
+ if k == method {
+ n++
+ }
+ }
+ return n
+}
+
+// TestAccountManifestCheckedOncePerProcess: once the account manifest is
+// known to exist (read, or written by the backfill), later app tab views in
+// this process do not ask the bucket again.
+func TestAccountManifestCheckedOncePerProcess(t *testing.T) {
+ t.Run("existing manifest is read once", func(t *testing.T) {
+ fx, lat := newPerfFixture(t)
+ c := signInPaul(t, fx)
+ key := AccountManifestKey(fx.sqid)
+ if err := WriteAccountManifest(context.Background(), fx.rel, OpsAccountID, fx.sqid, "ops", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ reqs := recordKeyRequests(lat, key)
+ for range 2 {
+ if status, _, body := get(t, c, fx.u("/apps/kass/activity")); status != http.StatusOK {
+ t.Fatalf("activity = %d:\n%s", status, body)
+ }
+ }
+ if got := reqs.count(http.MethodGet); got != 1 {
+ t.Errorf("account.json read %d times across two views, want 1", got)
+ }
+ if got := reqs.count(http.MethodPut); got != 0 {
+ t.Errorf("account.json written %d times, want 0", got)
+ }
+ })
+ t.Run("backfilled manifest is not read again", func(t *testing.T) {
+ fx, lat := newPerfFixture(t)
+ c := signInPaul(t, fx)
+ key := AccountManifestKey(fx.sqid)
+ if err := fx.rel.Delete(context.Background(), key); err != nil {
+ t.Fatal(err)
+ }
+ reqs := recordKeyRequests(lat, key)
+ if status, _, body := get(t, c, fx.u("/apps/kass/activity")); status != http.StatusOK {
+ t.Fatalf("activity = %d:\n%s", status, body)
+ }
+ gets, puts := reqs.count(http.MethodGet), reqs.count(http.MethodPut)
+ if puts != 1 {
+ t.Errorf("first view wrote account.json %d times, want 1", puts)
+ }
+ if status, _, body := get(t, c, fx.u("/apps/kass/activity")); status != http.StatusOK {
+ t.Fatalf("activity = %d:\n%s", status, body)
+ }
+ if g, p := reqs.count(http.MethodGet), reqs.count(http.MethodPut); g != gets || p != puts {
+ t.Errorf("second view touched account.json (reads %d -> %d, writes %d -> %d), want nothing", gets, g, puts, p)
+ }
+ })
+}
+
+// s3Recorder records every S3 request the fake answers: an object request's
+// method and key, or a listing's prefix.
+type s3Recorder struct {
+ mu sync.Mutex
+ reqs []s3Req
+}
+
+type s3Req struct {
+ Method string
+ Key string // "" for a listing
+ Prefix string // a listing's prefix
+}
+
+// recordS3 installs the recorder as the fake's request hook; fail, when
+// non-nil, answers the requests it names with a 403 (which the SDK does
+// not retry).
+func recordS3(lat *perfLatency, fail func(s3Req) bool) *s3Recorder {
+ rec := &s3Recorder{}
+ lat.Fake().OnRequest(func(r *http.Request) (int, <-chan struct{}) {
+ _, key, _ := strings.Cut(strings.TrimPrefix(r.URL.Path, "/"), "/")
+ q := s3Req{Method: r.Method, Key: key}
+ if key == "" {
+ q.Prefix = r.URL.Query().Get("prefix")
+ }
+ rec.mu.Lock()
+ rec.reqs = append(rec.reqs, q)
+ rec.mu.Unlock()
+ if fail != nil && fail(q) {
+ return http.StatusForbidden, nil
+ }
+ return 0, nil
+ })
+ return rec
+}
+
+func (rec *s3Recorder) reset() {
+ rec.mu.Lock()
+ rec.reqs = nil
+ rec.mu.Unlock()
+}
+
+// listings counts the listings of exactly prefix.
+func (rec *s3Recorder) listings(prefix string) int {
+ rec.mu.Lock()
+ defer rec.mu.Unlock()
+ n := 0
+ for _, q := range rec.reqs {
+ if q.Key == "" && q.Prefix == prefix {
+ n++
+ }
+ }
+ return n
+}
+
+// touching counts the requests that name a key or listing under prefix.
+func (rec *s3Recorder) touching(prefix string) int {
+ rec.mu.Lock()
+ defer rec.mu.Unlock()
+ n := 0
+ for _, q := range rec.reqs {
+ if strings.HasPrefix(q.Key, prefix) || (q.Key == "" && strings.HasPrefix(q.Prefix, prefix)) {
+ n++
+ }
+ }
+ return n
+}
+
+func (rec *s3Recorder) all() []s3Req {
+ rec.mu.Lock()
+ defer rec.mu.Unlock()
+ return slices.Clone(rec.reqs)
+}
+
+// TestInstancePageLoadsBoxesOnce: the instance page's three box readers
+// (layout, rollout join, updates) share one read of the platform's box
+// reports and one of each fleet's.
+func TestInstancePageLoadsBoxesOnce(t *testing.T) {
+ fx, lat := newPerfFixture(t)
+ c := signInPaul(t, fx)
+ u := fx.u("/apps/kass/instances/kass.carlosapp.dev")
+ if status, _, body := get(t, c, u); status != http.StatusOK {
+ t.Fatalf("instance page = %d:\n%s", status, body)
+ }
+ // One load's listings of each prefix: the platform store may list
+ // twice in one load (ListMod, then List), a fleet's prefix store once.
+ rec := recordS3(lat, nil)
+ once := map[string]int{}
+ for _, prefix := range []string{"", "fleets/fleet-a/"} {
+ if _, _, err := fx.srv.loadBoxes(context.Background(), fx.srv.cfg.Releases, prefix); err != nil {
+ t.Fatal(err)
+ }
+ once[prefix+"status/boxes/"] = rec.listings(prefix + "status/boxes/")
+ }
+ rec.reset()
+ if status, _, body := get(t, c, u); status != http.StatusOK {
+ t.Fatalf("instance page = %d:\n%s", status, body)
+ }
+ for prefix, want := range once {
+ if got := rec.listings(prefix); got != want {
+ t.Errorf("%s listed %d times in one view, want %d, one load's (requests: %v)", prefix, got, want, rec.all())
+ }
+ }
+}
+
+// TestRunningTabReadsEdgesOnce: the Running tab's region note and its
+// app default share one read of the edges files.
+func TestRunningTabReadsEdgesOnce(t *testing.T) {
+ fx, lat := newPerfFixture(t)
+ c := signInPaul(t, fx)
+ u := fx.u("/apps/kass/instances")
+ if status, _, body := get(t, c, u); status != http.StatusOK {
+ t.Fatalf("running = %d:\n%s", status, body)
+ }
+ rec := recordS3(lat, nil)
+ if status, _, body := get(t, c, u); status != http.StatusOK {
+ t.Fatalf("running = %d:\n%s", status, body)
+ }
+ if got := rec.listings("control/edges/"); got != 1 {
+ t.Errorf("control/edges/ listed %d times in one view, want 1 (requests: %v)", got, rec.all())
+ }
+}
+
+// TestRequestMemoKeepsBoxCompleteness: a box report that will not read
+// leaves the listing partial, and the memo hands the second reader in the
+// request the same partial answer, without asking the bucket again.
+func TestRequestMemoKeepsBoxCompleteness(t *testing.T) {
+ fx, lat := newPerfFixture(t)
+ rec := recordS3(lat, func(q s3Req) bool { return q.Key == "status/boxes/box-a.json" })
+ ctx := withReqMemo(context.Background())
+ first, complete, err := fx.srv.loadBoxes(ctx, fx.srv.cfg.Releases, "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if complete {
+ t.Error("first read: complete with box-a's report unreadable, want partial")
+ }
+ n := len(rec.all())
+ second, complete, err := fx.srv.loadBoxes(ctx, fx.srv.cfg.Releases, "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if complete {
+ t.Error("second read: complete with box-a's report unreadable, want partial")
+ }
+ if got := len(rec.all()); got != n {
+ t.Errorf("second read made %d S3 requests, want none", got-n)
+ }
+ labels := func(bs []status.Box) []string {
+ var out []string
+ for _, b := range bs {
+ out = append(out, b.Label)
+ }
+ return out
+ }
+ if !slices.Equal(labels(first), labels(second)) || !slices.Contains(labels(first), "box-b") || slices.Contains(labels(first), "box-a") {
+ t.Errorf("boxes: first %v, second %v; want both [box-b]", labels(first), labels(second))
+ }
+ // Without a memo every call reads again.
+ n = len(rec.all())
+ if _, complete, _ := fx.srv.loadBoxes(context.Background(), fx.srv.cfg.Releases, ""); complete {
+ t.Error("unmemoized read: complete, want partial")
+ }
+ if len(rec.all()) == n {
+ t.Error("a read with no memo in its context made no S3 request")
+ }
+}
+
+// TestLogsHostPickerReadsNoRecords: the Logs tab's host picker takes the
+// records' hosts from the page's cached record read, not a read of its own.
+func TestLogsHostPickerReadsNoRecords(t *testing.T) {
+ fx, lat := newPerfFixture(t)
+ c := signInPaul(t, fx)
+ ctx := context.Background()
+ hosts := []string{"one.kass.carlosapp.dev", "two.kass.carlosapp.dev", "three.kass.carlosapp.dev"}
+ for _, h := range hosts {
+ rec := provision.Record{Schema: 1, Host: h, App: "kass", Account: fx.sqid, Channel: "stable", Region: "ie",
+ CreatedAt: time.Now(), CreatedBy: "paul@keymail.dev", Slug: strings.Split(h, ".")[0]}
+ if err := provision.CreateRecord(ctx, fx.rel, rec); err != nil {
+ t.Fatal(err)
+ }
+ }
+ u := fx.u("/apps/kass/logs")
+ if status, _, body := get(t, c, u); status != http.StatusOK {
+ t.Fatalf("logs = %d:\n%s", status, body)
+ }
+ rec := recordS3(lat, nil)
+ status, _, body := get(t, c, u)
+ if status != http.StatusOK {
+ t.Fatalf("logs = %d:\n%s", status, body)
+ }
+ if got := rec.touching(provision.RecordsPrefix(fx.sqid, "kass")); got != 0 {
+ t.Errorf("a warm Logs view made %d requests for instance records, want 0 (requests: %v)", got, rec.all())
+ }
+ for _, h := range hosts {
+ if !strings.Contains(body, `<option value="`+h+`"`) {
+ t.Errorf("the host picker has no %s", h)
+ }
+ }
+}
+
+// TestReqMemoOnlyOnViews: memoize with no memo in the context loads every
+// time; registerRoute installs a memo for GET and HEAD requests only.
+func TestReqMemoOnlyOnViews(t *testing.T) {
+ loads := 0
+ load := func() (int, error) { loads++; return loads, nil }
+ for range 2 {
+ if _, err := memoize(context.Background(), "k", load); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if loads != 2 {
+ t.Errorf("with no memo: %d loads for two calls, want 2", loads)
+ }
+ ctx := withReqMemo(context.Background())
+ loads = 0
+ a, _ := memoize(ctx, "k", load)
+ b, _ := memoize(ctx, "k", load)
+ if loads != 1 || a != b {
+ t.Errorf("with a memo: %d loads, values %d and %d; want 1 load and one value", loads, a, b)
+ }
+ errs := 0
+ failing := func() (int, error) { errs++; return 0, errors.New("unreadable") }
+ _, e1 := memoize(ctx, "bad", failing)
+ _, e2 := memoize(ctx, "bad", failing)
+ if errs != 1 || e1 == nil || e2 == nil {
+ t.Errorf("a failed load: %d loads, errors %v and %v; want 1 load and its error twice", errs, e1, e2)
+ }
+
+ for _, tc := range []struct {
+ pattern, method string
+ memo bool
+ }{
+ {"POST /x", http.MethodPost, false},
+ {"GET /x", http.MethodGet, true},
+ {"GET /x", http.MethodHead, true},
+ {"/x", http.MethodGet, true},
+ {"/x", http.MethodPost, false},
+ {"/x", http.MethodDelete, false},
+ } {
+ t.Run(tc.method+" "+tc.pattern, func(t *testing.T) {
+ s := &Server{mux: http.NewServeMux()}
+ seen := false
+ s.registerRoute(tc.pattern, func(w http.ResponseWriter, r *http.Request) {
+ seen = r.Context().Value(reqMemoKey{}) != nil
+ })
+ s.mux.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(tc.method, "/x", nil))
+ if seen != tc.memo {
+ t.Errorf("memo in the request context: %v, want %v", seen, tc.memo)
+ }
+ })
+ }
+}
+
+// settingsGroup names which settings read a request belongs to, from the
+// key it names or the prefix it lists. "" is anything else (the app-tab
+// frame, the swap policy, the manifest).
+func settingsGroup(q s3Req) string {
+ name := q.Key
+ if name == "" {
+ name = q.Prefix
+ }
+ switch {
+ case strings.Contains(name, "status/boxes/"):
+ return "boxes"
+ case strings.Contains(name, "control/cert-warm/"):
+ return "cert-warm"
+ case strings.Contains(name, "/instances/"):
+ return "instances"
+ case strings.Contains(name, "/environments/"):
+ return "environments"
+ case strings.Contains(name, "/stores/"), strings.HasSuffix(name, "/store.json"):
+ return "stores"
+ case strings.Contains(name, "/senders/"), strings.HasSuffix(name, "/email.json"):
+ return "mail"
+ case strings.HasSuffix(name, "/features.json"):
+ return "features"
+ }
+ return ""
+}
+
+// TestSettingsSectionReadsOnlyItsOwn: a settings section's view asks the
+// bucket only for what it shows, and still shows all of it.
+func TestSettingsSectionReadsOnlyItsOwn(t *testing.T) {
+ for _, tc := range []struct {
+ section string
+ path string
+ allowed []string // read groups the section may touch
+ want []string // what the rendered page must carry
+ }{
+ {"general", "/apps/kass/settings", nil,
+ []string{"<h2>Identity</h2>", "Renaming: ", "Deploys"}},
+ {"environments", "/apps/kass/settings/environments", []string{"environments", "stores"},
+ []string{"<code>staging</code>", "<code>production</code>", "<code>APP_ORIGIN</code>", "<code>API_KEY</code>", "carlos-"}},
+ {"storage", "/apps/kass/settings/storage", []string{"stores"},
+ []string{"Object storage &mdash; staging environment", "Object storage &mdash; production environment", "<code>CARLOS_STORE_*</code>"}},
+ {"email", "/apps/kass/settings/email", []string{"mail"},
+ []string{"hi@shop.example.com", "shop.example.com", "AKIAEXAMPLE"}},
+ {"features", "/apps/kass/settings/features", []string{"features"},
+ []string{"checkout", "beta"}},
+ } {
+ t.Run(tc.section, func(t *testing.T) {
+ fx, lat := newPerfFixture(t)
+ c := signInPaul(t, fx)
+ if status, _, body := get(t, c, fx.u(tc.path)); status != http.StatusOK {
+ t.Fatalf("%s = %d:\n%s", tc.path, status, body)
+ }
+ rec := recordS3(lat, nil)
+ status, _, body := get(t, c, fx.u(tc.path))
+ if status != http.StatusOK {
+ t.Fatalf("%s = %d:\n%s", tc.path, status, body)
+ }
+ for _, q := range rec.all() {
+ if g := settingsGroup(q); g != "" && !slices.Contains(tc.allowed, g) {
+ t.Errorf("%s read %s (%+v), which it does not show", tc.section, g, q)
+ }
+ }
+ for _, w := range tc.want {
+ if !strings.Contains(body, w) {
+ t.Errorf("%s section lacks %q", tc.section, w)
+ }
+ }
+ })
+ }
+}
+
+// TestSettingsDomainsKeepsItsReads: the Domains section is the one that
+// still reads claims, box reports, cert-warm records and instance records,
+// and shows what they say.
+func TestSettingsDomainsKeepsItsReads(t *testing.T) {
+ fx, lat := newPerfFixture(t)
+ c := signInPaul(t, fx)
+ u := fx.u("/apps/kass/settings/domains")
+ if status, _, body := get(t, c, u); status != http.StatusOK {
+ t.Fatalf("domains = %d:\n%s", status, body)
+ }
+ rec := recordS3(lat, nil)
+ status, _, body := get(t, c, u)
+ if status != http.StatusOK {
+ t.Fatalf("domains = %d:\n%s", status, body)
+ }
+ seen := map[string]bool{}
+ for _, q := range rec.all() {
+ seen[settingsGroup(q)] = true
+ }
+ for _, g := range []string{"boxes", "cert-warm", "instances"} {
+ if !seen[g] {
+ t.Errorf("domains did not read %s (requests: %v)", g, rec.all())
+ }
+ }
+ for _, g := range []string{"environments", "stores", "mail", "features"} {
+ if seen[g] {
+ t.Errorf("domains read %s, which it does not show", g)
+ }
+ }
+ for _, w := range []string{"shop.example.com", "kass.carlosapp.dev", "Password"} {
+ if !strings.Contains(body, w) {
+ t.Errorf("domains section lacks %q", w)
+ }
+ }
+}
+
+// TestSettingsStorageReadsEachStoreOnce: the Storage section reads each
+// environment's store record one time, not once for an environment card and
+// again for a storage card.
+func TestSettingsStorageReadsEachStoreOnce(t *testing.T) {
+ fx, lat := newPerfFixture(t)
+ c := signInPaul(t, fx)
+ u := fx.u("/apps/kass/settings/storage")
+ if status, _, body := get(t, c, u); status != http.StatusOK {
+ t.Fatalf("storage = %d:\n%s", status, body)
+ }
+ rec := recordS3(lat, nil)
+ if status, _, body := get(t, c, u); status != http.StatusOK {
+ t.Fatalf("storage = %d:\n%s", status, body)
+ }
+ acct := fx.sqid
+ for _, env := range []string{"staging", "production"} {
+ key := objstore.KeyIn(acct, "kass", env)
+ n := 0
+ for _, q := range rec.all() {
+ if q.Key == key {
+ n++
+ }
+ }
+ if n != 1 {
+ t.Errorf("store record of %s requested %d times, want 1 (requests: %v)", env, n, rec.all())
+ }
+ }
+}
+
+// pagedStore answers the bounded listing and records how it is asked;
+// listOnly (below) is the same store without it.
+type pagedStore struct {
+ release.Store
+ limits []int
+ lists int
+}
+
+func (p *pagedStore) List(ctx context.Context, prefix string) ([]string, error) {
+ p.lists++
+ return p.Store.List(ctx, prefix)
+}
+
+func (p *pagedStore) ListPage(ctx context.Context, prefix, after string, limit int) ([]string, error) {
+ p.limits = append(p.limits, limit)
+ return p.Store.(release.PageLister).ListPage(ctx, prefix, after, limit)
+}
+
+type listOnly struct {
+ release.Store
+ lists int
+}
+
+func (l *listOnly) List(ctx context.Context, prefix string) ([]string, error) {
+ l.lists++
+ return l.Store.List(ctx, prefix)
+}
+
+// TestAppDeployEmptyAsksForOneKey: the emptiness check wants one key per
+// prefix, so it asks for one when the store can page, and lists when not.
+func TestAppDeployEmptyAsksForOneKey(t *testing.T) {
+ seed := func(t *testing.T, key string) release.Store {
+ st := release.NewDirStore(t.TempDir())
+ if key != "" {
+ if _, err := st.Put(context.Background(), key, []byte("x"), ""); err != nil {
+ t.Fatal(err)
+ }
+ }
+ return st
+ }
+ cases := []struct {
+ name string
+ key string
+ empty bool
+ calls int // prefixes asked before the answer
+ }{
+ {"nothing under either prefix", "", true, 2},
+ {"a key under the account prefix", release.AppPrefix("bab", "shop") + "releases/v1/manifest.json", false, 1},
+ {"a key under the legacy prefix", release.LegacyAppPrefix("shop") + "releases/v1/manifest.json", false, 2},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ ps := &pagedStore{Store: seed(t, tc.key)}
+ s := &Server{}
+ s.cfg.Releases = ps
+ empty, err := s.appDeployEmpty(context.Background(), "bab", "shop")
+ if err != nil || empty != tc.empty {
+ t.Fatalf("paged: empty %v err %v, want %v", empty, err, tc.empty)
+ }
+ if ps.lists != 0 {
+ t.Errorf("paged: List called %d times, want 0", ps.lists)
+ }
+ if len(ps.limits) != tc.calls {
+ t.Fatalf("paged: ListPage called %d times, want %d", len(ps.limits), tc.calls)
+ }
+ for _, l := range ps.limits {
+ if l != 1 {
+ t.Errorf("paged: ListPage limit %d, want 1", l)
+ }
+ }
+
+ lo := &listOnly{Store: seed(t, tc.key)}
+ s.cfg.Releases = lo
+ empty, err = s.appDeployEmpty(context.Background(), "bab", "shop")
+ if err != nil || empty != tc.empty {
+ t.Fatalf("fallback: empty %v err %v, want %v", empty, err, tc.empty)
+ }
+ if lo.lists != tc.calls {
+ t.Errorf("fallback: List called %d times, want %d", lo.lists, tc.calls)
+ }
+ })
+ }
+}
+
+// TestAccountSettingsReadsNoAppTelemetryKey: the account settings page asks
+// for the account's telemetry object and for no app-level key (an empty app
+// name makes a key with "//" in it, which nothing writes).
+func TestAccountSettingsReadsNoAppTelemetryKey(t *testing.T) {
+ fx, lat := newPerfFixture(t)
+ c := signInPaul(t, fx)
+ if status, _, body := get(t, c, fx.u("/settings")); status != http.StatusOK {
+ t.Fatalf("settings = %d:\n%s", status, body)
+ }
+ rec := recordS3(lat, nil)
+ status, _, body := get(t, c, fx.u("/settings"))
+ if status != http.StatusOK {
+ t.Fatalf("settings = %d:\n%s", status, body)
+ }
+ for _, q := range rec.all() {
+ if strings.Contains(q.Key, "//") || strings.Contains(q.Prefix, "//") {
+ t.Errorf("account settings requested %+v, an app-level key with no app", q)
+ }
+ }
+ if n := rec.touching("accounts/" + fx.sqid + "/telemetry.json"); n != 1 {
+ t.Errorf("account telemetry requested %d times, want 1 (requests: %v)", n, rec.all())
+ }
+ for _, w := range []string{`action="`, "/errors/level", "/analytics/setting"} {
+ if !strings.Contains(body, w) {
+ t.Errorf("account settings lacks %q", w)
+ }
+ }
+}
+
+// TestAccountSettingsShowsAccountLevel: an Errors level and an analytics
+// setting saved through the real account doors show on the account page,
+// said to come from the account.
+func TestAccountSettingsShowsAccountLevel(t *testing.T) {
+ fx, _ := newPerfFixture(t)
+ c := signInPaul(t, fx)
+ csrf := sessionToken(t, fx, c)
+ if status, _, body := postForm(t, c, fx.u("/errors/level"), url.Values{"csrf": {csrf}, "level": {"warn"}}); status != http.StatusSeeOther {
+ t.Fatalf("errors level = %d:\n%s", status, body)
+ }
+ if status, _, body := postForm(t, c, fx.u("/analytics/setting"), url.Values{"csrf": {csrf}, "count": {"edge"}}); status != http.StatusSeeOther {
+ t.Fatalf("analytics setting = %d:\n%s", status, body)
+ }
+ status, _, body := get(t, c, fx.u("/settings"))
+ if status != http.StatusOK {
+ t.Fatalf("settings = %d:\n%s", status, body)
+ }
+ for _, w := range []string{
+ `<option value="warn" selected>`,
+ "Currently warn, from the account",
+ `<option value="edge" selected>`,
+ "Currently edge, from the account",
+ } {
+ if !strings.Contains(body, w) {
+ t.Errorf("account settings lacks %q:\n%s", w, body)
+ }
+ }
+}
diff --git a/internal/console/perfspeed_test.go b/internal/console/perfspeed_test.go
index 2f9e22ac0..27020e10d 100644
--- a/internal/console/perfspeed_test.go
+++ b/internal/console/perfspeed_test.go
@@ -59,6 +59,10 @@ func TestFleetMetricsSpeedRowsNameTheMethod(t *testing.T) {
t.Fatal(err)
}
resp.Body.Close()
+ // The sample lands when the handler returns, which can be after the
+ // client has its response (a closed body never waits for it), and
+ // the metrics page reads whatever has landed.
+ waitPerfRequests(t, fx.srv, "/fleet/architecture", m, 1)
}
status, _, body := get(t, c, fx.ts.URL+"/fleet/metrics")
if status != 200 {
@@ -101,6 +105,7 @@ func TestFleetMetricsShowsConsoleSpeed(t *testing.T) {
if status, _, _ := get(t, c, fx.u("/apps/kass")); status != 200 {
t.Fatalf("app page = %d, want 200", status)
}
+ waitPerfRequests(t, fx.srv, "GET /a/{sqid}/apps/{app}", "GET", 1)
status, _, body := get(t, c, fx.ts.URL+"/fleet/metrics")
if status != 200 {
t.Fatalf("/fleet/metrics = %d: %s", status, body)
@@ -132,6 +137,7 @@ func TestFleetMetricsConsoleSpeedEmptyState(t *testing.T) {
t.Errorf("first /fleet/metrics lacks the empty state:\n%s", body)
}
// The metrics GET is measured once it has rendered, so the next view has a row.
+ waitPerfRequests(t, fx.srv, "GET /fleet/metrics", "GET", 1)
_, _, again := get(t, c, fx.ts.URL+"/fleet/metrics")
if strings.Contains(again, "No requests measured since the console started.") {
t.Errorf("second /fleet/metrics still shows the empty state")
diff --git a/internal/console/perfwalk_test.go b/internal/console/perfwalk_test.go
index 165877b64..7efec4070 100644
--- a/internal/console/perfwalk_test.go
+++ b/internal/console/perfwalk_test.go
@@ -66,8 +66,12 @@ type perfScreenTarget struct {
var perfQuiesce = func(fx *consoleFixture) {}
// perfColdReset runs before a screen's cold request, so that it meets a
-// console that has cached nothing for it. Plan 2 fills it in.
-var perfColdReset = func(fx *consoleFixture) {}
+// console that has cached nothing for it: no app-tab frames (appframe.go)
+// and no remembered account manifests.
+var perfColdReset = func(fx *consoleFixture) {
+ fx.srv.frames.forgetAll()
+ fx.srv.manifestSeen.Clear()
+}
// perfEnforce is whether timing fails the walk: only in CI, where the
// machine is quiet enough to hold to a number. Call counts and fixture
diff --git a/internal/console/perfwiring_test.go b/internal/console/perfwiring_test.go
index 0ca62c495..e300d9372 100644
--- a/internal/console/perfwiring_test.go
+++ b/internal/console/perfwiring_test.go
@@ -38,6 +38,30 @@ func perfGet(t *testing.T, c *http.Client, u string) (*http.Response, string) {
return resp, string(body)
}
+// waitPerfRequests blocks until the recorder holds at least n requests for
+// screen (any method when method is ""), or fails the test after a bound.
+// The middleware records a sample when the handler returns, which can be
+// after the client has the whole response, so a test that reads the
+// recorder right after a request must wait for that request's sample.
+func waitPerfRequests(t *testing.T, srv *Server, screen, method string, n int) {
+ t.Helper()
+ count := func() (total int) {
+ for _, g := range srv.PerfGroups() {
+ if g.Screen == screen && (method == "" || g.Method == method) {
+ total += g.Requests
+ }
+ }
+ return total
+ }
+ deadline := time.Now().Add(10 * time.Second)
+ for count() < n {
+ if time.Now().After(deadline) {
+ t.Fatalf("recorder has %d requests for %s %q after 10s, want %d: %+v", count(), method, screen, n, srv.PerfGroups())
+ }
+ time.Sleep(2 * time.Millisecond)
+ }
+}
+
func findGroup(groups []perf.Group, screen string) *perf.Group {
for i := range groups {
if groups[i].Screen == screen {
@@ -72,6 +96,7 @@ func TestPerfGroupsByPattern(t *testing.T) {
fx := newConsoleFixture(t)
c := signInPaul(t, fx)
perfGet(t, c, fx.u("/apps/kass"))
+ waitPerfRequests(t, fx.srv, "GET /a/{sqid}/apps/{app}", "GET", 1)
groups := fx.srv.PerfGroups()
g := findGroup(groups, "GET /a/{sqid}/apps/{app}")
if g == nil || g.Method != "GET" {
@@ -88,6 +113,7 @@ func TestPerfGroupsMethodlessPattern(t *testing.T) {
fx := newConsoleFixture(t)
c := signInPaul(t, fx)
perfGet(t, c, fx.ts.URL+"/fleet/architecture")
+ waitPerfRequests(t, fx.srv, "/fleet/architecture", "GET", 1)
if g := findGroup(fx.srv.PerfGroups(), "/fleet/architecture"); g == nil {
t.Fatalf("no group for /fleet/architecture in %+v", fx.srv.PerfGroups())
}
@@ -98,6 +124,8 @@ func TestPerfGroupsNeverCarryPaths(t *testing.T) {
c := newBrowser(t)
perfGet(t, c, fx.ts.URL+"/invite/tok-abc123")
perfGet(t, c, fx.ts.URL+"/no/such/path")
+ waitPerfRequests(t, fx.srv, "GET /invite/{token}", "GET", 1)
+ waitPerfRequests(t, fx.srv, "unmatched", "", 1)
groups := fx.srv.PerfGroups()
for _, g := range groups {
if strings.Contains(g.Screen, "tok-abc123") || strings.Contains(g.Screen, "/no/such/path") {
@@ -263,6 +291,7 @@ func TestRunningTabTimesTheAppHost(t *testing.T) {
t.Errorf("Server-Timing = %q, want a box span", st)
}
// And the call is counted on that page's own sample, once.
+ waitPerfRequests(t, fx.srv, "GET /a/{sqid}/apps/{app}/instances", "GET", 1)
var found bool
for _, smp := range fx.srv.perf.Snapshot() {
if smp.Screen != "GET /a/{sqid}/apps/{app}/instances" {
diff --git a/internal/console/pipelinepage.go b/internal/console/pipelinepage.go
index 75e828d61..295284fad 100644
--- a/internal/console/pipelinepage.go
+++ b/internal/console/pipelinepage.go
@@ -217,15 +217,12 @@ func (s *Server) writePipeline(ctx context.Context, acct *Account, app string, c
// same as the rest of the app's settings tab.
func (s *Server) handlePipelineSettingsPage(w http.ResponseWriter, r *http.Request, p page, acct *Account) {
setAppSettingsSection(&p, "pipeline")
- ctx, cancel := context.WithTimeout(r.Context(), pipelineStoreTimeout)
- defer cancel()
- pipe, err := release.GetPipeline(ctx, s.cfg.Releases, s.cfg.ReleasePub, acct.Sqid, p.AppName)
channels := release.DefaultPipelineChannels()
- if err != nil {
- log.Printf("console: pipeline settings %s/%s: %v", acct.Sqid, p.AppName, err)
+ if p.Detail.PipelineErr != "" {
+ log.Printf("console: pipeline settings %s/%s: %s", acct.Sqid, p.AppName, p.Detail.PipelineErr)
p.FlashErr = "Could not read the pipeline — showing the default. Try again to see the real one."
- } else if pipe != nil {
- channels = pipe.Channels
+ } else if p.Detail.Pipeline != nil {
+ channels = p.Detail.Pipeline.Channels
}
p.PipelineRows = pipelineRowsFromChannels(channels)
p.PipelineIsDefault = pipelineIsDefault(p.PipelineRows)
diff --git a/internal/console/regionbudget_test.go b/internal/console/regionbudget_test.go
index 7c6ee7434..da63d591b 100644
--- a/internal/console/regionbudget_test.go
+++ b/internal/console/regionbudget_test.go
@@ -141,14 +141,17 @@ func measureBudget(t *testing.T, tb *twoBoxes) map[string]map[string]int {
// regionBudgetBaseline is measureBudget at the branch base, before any
// region-label code: first at a64f5a41, re-measured at origin/main ed03ca7d
-// when that was merged (the Deployments tab became Releases).
+// when that was merged (the Deployments tab became Releases). The account
+// home's "Get apps" is 5, not 4, since console-perf-quick-wins: its first
+// (cold) view reads each app's frame (appframe.go), which carries the
+// pipeline the home did not read before; a warm view reads none of it.
var regionBudgetBaseline = map[string]map[string]int{
"CLI /api/cli/apps/{sqid}/list": {},
"CLI /api/cli/apps/{sqid}/shop/instances": {"Get apps": 3, "Get control": 3, "Get status": 2, "List apps": 1, "List control": 1, "List status": 1},
"CLI /api/cli/apps/{sqid}/shop/instances/eu.shop.example.com": {"Get apps": 1, "Get control": 3, "List control": 1},
"CLI /api/cli/apps/{sqid}/shop/regions": {"Get apps": 1, "Get control": 9, "Get status": 4, "List control": 3, "List status": 2},
"CLI /api/cli/apps/{sqid}/shop/routes": {"Get status": 2, "List status": 1},
- "GET /a/{sqid}/": {"Get apps": 4, "Get status": 2, "List apps": 2, "List status": 1},
+ "GET /a/{sqid}/": {"Get apps": 5, "Get status": 2, "List apps": 2, "List status": 1},
"GET /a/{sqid}/apps/shop": {"Get accounts": 1, "Get apps": 4, "Get metrics": 48, "List alerts": 1, "List apps": 2, "List metrics": 1},
"GET /a/{sqid}/apps/shop/releases": {"Get accounts": 1, "Get apps": 6, "List apps": 3},
"GET /a/{sqid}/apps/shop/instances": {"Get accounts": 1, "Get apps": 4, "Get control": 3, "Get status": 2, "List apps": 1, "List control": 1, "List status": 1},
diff --git a/internal/console/regioncandidates.go b/internal/console/regioncandidates.go
index 4eec3cad0..97804fcc4 100644
--- a/internal/console/regioncandidates.go
+++ b/internal/console/regioncandidates.go
@@ -7,7 +7,6 @@ import (
"os"
"sort"
"sync"
- "time"
"github.com/carlosframework/platform/internal/geo"
"github.com/carlosframework/platform/internal/provision"
@@ -198,12 +197,6 @@ func (s *Server) regionCands(snap edgesSnapshot) []regionCandidate {
return regionCandidates(snap, s.cfg.HomeRegion, s.expectedSecretsFP())
}
-// liveEdges is the one read every automatic-eligibility caller makes: the
-// edges files joined with box liveness as of now (F1).
-func (s *Server) liveEdges(ctx context.Context) (edgesSnapshot, error) {
- return readLiveEdgesSnapshot(ctx, s.cfg.Releases, time.Now())
-}
-
// candsOrHome is the candidates from a fresh snapshot, or the home alone
// when the listing fails (or there is no bucket): for displays and guesses
// that must not fail.
@@ -275,14 +268,15 @@ type regionPolicy struct {
}
// appPolicy reads the manifest directly (never instanceManifest, which
-// answers the caller itself) and the fleet placement. Any failure is
-// policyUnreadable: an unrestricted policy is never invented.
+// answers the caller itself; once per page view, through the request memo)
+// and the fleet placement. Any failure is policyUnreadable: an
+// unrestricted policy is never invented.
func (s *Server) appPolicy(ctx context.Context, acct *Account, app string) regionPolicy {
var p regionPolicy
if s.cfg.Releases == nil {
return regionPolicy{State: policyUnreadable} // no bucket: nothing to read, so nothing is allowed
}
- m, err := provision.GetManifest(ctx, s.cfg.Releases, acct.Sqid, app)
+ m, err := s.instancesManifest(ctx, acct.Sqid, app)
switch {
case err == nil:
p.State, p.M = policyKnown, m
diff --git a/internal/console/remoteinstances.go b/internal/console/remoteinstances.go
index 2b3a4c77b..6936bf6ea 100644
--- a/internal/console/remoteinstances.go
+++ b/internal/console/remoteinstances.go
@@ -541,9 +541,18 @@ func (s *Server) remoteSource(ctx context.Context, acct string) *remoteRows {
}
// assembleApps is Assemble for a page view: the console box's registry rows
-// plus the account's instances on other boxes.
+// plus the account's instances on other boxes, each app's release-store
+// reads from the frame cache (appframe.go).
func (s *Server) assembleApps(ctx context.Context, acct string, apps []string) ([]AppView, error) {
- return Assemble(ctx, s.cfg.Registry, s.cfg.Releases, s.cfg.ReleasePub, acct, apps, s.dnsTargets(ctx), s.remoteSource(ctx, acct))
+ return s.assembleAppsNamed(ctx, acct, "", apps)
+}
+
+// assembleAppsNamed is assembleApps for a caller that knows the account's
+// name, which the frame cache keeps so a write addressed by name clears it.
+func (s *Server) assembleAppsNamed(ctx context.Context, acct, acctName string, apps []string) ([]AppView, error) {
+ return assembleViews(ctx, s.cfg.Registry, acct, apps, s.dnsTargets(ctx), s.remoteSource(ctx, acct), func(app string) appFrame {
+ return s.appFrame(ctx, acct, acctName, app)
+ })
}
// errRetireUnsettled is channelHosts' answer when no record names the
diff --git a/internal/console/remoteinstances_round4_test.go b/internal/console/remoteinstances_round4_test.go
index c0470a852..54e5f27ac 100644
--- a/internal/console/remoteinstances_round4_test.go
+++ b/internal/console/remoteinstances_round4_test.go
@@ -264,6 +264,7 @@ func TestRetireDoesNotResurrectRemovedPointer(t *testing.T) {
if err := tb.fx.rel.Delete(context.Background(), release.ChannelKey(tb.sqid, "shop", "canary/rc")); err != nil {
t.Error(err)
}
+ tb.fx.forgetFrame("shop")
}
if page := retireRC(t, tb); !strings.Contains(page, notSettled) {
t.Fatalf("retire with the pointer removed during the check:\n%s", page)
diff --git a/internal/console/remoteinstances_test.go b/internal/console/remoteinstances_test.go
index 0b10e25f4..0e12944a1 100644
--- a/internal/console/remoteinstances_test.go
+++ b/internal/console/remoteinstances_test.go
@@ -101,6 +101,7 @@ func shipAndPromote(t *testing.T, fx *consoleFixture, sqid, app, version, channe
if err := release.Promote(ctx, fx.rel, fx.priv, sqid, app, channel, version); err != nil {
t.Fatal(err)
}
+ fx.forgetFrame(app)
}
// create runs the console's create door for host in region.
diff --git a/internal/console/reqmemo.go b/internal/console/reqmemo.go
new file mode 100644
index 000000000..6cc401eb4
--- /dev/null
+++ b/internal/console/reqmemo.go
@@ -0,0 +1,124 @@
+package console
+
+import (
+ "context"
+ "errors"
+ "net/http"
+ "sync"
+ "time"
+
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/status"
+)
+
+// The request memo: one page view reads each of a few remote things at most
+// once, however many of its parts ask (the box reports, the edges files, the
+// app's instances.json). It lives in the request's context and dies with the
+// request: nothing is shared between requests, so nothing here can go stale.
+//
+// registerRoute installs it on GET and HEAD requests only. A write door's
+// request has none, so every read a door decides on (liveEdges for
+// placement, the strict box loads) is its own, made when it asks.
+//
+// A memoized value is shared by every reader in the request: callers treat
+// these results as read-only, as they always have. A failed load is
+// memoized too, so a second reader in the same request gets the same error
+// rather than a second attempt. The load runs under the first reader's
+// context (a part with a shorter timeout bounds it for every reader after).
+
+type reqMemoKey struct{}
+
+type reqMemo struct {
+ mu sync.Mutex
+ entries map[string]*reqMemoEntry
+}
+
+type reqMemoEntry struct {
+ done chan struct{}
+ val any
+ err error
+}
+
+// errMemoLoadPanicked is what a reader waiting on a load sees when that
+// load panicked.
+var errMemoLoadPanicked = errors.New("console: request memo: the load panicked")
+
+// withReqMemo returns ctx with a fresh, empty memo.
+func withReqMemo(ctx context.Context) context.Context {
+ return context.WithValue(ctx, reqMemoKey{}, &reqMemo{entries: map[string]*reqMemoEntry{}})
+}
+
+// memoize is load's answer for key, made at most once per memo. With no
+// memo in ctx, load runs every time. Concurrent readers of one key in one
+// request wait for the first one's load.
+func memoize[T any](ctx context.Context, key string, load func() (T, error)) (T, error) {
+ m, _ := ctx.Value(reqMemoKey{}).(*reqMemo)
+ if m == nil {
+ return load()
+ }
+ m.mu.Lock()
+ e, ok := m.entries[key]
+ if !ok {
+ e = &reqMemoEntry{done: make(chan struct{}), err: errMemoLoadPanicked}
+ m.entries[key] = e
+ }
+ m.mu.Unlock()
+ if ok {
+ <-e.done
+ v, _ := e.val.(T)
+ return v, e.err
+ }
+ defer close(e.done)
+ v, err := load()
+ e.val, e.err = v, err
+ return v, err
+}
+
+// withReqMemoOnViews gives each GET and HEAD request a memo of its own.
+func withReqMemoOnViews(h http.HandlerFunc) http.HandlerFunc {
+ return func(w http.ResponseWriter, r *http.Request) {
+ if readOnlyMethod(r.Method) {
+ r = r.WithContext(withReqMemo(r.Context()))
+ }
+ h(w, r)
+ }
+}
+
+// loadBoxes is status.LoadBoxesComplete on st under prefix ("" for the
+// platform's own boxes, "fleets/<name>/" for a customer fleet's), once per
+// request. complete and err are exactly the load's: a partial listing stays
+// partial for every reader. The memo key names only the prefix, so st is
+// always the console's release store. The slice is clipped, so a reader
+// that appends to it gets a copy rather than writing into the memo's.
+func (s *Server) loadBoxes(ctx context.Context, st release.Store, prefix string) (boxes []status.Box, complete bool, err error) {
+ type loaded struct {
+ boxes []status.Box
+ complete bool
+ }
+ l, err := memoize(ctx, "boxes:"+prefix, func() (loaded, error) {
+ store := st
+ if prefix != "" {
+ store = release.NewPrefixStore(st, prefix)
+ }
+ b, c, err := status.LoadBoxesComplete(ctx, store)
+ return loaded{b, c}, err
+ })
+ return l.boxes[:len(l.boxes):len(l.boxes)], l.complete, err
+}
+
+// liveEdges is the one read every automatic-eligibility caller makes: the
+// edges files joined with box liveness as of now (F1), once per request.
+func (s *Server) liveEdges(ctx context.Context) (edgesSnapshot, error) {
+ return memoize(ctx, "edges", func() (edgesSnapshot, error) {
+ return readLiveEdgesSnapshot(ctx, s.cfg.Releases, time.Now())
+ })
+}
+
+// instancesManifest is the app's instances.json (provision.GetManifest),
+// once per request.
+func (s *Server) instancesManifest(ctx context.Context, sqid, app string) (*provision.Manifest, error) {
+ return memoize(ctx, "instances-manifest:"+sqid+"/"+app, func() (*provision.Manifest, error) {
+ return provision.GetManifest(ctx, s.cfg.Releases, sqid, app)
+ })
+}
diff --git a/internal/console/rolloutjoin_test.go b/internal/console/rolloutjoin_test.go
index c77285386..45c1bf5e7 100644
--- a/internal/console/rolloutjoin_test.go
+++ b/internal/console/rolloutjoin_test.go
@@ -108,6 +108,7 @@ func TestAPIPromoteHeldSaysWhenItLifts(t *testing.T) {
if err := release.SetProduction(context.Background(), fx.rel, fx.priv, release.OpsAccount, "titogo", true, "test"); err != nil {
t.Fatal(err)
}
+ fx.forgetFrame("titogo")
token := cliToken(t, fx, "paul@keymail.dev", "code-held-until")
before := time.Now()
code, body := postRaw(t, fx.ts.URL+"/api/cli/apps/bab/titogo/promote",
diff --git a/internal/console/serialbump_test.go b/internal/console/serialbump_test.go
index a12eb61ab..106fafaef 100644
--- a/internal/console/serialbump_test.go
+++ b/internal/console/serialbump_test.go
@@ -126,6 +126,7 @@ func TestAPIPromoteHeldOnProductionBeta(t *testing.T) {
release.OpsAccount, "titogo", true, "test"); err != nil {
t.Fatal(err)
}
+ fx.forgetFrame("titogo")
token := cliToken(t, fx, "paul@keymail.dev", "code-serial-held")
status, body := postRaw(t, fx.ts.URL+"/api/cli/apps/bab/titogo/promote",
@@ -169,6 +170,7 @@ func TestAPIPromoteNotHeldOffProduction(t *testing.T) {
release.OpsAccount, "titogo", true, "test"); err != nil {
t.Fatal(err)
}
+ fx.forgetFrame("titogo")
status, body = postRaw(t, fx.ts.URL+"/api/cli/apps/bab/titogo/promote",
map[string]string{"version": "abc1234", "channel": "canary/x"}, token)
if status != http.StatusOK {
@@ -197,6 +199,7 @@ func TestAPIPromoteNoOpReportsHeld(t *testing.T) {
release.OpsAccount, "titogo", true, "test"); err != nil {
t.Fatal(err)
}
+ fx.forgetFrame("titogo")
token := cliToken(t, fx, "paul@keymail.dev", "code-serial-noopheld")
// beta already carries this version: a no-op, and held.
diff --git a/internal/console/server.go b/internal/console/server.go
index a1c8be99d..34f966e5e 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -906,6 +906,12 @@ type Config struct {
// Server is the console's http.Handler.
type Server struct {
+ // manifestSeen is the sqids whose accounts/<sqid>/account.json this
+ // process has seen exist (read, or written by the backfill), so an app
+ // tab stops asking the bucket for it on every view. Keyed by sqid, value
+ // struct{}; handleDeleteAccount forgets the sqid it retires.
+ manifestSeen sync.Map
+
// billing is nil when billing is off (Config.Billing, plans 6a).
billing *billingRuntime
@@ -1286,6 +1292,8 @@ type Server struct {
// (applocks.go). Zero values are ready.
appLocks keyedLocks
acctLocks keyedLocks
+ // frames is the app-tab frame cache (appframe.go). Zero value ready.
+ frames appFrames
// hostLocks is withHostname's refcounted mutex per hostname
// (lifetimes.go), and lifetimeLogged the last time each hourly lifetime
// log line was written, pruned past two hours. Zero values are ready.
@@ -3562,7 +3570,7 @@ func (s *Server) handleAccountHome(w http.ResponseWriter, r *http.Request) {
return
}
if len(apps) > 0 {
- views, err := s.assembleApps(r.Context(), acct.Sqid, apps)
+ views, err := s.assembleAppsNamed(r.Context(), acct.Sqid, acct.Name, apps)
if err != nil {
log.Printf("console: assemble: %v", err)
s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not read platform state. Please try again.")
@@ -3637,17 +3645,19 @@ func (s *Server) handleAccountSettings(w http.ResponseWriter, r *http.Request) {
if role == RoleOwner {
s.servicePane(&p, acct)
}
- // The account's own Errors log level. Resolved with an EMPTY app name on
- // purpose: AppKey(sqid, "") names a key no app ever writes, so the app
- // layer contributes nothing and what comes back is the account setting
- // or the default — which is exactly what this page sets. A failed read
- // is said rather than defaulted (see ErrLevelUnread), and never fails
- // the page.
- if res, err := telemetry.Resolve(r.Context(), s.cfg.Releases, acct.Sqid, ""); err != nil {
+ // The account's own Errors log level: the account's telemetry object,
+ // the key the two account forms write, folded over the defaults. No app
+ // layer is read (an empty app name would name apps/<sqid>//telemetry.json,
+ // which nothing writes). A failed read is said rather than defaulted (see
+ // ErrLevelUnread), and never fails the page. A bucketless console folds
+ // the defaults, as telemetry.Resolve does.
+ if s.cfg.Releases == nil {
+ p.ErrLevelSetting = telemetry.Fold(telemetry.Settings{}, telemetry.Settings{})
+ } else if st, _, err := telemetry.Read(r.Context(), s.cfg.Releases, telemetry.AccountKey(acct.Sqid)); err != nil {
log.Printf("console: account telemetry %s: %v", acct.Sqid, err)
p.ErrLevelUnread = true
} else {
- p.ErrLevelSetting = res
+ p.ErrLevelSetting = telemetry.Fold(st, telemetry.Settings{})
}
// The analytics switch is the OTHER half of that same resolved object —
// one settings file, one read — under the name its own section uses.
@@ -3733,7 +3743,7 @@ func (s *Server) appPage(w http.ResponseWriter, r *http.Request, tab string) (pa
// bucket hiccup there is deliberately non-fatal, and this is where it gets
// another chance. Best-effort — a page view never fails on it.
s.ensureAccountManifest(r.Context(), acct)
- views, err := s.assembleApps(r.Context(), acct.Sqid, []string{app})
+ views, err := s.assembleAppsNamed(r.Context(), acct.Sqid, acct.Name, []string{app})
if err != nil || len(views) != 1 {
log.Printf("console: assemble %s: %v", app, err)
s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not read platform state. Please try again.")
@@ -3782,7 +3792,7 @@ func (s *Server) appPage(w http.ResponseWriter, r *http.Request, tab string) (pa
p.Detail.RouteAccount = review.Groups[0].Account.Sqid
}
}
- s.applyPipelineView(r.Context(), p.Detail, acct)
+ s.applyPipelineView(p.Detail, acct)
return p, acct, true
}
@@ -3810,14 +3820,12 @@ func hasPublishedChannel(channels []ChannelView) bool {
// disagree again by construction. Best-effort and view-only, like every
// other read in this family: an unreadable pipeline degrades the render to
// the legacy ladder rather than failing the page.
-func (s *Server) applyPipelineView(ctx context.Context, view *AppView, acct *Account) {
- ctx, cancel := context.WithTimeout(ctx, pipelineStoreTimeout)
- defer cancel()
- pipe, err := release.GetPipeline(ctx, s.cfg.Releases, s.cfg.ReleasePub, acct.Sqid, view.App)
- if err != nil {
- log.Printf("console: app page %s/%s: read pipeline: %v", acct.Sqid, view.App, err)
+func (s *Server) applyPipelineView(view *AppView, acct *Account) {
+ if view.PipelineErr != "" {
+ log.Printf("console: app page %s/%s: read pipeline: %s", acct.Sqid, view.App, view.PipelineErr)
return
}
+ pipe := view.Pipeline
if pipe == nil {
return
}
@@ -3942,9 +3950,9 @@ func (s *Server) handleApp(w http.ResponseWriter, r *http.Request) {
if err != nil {
log.Printf("console: pending changes %s/%s: %v", acct.Sqid, app, err)
} else if len(pcs) > 0 {
- // One pipeline read for the whole card: the rows show the quorum
+ // The frame's pipeline for the whole card: the rows show the quorum
// EXECUTION will require, not the one they were proposed under.
- p.Pending = s.pendingChangeViews(pcs, s.pendingPipeline(r.Context(), acct, app))
+ p.Pending = s.pendingChangeViews(pcs, p.Detail.Pipeline)
}
s.render(w, http.StatusOK, "app_overview", p)
}
@@ -3961,9 +3969,10 @@ const overviewActivityCap = 5
// Its data, in one place for perf plan 2's cache. From appPage's p.Detail:
// Channels (Live now targets, What's next, the Channels fold, promote
// options), Routes (Live now's running versions and instance counts),
-// Pipeline and OneChannelPipeline (Live now's columns and rows, the folds),
-// Canaries (the Canaries fold) and Production (the ladder). Read here, per
-// request: PendingChangesForContext and pendingPipeline (the pending card),
+// Pipeline and OneChannelPipeline (Live now's columns and rows, the folds,
+// the pending card's quorum), Canaries (the Canaries fold) and Production
+// (the ladder). Read here, per request: PendingChangesForContext (the
+// pending card),
// versionsPage (Versions, and from the same listing page 1's names for the
// canary form, whatever ?page= is), release.ListTags (tag pills and the
// Tags fold), release.GetRetention (the retention line) and attachHint (the
@@ -3983,7 +3992,7 @@ func (s *Server) handleAppReleases(w http.ResponseWriter, r *http.Request) {
if err != nil {
log.Printf("console: pending changes %s/%s: %v", acct.Sqid, p.AppName, err)
} else if len(pcs) > 0 {
- p.Pending = s.pendingChangeViews(pcs, s.pendingPipeline(r.Context(), acct, p.AppName))
+ p.Pending = s.pendingChangeViews(pcs, p.Detail.Pipeline)
}
p.ReleaseSummary = assembleReleaseSummary(p.Detail.Channels, p.Detail.Routes, acct.Sqid)
p.PromoteChannels = promoteChannelOptions(p.Detail.Channels, p.Detail.Pipeline)
@@ -4172,9 +4181,11 @@ func (s *Server) handleAppLogs(w http.ResponseWriter, r *http.Request) {
p.LogHosts = append(p.LogHosts, rt.Host)
}
}
+ // The records' hosts come from the page's own record read (pageRecords,
+ // held in the box-report cache), not a second listing of its own.
if s.cfg.Releases != nil {
ctx, cancel := context.WithTimeout(r.Context(), instanceStoreTimeout)
- recs, _, err := s.listRecords(ctx, acct.Sqid, p.AppName, instanceListMax)
+ recs, err := s.pageRecords(ctx, acct.Sqid, p.AppName)
cancel()
if err == nil {
for _, rec := range recs {
@@ -4415,26 +4426,47 @@ func setAppSettingsSection(p *page, section string) {
}
// settingsSectionReads is what one settings section renders beyond the
-// app-tab frame, so a section view reads only that. record is the
-// SettingsView assembleSettings builds (domains, gates, environments,
-// storage, email, features, rename and the account move: every section that
-// reads .Settings); telemetry is the resolved errors and analytics settings;
-// swap is the swap policy; placement is the Placement section's registry
-// read. A section that reads none of these (Delete) costs only the frame.
-type settingsSectionReads struct{ record, telemetry, swap, placement bool }
+// app-tab frame, so a section view reads only that. The first seven are the
+// parts of the SettingsView assembleSettings builds: domains (claims, box
+// reports and cert-warm records), gates (the instance records), deployEmpty
+// (the never-shipped check behind the rename form), envs (each environment
+// and its store), store (the app's own store plus the environment stores),
+// mail and features. telemetry is the resolved errors and analytics
+// settings; swap is the swap policy; placement is the Placement section's
+// registry read. A section that reads none of these (Delete) costs only the
+// frame.
+type settingsSectionReads struct {
+ domains, gates, deployEmpty, envs, store, mail, features bool
+ telemetry, swap, placement bool
+}
+
+// record reports whether the section reads any part of the SettingsView.
+// General does, by its deployEmpty read: the rename form, the control-plane
+// flag and the account mismatch come with it.
+func (r settingsSectionReads) record() bool {
+ return r.domains || r.gates || r.deployEmpty || r.envs || r.store || r.mail || r.features
+}
func settingsSectionReadsFor(section string) settingsSectionReads {
switch section {
case "general":
- return settingsSectionReads{record: true, swap: true}
+ return settingsSectionReads{deployEmpty: true, swap: true}
+ case "domains":
+ return settingsSectionReads{domains: true, gates: true}
+ case "environments":
+ return settingsSectionReads{envs: true}
+ case "storage":
+ return settingsSectionReads{store: true}
+ case "email":
+ return settingsSectionReads{mail: true}
+ case "features":
+ return settingsSectionReads{features: true}
case "placement":
return settingsSectionReads{placement: true}
case "errors-analytics":
return settingsSectionReads{telemetry: true}
- case "delete":
+ default: // delete
return settingsSectionReads{}
- default: // domains, environments, storage, email, features
- return settingsSectionReads{record: true}
}
}
@@ -4442,8 +4474,8 @@ func settingsSectionReadsFor(section string) settingsSectionReads {
// settingsSectionReadsFor).
func (s *Server) populateAppSettings(r *http.Request, p *page, acct *Account, section string) {
reads := settingsSectionReadsFor(section)
- if reads.record {
- p.Settings = s.assembleSettings(r.Context(), p, acct)
+ if reads.record() {
+ p.Settings = s.assembleSettings(r.Context(), p, acct, reads)
}
if reads.placement {
s.populateAppPlacement(p, acct)
@@ -4520,9 +4552,13 @@ func (s *Server) ensureAccountManifest(ctx context.Context, acct *Account) {
if s.cfg.Releases == nil {
return
}
+ if _, ok := s.manifestSeen.Load(acct.Sqid); ok {
+ return // seen in this process — nothing to check or backfill
+ }
key := AccountManifestKey(acct.Sqid)
_, _, err := s.cfg.Releases.Get(ctx, key)
if err == nil {
+ s.manifestSeen.Store(acct.Sqid, struct{}{})
return // already there — nothing to backfill
}
if !errors.Is(err, os.ErrNotExist) {
@@ -4533,6 +4569,7 @@ func (s *Server) ensureAccountManifest(ctx context.Context, acct *Account) {
log.Printf("console: backfill account manifest %s: %v", key, err)
return
}
+ s.manifestSeen.Store(acct.Sqid, struct{}{})
log.Printf("console: backfilled account manifest for %s (%s)", acct.Sqid, acct.Name)
}
@@ -5835,7 +5872,7 @@ func (s *Server) handleNewCanary(w http.ResponseWriter, r *http.Request) {
// of a transient bucket error sends them at a door that will refuse them.
// Unreadable therefore renders the neutral form, never the enable step.
func (s *Server) instanceDomainFor(ctx context.Context, sqid, app string) (domain string, absent bool) {
- m, err := provision.GetManifest(ctx, s.cfg.Releases, sqid, app)
+ m, err := s.instancesManifest(ctx, sqid, app)
switch {
case err == nil:
return m.Domain, false
diff --git a/internal/console/server_test.go b/internal/console/server_test.go
index 611f58623..2a2312923 100644
--- a/internal/console/server_test.go
+++ b/internal/console/server_test.go
@@ -352,6 +352,7 @@ func TestConsoleE2E(t *testing.T) {
if err := release.SetProduction(context.Background(), fx.rel, fx.priv, release.OpsAccount, "kass", true, "test"); err != nil {
t.Fatal(err)
}
+ fx.forgetFrame("kass")
// The ladder, with channel names and versions on it, now lives on the
// Releases tab rather than the Overview page.
diff --git a/internal/console/testdata/perf-budgets.txt b/internal/console/testdata/perf-budgets.txt
index f7be87057..91ec374af 100644
--- a/internal/console/testdata/perf-budgets.txt
+++ b/internal/console/testdata/perf-budgets.txt
@@ -2,7 +2,7 @@
# ignored. Read by the perf walk (perfbudgets_test.go).
#
# <screen> over: <reason> known slow today; measured and printed, never
-# failed; plan 2 deletes the record
+# failed; the next round deletes the record
# <screen> calls <n>: <reason> this screen may make n remote calls on a
# warm-cache GET (n >= 1)
# <screen> deferred: <reason> a deferred-part endpoint: timed and printed,
@@ -31,31 +31,37 @@ GET /auth/cli/whoami skip: a bearer-token JSON door, not a screen; timed in prod
# Deferred parts: timed and printed, exempt from 150 ms and the call count.
GET /a/{sqid}/apps/{app}/logs/data deferred: deferred part (the Logs tab's data endpoint)
-# Known slow today (measured 2026-10-26, with 25 ms per S3 request and 40 ms
-# per app-host call). Plan 2 deletes these. "the app-tab frame" is what every
-# app tab reads before its own part: the account manifest, the production
-# flag, the pipeline, and a listing plus one read per channel (7 S3 calls).
-/fleet/architecture over: reads economics/active.json, infra/inventory.json and status/fleet.json, and lists and reads every box report (8 S3 calls warm)
-GET /a/{sqid}/apps/{app} over: Overview is the app-tab frame plus a second pipeline read, the release listing, every manifest and every box report (16 S3 calls warm); cold, also every box's metrics hours for two days (about 110)
-GET /a/{sqid}/apps/{app}/account-review over: the app-tab frame (7 S3 calls warm)
-GET /a/{sqid}/apps/{app}/activity over: the app-tab frame (7 S3 calls warm)
-GET /a/{sqid}/apps/{app}/analytics over: the app-tab frame plus both telemetry settings and the analytics day listing and reads (11 S3 calls warm)
-GET /a/{sqid}/apps/{app}/availability over: the app-tab frame plus both telemetry settings and three listings and a read each for the log and error chunks (17 S3 calls warm)
-GET /a/{sqid}/apps/{app}/errors over: the app-tab frame plus both telemetry settings and three listings and a read each for the log and error chunks (17 S3 calls warm)
-GET /a/{sqid}/apps/{app}/instances over: the app-tab frame plus instances.json, and every edges file and box report listed and read twice (24 S3 calls warm)
-GET /a/{sqid}/apps/{app}/instances/{host} over: the app-tab frame plus the instance record, and the box reports and the fleet box reports listed and read three times (31 S3 calls warm)
-GET /a/{sqid}/apps/{app}/logs over: the app-tab frame plus a listing and a read of every instance record and three listings for the log chunks (15 S3 calls warm)
-GET /a/{sqid}/apps/{app}/releases over: the app-tab frame plus a second pipeline read for the pending card, the release and tag listings, at most 20 manifests, retention and instances.json (14 S3 calls warm; 12 on the fixture's empty page 2)
-GET /a/{sqid}/apps/{app}/settings over: General builds the whole settings record: each environment and its store read twice, every instance record, the domain claims, cert-warm records, every box report and a listing of every key under the app, plus the swap policy (32 S3 calls warm)
-GET /a/{sqid}/apps/{app}/settings/{section} over: Domains, Environments, Storage, Email and Feature flags build the whole settings record, as General does (31 S3 calls warm; General 32); Errors and analytics 9, the pipeline section 8, Placement and Delete 7 (the app-tab frame); the advanced redirect none
-GET /a/{sqid}/fleet over: reads status/fleet.json and lists and reads each customer fleet's box reports (3 S3 calls warm)
-GET /a/{sqid}/fleets/{fleet} over: lists and reads the fleet's box reports (2 S3 calls warm)
+# Known slow today (measured 2026-10-26 after console-perf-quick-wins, with
+# 25 ms per S3 request and 40 ms per app-host call). The next round deletes
+# these. "the app-tab frame" is what every app tab reads before its own part:
+# the production flag, the pipeline, and a listing plus one read per channel
+# (6 S3 calls). It is cached per app for 30 s (appframe.go), so a warm view
+# reads none of it; the account manifest is read once per process and then
+# remembered. A cold view (perfColdReset) reads both: 7 S3 calls, about
+# 180 ms, over the 150 ms budget on their own, which keeps every app tab here.
+# The walk prints only warm counts for these records; the cold counts below
+# were measured by walking with each record turned into a calls record.
+/fleet/architecture over: reads economics/active.json, infra/inventory.json and status/fleet.json, and lists and reads every box report (8 S3 calls warm and cold, median about 260 ms)
+GET /a/{sqid}/apps/{app} over: Overview is the release listing and every manifest (3 S3 calls warm, median about 80 ms); cold, also the app-tab frame, the account manifest and every box's metrics hours for two days (129 S3 calls, about 1.1 s)
+GET /a/{sqid}/apps/{app}/account-review over: a warm view reads nothing (0 S3 calls; the app-tab frame is cached); a cold view reads the frame and the account manifest (7 S3 calls, about 185 ms)
+GET /a/{sqid}/apps/{app}/activity over: a warm view reads nothing (0 S3 calls; the app-tab frame is cached); a cold view reads the frame and the account manifest (7 S3 calls, about 185 ms)
+GET /a/{sqid}/apps/{app}/analytics over: both telemetry settings, the analytics day listing and one day read (4 S3 calls warm, median about 105 ms); cold, also the app-tab frame and the account manifest (11 S3 calls, about 285 ms)
+GET /a/{sqid}/apps/{app}/availability over: both telemetry settings and three listings and a read each for the log and error chunks (10 S3 calls warm, median about 260 ms); cold, also the app-tab frame and the account manifest (17 S3 calls, about 440 ms)
+GET /a/{sqid}/apps/{app}/errors over: both telemetry settings and three listings and a read each for the log and error chunks (10 S3 calls warm, median about 260 ms); cold, also the app-tab frame and the account manifest (17 S3 calls, about 440 ms)
+GET /a/{sqid}/apps/{app}/instances over: instances.json, and every edges file and box report listed and read once per view (9 S3 calls warm, median about 290 ms); cold, also the app-tab frame and the account manifest (16 S3 calls and 1 host call, about 510 ms)
+GET /a/{sqid}/apps/{app}/instances/{host} over: the instance record, instances.json, the edges listing, and the box reports and the fleet box reports listed and read once per view (10 S3 calls warm, median about 315 ms); cold, also the app-tab frame and the account manifest (17 S3 calls, about 495 ms)
+GET /a/{sqid}/apps/{app}/logs over: three listings for the log chunks and a chunk read; the host picker uses the records the page already holds (4 S3 calls warm, median about 105 ms); cold, also the app-tab frame and the account manifest (11 S3 calls, about 285 ms)
+GET /a/{sqid}/apps/{app}/releases over: the release and tag listings, at most 20 manifests, retention and instances.json (6 S3 calls warm, median about 160 ms; 4 on the fixture's empty page 2); cold, also the app-tab frame and the account manifest (13 S3 calls, about 340 ms; 11 on page 2)
+GET /a/{sqid}/apps/{app}/settings over: the one-key app listing for the rename check (a second for the legacy prefix when the first is empty) and the swap policy (2 S3 calls warm, 3 at most, median about 55 ms); cold, also the app-tab frame and the account manifest (9 S3 calls, about 235 ms)
+GET /a/{sqid}/apps/{app}/settings/{section} over: Domains still reads the domain claims, cert-warm records, every box report and every instance record (12 S3 calls warm, median about 365 ms; 20 cold); the other sections read only their own data, warm (cold adds the app-tab frame and the account manifest, 7 more): General 2 (cold 9), Environments 5 (12), Storage 4 (11), Email 1 (8), Feature flags 1 (8), Errors and analytics 2 (9), the pipeline section, Placement and Delete none (7); the advanced redirect none, warm or cold
+GET /a/{sqid}/fleet over: reads status/fleet.json and lists and reads each customer fleet's box reports (3 S3 calls warm and cold, median about 80 ms)
+GET /a/{sqid}/fleets/{fleet} over: lists and reads the fleet's box reports (2 S3 calls warm and cold, median about 55 ms)
GET /a/{sqid}/plan/keep over: the lapse inventory lists every app's instance records and reads each one, lists every app's sidecar records, and lists the domain claims (8 S3 calls warm for two apps and three instances, median 209 ms; it grows with the account)
-GET /a/{sqid}/settings over: reads the account and app telemetry settings and the storage entitlement (3 S3 calls warm)
-GET /a/{sqid}/trash over: reads each trashed app's deleted.json marker (1 S3 call warm per app)
-GET /a/{sqid}/{$} over: the account home lists and reads every app's channels and its production flag (5 S3 calls warm)
-GET /fleet over: lists and reads every box report, reads status/fleet.json, and lists and reads the storage entitlements (8 S3 calls warm)
-GET /fleet/economics over: the cold view sweeps usage for every day of the period (about 160 S3 calls, over 4 s); warm views come from the 60 s cache
-GET /fleet/economics/accounts over: shares /fleet/economics's sweep cache, so its own cold view is that same sweep
-GET /fleet/metrics over: a cold view reads every box's metrics hours for two days (about 100 S3 calls, 170 ms); warm views are cached, and in the walk the app pages before it fill that cache until perfColdReset clears it
-GET /fleet/store over: lists the storage entitlements and the storage usage days and reads each pending application (3 S3 calls warm)
+GET /a/{sqid}/settings calls 2: the account telemetry settings and the storage entitlement
+GET /a/{sqid}/{$} over: a warm view reads nothing (0 S3 calls; each app's frame is cached); a cold view reads every app's frame (6 S3 calls per app, about 155 ms for one)
+GET /a/{sqid}/trash over: reads each trashed app's deleted.json marker (1 S3 call warm and cold per app)
+GET /fleet over: lists and reads every box report, reads status/fleet.json, and lists and reads the storage entitlements (8 S3 calls warm and cold, median about 260 ms)
+GET /fleet/economics over: the cold view sweeps usage for every day of the period (162 S3 calls, about 4.1 s); warm views come from the 60 s cache (0 S3 calls)
+GET /fleet/economics/accounts over: shares /fleet/economics's sweep cache, so its own cold view is that same sweep (0 S3 calls warm)
+GET /fleet/metrics over: a cold view reads every box's metrics hours for two days (about 120 S3 calls, counted in Overview's cold view); warm views are cached (0 S3 calls), and the walk never sees it cold: the app pages before it fill that cache and perfColdReset leaves it
+GET /fleet/store over: lists the storage entitlements and the storage usage days and reads each pending application (3 S3 calls warm and cold, median about 80 ms)
diff --git a/internal/console/testdata/perf-session-s3.txt b/internal/console/testdata/perf-session-s3.txt
index 2f4ff340c..9cb4ea6f7 100644
--- a/internal/console/testdata/perf-session-s3.txt
+++ b/internal/console/testdata/perf-session-s3.txt
@@ -1 +1 @@
-1000 baseline before plan 2, 2026-10-26
+320 after console-perf-quick-wins, 2026-10-26
diff --git a/internal/console/view.go b/internal/console/view.go
index bb2d26eb2..01d1c892c 100644
--- a/internal/console/view.go
+++ b/internal/console/view.go
@@ -58,22 +58,23 @@ type AppView struct {
AllMismatched bool
// Pipeline is the app's declared release pipeline (release pipelines v2
// §2) — nil for a legacy app that has never opted in, or when the read
- // failed (best-effort for a VIEW: a page that cannot read the object
- // degrades to the legacy ladder rather than failing outright; a WRITE
- // door such as handlePromote reads its own copy and refuses on error
- // instead, which is the place that distinction is load-bearing).
+ // failed (PipelineErr then says why: best-effort for a VIEW, a page that
+ // cannot read the object degrades to the legacy ladder rather than
+ // failing outright; a WRITE door such as handlePromote reads its own
+ // copy and refuses on error instead, which is the place that
+ // distinction is load-bearing).
//
- // Deliberately NOT populated by Assemble (view.go's own tagByRelease
- // precedent: VersionView.Tag is never read there either — every caller
- // that wants it joins separately). Assemble builds a whole account's app
- // list for the account home page, which never renders Ladder or
- // Pipeline at all; a pipeline read per app there would be a bucket GET
- // nobody looks at. appPage (server.go) is the one place every APP page
- // funnels through, so it is the one place that reads this, and rebuilds
- // Ladder — and corrects each ChannelView's BakedUntil, which the legacy
- // per-app table below computes and which means nothing for a pipelined
- // channel's own window (Task 9 review) — once it has one.
- Pipeline *release.Pipeline
+ // Assemble fills it from the app's frame (appframe.go), which reads the
+ // pipeline alongside the channels so every app tab, the pending cards
+ // and the Pipeline settings section share one read. Assemble itself
+ // does not apply it: appPage (server.go) is the one place every APP
+ // page funnels through, so it is the one place that rebuilds Ladder —
+ // and corrects each ChannelView's BakedUntil, which the legacy per-app
+ // table computes and which means nothing for a pipelined channel's own
+ // window (Task 9 review) — from it (applyPipelineView). The account
+ // home page never renders Ladder or Pipeline.
+ Pipeline *release.Pipeline
+ PipelineErr string
}
// OneChannelPipeline reports whether this app has opted into a pipeline with
@@ -574,6 +575,15 @@ func openRegistry(path string) (consoleRegistry, error) {
// cannot be read costs that app its remote rows and nothing else. nil is
// the console box's registry alone.
func Assemble(ctx context.Context, regPath string, s release.Store, pub ed25519.PublicKey, acct string, apps []string, dns DNSTargets, remote *remoteRows) ([]AppView, error) {
+ return assembleViews(ctx, regPath, acct, apps, dns, remote, func(app string) appFrame {
+ return loadAppFrame(ctx, s, pub, acct, app)
+ })
+}
+
+// assembleViews is Assemble with each app's release-store reads coming from
+// frame: a fresh load for Assemble, the frame cache for a page view
+// (Server.assembleApps).
+func assembleViews(ctx context.Context, regPath, acct string, apps []string, dns DNSTargets, remote *remoteRows, frame func(app string) appFrame) ([]AppView, error) {
reg, err := openRegistry(regPath)
if err != nil {
return nil, err
@@ -646,8 +656,9 @@ func Assemble(ctx context.Context, regPath string, s release.Store, pub ed25519.
if remote != nil {
byApp[app], domainsByApp[app] = addRemoteRows(remote, acct, app, localHosts, byApp[app], domainsByApp[app], dns)
}
- channels := assembleChannels(ctx, s, pub, acct, app, now)
- pv := assembleProduction(ctx, s, pub, acct, app, channels, byApp[app], now)
+ f := frame(app)
+ channels := assembleChannels(f, now)
+ pv := assembleProduction(f, channels, byApp[app], now)
if pv.Err == "" && !pv.On {
// No production flag (or off): nothing bakes, so no estimate. An
// Err keeps the estimate — boxes fail toward baking.
@@ -667,13 +678,14 @@ func Assemble(ctx context.Context, regPath string, s release.Store, pub ed25519.
Channels: channels,
Canaries: assembleCanaries(channels, byApp[app]),
// nil pipeline here, always: this Ladder is the legacy shape.
- // Pipeline itself is deliberately NOT read here — see
- // AppView.Pipeline's doc comment — so appPage (server.go) is
- // where a single app's view gets pipeline-aware, and rebuilds
- // Ladder from the corrected Channels once it has one.
- Ladder: assembleLadder(channels, byApp[app], nil, now),
- Production: pv,
- routeFleet: fleetFromRoutes(routes, acct, app),
+ // appPage (server.go) is where a single app's view gets
+ // pipeline-aware (applyPipelineView), and rebuilds Ladder from
+ // the corrected Channels once it has one.
+ Ladder: assembleLadder(channels, byApp[app], nil, now),
+ Production: pv,
+ Pipeline: f.Pipeline,
+ PipelineErr: f.PipelineErr,
+ routeFleet: fleetFromRoutes(routes, acct, app),
})
}
return out, nil
@@ -809,31 +821,21 @@ func tagByRelease(ctx context.Context, s release.Store, acct, app string) (map[s
return tagIndex(tags), nil
}
-// assembleChannels lists the app's account-qualified channel pointers and
-// resolves each one. An app whose objects are still at the legacy unqualified
-// keys lists as empty here, exactly as the fleet sees it — the console showing
+// assembleChannels turns the frame's channel pointers (the app's
+// account-qualified channels, listed and resolved by loadAppFrame) into the
+// view's rows. An app whose objects are still at the legacy unqualified keys
+// lists as empty, exactly as the fleet sees it — the console showing
// channels the boxes cannot follow is the disagreement the retired
// read-fallback used to create.
-func assembleChannels(ctx context.Context, s release.Store, pub ed25519.PublicKey, acct, app string, now time.Time) []ChannelView {
- prefix := release.ChannelsPrefix(acct, app)
- keys, err := s.List(ctx, prefix)
- if err != nil {
- return []ChannelView{{Name: "(all)", Err: "listing channels: " + err.Error()}}
+func assembleChannels(f appFrame, now time.Time) []ChannelView {
+ if f.ChannelsErr != "" {
+ return []ChannelView{{Name: "(all)", Err: "listing channels: " + f.ChannelsErr}}
}
- var names []string
- for _, k := range keys {
- name := strings.TrimPrefix(k, prefix)
- if !strings.HasSuffix(name, ".json") {
- continue
- }
- names = append(names, strings.TrimSuffix(name, ".json"))
- }
- sort.Strings(names)
var out []ChannelView
- for _, name := range names {
- p, err := release.Channel(ctx, s, pub, acct, app, name)
- if err != nil {
- out = append(out, ChannelView{Name: name, Err: err.Error()})
+ for _, fc := range f.Channels {
+ name, p := fc.Name, fc.Pointer
+ if fc.Err != "" || p == nil {
+ out = append(out, ChannelView{Name: name, Err: fc.Err})
continue
}
cv := ChannelView{
@@ -862,14 +864,14 @@ func assembleChannels(ctx context.Context, s release.Store, pub ed25519.PublicKe
return out
}
-// assembleProduction reads the app's flag and derives the console's view of
-// it: on/off, the turning-off ratchet estimate, and the prod-wiring nudge.
-func assembleProduction(ctx context.Context, s release.Store, pub ed25519.PublicKey, acct, app string, channels []ChannelView, routes []RouteView, now time.Time) ProductionView {
+// assembleProduction derives the console's view of the frame's production
+// flag: on/off, the turning-off ratchet estimate, and the prod-wiring nudge.
+func assembleProduction(f appFrame, channels []ChannelView, routes []RouteView, now time.Time) ProductionView {
pv := ProductionView{}
- flag, err := release.GetProduction(ctx, s, pub, acct, app)
+ flag := f.Production
switch {
- case err != nil:
- pv.Err = err.Error()
+ case f.ProductionErr != "":
+ pv.Err = f.ProductionErr
pv.On = true // what the boxes will do: fail toward baking
return pv
case flag != nil: