Public: anyone can read this; the crew can change it.
Observability 7: /explore - query the series, select to explain, pin to home, save as a report #16868
Merged 46h 2m ago, live in production
scout/forge:scout/3696-observability-7-explore-query-the-series → main 0 commits fork 7 threads · 7 unresolved
- docs/design/attention-budget.json
- docs/design/audit.md
- docs/features/series.md
- src/core/empty_words.ts
- src/core/migration-pins/20261130150000-series.pin
- src/core/migrations/20261130150000-series.ts
- src/generated/migrations.ts
- src/generated/screens.ts
- src/http/server.ts
- src/main.ts
- src/series/explain.ts
- src/series/parse.ts
- src/series/pins.ts
- src/series/query.ts
- src/series/sampler.ts
- src/series/saved.ts
- src/series/store.ts
- src/series/text.ts
- src/series/view.ts
- src/tui/screens/series.ts
- src/tui/screens/system.ts
- src/web/empty_words.ts
- src/web/pages/home_flow.ts
- src/web/pages/series.ts
- src/web/pages/series_pins.ts
- src/web/studio/explore.ts
- test/data-browser.test.ts
- test/empty-notes.test.ts
- test/job-slices.test.ts
- test/keymap-terminal.test.ts
- test/palette-roster.test.ts
- test/series-explore.test.ts
- test/tui-series.test.ts
docs/design/attention-budget.json +5 −5
| @@ -190,15 +190,15 @@ | ||
| 190 | 190 | "note": "Measured on the test forge's empty state with the machine reading replaced by an empty one and the two cell-cap sentences fixed (the live page's counts depend on the host's cores, disks, processes and cgroups); nothing seeded or waited for. Blocks 65 -> 67 (#11805): the off-site backup section's heading and one-sentence state stay on first view so a red lane is seen without a click; its rows sit behind the disclosure. Blocks 67 -> 69 (#12010): the database size section's heading and its one-sentence state (the file's size and growth, a badge when either is worth a look) stay on first view, as the off-site lane's do; its fact rows and the table of the ten largest tables and indexes sit behind the disclosure. Words +22, blocks +1 (#12092): the footprint section's heading and its one-sentence state (on an empty forge, not read yet and the memory budget) stay on first view; the measured facts and the optional parts sit behind the disclosure. Words +6, blocks +2 (#12420): the stale-pulls section's heading and \"None.\" on a forge with no quiet pull. Words +4, blocks +2 (#13052): the Restore section's heading and its one sentence (\"Restore never proven.\" on an empty forge) stay on first view, so the owner sees whether a restore works without a click. Words +16, blocks +2 (#15073): the least-used-routes section's heading and its one-sentence count stay on first view (how many route groups had no request in 30 days); the table sits behind the disclosure. Words +6, blocks +2 (#15309): the heap census section's heading and its one-sentence state (\"No heap census yet.\" on an empty forge) stay on first view; the button, what a census costs and the table of types that grew sit behind the disclosure." |
| 191 | 191 | }, |
| 192 | 192 | "explore": { |
| 193 | "note": "Measured as an admin: the unfiltered count reads 'N apps, forges and people' (+3 words over 'N results'); a guest reads two fewer. An app row says forks by people (+1 word, #14323). A person row says its ships and forks in 30 days, the figures its place is made of: words +3 (#15754). The admin-only metric box adds its Run button: +1 word, +1 block (#17049).", | |
| 193 | "note": "Measured as an admin: the unfiltered count reads 'N apps, forges and people' (+3 words over 'N results'); a guest reads two fewer. An app row says forks by people (+1 word, #14323). A person row says its ships and forks in 30 days, the figures its place is made of: words +3 (#15754). The admin-only metric box adds its Run button: +1 word, +1 block (#17049). The owner's link to /explore/series, its only way in from a page: +3 words, +1 block (#3696).", | |
| 194 | 194 | "390": { |
| 195 | "words": 47, | |
| 196 | "blocks": 10, | |
| 195 | "words": 50, | |
| 196 | "blocks": 11, | |
| 197 | 197 | "colours": 0 |
| 198 | 198 | }, |
| 199 | 199 | "1280": { |
| 200 | "words": 47, | |
| 201 | "blocks": 10, | |
| 200 | "words": 50, | |
| 201 | "blocks": 11, | |
| 202 | 202 | "colours": 0 |
| 203 | 203 | } |
| 204 | 204 | }, |
docs/design/audit.md +1
| @@ -55,6 +55,7 @@ Machine routes are not pages and have no entry: `/audit.csv`, | ||
| 55 | 55 | - `/templates` — `pages/templates.ts` · the templates a new forge starts from, one button each to New forge with it chosen, public · `/forges/new` · none seen. |
| 56 | 56 | - `/terms` — `pages/terms.ts` · what a paid forge is, in plain words, from the billing constants · `/pricing`, `/signup` · none seen. |
| 57 | 57 | - `/explore` — `studio/explore.ts` · browse what the forge holds · `/search`, `/apps` · colours 2. |
| 58 | - `/explore/series` — `pages/series.ts` · query /metrics kept over time, select a region to explain it, pin or save as a report · `/explore` · none seen; reuses the card and muted text. | |
| 58 | 59 | - `/cockpit` — `pages/cockpit.ts` · board and map as one screen: Today lines, what needs me (five cards at most), waves toward milestones; four keys, readable at 3 m, `?kiosk=1` · `/board`, `/asks`, `/` · colours 4 (one per meaning), sizes 3. Styles in `docs/design/areas/cockpit.md`. |
| 59 | 60 | - `/board` — `pages/board.ts` (1,231 lines) · every app the viewer can see, with a wall mode · `/boards` (saved queries as panels), `/flow`, `/` · colour 1, sizes 6. |
| 60 | 61 | - `/home` — `pages/home_flow.ts` (`homeRedirect`) · an old address: goes to `/`, keeping the view and the filters · `/` · none seen. |
docs/features/series.md added +17
| @@ -0,0 +1,17 @@ | ||
| 1 | --- | |
| 2 | topic: When something is wrong | |
| 3 | row: Explore series (owner) | |
| 4 | --- | |
| 5 | # Explore series (owner) | |
| 6 | ||
| 7 | `/explore/series` queries the forge's own `/metrics` over time, for a forge admin who is a person (anyone else gets a 404; a crew agent is refused with one sentence). Reach it from the Explore series link on `/explore` (shown to that admin only), or in the terminal as the palette command Explore series (`src/tui/screens/series.ts`). | |
| 8 | ||
| 9 | - **Samples.** Every 30 s `src/series/sampler.ts` reads the same text `GET /metrics` answers and keeps it as rows of `series_sample` (`src/series/store.ts`): six hours, at most 3,000 samples a tick. A histogram is its `_bucket`, `_count` and `_sum` series, as `/metrics` writes it. It is telemetry: a lost row is a gap. | |
| 10 | - **Query** (`src/series/parse.ts`, `query.ts`): a selector `name{label="v", label!="v", label=~"a|b"}`; `rate(sel[5m])` (per second, a counter reset counted from zero) and `avg_over_time(sel[5m])`; `sum`, `avg`, `max`, `min`, with `by (labels)` before or after the argument; `topk(n, expr)`. A regex is alternatives of literals with `.*` at either end of one; nothing else is compiled, so no query can be slow by its pattern. At most 300 characters, 120 steps, 50 series. A query that is not one says why, in a sentence. | |
| 11 | - **Chart and table.** The six largest series are drawn with the forge's line chart (`boards/chart.ts`); the table lists every series with its latest, peak and points. Range 15 minutes, 1 or 6 hours; the address (`q`, `range`, `from`, `to`) holds the whole view. | |
| 12 | - **Select to explain** (`src/series/explain.ts`). A point on the chart selects the three steps either side of it (or `from` and `to` in the address; in the terminal `x` takes minutes ago, `10-5`). The page then ranks the label values that weigh more inside the selection than outside it, as Honeycomb's BubbleUp does: a label value's share of the total, inside and outside, and the lift between them; lifts under 5 points are left out. | |
| 13 | - **Pin and save.** A pin stays at the top of the page and is a row on the home with its latest value (`src/web/pages/series_pins.ts`, up to five); a report is a query with a note. Both are rows of `series_saved` (at most 100), a query kept only when it parses. The web form needs the same origin and the admin account. In the terminal `p` pins, `s` saves a report with a note, `n` opens the next saved query and `d` removes it after asking. | |
| 14 | ||
| 15 | Syntax, once: `name{l="v"}`, `rate(name[5m])`, `avg_over_time(name[5m])`, `sum|avg|max|min by (l) (…)`, `topk(5, …)`. | |
| 16 | ||
| 17 | Not done: crew-written commentary on a report, dragging a region on the chart (a click selects), and queries across forges. |
src/core/empty_words.ts +1
| @@ -67,6 +67,7 @@ const TABLE = { | ||
| 67 | 67 | branches: { sentence: "No branches yet." }, |
| 68 | 68 | labels: { sentence: "No labels yet." }, |
| 69 | 69 | events: { sentence: "No events yet." }, |
| 70 | seriesAnswered: { sentence: "No series answered." }, | |
| 70 | 71 | displays: { sentence: "No displays yet.", reason: "Add a display.json to a repository's default branch to make one." }, |
| 71 | 72 | changes: { sentence: "No change yet." }, |
| 72 | 73 | auditApps: { sentence: "No apps to audit.", reason: "An app's policy shows here once it has a contract.", label: "New app", href: "/apps/new" }, |
src/core/migration-pins/20261130150000-series.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | 1cd43de193ab09e3fd7ddc21009fef6c302055bfc9dc425a28cbb5ad1e9ea7ac |
src/core/migrations/20261130150000-series.ts added +22
| @@ -0,0 +1,22 @@ | ||
| 1 | // The forge's own /metrics, kept as a series (#3696): one row per sample per | |
| 2 | // tick, so /explore/series can query it over time; and the queries a person | |
| 3 | // pinned or saved as a report. Telemetry, not state: the samples are pruned | |
| 4 | // past six hours, and a lost row is a gap in a chart. | |
| 5 | export default ` | |
| 6 | CREATE TABLE series_sample ( | |
| 7 | at INTEGER NOT NULL, | |
| 8 | name TEXT NOT NULL, | |
| 9 | labels TEXT NOT NULL, | |
| 10 | value REAL NOT NULL | |
| 11 | ); | |
| 12 | CREATE INDEX series_sample_name ON series_sample (name, at); | |
| 13 | CREATE INDEX series_sample_at ON series_sample (at); | |
| 14 | CREATE TABLE series_saved ( | |
| 15 | id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| 16 | kind TEXT NOT NULL, | |
| 17 | title TEXT NOT NULL, | |
| 18 | query TEXT NOT NULL, | |
| 19 | note TEXT NOT NULL DEFAULT '', | |
| 20 | created_at INTEGER NOT NULL | |
| 21 | ); | |
| 22 | `; |
src/generated/migrations.ts +34 −32
| @@ -438,22 +438,23 @@ import m433 from "../core/migrations/20261130130000-look-theme-key.ts"; | ||
| 438 | 438 | import m434 from "../core/migrations/20261130140000-config-store.ts"; |
| 439 | 439 | import m435 from "../core/migrations/20261130140000-lent-runner-scope.ts"; |
| 440 | 440 | import m436 from "../core/migrations/20261130140000-look-drops-old-key.ts"; |
| 441 | import m437 from "../core/migrations/20261130170000-fence-read-from.ts"; | |
| 442 | import m438 from "../core/migrations/20261130170100-chat-build-lane.ts"; | |
| 443 | import m439 from "../core/migrations/20261130235220-run-check-plan.ts"; | |
| 444 | import m440 from "../core/migrations/20261201000000-games.ts"; | |
| 445 | import m441 from "../core/migrations/20261201090000-app-vital-member.ts"; | |
| 446 | import m442 from "../core/migrations/20261201120000-first-change-forge.ts"; | |
| 447 | import m443 from "../core/migrations/20261201121000-repo-check-slots.ts"; | |
| 448 | import m444 from "../core/migrations/20261201130000-finding-touched.ts"; | |
| 449 | import m445 from "../core/migrations/20261201130000-game-box-boot.ts"; | |
| 450 | import m446 from "../core/migrations/20261201140000-app-registry-item.ts"; | |
| 451 | import m447 from "../core/migrations/20261201140000-infra-snapshot.ts"; | |
| 452 | import m448 from "../core/migrations/20261201140000-scan-finding-excerpt.ts"; | |
| 453 | import m449 from "../core/migrations/20261201150000-pinned-firewall.ts"; | |
| 454 | import m450 from "../core/migrations/20261201170000-managed-database.ts"; | |
| 455 | import m451 from "../core/migrations/20261201180000-game-box-diag.ts"; | |
| 456 | import m452 from "../core/migrations/20261201190500-runner-machine.ts"; | |
| 441 | import m437 from "../core/migrations/20261130150000-series.ts"; | |
| 442 | import m438 from "../core/migrations/20261130170000-fence-read-from.ts"; | |
| 443 | import m439 from "../core/migrations/20261130170100-chat-build-lane.ts"; | |
| 444 | import m440 from "../core/migrations/20261130235220-run-check-plan.ts"; | |
| 445 | import m441 from "../core/migrations/20261201000000-games.ts"; | |
| 446 | import m442 from "../core/migrations/20261201090000-app-vital-member.ts"; | |
| 447 | import m443 from "../core/migrations/20261201120000-first-change-forge.ts"; | |
| 448 | import m444 from "../core/migrations/20261201121000-repo-check-slots.ts"; | |
| 449 | import m445 from "../core/migrations/20261201130000-finding-touched.ts"; | |
| 450 | import m446 from "../core/migrations/20261201130000-game-box-boot.ts"; | |
| 451 | import m447 from "../core/migrations/20261201140000-app-registry-item.ts"; | |
| 452 | import m448 from "../core/migrations/20261201140000-infra-snapshot.ts"; | |
| 453 | import m449 from "../core/migrations/20261201140000-scan-finding-excerpt.ts"; | |
| 454 | import m450 from "../core/migrations/20261201150000-pinned-firewall.ts"; | |
| 455 | import m451 from "../core/migrations/20261201170000-managed-database.ts"; | |
| 456 | import m452 from "../core/migrations/20261201180000-game-box-diag.ts"; | |
| 457 | import m453 from "../core/migrations/20261201190500-runner-machine.ts"; | |
| 457 | 458 | |
| 458 | 459 | /** Each migration file's name and its default export, in name order. */ |
| 459 | 460 | export const MIGRATION_MODULES: readonly (readonly [string, unknown])[] = [ |
| @@ -894,20 +895,21 @@ export const MIGRATION_MODULES: readonly (readonly [string, unknown])[] = [ | ||
| 894 | 895 | ["20261130140000-config-store.ts", m434], |
| 895 | 896 | ["20261130140000-lent-runner-scope.ts", m435], |
| 896 | 897 | ["20261130140000-look-drops-old-key.ts", m436], |
| 897 | ["20261130170000-fence-read-from.ts", m437], | |
| 898 | ["20261130170100-chat-build-lane.ts", m438], | |
| 899 | ["20261130235220-run-check-plan.ts", m439], | |
| 900 | ["20261201000000-games.ts", m440], | |
| 901 | ["20261201090000-app-vital-member.ts", m441], | |
| 902 | ["20261201120000-first-change-forge.ts", m442], | |
| 903 | ["20261201121000-repo-check-slots.ts", m443], | |
| 904 | ["20261201130000-finding-touched.ts", m444], | |
| 905 | ["20261201130000-game-box-boot.ts", m445], | |
| 906 | ["20261201140000-app-registry-item.ts", m446], | |
| 907 | ["20261201140000-infra-snapshot.ts", m447], | |
| 908 | ["20261201140000-scan-finding-excerpt.ts", m448], | |
| 909 | ["20261201150000-pinned-firewall.ts", m449], | |
| 910 | ["20261201170000-managed-database.ts", m450], | |
| 911 | ["20261201180000-game-box-diag.ts", m451], | |
| 912 | ["20261201190500-runner-machine.ts", m452], | |
| 898 | ["20261130150000-series.ts", m437], | |
| 899 | ["20261130170000-fence-read-from.ts", m438], | |
| 900 | ["20261130170100-chat-build-lane.ts", m439], | |
| 901 | ["20261130235220-run-check-plan.ts", m440], | |
| 902 | ["20261201000000-games.ts", m441], | |
| 903 | ["20261201090000-app-vital-member.ts", m442], | |
| 904 | ["20261201120000-first-change-forge.ts", m443], | |
| 905 | ["20261201121000-repo-check-slots.ts", m444], | |
| 906 | ["20261201130000-finding-touched.ts", m445], | |
| 907 | ["20261201130000-game-box-boot.ts", m446], | |
| 908 | ["20261201140000-app-registry-item.ts", m447], | |
| 909 | ["20261201140000-infra-snapshot.ts", m448], | |
| 910 | ["20261201140000-scan-finding-excerpt.ts", m449], | |
| 911 | ["20261201150000-pinned-firewall.ts", m450], | |
| 912 | ["20261201170000-managed-database.ts", m451], | |
| 913 | ["20261201180000-game-box-diag.ts", m452], | |
| 914 | ["20261201190500-runner-machine.ts", m453], | |
| 913 | 915 | ]; |
src/generated/screens.ts +19 −17
| @@ -109,23 +109,24 @@ import * as s104 from "../tui/screens/scorecard.ts"; | ||
| 109 | 109 | import * as s105 from "../tui/screens/scrapes.ts"; |
| 110 | 110 | import * as s106 from "../tui/screens/secrets.ts"; |
| 111 | 111 | import * as s107 from "../tui/screens/sentinel.ts"; |
| 112 | import * as s108 from "../tui/screens/ship_time.ts"; | |
| 113 | import * as s109 from "../tui/screens/slowpages.ts"; | |
| 114 | import * as s110 from "../tui/screens/sold.ts"; | |
| 115 | import * as s111 from "../tui/screens/spend.ts"; | |
| 116 | import * as s112 from "../tui/screens/stalepulls.ts"; | |
| 117 | import * as s113 from "../tui/screens/subscriptions.ts"; | |
| 118 | import * as s114 from "../tui/screens/system.ts"; | |
| 119 | import * as s115 from "../tui/screens/teams.ts"; | |
| 120 | import * as s116 from "../tui/screens/telemetry.ts"; | |
| 121 | import * as s117 from "../tui/screens/tell_undo.ts"; | |
| 122 | import * as s118 from "../tui/screens/traffic.ts"; | |
| 123 | import * as s119 from "../tui/screens/trafficview.ts"; | |
| 124 | import * as s120 from "../tui/screens/valves.ts"; | |
| 125 | import * as s121 from "../tui/screens/waiting.ts"; | |
| 126 | import * as s122 from "../tui/screens/waiting_for_me.ts"; | |
| 127 | import * as s123 from "../tui/screens/wayback.ts"; | |
| 128 | import * as s124 from "../tui/screens/weekcard.ts"; | |
| 112 | import * as s108 from "../tui/screens/series.ts"; | |
| 113 | import * as s109 from "../tui/screens/ship_time.ts"; | |
| 114 | import * as s110 from "../tui/screens/slowpages.ts"; | |
| 115 | import * as s111 from "../tui/screens/sold.ts"; | |
| 116 | import * as s112 from "../tui/screens/spend.ts"; | |
| 117 | import * as s113 from "../tui/screens/stalepulls.ts"; | |
| 118 | import * as s114 from "../tui/screens/subscriptions.ts"; | |
| 119 | import * as s115 from "../tui/screens/system.ts"; | |
| 120 | import * as s116 from "../tui/screens/teams.ts"; | |
| 121 | import * as s117 from "../tui/screens/telemetry.ts"; | |
| 122 | import * as s118 from "../tui/screens/tell_undo.ts"; | |
| 123 | import * as s119 from "../tui/screens/traffic.ts"; | |
| 124 | import * as s120 from "../tui/screens/trafficview.ts"; | |
| 125 | import * as s121 from "../tui/screens/valves.ts"; | |
| 126 | import * as s122 from "../tui/screens/waiting.ts"; | |
| 127 | import * as s123 from "../tui/screens/waiting_for_me.ts"; | |
| 128 | import * as s124 from "../tui/screens/wayback.ts"; | |
| 129 | import * as s125 from "../tui/screens/weekcard.ts"; | |
| 129 | 130 | |
| 130 | 131 | /** Each screen file that declares palette entries: its module and the export names. */ |
| 131 | 132 | export const SCREEN_MODULES: readonly (readonly [Record<string, unknown>, readonly string[]])[] = [ |
| @@ -254,4 +255,5 @@ export const SCREEN_MODULES: readonly (readonly [Record<string, unknown>, readon | ||
| 254 | 255 | [s122, ["entry"]], |
| 255 | 256 | [s123, ["entry"]], |
| 256 | 257 | [s124, ["entry"]], |
| 258 | [s125, ["entry"]], | |
| 257 | 259 | ]; |
src/http/server.ts +6
| @@ -383,6 +383,7 @@ import { HOME_REGIONS } from "../web/studio/home_last.ts"; | ||
| 383 | 383 | import { serviceWorker } from "../web/sw.ts"; |
| 384 | 384 | import { offlinePage } from "../web/pages/offline.ts"; |
| 385 | 385 | import { explorePage } from "../web/studio/explore.ts"; |
| 386 | import { seriesPage, seriesRemove, seriesSave } from "../web/pages/series.ts"; | |
| 386 | 387 | import { componentsPage, designPage, designPublish, designRevert, themeFile, themeLive } from "../web/studio/design.ts"; |
| 387 | 388 | import { exploreJson } from "./explore_json.ts"; |
| 388 | 389 | import { isPacksMirror, MIRROR_PUSH_REFUSED } from "../packs/owner.ts"; |
| @@ -1025,6 +1026,11 @@ export function buildRouter(): Router<Handler> { | ||
| 1025 | 1026 | router.add("GET", "/front", studioDoor); |
| 1026 | 1027 | // Apps and people ranked by real numbers, narrowed in one line (#607). |
| 1027 | 1028 | router.add("GET", "/explore", explorePage); |
| 1029 | // The forge's own /metrics as a series, queried and explained (#3696); an owner's, gated in the | |
| 1030 | // handlers. | |
| 1031 | router.add("GET", "/explore/series", seriesPage); | |
| 1032 | router.add("POST", "/explore/series/save", seriesSave); | |
| 1033 | router.add("POST", "/explore/series/remove", seriesRemove); | |
| 1028 | 1034 | router.add("GET", "/design", designPage); |
| 1029 | 1035 | router.add("GET", "/design/components", componentsPage); |
| 1030 | 1036 | router.add("POST", "/design/publish", designPublish); |
src/main.ts +4
| @@ -20,6 +20,7 @@ import { BATCH_EVERY_MS, ledgerGitTick } from "./core/ledger_git.ts"; | ||
| 20 | 20 | import { getRepoById } from "./core/repos.ts"; |
| 21 | 21 | import { BOOT_ACTOR, setSignup, signupFromEnv } from "./settings/signup.ts"; |
| 22 | 22 | import { startMemorySampler } from "./boards/memory.ts"; |
| 23 | import { startSeriesSampler } from "./series/sampler.ts"; | |
| 23 | 24 | import { startHeapCapture } from "./perf/heap_capture.ts"; |
| 24 | 25 | import { startSampler } from "./boards/sampler.ts"; |
| 25 | 26 | import { sweepStanding } from "./crew/standing.ts"; |
| @@ -781,6 +782,8 @@ const sampler = startSampler(app, {}); | ||
| 781 | 782 | // it has a thread of its own. |
| 782 | 783 | const stopRetention = startRetention(app, { local: true, engine: !engineOn }); |
| 783 | 784 | const memorySampler = startMemorySampler(app, workerMemoryEvery()); |
| 785 | // /metrics kept as a series every 30 s for /explore/series (series/sampler.ts). | |
| 786 | const seriesSampler = startSeriesSampler(app); | |
| 784 | 787 | // Off unless FORGE_HEAP_CAPTURE_DIR is set, for a copy of production (perf/heap_capture.ts). |
| 785 | 788 | const stopHeapCapture = startHeapCapture(process.env, (m) => app.log.info(m)); |
| 786 | 789 | // The starting boards, once each (actions/boards.ts). |
| @@ -1327,6 +1330,7 @@ function drain(signal: NodeJS.Signals): Promise<unknown> { | ||
| 1327 | 1330 | sampler.stop(), |
| 1328 | 1331 | stopRetention(), |
| 1329 | 1332 | memorySampler.stop(), |
| 1333 | seriesSampler.stop(), | |
| 1330 | 1334 | stopHeapCapture(), |
| 1331 | 1335 | engineStopped, |
| 1332 | 1336 | ]) |
src/series/explain.ts added +43
| @@ -0,0 +1,43 @@ | ||
| 1 | /** | |
| 2 | * Select a region, ask why (#3696): which label values account for more of the | |
| 3 | * total inside the selection than outside it, as Honeycomb's BubbleUp ranks | |
| 4 | * them. A series' weight is its summed value in a region; a label value's | |
| 5 | * share is the weight of the series that carry it over all weight in that | |
| 6 | * region; its lift is the share inside minus the share outside. Plain data in | |
| 7 | * and out: the series are `runQuery`'s. | |
| 8 | */ | |
| 9 | import type { Series } from "./query.ts"; | |
| 10 | ||
| 11 | export type Cause = { label: string; value: string; inside: number; outside: number; lift: number }; | |
| 12 | ||
| 13 | export const CAUSES_MAX = 10; | |
| 14 | ||
| 15 | /** | |
| 16 | * The labels whose values shift most between `[from, to]` and the rest, largest absolute lift | |
| 17 | * first. | |
| 18 | */ | |
| 19 | export function explain(series: readonly Series[], from: number, to: number): Cause[] { | |
| 20 | const weight = (s: Series, inside: boolean): number => | |
| 21 | s.points.filter((p) => (p.at >= from && p.at <= to) === inside).reduce((a, p) => a + Math.max(p.value, 0), 0); | |
| 22 | const total = (inside: boolean) => series.reduce((a, s) => a + weight(s, inside), 0); | |
| 23 | const tin = total(true); | |
| 24 | const tout = total(false); | |
| 25 | if (tin === 0 || tout === 0) return []; | |
| 26 | const shares = new Map<string, Cause>(); | |
| 27 | for (const s of series) { | |
| 28 | const wi = weight(s, true) / tin; | |
| 29 | const wo = weight(s, false) / tout; | |
| 30 | for (const [label, value] of Object.entries(s.labels)) { | |
| 31 | const k = `${label}\n${value}`; | |
| 32 | const c = shares.get(k) ?? { label, value, inside: 0, outside: 0, lift: 0 }; | |
| 33 | c.inside += wi; | |
| 34 | c.outside += wo; | |
| 35 | shares.set(k, c); | |
| 36 | } | |
| 37 | } | |
| 38 | return [...shares.values()] | |
| 39 | .map((c) => ({ ...c, lift: c.inside - c.outside })) | |
| 40 | .filter((c) => Math.abs(c.lift) >= 0.05) | |
| 41 | .sort((a, b) => Math.abs(b.lift) - Math.abs(a.lift) || (a.label + a.value < b.label + b.value ? -1 : 1)) | |
| 42 | .slice(0, CAUSES_MAX); | |
| 43 | } |
src/series/parse.ts added +174
| @@ -0,0 +1,174 @@ | ||
| 1 | /** | |
| 2 | * A small PromQL subset, parsed (#3696): a selector `name{l="v",l!="v",l=~"a|b"}`; | |
| 3 | * `rate(sel[5m])` and `avg_over_time(sel[5m])`; `sum`, `avg`, `max`, `min`, | |
| 4 | * each with `by (labels)` before or after its argument; and `topk(n, expr)`. | |
| 5 | * Nothing is evaluated here, and no user text becomes a regular expression: | |
| 6 | * `=~` takes alternatives of literals, with `.*` at either end of one. | |
| 7 | */ | |
| 8 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 9 | ||
| 10 | export const QUERY_MAX = 300; | |
| 11 | ||
| 12 | export type Matcher = { label: string; op: "=" | "!=" | "=~" | "!~"; value: string }; | |
| 13 | export type Selector = { kind: "select"; name: string; matchers: Matcher[] }; | |
| 14 | export type Expr = | |
| 15 | | Selector | |
| 16 | | { kind: "window"; fn: "rate" | "avg_over_time"; sel: Selector; ms: number } | |
| 17 | | { kind: "agg"; fn: "sum" | "avg" | "max" | "min"; by: string[]; arg: Expr } | |
| 18 | | { kind: "topk"; n: number; arg: Expr }; | |
| 19 | ||
| 20 | const AGG = new Set(["sum", "avg", "max", "min"]); | |
| 21 | const UNITS: Record<string, number> = { s: 1000, m: 60_000, h: 3_600_000 }; | |
| 22 | const IDENT = /^[a-zA-Z_:][a-zA-Z0-9_:]*/; | |
| 23 | ||
| 24 | class Syntax extends Error {} | |
| 25 | ||
| 26 | class Reader { | |
| 27 | at = 0; | |
| 28 | constructor(readonly text: string) {} | |
| 29 | space(): void { | |
| 30 | while (this.text[this.at] === " ") this.at++; | |
| 31 | } | |
| 32 | peek(): string { | |
| 33 | this.space(); | |
| 34 | return this.text[this.at] ?? ""; | |
| 35 | } | |
| 36 | eat(ch: string): boolean { | |
| 37 | if (this.peek() === ch) { | |
| 38 | this.at++; | |
| 39 | return true; | |
| 40 | } | |
| 41 | return false; | |
| 42 | } | |
| 43 | need(ch: string): void { | |
| 44 | if (!this.eat(ch)) throw new Syntax(`expected ${ch} at ${this.at + 1}`); | |
| 45 | } | |
| 46 | ident(): string { | |
| 47 | this.space(); | |
| 48 | const m = IDENT.exec(this.text.slice(this.at)); | |
| 49 | if (m === null) throw new Syntax(`expected a name at ${this.at + 1}`); | |
| 50 | this.at += m[0].length; | |
| 51 | return m[0]; | |
| 52 | } | |
| 53 | string(): string { | |
| 54 | this.space(); | |
| 55 | if (this.text[this.at] !== '"') throw new Syntax(`expected a quoted value at ${this.at + 1}`); | |
| 56 | let out = ""; | |
| 57 | for (this.at++; this.at < this.text.length; this.at++) { | |
| 58 | const c = this.text[this.at]!; | |
| 59 | if (c === '"') { | |
| 60 | this.at++; | |
| 61 | return out; | |
| 62 | } | |
| 63 | if (c === "\\") out += this.text[++this.at] ?? ""; | |
| 64 | else out += c; | |
| 65 | } | |
| 66 | throw new Syntax("a quoted value is not closed"); | |
| 67 | } | |
| 68 | number(): number { | |
| 69 | this.space(); | |
| 70 | const m = /^\d+/.exec(this.text.slice(this.at)); | |
| 71 | if (m === null) throw new Syntax(`expected a number at ${this.at + 1}`); | |
| 72 | this.at += m[0].length; | |
| 73 | return Number(m[0]); | |
| 74 | } | |
| 75 | } | |
| 76 | ||
| 77 | function selector(r: Reader, name = r.ident()): Selector { | |
| 78 | const matchers: Matcher[] = []; | |
| 79 | if (r.eat("{")) { | |
| 80 | while (r.peek() !== "}") { | |
| 81 | const label = r.ident(); | |
| 82 | r.space(); | |
| 83 | const op = (["=~", "!~", "!=", "="] as const).find((o) => r.text.startsWith(o, r.at)); | |
| 84 | if (op === undefined) throw new Syntax(`expected = != =~ or !~ at ${r.at + 1}`); | |
| 85 | r.at += op.length; | |
| 86 | const value = r.string(); | |
| 87 | if ((op === "=~" || op === "!~") && !simpleRegex(value)) throw new Syntax("a regex here is alternatives of literals, with .* at either end"); | |
| 88 | matchers.push({ label, op, value }); | |
| 89 | if (!r.eat(",")) break; | |
| 90 | } | |
| 91 | r.need("}"); | |
| 92 | } | |
| 93 | return { kind: "select", name, matchers }; | |
| 94 | } | |
| 95 | ||
| 96 | const simpleRegex = (v: string): boolean => v.split("|").every((a) => /^(\.\*)?[^.*+?()[\]{}^$\\|]*(\.\*)?$/.test(a)); | |
| 97 | ||
| 98 | /** Whether `value` is matched by `=~`'s alternatives (anchored, as PromQL's are). */ | |
| 99 | export function regexHolds(pattern: string, value: string): boolean { | |
| 100 | return pattern.split("|").some((alt) => { | |
| 101 | const head = alt.startsWith(".*"); | |
| 102 | const tail = alt.length > 2 && alt.endsWith(".*"); | |
| 103 | const lit = alt.slice(head ? 2 : 0, tail ? -2 : undefined); | |
| 104 | if (head && tail) return value.includes(lit); | |
| 105 | if (head) return value.endsWith(lit); | |
| 106 | if (tail) return value.startsWith(lit); | |
| 107 | return value === lit; | |
| 108 | }); | |
| 109 | } | |
| 110 | ||
| 111 | function labels(r: Reader): string[] { | |
| 112 | r.need("("); | |
| 113 | const out: string[] = []; | |
| 114 | while (r.peek() !== ")") { | |
| 115 | out.push(r.ident()); | |
| 116 | if (!r.eat(",")) break; | |
| 117 | } | |
| 118 | r.need(")"); | |
| 119 | return out; | |
| 120 | } | |
| 121 | ||
| 122 | function expr(r: Reader, depth: number): Expr { | |
| 123 | if (depth > 6) throw new Syntax("nested too deep"); | |
| 124 | const name = r.ident(); | |
| 125 | if (name === "rate" || name === "avg_over_time") { | |
| 126 | r.need("("); | |
| 127 | const sel = selector(r); | |
| 128 | r.need("["); | |
| 129 | const n = r.number(); | |
| 130 | const unit = r.text[r.at++] ?? ""; | |
| 131 | if (UNITS[unit] === undefined || n < 1) throw new Syntax("a range is a number and s, m or h"); | |
| 132 | r.need("]"); | |
| 133 | r.need(")"); | |
| 134 | return { kind: "window", fn: name, sel, ms: n * UNITS[unit]! }; | |
| 135 | } | |
| 136 | if (AGG.has(name)) { | |
| 137 | let by: string[] = []; | |
| 138 | if (r.peek() !== "(") { | |
| 139 | if (r.ident() !== "by") throw new Syntax("expected by or ( after " + name); | |
| 140 | by = labels(r); | |
| 141 | } | |
| 142 | r.need("("); | |
| 143 | const arg = expr(r, depth + 1); | |
| 144 | r.need(")"); | |
| 145 | if (by.length === 0 && r.peek() !== "" && r.peek() !== ")" && r.peek() !== ",") { | |
| 146 | if (r.ident() !== "by") throw new Syntax("expected by"); | |
| 147 | by = labels(r); | |
| 148 | } | |
| 149 | return { kind: "agg", fn: name as "sum", by, arg }; | |
| 150 | } | |
| 151 | if (name === "topk") { | |
| 152 | r.need("("); | |
| 153 | const n = r.number(); | |
| 154 | r.need(","); | |
| 155 | const arg = expr(r, depth + 1); | |
| 156 | r.need(")"); | |
| 157 | if (n < 1 || n > 50) throw new Syntax("topk takes 1 to 50"); | |
| 158 | return { kind: "topk", n, arg }; | |
| 159 | } | |
| 160 | return selector(r, name); | |
| 161 | } | |
| 162 | ||
| 163 | export function parseQuery(text: string): Result<Expr, string> { | |
| 164 | if (text.length > QUERY_MAX) return err(`a query is at most ${QUERY_MAX} characters`); | |
| 165 | const r = new Reader(text); | |
| 166 | try { | |
| 167 | const e = expr(r, 0); | |
| 168 | if (r.peek() !== "") throw new Syntax(`unexpected ${r.peek()} at ${r.at + 1}`); | |
| 169 | return ok(e); | |
| 170 | } catch (e) { | |
| 171 | if (e instanceof Syntax) return err(e.message); | |
| 172 | throw e; | |
| 173 | } | |
| 174 | } |
src/series/pins.ts added +23
| @@ -0,0 +1,23 @@ | ||
| 1 | /** | |
| 2 | * The pinned queries as the home shows them (#3696): each pin with its latest | |
| 3 | * value, read over the last 15 minutes. At most `PINS_SHOWN` are run, so the | |
| 4 | * home stays a few cheap reads however many are kept. | |
| 5 | */ | |
| 6 | import type { Database } from "bun:sqlite"; | |
| 7 | import { listSaved, type Saved } from "./saved.ts"; | |
| 8 | import { answer } from "./view.ts"; | |
| 9 | ||
| 10 | export const PINS_SHOWN = 5; | |
| 11 | ||
| 12 | export type PinNow = { pin: Saved; series: number; latest: number | undefined; error: string | undefined }; | |
| 13 | ||
| 14 | export function pinsNow(db: Database, now: number): PinNow[] { | |
| 15 | return listSaved(db) | |
| 16 | .filter((s) => s.kind === "pin") | |
| 17 | .slice(0, PINS_SHOWN) | |
| 18 | .map((pin) => { | |
| 19 | const a = answer(db, { query: pin.query, minutes: 15 }, now); | |
| 20 | const last = a.series.map((s) => s.points[s.points.length - 1]?.value).filter((v): v is number => v !== undefined); | |
| 21 | return { pin, series: a.series.length, latest: last.length === 0 ? undefined : Math.max(...last), error: a.error }; | |
| 22 | }); | |
| 23 | } |
src/series/query.ts added +117
| @@ -0,0 +1,117 @@ | ||
| 1 | /** | |
| 2 | * A parsed query (`parse.ts`) evaluated over the stored samples (`store.ts`) | |
| 3 | * between two instants, one value a step per series (#3696). A selector reads | |
| 4 | * each series' latest sample within `LOOKBACK_MS`; `rate` is the per-second | |
| 5 | * increase over its window, a counter reset counted from zero; `avg_over_time` | |
| 6 | * the window's mean; an aggregate folds series by the labels named, or all of | |
| 7 | * them. At most `SERIES_MAX` series and `STEPS_MAX` steps come back. | |
| 8 | */ | |
| 9 | import type { Database } from "bun:sqlite"; | |
| 10 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 11 | import { parseQuery, regexHolds, type Expr, type Selector } from "./parse.ts"; | |
| 12 | import { readRaw, type Raw } from "./store.ts"; | |
| 13 | ||
| 14 | export const LOOKBACK_MS = 90_000; | |
| 15 | export const STEPS_MAX = 120; | |
| 16 | export const SERIES_MAX = 50; | |
| 17 | ||
| 18 | export type Labels = Record<string, string>; | |
| 19 | export type Series = { labels: Labels; points: { at: number; value: number }[] }; | |
| 20 | export type Window = { from: number; to: number; stepMs: number }; | |
| 21 | ||
| 22 | type Held = { labels: Labels; samples: { at: number; value: number }[] }; | |
| 23 | ||
| 24 | const keyOf = (l: Labels): string => JSON.stringify(Object.entries(l).sort(([a], [b]) => (a < b ? -1 : 1))); | |
| 25 | ||
| 26 | function holds(l: Labels, sel: Selector): boolean { | |
| 27 | return sel.matchers.every((m) => { | |
| 28 | const v = l[m.label] ?? ""; | |
| 29 | return m.op === "=" ? v === m.value : m.op === "!=" ? v !== m.value : m.op === "=~" ? regexHolds(m.value, v) : !regexHolds(m.value, v); | |
| 30 | }); | |
| 31 | } | |
| 32 | ||
| 33 | function load(db: Database, sel: Selector, from: number, to: number): Held[] { | |
| 34 | const by = new Map<string, Held>(); | |
| 35 | for (const r of readRaw(db, sel.name, from, to) as Raw[]) { | |
| 36 | if (!holds(r.labels, sel)) continue; | |
| 37 | const k = keyOf(r.labels); | |
| 38 | const h = by.get(k) ?? { labels: r.labels, samples: [] }; | |
| 39 | by.set(k, h); | |
| 40 | h.samples.push({ at: r.at, value: r.value }); | |
| 41 | } | |
| 42 | return [...by.values()]; | |
| 43 | } | |
| 44 | ||
| 45 | const inWindow = (h: Held, lo: number, hi: number) => h.samples.filter((s) => s.at > lo && s.at <= hi); | |
| 46 | ||
| 47 | function rateOf(s: { at: number; value: number }[]): number | undefined { | |
| 48 | if (s.length < 2) return undefined; | |
| 49 | let up = 0; | |
| 50 | for (let i = 1; i < s.length; i++) up += s[i]!.value >= s[i - 1]!.value ? s[i]!.value - s[i - 1]!.value : s[i]!.value; | |
| 51 | const secs = (s[s.length - 1]!.at - s[0]!.at) / 1000; | |
| 52 | return secs > 0 ? up / secs : undefined; | |
| 53 | } | |
| 54 | ||
| 55 | function evaluate(db: Database, e: Expr, w: Window, steps: number[]): Series[] { | |
| 56 | if (e.kind === "select" || e.kind === "window") { | |
| 57 | const sel = e.kind === "select" ? e : e.sel; | |
| 58 | const reach = e.kind === "select" ? LOOKBACK_MS : e.ms; | |
| 59 | return load(db, sel, w.from - reach, w.to).map((h) => { | |
| 60 | const points: Series["points"] = []; | |
| 61 | for (const at of steps) { | |
| 62 | const s = inWindow(h, at - reach, at); | |
| 63 | if (s.length === 0) continue; | |
| 64 | const value = | |
| 65 | e.kind === "select" ? s[s.length - 1]!.value : e.fn === "rate" ? rateOf(s) : s.reduce((a, x) => a + x.value, 0) / s.length; | |
| 66 | if (value !== undefined) points.push({ at, value }); | |
| 67 | } | |
| 68 | return { labels: h.labels, points }; | |
| 69 | }).filter((s) => s.points.length > 0); | |
| 70 | } | |
| 71 | const inner = evaluate(db, e.arg, w, steps); | |
| 72 | if (e.kind === "topk") { | |
| 73 | const keep = new Map<string, Series>(); | |
| 74 | for (const at of steps) { | |
| 75 | const here = inner.flatMap((s) => { const p = s.points.find((x) => x.at === at); return p ? [{ s, v: p.value }] : []; }); | |
| 76 | for (const { s } of here.sort((a, b) => b.v - a.v).slice(0, e.n)) { | |
| 77 | const k = keyOf(s.labels); | |
| 78 | const out = keep.get(k) ?? { labels: s.labels, points: [] }; | |
| 79 | keep.set(k, out); | |
| 80 | out.points.push(s.points.find((x) => x.at === at)!); | |
| 81 | } | |
| 82 | } | |
| 83 | return [...keep.values()]; | |
| 84 | } | |
| 85 | const groups = new Map<string, { labels: Labels; at: Map<number, number[]> }>(); | |
| 86 | for (const s of inner) { | |
| 87 | const labels: Labels = {}; | |
| 88 | for (const l of e.by) if (s.labels[l] !== undefined) labels[l] = s.labels[l]!; | |
| 89 | const k = keyOf(labels); | |
| 90 | const g = groups.get(k) ?? { labels, at: new Map() }; | |
| 91 | groups.set(k, g); | |
| 92 | for (const p of s.points) g.at.set(p.at, [...(g.at.get(p.at) ?? []), p.value]); | |
| 93 | } | |
| 94 | const fold = (vs: number[]) => | |
| 95 | e.fn === "sum" ? vs.reduce((a, b) => a + b, 0) : e.fn === "avg" ? vs.reduce((a, b) => a + b, 0) / vs.length : e.fn === "max" ? Math.max(...vs) : Math.min(...vs); | |
| 96 | return [...groups.values()].map((g) => ({ | |
| 97 | labels: g.labels, | |
| 98 | points: [...g.at].sort(([a], [b]) => a - b).map(([at, vs]) => ({ at, value: fold(vs) })), | |
| 99 | })); | |
| 100 | } | |
| 101 | ||
| 102 | /** The instants of a window, `stepMs` apart, ending at `to`. */ | |
| 103 | export function stepsOf(w: Window): number[] { | |
| 104 | const out: number[] = []; | |
| 105 | for (let at = w.to; at >= w.from && out.length < STEPS_MAX; at -= w.stepMs) out.unshift(at); | |
| 106 | return out; | |
| 107 | } | |
| 108 | ||
| 109 | /** The series of `text` over `w`, biggest last value first; or one sentence on why not. */ | |
| 110 | export function runQuery(db: Database, text: string, w: Window): Result<Series[], string> { | |
| 111 | if (!(w.stepMs >= 1000) || !Number.isFinite(w.from) || !Number.isFinite(w.to) || w.to < w.from) return err("the range is not a window of time"); | |
| 112 | const parsed = parseQuery(text); | |
| 113 | if (!parsed.ok) return err(parsed.error); | |
| 114 | const steps = stepsOf(w); | |
| 115 | const last = (s: Series) => s.points[s.points.length - 1]!.value; | |
| 116 | return ok(evaluate(db, parsed.value, w, steps).sort((a, b) => last(b) - last(a)).slice(0, SERIES_MAX)); | |
| 117 | } |
src/series/sampler.ts added +30
| @@ -0,0 +1,30 @@ | ||
| 1 | /** | |
| 2 | * Every 30 s the forge's own `/metrics` text is read once (the same families | |
| 3 | * `GET /metrics` answers) and kept as a tick of samples (`store.ts`), so | |
| 4 | * /explore/series has a past to query. A failed tick is logged; the next one tries again. | |
| 5 | */ | |
| 6 | import type { App } from "../app.ts"; | |
| 7 | import { egressMetrics } from "../apps/egress_metrics.ts"; | |
| 8 | import { during } from "../perf/jobs.ts"; | |
| 9 | import { liveOf } from "../perf/live.ts"; | |
| 10 | import { forgeMetrics } from "../metrics/forge.ts"; | |
| 11 | import { appSources } from "../metrics/app_sources.ts"; | |
| 12 | import { egressRowsFor, egressTotalsFor } from "../spawn/process_counters.ts"; | |
| 13 | import { record } from "./store.ts"; | |
| 14 | import { parseExposition } from "./text.ts"; | |
| 15 | ||
| 16 | export const SERIES_EVERY_MS = 30_000; | |
| 17 | ||
| 18 | export function startSeriesSampler(app: App, everyMs = SERIES_EVERY_MS): { tick(now?: number): void; stop(): void } { | |
| 19 | const tick = (now = Date.now()) => { | |
| 20 | try { | |
| 21 | const text = egressMetrics(egressRowsFor(app), egressTotalsFor(app)) + forgeMetrics(app.db, appSources(app), now, liveOf(app).loopWatch); | |
| 22 | record(app.db, parseExposition(text), now); | |
| 23 | } catch (error) { | |
| 24 | app.log.warn("series sample failed", { error: String(error) }); | |
| 25 | } | |
| 26 | }; | |
| 27 | const timer = setInterval(() => during("series-sampler", () => tick(), undefined, app), everyMs); | |
| 28 | timer.unref?.(); | |
| 29 | return { tick, stop: () => clearInterval(timer) }; | |
| 30 | } |
src/series/saved.ts added +45
| @@ -0,0 +1,45 @@ | ||
| 1 | /** | |
| 2 | * Queries kept (#3696): a pin is a query that stays at the top of | |
| 3 | * /explore/series; a report is a query with a note, the commentary a person | |
| 4 | * (or the crew, through the same function) writes beside it. Both are rows of | |
| 5 | * `series_saved`; the query is checked by `parseQuery` before it is kept, so | |
| 6 | * nothing stored fails to parse. | |
| 7 | */ | |
| 8 | import type { Database } from "bun:sqlite"; | |
| 9 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 10 | import { parseQuery } from "./parse.ts"; | |
| 11 | ||
| 12 | export const KINDS = ["pin", "report"] as const; | |
| 13 | export type Kind = (typeof KINDS)[number]; | |
| 14 | export const TITLE_MAX = 80; | |
| 15 | export const NOTE_MAX = 1000; | |
| 16 | export const SAVED_MAX = 100; | |
| 17 | ||
| 18 | export type Saved = { id: number; kind: Kind; title: string; query: string; note: string; createdAt: number }; | |
| 19 | ||
| 20 | export function save(db: Database, input: { kind: string; title: string; query: string; note?: string }, now: number): Result<Saved, string> { | |
| 21 | if (!(KINDS as readonly string[]).includes(input.kind)) return err("a saved query is a pin or a report"); | |
| 22 | const title = input.title.trim().replace(/\s+/g, " "); | |
| 23 | const note = (input.note ?? "").trim(); | |
| 24 | if (title === "" || title.length > TITLE_MAX) return err(`a title is 1 to ${TITLE_MAX} characters`); | |
| 25 | if (note.length > NOTE_MAX) return err(`a note is at most ${NOTE_MAX} characters`); | |
| 26 | const parsed = parseQuery(input.query.trim()); | |
| 27 | if (!parsed.ok) return err(parsed.error); | |
| 28 | if (db.query<{ n: number }, []>("SELECT count(*) AS n FROM series_saved").get()!.n >= SAVED_MAX) return err(`at most ${SAVED_MAX} saved queries: remove one first`); | |
| 29 | const query = input.query.trim(); | |
| 30 | const { lastInsertRowid } = db.run("INSERT INTO series_saved (kind, title, query, note, created_at) VALUES (?, ?, ?, ?, ?)", [input.kind, title, query, note, now]); | |
| 31 | return ok({ id: Number(lastInsertRowid), kind: input.kind as Kind, title, query, note, createdAt: now }); | |
| 32 | } | |
| 33 | ||
| 34 | export function listSaved(db: Database): Saved[] { | |
| 35 | return db | |
| 36 | .query<{ id: number; kind: Kind; title: string; query: string; note: string; created_at: number }, []>( | |
| 37 | "SELECT id, kind, title, query, note, created_at FROM series_saved ORDER BY kind = 'pin' DESC, id DESC", | |
| 38 | ) | |
| 39 | .all() | |
| 40 | .map((r) => ({ id: r.id, kind: r.kind, title: r.title, query: r.query, note: r.note, createdAt: r.created_at })); | |
| 41 | } | |
| 42 | ||
| 43 | export function removeSaved(db: Database, id: number): boolean { | |
| 44 | return db.run("DELETE FROM series_saved WHERE id = ?", [id]).changes > 0; | |
| 45 | } |
src/series/store.ts added +48
| @@ -0,0 +1,48 @@ | ||
| 1 | /** | |
| 2 | * The samples `/metrics` carries, one tick a row set, in `series_sample` | |
| 3 | * (#3696): `record` writes a tick, `readRaw` reads one metric between two | |
| 4 | * instants. Six hours are kept and at most `TICK_MAX` samples a tick, so the | |
| 5 | * table is bounded whatever a label does. | |
| 6 | */ | |
| 7 | import type { Database } from "bun:sqlite"; | |
| 8 | import { quietly } from "../core/write_clock.ts"; | |
| 9 | import type { Point } from "./text.ts"; | |
| 10 | ||
| 11 | export const KEEP_MS = 6 * 3_600_000; | |
| 12 | export const TICK_MAX = 3000; | |
| 13 | export const PRUNE_BATCH = 6000; | |
| 14 | ||
| 15 | export type Raw = { at: number; labels: Record<string, string>; value: number }; | |
| 16 | ||
| 17 | /** | |
| 18 | * One tick's points at `now`, and anything past `KEEP_MS` dropped. A point past the cap is not | |
| 19 | * kept. | |
| 20 | */ | |
| 21 | export function record(db: Database, points: readonly Point[], now: number): number { | |
| 22 | const kept = points.slice(0, TICK_MAX); | |
| 23 | db.transaction(() => | |
| 24 | quietly(db, () => { | |
| 25 | const put = db.prepare("INSERT INTO series_sample (at, name, labels, value) VALUES (?, ?, ?, ?)"); | |
| 26 | for (const p of kept) put.run(now, p.name, JSON.stringify(p.labels), p.value); | |
HIGH (denial of service, a Never: the forge locks up). Every 30 s this runs synchronously on the main thread: up to 3,000 inserts, then a DELETE on |
||
| 27 | // Through the `at` index, a bounded batch a tick: a long gap is caught up over a few ticks, | |
| 28 | // never one long stall on the main thread. | |
| 29 | db.run("DELETE FROM series_sample WHERE rowid IN (SELECT rowid FROM series_sample WHERE at < ? LIMIT ?)", [now - KEEP_MS, PRUNE_BATCH]); | |
| 30 | }), | |
| 31 | )(); | |
| 32 | return kept.length; | |
| 33 | } | |
| 34 | ||
| 35 | /** Every sample of `name` in `[from, to]`, oldest first. */ | |
| 36 | export function readRaw(db: Database, name: string, from: number, to: number): Raw[] { | |
| 37 | return db | |
| 38 | .query<{ at: number; labels: string; value: number }, [string, number, number]>( | |
| 39 | "SELECT at, labels, value FROM series_sample WHERE name = ? AND at >= ? AND at <= ? ORDER BY at", | |
| 40 | ) | |
| 41 | .all(name, from, to) | |
| 42 | .map((r) => ({ at: r.at, labels: JSON.parse(r.labels) as Record<string, string>, value: r.value })); | |
| 43 | } | |
| 44 | ||
| 45 | /** The metric names held, sorted: what a query may start from. */ | |
| 46 | export function names(db: Database): string[] { | |
| 47 | return db.query<{ name: string }, []>("SELECT DISTINCT name FROM series_sample ORDER BY name").all().map((r) => r.name); | |
| 48 | } |
src/series/text.ts added +27
| @@ -0,0 +1,27 @@ | ||
| 1 | /** | |
| 2 | * Prometheus text exposition back into plain samples: `name{a="b"} 1.5` a | |
| 3 | * line. Comments and blank lines are skipped; a line that does not parse is | |
| 4 | * dropped, never guessed at. It reads what `metrics/openmetrics.ts` writes. | |
| 5 | */ | |
| 6 | ||
| 7 | export type Point = { name: string; labels: Record<string, string>; value: number }; | |
| 8 | ||
| 9 | const LINE = /^([a-zA-Z_:][a-zA-Z0-9_:]*)(\{(.*)\})?\s+(\S+)/; | |
| 10 | const PAIR = /([a-zA-Z_][a-zA-Z0-9_]*)="((?:[^"\\]|\\.)*)"/g; | |
| 11 | ||
| 12 | const unescape = (v: string): string => v.replace(/\\(n|\\|")/g, (_, c: string) => (c === "n" ? "\n" : c)); | |
| 13 | ||
| 14 | export function parseExposition(text: string): Point[] { | |
| 15 | const out: Point[] = []; | |
| 16 | for (const line of text.split("\n")) { | |
| 17 | if (line === "" || line.startsWith("#")) continue; | |
| 18 | const m = LINE.exec(line); | |
| 19 | if (m === null) continue; | |
| 20 | const value = m[4] === "+Inf" ? Infinity : Number(m[4]); | |
| 21 | if (!Number.isFinite(value)) continue; | |
| 22 | const labels: Record<string, string> = {}; | |
| 23 | for (const p of (m[3] ?? "").matchAll(PAIR)) labels[p[1]!] = unescape(p[2]!); | |
| 24 | out.push({ name: m[1]!, labels, value }); | |
| 25 | } | |
| 26 | return out; | |
| 27 | } |
src/series/view.ts added +66
| @@ -0,0 +1,66 @@ | ||
| 1 | /** | |
| 2 | * What /explore/series and its terminal screen both show (#3696): one | |
| 3 | * question in, plain data out — the series a query gives over a range, the | |
| 4 | * labels that explain a selected region, and the sentence when the query is | |
| 5 | * not one. The page and the screen draw this; neither decides it. | |
| 6 | */ | |
| 7 | import type { Database } from "bun:sqlite"; | |
| 8 | import { explain, type Cause } from "./explain.ts"; | |
| 9 | import { runQuery, STEPS_MAX, type Series } from "./query.ts"; | |
| 10 | import { names } from "./store.ts"; | |
| 11 | ||
| 12 | export const DEFAULT_QUERY = "sum by (pattern) (rate(forge_http_request_duration_seconds_count[5m]))"; | |
| 13 | export const RANGES_MIN = [15, 60, 360] as const; | |
| 14 | ||
| 15 | export type Ask = { query: string; minutes: number; from?: number; to?: number }; | |
| 16 | export type Answer = { | |
| 17 | query: string; | |
| 18 | minutes: number; | |
| 19 | from: number; | |
| 20 | to: number; | |
| 21 | stepMs: number; | |
| 22 | series: Series[]; | |
| 23 | error?: string; | |
| 24 | /** Set when a region was selected: its bounds and what differs inside it. */ | |
| 25 | selected?: { from: number; to: number; causes: Cause[] }; | |
| 26 | }; | |
| 27 | ||
| 28 | /** An address's parameters as an `Ask`: anything out of range falls to its default. */ | |
| 29 | export function askOf(p: URLSearchParams): Ask { | |
| 30 | const minutes = Number(p.get("range")); | |
| 31 | const num = (k: string): number | undefined => { | |
| 32 | const v = p.get(k); | |
| 33 | return v !== null && /^\d{1,15}$/.test(v) ? Number(v) : undefined; | |
| 34 | }; | |
| 35 | const ask: Ask = { query: (p.get("q") ?? "").trim() || DEFAULT_QUERY, minutes: (RANGES_MIN as readonly number[]).includes(minutes) ? minutes : 60 }; | |
| 36 | const from = num("from"); | |
| 37 | const to = num("to"); | |
| 38 | if (from !== undefined && to !== undefined && from < to) { | |
| 39 | ask.from = from; | |
| 40 | ask.to = to; | |
| 41 | } | |
| 42 | return ask; | |
| 43 | } | |
| 44 | ||
| 45 | export function answer(db: Database, ask: Ask, now: number): Answer { | |
| 46 | const span = ask.minutes * 60_000; | |
| 47 | const stepMs = Math.max(30_000, Math.ceil(span / (STEPS_MAX - 1) / 30_000) * 30_000); | |
| 48 | const base = { query: ask.query, minutes: ask.minutes, from: now - span, to: now, stepMs }; | |
| 49 | const ran = runQuery(db, ask.query, base); | |
| 50 | if (!ran.ok) return { ...base, series: [], error: ran.error }; | |
| 51 | const out: Answer = { ...base, series: ran.value }; | |
| 52 | if (ask.from !== undefined && ask.to !== undefined) out.selected = { from: ask.from, to: ask.to, causes: explain(ran.value, ask.from, ask.to) }; | |
| 53 | return out; | |
| 54 | } | |
| 55 | ||
| 56 | /** The metric names a query may start from. */ | |
| 57 | export const known = (db: Database): string[] => names(db); | |
| 58 | ||
| 59 | /** `a="b",c="d"`, or the word for a series with no labels. */ | |
| 60 | export const labelWords = (l: Record<string, string>): string => { | |
| 61 | const e = Object.entries(l); | |
| 62 | return e.length === 0 ? "(all)" : e.map(([k, v]) => `${k}="${v}"`).join(", "); | |
| 63 | }; | |
| 64 | ||
| 65 | /** A value as a few digits: whole when large, two places from 1, two figures below. */ | |
| 66 | export const figure = (v: number): string => (Math.abs(v) >= 100 ? v.toFixed(0) : Math.abs(v) >= 1 ? v.toFixed(2) : v.toPrecision(2)); |
src/tui/screens/series.ts added +192
| @@ -0,0 +1,192 @@ | ||
| 1 | /** | |
| 2 | * /explore/series in the terminal, the owner's (#3696): a query over the | |
| 3 | * forge's /metrics kept as a series, one row a series with its latest, peak and | |
| 4 | * a sparkline; and, when a region is selected, the label values that weigh more | |
| 5 | * inside it than outside — the rows the page draws, from `series/view.ts`. | |
| 6 | * Keys: `/` types a query, `r` cycles the range, `x` explains a region (minutes | |
| 7 | * ago, `10-5`), `p` pins the query, `s` saves it as a report with a note, `n` opens the next | |
| 8 | * pinned or saved one, `d` removes that one (after asking), | |
| 9 | * `j`/`k` scroll, `q` back. The gate is the page's (`canSeeMemory`). | |
| 10 | */ | |
| 11 | import { canSeeMemory } from "../../boards/memory.ts"; | |
| 12 | import { QUERY_MAX } from "../../series/parse.ts"; | |
| 13 | import { listSaved, removeSaved, save } from "../../series/saved.ts"; | |
| 14 | import { answer, DEFAULT_QUERY, figure as num, labelWords, RANGES_MIN, type Answer } from "../../series/view.ts"; | |
| 15 | import { spark } from "../../system/format.ts"; | |
| 16 | import type { Ctx, Screen } from "../app/app.ts"; | |
| 17 | import { binding } from "../app/keys.ts"; | |
| 18 | import type { Session } from "../session.ts"; | |
| 19 | import { style } from "../term/style.ts"; | |
| 20 | import { pad } from "../term/width.ts"; | |
| 21 | import { Scroll, confirmScreen, drawLines, hitScroll, later, promptScreen } from "./common.ts"; | |
| 22 | import type { PaletteEntry } from "./entries.ts"; | |
| 23 | ||
| 24 | const mayRead = (session: Session): boolean => canSeeMemory(session.user); | |
| 25 | const clock = (at: number) => new Date(at).toISOString().slice(11, 19); | |
| 26 | ||
| 27 | /** The answer as the lines the screen draws: the query, its series, then the selection's causes. */ | |
| 28 | export function seriesLines(a: Answer): string[] { | |
| 29 | const lines = [`${a.query} (last ${a.minutes} min, ${a.stepMs / 1000} s steps)`, ""]; | |
| 30 | if (a.error !== undefined) return [...lines, a.error]; | |
| 31 | if (a.series.length === 0) return [...lines, "No series answered in this range."]; | |
| 32 | lines.push(`${pad("Labels", 44)}${pad("Latest", 10, "right")}${pad("Peak", 10, "right")} Trend`); | |
| 33 | for (const s of a.series) { | |
| 34 | const v = s.points.map((p) => p.value); | |
| 35 | lines.push(`${pad(labelWords(s.labels), 44)}${pad(num(v[v.length - 1]!), 10, "right")}${pad(num(Math.max(...v)), 10, "right")} ${spark(v)}`); | |
| 36 | } | |
| 37 | const sel = a.selected; | |
| 38 | if (sel !== undefined) { | |
| 39 | lines.push("", `Why ${clock(sel.from)}–${clock(sel.to)} UTC differs`); | |
| 40 | if (sel.causes.length === 0) lines.push("Nothing stands out."); | |
| 41 | for (const c of sel.causes) lines.push(`${pad(`${c.label}="${c.value}"`, 44)}${pad(`${Math.round(c.inside * 100)}%`, 10, "right")}${pad(`${Math.round(c.outside * 100)}%`, 10, "right")} ${c.lift > 0 ? "+" : "−"}${Math.round(Math.abs(c.lift) * 100)}`); | |
| 42 | } | |
| 43 | return lines; | |
| 44 | } | |
| 45 | ||
| 46 | export function seriesScreen(session: Session, ctx: Ctx): Screen { | |
| 47 | const scroll = new Scroll(); | |
| 48 | let query = DEFAULT_QUERY; | |
| 49 | let minutes = 60; | |
| 50 | let region: { from: number; to: number } | undefined; | |
| 51 | let next = 0; | |
| 52 | let open: { id: number; title: string } | undefined; | |
| 53 | const read = () => answer(session.app.db, { query, minutes, ...(region ?? {}) }, Date.now()); | |
| 54 | let held = read(); | |
| 55 | const again = () => { | |
| 56 | held = read(); | |
| 57 | }; | |
| 58 | const ask = (parent: Screen, o: Parameters<typeof promptScreen>[2]) => ctx.push(promptScreen(ctx, parent, o)); | |
| 59 | const screen: Screen = { | |
| 60 | title: "Explore series", | |
| 61 | keys: [binding(["/"], "query"), binding(["r"], "range"), binding(["x"], "explain"), binding(["p"], "pin"), binding(["s"], "save report"), binding(["n"], "next saved"), binding(["d"], "remove saved"), binding(["j", "k"], "scroll"), binding(["esc", "q"], "back")], | |
| 62 | render(area, s) { | |
| 63 | const c = ctx.theme.c; | |
| 64 | const lines = seriesLines(held); | |
| 65 | drawLines(s, area, c, scroll, lines.map((text, i) => [{ text, style: style(i === 0 ? c.fg : c.mutedFg, c.bg) }])); | |
| 66 | hitScroll(ctx, area, scroll, lines.length); | |
| 67 | }, | |
| 68 | key(e) { | |
| 69 | if (scroll.key(e, seriesLines(held).length)) return true; | |
| 70 | if (e.key === "esc" || e.key === "q") { | |
| 71 | ctx.pop(); | |
| 72 | return true; | |
| 73 | } | |
| 74 | if (e.key === "r") { | |
| 75 | minutes = RANGES_MIN[(RANGES_MIN.indexOf(minutes as 15) + 1) % RANGES_MIN.length]!; | |
| 76 | region = undefined; | |
| 77 | again(); | |
| 78 | return true; | |
| 79 | } | |
| 80 | if (e.key === "/") { | |
| 81 | ask(screen, { | |
| 82 | title: "Query", | |
| 83 | label: "rate(name[5m]), sum by (label) (…), topk(5, …)", | |
| 84 | value: query, | |
| 85 | onSubmit: (v) => { | |
| 86 | if (v === "" || v.length > QUERY_MAX) return `a query is 1 to ${QUERY_MAX} characters`; | |
| 87 | query = v; | |
| 88 | region = undefined; | |
| 89 | again(); | |
| 90 | return undefined; | |
| 91 | }, | |
| 92 | }); | |
| 93 | return true; | |
| 94 | } | |
| 95 | if (e.key === "x") { | |
| 96 | ask(screen, { | |
| 97 | title: "Explain a region", | |
| 98 | label: "minutes ago, from-to (10-5)", | |
| 99 | hint: "Which label values weigh more inside it than outside", | |
| 100 | onSubmit: (v) => { | |
| 101 | const m = /^(\d{1,4})\s*-\s*(\d{1,4})$/.exec(v); | |
| 102 | if (m === null || Number(m[1]) <= Number(m[2]) || Number(m[1]) > minutes) return `two minutes-ago numbers, the first larger, within ${minutes}`; | |
| 103 | region = { from: Date.now() - Number(m[1]) * 60_000, to: Date.now() - Number(m[2]) * 60_000 }; | |
| 104 | again(); | |
| 105 | return undefined; | |
| 106 | }, | |
| 107 | }); | |
| 108 | return true; | |
| 109 | } | |
| 110 | if (e.key === "p") { | |
| 111 | ask(screen, { | |
| 112 | title: "Pin this query", | |
| 113 | label: "Title", | |
| 114 | onSubmit: (v) => { | |
| 115 | const r = save(session.app.db, { kind: "pin", title: v, query }, Date.now()); | |
| 116 | if (!r.ok) return r.error; | |
| 117 | ctx.toast("Pinned."); | |
| 118 | return undefined; | |
| 119 | }, | |
| 120 | }); | |
| 121 | return true; | |
| 122 | } | |
| 123 | if (e.key === "s") { | |
| 124 | ask(screen, { | |
| 125 | title: "Save as a report", | |
| 126 | label: "Title", | |
| 127 | onSubmit: (title) => { | |
| 128 | if (title.trim() === "") return "a title is 1 to 80 characters"; | |
| 129 | return later(ctx, () => | |
| 130 | promptScreen(ctx, screen, { | |
| 131 | title: "Report note", | |
| 132 | label: "Note (what this shows; may be empty)", | |
| 133 | onSubmit: (note) => { | |
| 134 | const r = save(session.app.db, { kind: "report", title, query, note }, Date.now()); | |
| 135 | if (!r.ok) return r.error; | |
| 136 | ctx.toast("Saved as a report."); | |
| 137 | return undefined; | |
| 138 | }, | |
| 139 | }), | |
| 140 | ); | |
| 141 | }, | |
| 142 | }); | |
| 143 | return true; | |
| 144 | } | |
| 145 | if (e.key === "d") { | |
| 146 | if (open === undefined) ctx.toast("Open a saved query with n first."); | |
| 147 | else { | |
| 148 | const gone = open; | |
| 149 | ctx.push( | |
| 150 | confirmScreen(ctx, screen, { | |
| 151 | title: "Remove saved query", | |
| 152 | body: [`Remove "${gone.title}"? The samples are kept.`], | |
| 153 | actions: [{ label: "Remove", variant: "danger" }, { label: "Keep" }], | |
| 154 | yesNo: true, | |
| 155 | onChoose: (i) => { | |
| 156 | if (i !== 0) return; | |
| 157 | ctx.toast(removeSaved(session.app.db, gone.id) ? "Removed." : "Already gone."); | |
| 158 | open = undefined; | |
| 159 | }, | |
| 160 | }), | |
| 161 | ); | |
| 162 | } | |
| 163 | return true; | |
| 164 | } | |
| 165 | if (e.key === "n") { | |
| 166 | const rows = listSaved(session.app.db); | |
| 167 | if (rows.length === 0) ctx.toast("Nothing pinned or saved yet."); | |
| 168 | else { | |
| 169 | const row = rows[next % rows.length]!; | |
| 170 | query = row.query; | |
| 171 | open = { id: row.id, title: row.title }; | |
| 172 | next++; | |
| 173 | region = undefined; | |
| 174 | again(); | |
| 175 | } | |
| 176 | return true; | |
| 177 | } | |
| 178 | return false; | |
| 179 | }, | |
| 180 | }; | |
| 181 | return screen; | |
| 182 | } | |
| 183 | ||
| 184 | export const entry: PaletteEntry = { | |
| 185 | rank: 135, | |
| 186 | id: "series", | |
| 187 | title: "Explore series", | |
| 188 | hint: "query /metrics over time, explain a region", | |
| 189 | after: ["stalls", "system"], | |
| 190 | offered: mayRead, | |
| 191 | run: (session, ctx) => ctx.push(seriesScreen(session, ctx)), | |
| 192 | }; |
src/tui/screens/system.ts +3 −1
| @@ -62,6 +62,7 @@ import { slowestRoutes } from "../../perf/history.ts"; | ||
| 62 | 62 | import { budgetFor } from "../../perf/budgets.ts"; |
| 63 | 63 | import { knownPatterns } from "../../http/server.ts"; |
| 64 | 64 | import type { PaletteEntry } from "./entries.ts"; |
| 65 | import { seriesScreen } from "./series.ts"; | |
| 65 | 66 | import { abstractionsScreen } from "./abstractions.ts"; |
| 66 | 67 | import { mayReadAtlas } from "../../actions/abstractions.ts"; |
| 67 | 68 | import { shapeWords } from "../../engine/mode.ts"; |
| @@ -441,7 +442,7 @@ export function systemScreen(ctx: Ctx, lines: readonly string[], session: Sessio | ||
| 441 | 442 | }; |
| 442 | 443 | const screen: Screen = { |
| 443 | 444 | title: "System", |
| 444 | keys: [binding(["h"], "window"), ...(reads ? [binding(["d"], "database size")] : []), ...(mayReadAtlas(session?.user) ? [binding(["a"], "tables")] : []), ...(offered ? [binding(["g"], "grant or take back telemetry")] : []), binding(["enter", "esc", "q"], "close")], | |
| 445 | keys: [binding(["h"], "window"), ...(reads ? [binding(["d"], "database size")] : []), ...(mayReadAtlas(session?.user) ? [binding(["a"], "tables")] : []), ...(offered ? [binding(["g"], "grant or take back telemetry")] : []), ...(canSeeMemory(session.user) ? [binding(["x"], "explore series")] : []), binding(["enter", "esc", "q"], "close")], | |
| 445 | 446 | render(area, s) { |
| 446 | 447 | const features = featuresLines(session); |
| 447 | 448 | // Never waits on the walk: the last measurement, a new one started behind it when stale. |
| @@ -481,6 +482,7 @@ export function systemScreen(ctx: Ctx, lines: readonly string[], session: Sessio | ||
| 481 | 482 | span = (span + 1) % WINDOWS.length; |
| 482 | 483 | history = historyLines(session, WINDOWS[span]!); |
| 483 | 484 | } else if (e.key === "g") askGrant(); |
| 485 | else if (e.key === "x" && canSeeMemory(session.user)) later(ctx, () => seriesScreen(session, ctx)); | |
| 484 | 486 | else if (e.key === "d" && reads) later(ctx, () => dbSizeScreen(session, ctx)); |
| 485 | 487 | else if (e.key === "a" && mayReadAtlas(session.user)) later(ctx, () => abstractionsScreen(session, ctx)); |
| 486 | 488 | else if (e.key === "enter" || e.key === "esc" || e.key === "q") ctx.pop(); |
src/web/empty_words.ts +1
src/web/pages/home_flow.ts +2
| @@ -15,6 +15,7 @@ | ||
| 15 | 15 | * version without being drawn. The page is a static picture with scripts off. |
| 16 | 16 | */ |
| 17 | 17 | |
| 18 | import { pinnedSeries } from "./series_pins.ts"; | |
| 18 | 19 | import { forkFlowsLine } from "../studio/fork_line.ts"; |
| 19 | 20 | import { firstWrong, firstWrongLine, readFacts } from "../first_wrong.ts"; |
| 20 | 21 | import { focusLine } from "../studio/held.ts"; |
| @@ -593,6 +594,7 @@ export async function homeFlowPage(ctx: Ctx, known?: { readonly spawned: Awaited | ||
| 593 | 594 | ${before} |
| 594 | 595 | ${strip} |
| 595 | 596 | ${deskStrip(ctx.app.db, readableNotes(ctx.app, ctx.auth.user))} |
| 597 | ${pinnedSeries(ctx, now)} | |
| 596 | 598 | ${after} |
| 597 | 599 | ${wide ? figuresSection(picture, now) : null} |
| 598 | 600 | ${forges} |
src/web/pages/series.ts added +137
| @@ -0,0 +1,137 @@ | ||
| 1 | /** | |
| 2 | * /explore/series, the owner's (#3696): a query over the forge's own /metrics | |
| 3 | * kept as a series (`series/`), a chart above and a table below. A point on | |
| 4 | * the chart selects the region around it ("explain this"), and the page says | |
| 5 | * which label values weigh more inside it than outside; a query can be pinned | |
| 6 | * (kept at the top) or saved as a report with a note. The gate is /system's: a | |
| 7 | * forge admin who is a person. Everything lives in the address (`q`, | |
| 8 | * `range`, `from`, `to`), so a view is a link; the only script is none. | |
| 9 | */ | |
| 10 | import { canSeeMemory } from "../../boards/memory.ts"; | |
| 11 | import type { Ctx } from "../../http/context.ts"; | |
| 12 | import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts"; | |
| 13 | import { listSaved, removeSaved, save, NOTE_MAX, TITLE_MAX, type Saved } from "../../series/saved.ts"; | |
| 14 | import { answer, askOf, figure as num, known, labelWords, RANGES_MIN, type Answer } from "../../series/view.ts"; | |
| 15 | import { QUERY_MAX } from "../../series/parse.ts"; | |
| 16 | import { chartBox, btn, disclosure, empty, field, row as rowOf } from "../ui.ts"; | |
| 17 | import { forbiddenPage, notFoundPage, pageHead, signInFirst } from "../chrome.ts"; | |
| 18 | import { readForm } from "../form.ts"; | |
| 19 | import { html, type Html } from "../html.ts"; | |
| 20 | import { flashTo, page } from "../layout.ts"; | |
| 21 | import { emptyList } from "../empty_words.ts"; | |
| 22 | ||
| 23 | const CHARTED = 6; | |
| 24 | /** A headed section, not a box: the rows and the chart inside it carry their own lines. */ | |
| 25 | const section = (body: Html, o: { head: string; id?: string }): Html => | |
| 26 | html`<section class="stack mt"${o.id !== undefined ? html` id="${o.id}"` : null} aria-label="${o.head}"><h2>${o.head}</h2>${body}</section>`; | |
| 27 | const clock = (at: number) => new Date(at).toISOString().slice(11, 19); | |
| 28 | ||
| 29 | /** The address of a view: the query, its range, and a selected region when there is one. */ | |
| 30 | export function seriesHref(q: string, minutes: number, region?: { from: number; to: number }): string { | |
| 31 | const p = new URLSearchParams({ q, range: String(minutes) }); | |
| 32 | if (region) { | |
| 33 | p.set("from", String(region.from)); | |
| 34 | p.set("to", String(region.to)); | |
| 35 | } | |
| 36 | return `/explore/series?${p.toString()}`; | |
| 37 | } | |
| 38 | ||
| 39 | function chart(a: Answer): Html { | |
| 40 | const shown = a.series.slice(0, CHARTED); | |
| 41 | const cells = shown.flatMap((s) => | |
| 42 | s.points.map((p) => ({ | |
| 43 | label: clock(p.at), | |
| 44 | value: p.value, | |
| 45 | series: labelWords(s.labels), | |
| 46 | href: seriesHref(a.query, a.minutes, { from: p.at - 3 * a.stepMs, to: p.at + 3 * a.stepMs }), | |
| 47 | })), | |
| 48 | ); | |
| 49 | return chartBox("line", cells, `${a.query} over the last ${a.minutes} minutes`); | |
| 50 | } | |
| 51 | ||
| 52 | function table(a: Answer): Html { | |
| 53 | return html`<div class="table-scroll"><table class="table" aria-label="Series"> | |
| 54 | <thead><tr><th scope="col">Labels</th><th scope="col" class="num">Latest</th><th scope="col" class="num">Peak</th><th scope="col" class="num">Points</th></tr></thead> | |
| 55 | <tbody>${a.series.map((s) => html`<tr><td class="mono">${labelWords(s.labels)}</td><td class="num mono">${num(s.points[s.points.length - 1]!.value)}</td><td class="num mono">${num(Math.max(...s.points.map((p) => p.value)))}</td><td class="num mono">${s.points.length}</td></tr>`)}</tbody> | |
| 56 | </table></div>`; | |
| 57 | } | |
| 58 | ||
| 59 | function explained(a: Answer): Html | null { | |
| 60 | const sel = a.selected; | |
| 61 | if (sel === undefined) return null; | |
| 62 | const title = `Why ${clock(sel.from)}–${clock(sel.to)} UTC differs`; | |
| 63 | const clear = btn("Clear selection", { href: seriesHref(a.query, a.minutes) }); | |
| 64 | if (sel.causes.length === 0) return section(html`<p class="muted">Nothing stands out: no label value weighs 5 points more inside the selection than outside it, or the selection holds the whole range.</p>${clear}`, { head: title, id: "explain" }); | |
| 65 | return section(html`<div class="table-scroll"><table class="table" aria-label="What differs inside the selection"> | |
| 66 | <thead><tr><th scope="col">Label</th><th scope="col" class="num">Inside</th><th scope="col" class="num">Outside</th><th scope="col" class="num">Lift</th></tr></thead> | |
| 67 | <tbody>${sel.causes.map((c) => html`<tr><td class="mono">${c.label}="${c.value}"</td><td class="num mono">${Math.round(c.inside * 100)}%</td><td class="num mono">${Math.round(c.outside * 100)}%</td><td class="num mono">${c.lift > 0 ? "+" : "−"}${Math.round(Math.abs(c.lift) * 100)}</td></tr>`)}</tbody> | |
| 68 | </table></div>${clear}`, { head: title, id: "explain" }); | |
| 69 | } | |
| 70 | ||
| 71 | function saveForm(a: Answer): Html { | |
| 72 | return html`<form method="post" action="/explore/series/save" class="stack"> | |
| 73 | <input type="hidden" name="q" value="${a.query}"> | |
| 74 | ${field({ name: "title", label: "Title", maxlength: TITLE_MAX, required: true })} | |
| 75 | ${field({ name: "note", label: "Note (a report keeps it beside the query)", type: "textarea", rows: 2, maxlength: NOTE_MAX })} | |
| 76 | <div class="row"><button class="btn" type="submit" name="kind" value="pin">Pin</button><button class="btn" type="submit" name="kind" value="report">Save as report</button></div> | |
| 77 | </form>`; | |
| 78 | } | |
| 79 | ||
| 80 | function savedList(rows: readonly Saved[], minutes: number): Html { | |
| 81 | if (rows.length === 0) return empty({ title: "Nothing pinned or saved", note: "Run a query and pin it, or save it as a report with a note." }); | |
| 82 | return html`${rows.map((r) => | |
| 83 | rowOf({ | |
| 84 | href: seriesHref(r.query, minutes), | |
| 85 | title: `${r.kind === "pin" ? "Pinned · " : ""}${r.title}`, | |
| 86 | meta: html`<code>${r.query}</code>${r.note === "" ? null : html` · ${r.note}`}`, | |
| 87 | after: html`<form method="post" action="/explore/series/remove"><input type="hidden" name="id" value="${String(r.id)}"><button class="btn" data-size="sm" type="submit" aria-label="Remove ${r.title}">Remove</button></form>`, | |
| 88 | }), | |
| 89 | )}`; | |
| 90 | } | |
| 91 | ||
| 92 | export function seriesPage(ctx: Ctx): Response { | |
| 93 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); | |
| 94 | if (!ctx.auth.user) return signInFirst(ctx); | |
| 95 | if (!canSeeMemory(ctx.auth.user)) return notFoundPage(ctx); | |
| 96 | const ask = askOf(ctx.url.searchParams); | |
| 97 | const a = answer(ctx.app.db, ask, Date.now()); | |
| 98 | const names = known(ctx.app.db); | |
| 99 | const form = html`<form method="get" action="/explore/series" class="stack"> | |
| 100 | ${field({ name: "q", label: "Query", value: a.query, mono: true, maxlength: QUERY_MAX, spellcheck: false, ...(a.error ? { error: a.error } : {}) })} | |
| 101 | ${field({ name: "range", label: "Range", type: "select", options: RANGES_MIN.map((m) => ({ value: String(m), label: m < 60 ? `${m} minutes` : `${m / 60} hour${m > 60 ? "s" : ""}`, selected: m === a.minutes })) })} | |
| 102 | ${btn("Run", { type: "submit" })} | |
| 103 | </form>`; | |
| 104 | const body = html`${pageHead("Explore series", { sub: "The forge's /metrics every 30 seconds: query it, click a point to ask why. Syntax is in the how-to." })} | |
| 105 | ${form} | |
| 106 | ${a.error !== undefined | |
| 107 | ? null | |
| 108 | : a.series.length === 0 | |
| 109 | ? emptyList("seriesAnswered", { note: names.length === 0 ? "The first sample is kept within 30 seconds of boot." : "No sample matches in this range. Try a name from the list below." }) | |
| 110 | : html`${chart(a)}${explained(a)}${section(table(a), { head: "Series" })}${section(saveForm(a), { head: "Keep this query" })}`} | |
Principles 6 and 7 (rows over boxes, few borders): the page is five boxed cards (Query, Chart, Series, Keep this query, Pinned and saved) plus a boxed explain card. The series table, the explanation and the saved list are rows, so lay them out as headed sections with hairlines where each ends, not a card around each. Principle 2 is met by the chart and the real rows, so keep those. |
||
| 111 | ${section(savedList(listSaved(ctx.app.db), a.minutes), { head: "Pinned and saved" })} | |
| 112 | ${disclosure(`Metric names (${names.length})`, html`<p class="mono small">${names.join(" ")}</p>`, { small: true })}`; | |
| 113 | return timePhase(ctx.request, "render", () => page({ ctx, title: "Explore series", body })); | |
Principle 1 (nothing explains itself twice): the sub line, this syntax paragraph, the disclosure of metric names and docs/features/series.md all explain the query language. Keep the one sentence under the title and move the grammar to the how-to, or show it only as the field's placeholder or hint. |
||
| 114 | } | |
| 115 | ||
| 116 | /** POST /explore/series/save: a pin or a report. */ | |
| 117 | export async function seriesSave(ctx: Ctx): Promise<Response> { | |
| 118 | if (!ctx.auth.user) return signInFirst(ctx); | |
| 119 | const form = await readForm(ctx, "admin"); | |
| 120 | if (form instanceof Response) return form; | |
| 121 | if (!canSeeMemory(ctx.auth.user)) return ctx.auth.user.kind === "agent" ? forbiddenPage(ctx, "Saving a query is a person's.") : notFoundPage(ctx); | |
| 122 | const text = (k: string) => (typeof form.get(k) === "string" ? (form.get(k) as string) : ""); | |
| 123 | const saved = save(ctx.app.db, { kind: text("kind"), title: text("title"), query: text("q"), note: text("note") }, Date.now()); | |
| 124 | if (!saved.ok) return flashTo(ctx, seriesHref(text("q") || "", 60), { tone: "danger", message: saved.error }); | |
| 125 | return flashTo(ctx, "/explore/series", { message: saved.value.kind === "pin" ? "Pinned." : "Saved as a report." }); | |
| 126 | } | |
| 127 | ||
| 128 | /** POST /explore/series/remove: forget one saved query. */ | |
| 129 | export async function seriesRemove(ctx: Ctx): Promise<Response> { | |
| 130 | if (!ctx.auth.user) return signInFirst(ctx); | |
| 131 | const form = await readForm(ctx, "admin"); | |
| 132 | if (form instanceof Response) return form; | |
| 133 | if (!canSeeMemory(ctx.auth.user)) return ctx.auth.user.kind === "agent" ? forbiddenPage(ctx, "Removing a saved query is a person's.") : notFoundPage(ctx); | |
| 134 | const id = Number(form.get("id")); | |
| 135 | if (!Number.isSafeInteger(id) || !removeSaved(ctx.app.db, id)) return flashTo(ctx, "/explore/series", { tone: "danger", message: "No such saved query." }); | |
| 136 | return flashTo(ctx, "/explore/series", { message: "Removed." }); | |
| 137 | } |
src/web/pages/series_pins.ts added +30
| @@ -0,0 +1,30 @@ | ||
| 1 | /** | |
| 2 | * The home's pinned series (#3696): one row a pin, its latest value beside | |
| 3 | * the title, a link to the query on /explore/series. Drawn for the people who | |
| 4 | * may open that page (`canSeeMemory`) and only when something is pinned. | |
| 5 | */ | |
| 6 | import { canSeeMemory } from "../../boards/memory.ts"; | |
| 7 | import { pinsNow } from "../../series/pins.ts"; | |
| 8 | import { DEFAULT_QUERY, figure } from "../../series/view.ts"; | |
| 9 | import type { Ctx } from "../../http/context.ts"; | |
| 10 | import { html, type Html } from "../html.ts"; | |
| 11 | import { row } from "../ui.ts"; | |
| 12 | import { seriesHref } from "./series.ts"; | |
| 13 | ||
| 14 | export function pinnedSeries(ctx: Ctx, now: number): Html | null { | |
| 15 | const user = ctx.auth.user; | |
| 16 | if (user === undefined || !canSeeMemory(user)) return null; | |
| 17 | const pins = pinsNow(ctx.app.db, now); | |
| 18 | if (pins.length === 0) return null; | |
| 19 | return html`<section class="stack" id="pinned-series" aria-label="Pinned series"> | |
| 20 | <h2>Pinned series</h2> | |
| 21 | ${pins.map((p) => | |
| 22 | row({ | |
| 23 | href: seriesHref(p.pin.query || DEFAULT_QUERY, 60), | |
| 24 | title: p.pin.title, | |
| 25 | meta: html`<code>${p.pin.query}</code>`, | |
| 26 | after: html`<span class="mono">${p.latest === undefined ? "no data" : figure(p.latest)}${p.series > 1 ? html` <span class="muted small">of ${String(p.series)} series</span>` : null}</span>`, | |
| 27 | }), | |
| 28 | )} | |
| 29 | </section>`; | |
| 30 | } |
src/web/studio/explore.ts +2
| @@ -37,6 +37,7 @@ import { | ||
| 37 | 37 | type ExploreRow, |
| 38 | 38 | } from "../../actions/explore.ts"; |
| 39 | 39 | import { drawChart } from "../../boards/chart.ts"; |
| 40 | import { canSeeMemory } from "../../boards/memory.ts"; | |
| 40 | 41 | import { MAX_METRIC_TEXT, MAX_TABLE } from "../../boards/query.ts"; |
| 41 | 42 | import { exploreThumbs } from "../../looks/explore_pictures.ts"; |
| 42 | 43 | import { frontWeights, type FrontWeights } from "../../core/front.ts"; |
| @@ -369,6 +370,7 @@ export async function explorePage(ctx: Ctx): Promise<Response> { | ||
| 369 | 370 | sub: query.kind === "person" ? PEOPLE_ORDER_WORDS : "Public apps and their builders, ranked by use, forks, deployments and recency.", |
| 370 | 371 | })} |
| 371 | 372 | ${!mayQueryMetric(ctx.auth.user) ? html`` : metricBox(metricText, metric)} |
| 373 | ${ctx.auth.user !== undefined && canSeeMemory(ctx.auth.user) ? html`<p class="small mb" data-series-link><a href="/explore/series">Series over time</a></p>` : html``} | |
| 372 | 374 | <div class="bar mb" data-filter-line> |
| 373 | 375 | <form method="get" action="/explore" class="bar"> |
| 374 | 376 | <input |
test/data-browser.test.ts +2
| @@ -64,6 +64,8 @@ const AUDITED_CLEAR: string[] = [ | ||
| 64 | 64 | "run.check_detail", |
| 65 | 65 | // When a secret start was last written: a timestamp, not the value. |
| 66 | 66 | "secret_start.value_updated_at", |
| 67 | // A /metrics sample kept over time: a REAL number, never text (#3696). | |
| 68 | "series_sample.value", | |
| 67 | 69 | "subscription.resting_said", |
| 68 | 70 | // A connection's last test, in words: what answered, never a key (core/connections.ts). |
| 69 | 71 | "subscription.test_said", |
test/empty-notes.test.ts +1
test/job-slices.test.ts +1
| @@ -266,6 +266,7 @@ function jobs(): Record<string, () => unknown> { | ||
| 266 | 266 | * on. |
| 267 | 267 | */ |
| 268 | 268 | const UNTIMED: Record<string, string> = { |
| 269 | "series-sampler": "every 30 s: one /metrics render and one batched insert (series/store.ts record), bounded by the rows it keeps; series-explore.test.ts drives tick directly", | |
| 269 | 270 | "machine-beats": "a 15 s timer (spawn/machine_beats.ts) whose beat only starts an async import and the machines' asks; its synchronous slice is the call that starts them; machine-load.test.ts drives sampleBeats and placeNew directly", |
| 270 | 271 | "osv-mirror": "hourly: fetches advisories for the pins the forge holds from api.osv.dev, then files fix issues; network and git reads off the loop (security/duty.ts, fix_issues.ts); security-osv.test.ts drives both", |
| 271 | 272 | "config-poll": "a short timer that re-reads one small row per scope and fires listeners only when another process changed it (core/config.ts start/refresh); config-store.test.ts drives a change from a second handle", |
test/keymap-terminal.test.ts +1
| @@ -51,6 +51,7 @@ const OWN_R: Record<string, string> = { | ||
| 51 | 51 | "src/tui/screens/queuegrowth.ts": "resume past the ceiling", |
| 52 | 52 | "src/tui/screens/resilience.ts": "run a restore drill", |
| 53 | 53 | "src/tui/screens/schedules.ts": "run now", |
| 54 | "src/tui/screens/series.ts": "range", | |
| 54 | 55 | "src/tui/screens/stalled.ts": "unblock", |
| 55 | 56 | "src/tui/screens/talk_chats.ts": "rename", |
| 56 | 57 | "src/tui/screens/variants.ts": "run a branch", |
test/palette-roster.test.ts +1
| @@ -146,6 +146,7 @@ test("a site-admin person is offered the whole roster", () => { | ||
| 146 | 146 | ["bottleneck", "Where the bottleneck is", "what limits the forge, what the host is tuned to, what changed"], |
| 147 | 147 | ["health-voice", "Health — spoken", "how the forge is, in two plain sentences"], |
| 148 | 148 | ["stalls", "Main-thread stalls", "the last hour's stall ms by route"], |
| 149 | ["series", "Explore series", "query /metrics over time, explain a region"], | |
| 149 | 150 | ["footing", "What the forge stands on", "each piece on another machine, in the order it would break the forge"], |
| 150 | 151 | ["design", "Design: the forge's theme", "colours and scales, the AA verdict; publish or revert"], |
| 151 | 152 | ["maintenanceweek", "Maintenance, last 7 days", "what each maintenance worker found and did this week"], |
test/series-explore.test.ts added +286
| @@ -0,0 +1,286 @@ | ||
| 1 | // /explore/series (#3696): a query over a fixture returns the expected series, a selection explains | |
| 2 | // a seeded outlier, a saved query must parse, and the page is the owner's. | |
| 3 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 4 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 5 | import { tmpdir } from "node:os"; | |
| 6 | import { join } from "node:path"; | |
| 7 | import { createApp, type App } from "../src/app.ts"; | |
| 8 | import { createSession } from "../src/core/sessions.ts"; | |
| 9 | import { createUser } from "../src/core/users.ts"; | |
| 10 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 11 | import { parseQuery } from "../src/series/parse.ts"; | |
| 12 | import { explain } from "../src/series/explain.ts"; | |
| 13 | import { runQuery } from "../src/series/query.ts"; | |
| 14 | import { listSaved, save } from "../src/series/saved.ts"; | |
| 15 | import { KEEP_MS, PRUNE_BATCH, record, TICK_MAX } from "../src/series/store.ts"; | |
| 16 | import { parseExposition } from "../src/series/text.ts"; | |
| 17 | import { answer, askOf } from "../src/series/view.ts"; | |
| 18 | import { seedAdmin } from "./helpers/admin.ts"; | |
| 19 | ||
| 20 | const T0 = 1_800_000_000_000; | |
| 21 | const STEP = 30_000; | |
| 22 | let dir: string; | |
| 23 | let app: App; | |
| 24 | let servers: Servers; | |
| 25 | let base: string; | |
| 26 | let adminCookie: string; | |
| 27 | let memberCookie: string; | |
| 28 | ||
| 29 | /** | |
| 30 | * Ten minutes of a request counter: /a climbs 1/s throughout, /b 1/s, then /c 20/s only from minute | |
| 31 | * 6 to 8 — the seeded outlier. | |
| 32 | */ | |
| 33 | function seed(): void { | |
| 34 | let a = 0, b = 0, c = 0; | |
| 35 | for (let i = 0; i <= 20; i++) { | |
| 36 | const at = T0 + i * STEP; | |
| 37 | const spike = i >= 12 && i <= 16; | |
| 38 | record(app.db, [ | |
| 39 | { name: "reqs_total", labels: { pattern: "/a", method: "GET" }, value: a }, | |
| 40 | { name: "reqs_total", labels: { pattern: "/b", method: "GET" }, value: b }, | |
| 41 | { name: "reqs_total", labels: { pattern: "/c", method: "POST" }, value: c }, | |
| 42 | { name: "up", labels: {}, value: 1 }, | |
| 43 | ], at); | |
| 44 | a += 30; b += 30; c += spike ? 600 : 0; | |
| 45 | } | |
| 46 | } | |
| 47 | const W = { from: T0, to: T0 + 20 * STEP, stepMs: STEP }; | |
| 48 | ||
| 49 | beforeAll(async () => { | |
| 50 | dir = await mkdtemp(join(tmpdir(), "forge-series-")); | |
| 51 | app = createApp({ dataDir: dir, port: 0 }); | |
| 52 | servers = await serve(app); | |
| 53 | base = servers.url; | |
| 54 | const root = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "a-good-passphrase" }); | |
| 55 | if (!root.ok) throw new Error(root.error); | |
| 56 | adminCookie = `forge_session=${createSession(app.db, root.value.id).token}`; | |
| 57 | const bob = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" }); | |
| 58 | if (!bob.ok) throw new Error(bob.error); | |
| 59 | memberCookie = `forge_session=${createSession(app.db, bob.value.id).token}`; | |
| 60 | seed(); | |
| 61 | }); | |
| 62 | afterAll(async () => { | |
| 63 | servers.stop(); | |
| 64 | await rm(dir, { recursive: true, force: true }); | |
| 65 | }); | |
| 66 | ||
| 67 | describe("the text and the store", () => { | |
| 68 | test("exposition lines become points; comments, +Inf and junk are dropped; escapes come back", () => { | |
| 69 | const pts = parseExposition('# HELP x y\nx_total{a="q\\"z",b="1"} 2.5\nup 1\nbad line\nh_bucket{le="+Inf"} +Inf\n'); | |
| 70 | expect(pts).toEqual([ | |
| 71 | { name: "x_total", labels: { a: 'q"z', b: "1" }, value: 2.5 }, | |
| 72 | { name: "up", labels: {}, value: 1 }, | |
| 73 | ]); | |
| 74 | }); | |
| 75 | ||
| 76 | test("a tick keeps at most TICK_MAX points and drops what is older than the keep window", () => { | |
| 77 | const big = Array.from({ length: TICK_MAX + 5 }, (_, i) => ({ name: "m", labels: { i: String(i) }, value: 1 })); | |
| 78 | expect(record(app.db, big, T0 + KEEP_MS * 3)).toBe(TICK_MAX); | |
| 79 | expect(app.db.query("SELECT count(*) AS n FROM series_sample WHERE at < ?").get(T0 + KEEP_MS * 3 - KEEP_MS)).toEqual({ n: 0 }); | |
| 80 | seed(); | |
| 81 | }); | |
| 82 | }); | |
| 83 | ||
| 84 | describe("the prune", () => { | |
| 85 | test("it goes through an index on `at` and drops a bounded batch a tick", () => { | |
| 86 | const plan = app.db.query("EXPLAIN QUERY PLAN SELECT rowid FROM series_sample WHERE at < ? LIMIT 1").all(0).map((r) => JSON.stringify(r)).join(" "); | |
| 87 | expect(plan).toContain("series_sample_at"); | |
| 88 | const old = T0 - KEEP_MS * 4; | |
| 89 | app.db.transaction(() => { | |
| 90 | for (let i = 0; i < PRUNE_BATCH + 10; i++) app.db.run("INSERT INTO series_sample (at, name, labels, value) VALUES (?, 'old', '{}', 1)", [old]); | |
| 91 | })(); | |
| 92 | record(app.db, [], T0 + KEEP_MS * 3); | |
| 93 | expect(app.db.query<{ n: number }, []>("SELECT count(*) AS n FROM series_sample WHERE name = 'old'").get()!.n).toBe(10); | |
| 94 | record(app.db, [], T0 + KEEP_MS * 3); | |
| 95 | expect(app.db.query<{ n: number }, []>("SELECT count(*) AS n FROM series_sample WHERE name = 'old'").get()!.n).toBe(0); | |
| 96 | seed(); | |
| 97 | }); | |
| 98 | }); | |
| 99 | ||
| 100 | describe("the query", () => { | |
| 101 | test("a selector reads the latest value of each matching series", () => { | |
| 102 | const r = runQuery(app.db, 'reqs_total{method="GET"}', W); | |
| 103 | expect(r.ok).toBe(true); | |
| 104 | if (!r.ok) return; | |
| 105 | expect(r.value.map((s) => s.labels["pattern"]).sort()).toEqual(["/a", "/b"]); | |
| 106 | expect(r.value[0]!.points.at(-1)!.value).toBe(600); | |
| 107 | }); | |
| 108 | ||
| 109 | test("rate is the per-second increase: 1/s for /a, and /c's spike is 20/s", () => { | |
| 110 | const r = runQuery(app.db, "rate(reqs_total[1m])", W); | |
| 111 | if (!r.ok) throw new Error(r.error); | |
| 112 | const a = r.value.find((s) => s.labels["pattern"] === "/a")!; | |
| 113 | expect(a.points.at(-1)!.value).toBeCloseTo(1, 5); | |
| 114 | const c = r.value.find((s) => s.labels["pattern"] === "/c")!; | |
| 115 | expect(Math.max(...c.points.map((p) => p.value))).toBeCloseTo(20, 5); | |
| 116 | }); | |
| 117 | ||
| 118 | test("sum by folds series by the named labels, before or after the argument", () => { | |
| 119 | const a = runQuery(app.db, "sum by (method) (rate(reqs_total[1m]))", W); | |
| 120 | const b = runQuery(app.db, "sum(rate(reqs_total[1m])) by (method)", W); | |
| 121 | if (!a.ok || !b.ok) throw new Error("did not run"); | |
| 122 | expect(a.value.map((s) => s.labels)).toEqual(expect.arrayContaining([{ method: "GET" }, { method: "POST" }])); | |
| 123 | expect(b.value).toEqual(a.value); | |
| 124 | const get = a.value.find((s) => s.labels["method"] === "GET")!; | |
| 125 | expect(get.points.at(-1)!.value).toBeCloseTo(2, 5); | |
| 126 | }); | |
| 127 | ||
| 128 | test("avg_over_time, max and topk", () => { | |
| 129 | const avg = runQuery(app.db, "avg_over_time(up[2m])", W); | |
| 130 | if (!avg.ok) throw new Error(avg.error); | |
| 131 | expect(avg.value[0]!.points.every((p) => p.value === 1)).toBe(true); | |
| 132 | const top = runQuery(app.db, "topk(1, rate(reqs_total[1m]))", W); | |
| 133 | if (!top.ok) throw new Error(top.error); | |
| 134 | const names = new Set(top.value.map((s) => s.labels["pattern"])); | |
| 135 | expect(names.has("/c")).toBe(true); // /c leads while it spikes | |
| 136 | const max = runQuery(app.db, "max(reqs_total)", W); | |
| 137 | if (!max.ok) throw new Error(max.error); | |
| 138 | expect(max.value[0]!.points.at(-1)!.value).toBe(3000); | |
| 139 | }); | |
| 140 | ||
| 141 | test("a counter reset counts from zero, not as a drop", () => { | |
| 142 | record(app.db, [{ name: "reset_total", labels: {}, value: 100 }], T0); | |
| 143 | record(app.db, [{ name: "reset_total", labels: {}, value: 130 }], T0 + 30_000); | |
| 144 | record(app.db, [{ name: "reset_total", labels: {}, value: 10 }], T0 + 60_000); | |
| 145 | const r = runQuery(app.db, "rate(reset_total[2m])", { from: T0 + 60_000, to: T0 + 60_000, stepMs: 30_000 }); | |
| 146 | if (!r.ok) throw new Error(r.error); | |
| 147 | expect(r.value[0]!.points[0]!.value).toBeCloseTo(40 / 60, 5); | |
| 148 | }); | |
| 149 | ||
| 150 | test("label matchers: != and =~ alternatives; a regex that is not alternatives of literals is refused", () => { | |
| 151 | const ne = runQuery(app.db, 'up{pattern!="/a"}', W); | |
| 152 | expect(ne.ok && ne.value.length).toBe(1); | |
| 153 | const re = runQuery(app.db, 'reqs_total{pattern=~"/a|/c"}', W); | |
| 154 | expect(re.ok && re.value.map((s) => s.labels["pattern"]).sort()).toEqual(["/a", "/c"]); | |
| 155 | const pre = runQuery(app.db, 'reqs_total{pattern=~"/.*"}', W); | |
| 156 | expect(pre.ok && pre.value.length).toBe(3); | |
| 157 | expect(parseQuery('reqs_total{pattern=~"/a.+"}').ok).toBe(false); | |
| 158 | const bad = parseQuery('reqs_total{pattern=~"(a+)+$"}'); | |
| 159 | expect(bad.ok).toBe(false); | |
| 160 | }); | |
| 161 | ||
| 162 | test("a query that is not one says why; it never throws and is capped in length", () => { | |
| 163 | for (const q of ["", "rate(", "sum by (a b) (x)", "topk(0, x)", "rate(x[5d])", "x{a=1}", "a b", "x".repeat(400)]) { | |
| 164 | const r = runQuery(app.db, q, W); | |
| 165 | expect(r.ok, q).toBe(false); | |
| 166 | } | |
| 167 | expect(runQuery(app.db, "up", { from: 5, to: 1, stepMs: 30_000 }).ok).toBe(false); | |
| 168 | }); | |
| 169 | }); | |
| 170 | ||
| 171 | describe("select to explain", () => { | |
| 172 | test("the seeded outlier /c (and POST) lead what weighs more inside the spike than outside", () => { | |
| 173 | const r = runQuery(app.db, "rate(reqs_total[1m])", W); | |
| 174 | if (!r.ok) throw new Error(r.error); | |
| 175 | const causes = explain(r.value, T0 + 12 * STEP, T0 + 16 * STEP); | |
| 176 | expect(causes[0]).toMatchObject({ label: expect.stringMatching(/pattern|method/) }); | |
| 177 | const top = causes.filter((c) => c.lift > 0).map((c) => `${c.label}=${c.value}`); | |
| 178 | expect(top).toContain("pattern=/c"); | |
| 179 | expect(top).toContain("method=POST"); | |
| 180 | expect(causes.find((c) => c.value === "/c")!.lift).toBeGreaterThan(0.4); | |
| 181 | expect(causes.find((c) => c.value === "/a")!.lift).toBeLessThan(0); | |
| 182 | }); | |
| 183 | ||
| 184 | test("a selection that is the whole range, or a flat one, explains nothing", () => { | |
| 185 | const r = runQuery(app.db, "rate(reqs_total[1m])", W); | |
| 186 | if (!r.ok) throw new Error(r.error); | |
| 187 | expect(explain(r.value, T0, T0 + 20 * STEP)).toEqual([]); | |
| 188 | const flat = runQuery(app.db, 'rate(reqs_total{method="GET"}[1m])', W); | |
| 189 | if (!flat.ok) throw new Error(flat.error); | |
| 190 | expect(explain(flat.value, T0 + 12 * STEP, T0 + 16 * STEP)).toEqual([]); | |
| 191 | }); | |
| 192 | ||
| 193 | test("answer() joins a query and a selection; askOf reads the address and keeps defaults for junk", () => { | |
| 194 | const ask = askOf(new URLSearchParams({ q: "rate(reqs_total[1m])", range: "15", from: String(T0 + 12 * STEP), to: String(T0 + 16 * STEP) })); | |
| 195 | expect(ask.minutes).toBe(15); | |
| 196 | const a = answer(app.db, ask, T0 + 20 * STEP); | |
| 197 | expect(a.selected?.causes.length).toBeGreaterThan(0); | |
| 198 | const junk = askOf(new URLSearchParams({ range: "7", from: "x", to: "y" })); | |
| 199 | expect(junk.minutes).toBe(60); | |
| 200 | expect(junk.from).toBeUndefined(); | |
| 201 | expect(answer(app.db, { query: "nope(", minutes: 60 }, T0).error).toBeDefined(); | |
| 202 | }); | |
| 203 | }); | |
| 204 | ||
| 205 | describe("pins and reports", () => { | |
| 206 | test("a query is kept only when it parses; a pin lists first, with its title and note trimmed", () => { | |
| 207 | expect(save(app.db, { kind: "pin", title: "x", query: "rate(" }, T0).ok).toBe(false); | |
| 208 | expect(save(app.db, { kind: "star", title: "x", query: "up" }, T0).ok).toBe(false); | |
| 209 | expect(save(app.db, { kind: "pin", title: " ", query: "up" }, T0).ok).toBe(false); | |
| 210 | expect(save(app.db, { kind: "report", title: "Traffic", query: "up", note: " busy at six " }, T0).ok).toBe(true); | |
| 211 | expect(save(app.db, { kind: "pin", title: "Up", query: "up" }, T0 + 1).ok).toBe(true); | |
| 212 | const rows = listSaved(app.db); | |
| 213 | expect(rows.map((r) => r.kind)).toEqual(["pin", "report"]); | |
| 214 | expect(rows[1]!.note).toBe("busy at six"); | |
| 215 | }); | |
| 216 | }); | |
| 217 | ||
| 218 | describe("the page", () => { | |
| 219 | const get = (path: string, cookie?: string) => fetch(`${base}${path}`, { headers: cookie ? { cookie } : {}, redirect: "manual" }); | |
| 220 | ||
| 221 | test("an owner sees the chart, the table and the selection's causes; a member finds nothing", async () => { | |
| 222 | // The sampler's own rows are what the page reads: seed fresh ones near now. | |
| 223 | const now = Date.now(); | |
| 224 | for (let i = 0; i < 20; i++) { | |
| 225 | record(app.db, [ | |
| 226 | { name: "pg_total", labels: { pattern: "/a" }, value: i * 30 }, | |
| 227 | { name: "pg_total", labels: { pattern: "/c" }, value: i >= 10 ? (i - 10) * 600 : 0 }, | |
| 228 | ], now - (20 - i) * 30_000); | |
| 229 | } | |
| 230 | const q = encodeURIComponent("rate(pg_total[1m])"); | |
| 231 | const res = await get(`/explore/series?q=${q}&range=15&from=${now - 10 * 30_000}&to=${now}`, adminCookie); | |
| 232 | expect(res.status).toBe(200); | |
| 233 | const text = await res.text(); | |
| 234 | expect(text).toContain("pattern="/c""); | |
| 235 | expect(text).toContain('id="explain"'); | |
| 236 | expect(text).toContain("Series"); | |
| 237 | expect((await get(`/explore/series?q=${q}`, memberCookie)).status).toBe(404); | |
| 238 | }); | |
| 239 | ||
| 240 | test("/explore links to the page for an owner, and not for a member or a guest", async () => { | |
| 241 | const link = 'href="/explore/series"'; | |
| 242 | expect(await (await get("/explore", adminCookie)).text()).toContain(link); | |
| 243 | expect(await (await get("/explore", memberCookie)).text()).not.toContain(link); | |
| 244 | expect(await (await get("/explore")).text()).not.toContain(link); | |
| 245 | }); | |
| 246 | ||
| 247 | test("a bad query shows its sentence on the page, escaped, and still answers 200", async () => { | |
| 248 | const res = await get(`/explore/series?q=${encodeURIComponent("<script>(")}`, adminCookie); | |
| 249 | expect(res.status).toBe(200); | |
| 250 | const text = await res.text(); | |
| 251 | expect(text).not.toContain("<script>("); | |
| 252 | expect(text).toContain("<script>("); | |
| 253 | }); | |
| 254 | ||
| 255 | test("saving needs the same origin and the owner; a pin then shows on the page and can be removed", async () => { | |
| 256 | const body = (kind: string) => new URLSearchParams({ kind, title: "Req rate", q: "rate(pg_total[1m])", note: "watch /c" }); | |
| 257 | const post = (path: string, b: URLSearchParams, o: { cookie: string; origin?: string }) => | |
| 258 | fetch(`${base}${path}`, { method: "POST", body: b, headers: { cookie: o.cookie, origin: o.origin ?? base }, redirect: "manual" }); | |
| 259 | expect((await post("/explore/series/save", body("pin"), { cookie: adminCookie, origin: "https://evil.example" })).status).toBe(403); | |
| 260 | expect((await post("/explore/series/save", body("pin"), { cookie: memberCookie })).status).toBe(404); | |
| 261 | const before = listSaved(app.db).length; | |
| 262 | expect((await post("/explore/series/save", body("pin"), { cookie: adminCookie })).status).toBe(303); | |
| 263 | expect(listSaved(app.db).length).toBe(before + 1); | |
| 264 | expect((await (await get("/explore/series", adminCookie)).text())).toContain("Pinned · Req rate"); | |
| 265 | const home = await (await get("/", adminCookie)).text(); | |
| 266 | expect(home).toContain('id="pinned-series"'); | |
| 267 | expect(home).toContain("Req rate"); | |
| 268 | expect(await (await get("/", memberCookie)).text()).not.toContain('id="pinned-series"'); | |
| 269 | const id = listSaved(app.db).find((r) => r.title === "Req rate")!.id; | |
| 270 | expect((await post("/explore/series/remove", new URLSearchParams({ id: String(id) }), { cookie: adminCookie })).status).toBe(303); | |
| 271 | expect(listSaved(app.db).some((r) => r.id === id)).toBe(false); | |
| 272 | }); | |
| 273 | }); | |
| 274 | ||
| 275 | describe("the sampler", () => { | |
| 276 | test("a tick keeps the forge's own /metrics as samples a query can read", async () => { | |
| 277 | const { startSeriesSampler } = await import("../src/series/sampler.ts"); | |
| 278 | const sampler = startSeriesSampler(app, 3_600_000); | |
| 279 | const now = Date.now(); | |
| 280 | sampler.tick(now); | |
| 281 | sampler.stop(); | |
| 282 | const r = runQuery(app.db, "forge_pulls_merged_total", { from: now - 1000, to: now, stepMs: 30_000 }); | |
| 283 | expect(r.ok).toBe(true); | |
| 284 | expect(app.db.query("SELECT count(*) AS n FROM series_sample WHERE at = ?").get(now)).not.toEqual({ n: 0 }); | |
| 285 | }); | |
| 286 | }); |
test/tui-series.test.ts added +104
| @@ -0,0 +1,104 @@ | ||
| 1 | // The terminal's Explore series (#3696): the page's rows as lines, the palette entry offered to a | |
| 2 | // person admin only, and the keys that change the range and the query. | |
| 3 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 4 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 5 | import { tmpdir } from "node:os"; | |
| 6 | import { join } from "node:path"; | |
| 7 | import { createApp, type App } from "../src/app.ts"; | |
| 8 | import { createUser, type User } from "../src/core/users.ts"; | |
| 9 | import { record } from "../src/series/store.ts"; | |
| 10 | import { listSaved, save } from "../src/series/saved.ts"; | |
| 11 | import { answer } from "../src/series/view.ts"; | |
| 12 | import { createForgeApp } from "../src/tui/forge.ts"; | |
| 13 | import { systemScreen } from "../src/tui/screens/system.ts"; | |
| 14 | import { entry, seriesLines, seriesScreen } from "../src/tui/screens/series.ts"; | |
| 15 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; | |
| 16 | import { seedAdmin } from "./helpers/admin.ts"; | |
| 17 | import { settleApp, settleUntil } from "./helpers/tui.ts"; | |
| 18 | import { quietLogs } from "./helpers/globals.ts"; | |
| 19 | ||
| 20 | quietLogs(); | |
| 21 | let dir = "", app: App, admin: User, person: User; | |
| 22 | beforeAll(async () => { | |
| 23 | dir = await mkdtemp(join(tmpdir(), "forge-tui-series-")); | |
| 24 | app = createApp({ dataDir: dir, port: 0 }); | |
| 25 | const boss = await seedAdmin(app, { username: "boss", email: "[email protected]" }); | |
| 26 | if (!boss.ok) throw new Error("admin"); | |
| 27 | admin = boss.value; | |
| 28 | const pat = await createUser(app.db, { username: "pat", email: "[email protected]", password: "a-good-passphrase", origin: "seed", trusted: true }); | |
| 29 | if (!pat.ok) throw new Error("person"); | |
| 30 | person = pat.value; | |
| 31 | const now = Date.now(); | |
| 32 | for (let i = 0; i < 20; i++) { | |
| 33 | record(app.db, [ | |
| 34 | { name: "forge_http_request_duration_seconds_count", labels: { pattern: "/a" }, value: i * 30 }, | |
| 35 | { name: "forge_http_request_duration_seconds_count", labels: { pattern: "/c" }, value: i >= 10 ? (i - 10) * 600 : 0 }, | |
| 36 | ], now - (20 - i) * 30_000); | |
| 37 | } | |
| 38 | }); | |
| 39 | afterAll(async () => { | |
| 40 | app.close(); | |
| 41 | await rm(dir, { recursive: true, force: true }); | |
| 42 | }); | |
| 43 | ||
| 44 | const sessionOf = (user: User) => | |
| 45 | createForgeApp(app, { sshUsername: user.username, remoteAddress: "127.0.0.1", fingerprint: "SHA256:t", user }, { terminal: headlessTerminal(120, 40), exitHooks: false }).session; | |
| 46 | ||
| 47 | const open = async (user: User) => { | |
| 48 | const terminal = headlessTerminal(120, 40); | |
| 49 | const { app: tui, session } = createForgeApp(app, { sshUsername: user.username, remoteAddress: "127.0.0.1", fingerprint: "SHA256:t", user }, { terminal, exitHooks: false }); | |
| 50 | tui.start(); | |
| 51 | tui.ctx.push(seriesScreen(session, tui.ctx)); | |
| 52 | await settleUntil(tui, "Explore series"); | |
| 53 | return { tui, session, text: () => tui.screen.toText(), press: async (keys: string) => { terminal.feed(keys); await settleApp(tui); } }; | |
| 54 | }; | |
| 55 | ||
| 56 | test("lines carry the query, each series with its latest and peak, and a selection's causes", () => { | |
| 57 | const now = Date.now(); | |
| 58 | const a = answer(app.db, { query: "rate(forge_http_request_duration_seconds_count[1m])", minutes: 15, from: now - 8 * 30_000, to: now }, now); | |
| 59 | const text = seriesLines(a).join("\n"); | |
| 60 | expect(text).toContain("rate(forge_http_request_duration_seconds_count[1m])"); | |
| 61 | expect(text).toContain('pattern="/c"'); | |
| 62 | expect(text).toContain("Why "); | |
| 63 | expect(seriesLines(answer(app.db, { query: "nope(", minutes: 15 }, now)).join("\n")).toContain("expected"); | |
| 64 | }); | |
| 65 | ||
| 66 | test("the palette offers it to a person admin and no one else", () => { | |
| 67 | expect(entry.offered(sessionOf(admin))).toBe(true); | |
| 68 | expect(entry.offered(sessionOf(person))).toBe(false); | |
| 69 | }); | |
| 70 | ||
| 71 | test("the screen shows the default query's series, and r cycles the range", async () => { | |
| 72 | const t = await open(admin); | |
| 73 | expect(t.text()).toContain("last 60 min"); | |
| 74 | expect(t.text()).toContain("/c"); | |
| 75 | await t.press("r"); | |
| 76 | expect(t.text()).toContain("last 360 min"); | |
| 77 | }); | |
| 78 | ||
| 79 | test("the system screen opens it with x for a person admin", async () => { | |
| 80 | const terminal = headlessTerminal(120, 40); | |
| 81 | const { app: tui, session } = createForgeApp(app, { sshUsername: admin.username, remoteAddress: "127.0.0.1", fingerprint: "SHA256:t", user: admin }, { terminal, exitHooks: false }); | |
| 82 | tui.start(); | |
| 83 | tui.ctx.push(systemScreen(tui.ctx, [], session)); | |
| 84 | await settleUntil(tui, "System"); | |
| 85 | terminal.feed("x"); | |
| 86 | await settleUntil(tui, "Explore series"); | |
| 87 | }); | |
| 88 | ||
| 89 | test("s saves a report with a note, and n then d removes a saved query after asking", async () => { | |
| 90 | const t = await open(admin); | |
| 91 | await t.press("s"); | |
| 92 | await t.press("Weekly rate\r"); | |
| 93 | await t.press("watch /c\r"); | |
| 94 | const rep = listSaved(app.db).find((r) => r.title === "Weekly rate"); | |
| 95 | expect(rep?.kind).toBe("report"); | |
| 96 | expect(rep?.note).toBe("watch /c"); | |
| 97 | const keep = save(app.db, { kind: "pin", title: "Keep", query: "up" }, Date.now()); | |
| 98 | expect(keep.ok).toBe(true); | |
| 99 | // The pin lists first; open saved ones until the report is the open one, then remove it. | |
| 100 | for (let i = 0; i < listSaved(app.db).length && !t.text().includes("Weekly rate"); i++) await t.press("n"); | |
| 101 | await t.press("d"); | |
| 102 | await t.press("y"); | |
| 103 | expect(listSaved(app.db).some((r) => r.title === "Weekly rate")).toBe(false); | |
| 104 | }); |
This says to reach the page from the link on /system, but that link was removed in the latest push. Name the real entry (the link you add on /explore) and keep the terminal sentence.