Public: anyone can read this; the crew can change it.
Revert "Observability 3: boards are live by streaming per-panel points, never by re-fetching HTML" #16668
Check · Review · Land · Live — Its check is red.
revert-16653 → main 1 commit
18 files
changed +53
−619
- docs/STATUS.md
- docs/features/boards-live.md
- scripts/unused-exports-allow.json
- src/boards/delta.ts
- src/boards/live_hub.ts
- src/boards/panel_data.ts
- src/http/marks/boards.json
- src/http/server.ts
- src/tui/screens/boards.ts
- src/web/pages/boards-stream.ts
- src/web/pages/boards-view.ts
- test/boards-doors.test.ts
- test/boards-store.test.ts
- test/boards-stream.test.ts
- test/job-slices.test.ts
- test/no-polling.test.ts
- test/pages-budget.test.ts
- test/tui-boards.test.ts
docs/STATUS.md +2 −2
| @@ -78,8 +78,8 @@ cannot confirm. A package registry is not shipped yet. | ||
| 78 | 78 | - `GET /api/v1/boards/pins` (the list, in order) and `POST /api/v1/boards/pins` with `{"op":"pin|unpin|move","slug":"…","title":"…","by":-1|1}` (`by` for move only); |
| 79 | 79 | - the `board_pins` MCP tool (no `op` lists; `op` pin, unpin or move changes). `pins` is therefore not a board slug. |
| 80 | 80 | The first boot also writes the starting boards, **Usage**, **Serving**, **Crew**, **Releases**, **Apps**, **Security**, **Throughput**, **Reach** and **Forges**; Serving is the forge's event-loop lag p99 beside the checks and crew runs running, so checks' concurrency is raised on numbers. Apps' per-app panels show repo ids until a source exposes a safe name; Security (sign-ins, failed sign-ins, tokens by scope, admin actions, from the admin-only `signins`, `tokens` and `adminActions` sources and `usage`) shows no token text, hash, payload or IP; Throughput is items entering each stage from issue to live, per hour, from the `stages` source. Each is written once: `.offered` in that repo records them, so an edit stays and a deletion sticks. |
| 81 | A live board (any `refresh` but `off`; the form offers off or on, and `10s` and `1m` are still accepted and mean the same) draws the points that moved in its line, bar and number charts when a run, pull, check, issue or usage event arrives, over one stream per tab | |
| 82 | (`/boards/:slug/stream`; one read per board is shared by every tab; `docs/features/boards-live.md`). The same doors are in the API: `GET /api/v1/boards`, `GET|PUT|DELETE /api/v1/boards/:slug`, and each panel's data as JSON or CSV at `GET /api/v1/boards/:slug/panels/:id?from=&to=&step=5m&format=csv`, bucketed in SQL to the step and never cut short (`docs/APPS.md`); each panel's card links `json` and `csv` (a plain download link) beside `explore` | |
| 81 | A live board (any `refresh` but `off`; the form offers off or on, and `10s` and `1m` are still accepted and mean the same) redraws its grid when a run, pull, check, issue or usage event arrives, through the live-region swap | |
| 82 | (`/boards/:slug/live`, etag'd, one fetch per burst). The same doors are in the API: `GET /api/v1/boards`, `GET|PUT|DELETE /api/v1/boards/:slug`, and each panel's data as JSON or CSV at `GET /api/v1/boards/:slug/panels/:id?from=&to=&step=5m&format=csv`, bucketed in SQL to the step and never cut short (`docs/APPS.md`); each panel's card links `json` and `csv` (a plain download link) beside `explore` | |
| 83 | 83 | (an agent or anyone but an admin is 403; a panel whose query cannot run is refused with 422). The same four doors are MCP tools (`boards`, `board_write`, `board_delete`; `boards` with a `slug` reads one, and with a `panel` too that panel's data, with the same `from`, `to` and `step`) and, for the same person, a **Boards** screen in the terminal that lists boards and shows a board's panels as text, each with what its data holds now (a time panel's last bucket and step, another's row count). No dependency was added. |
| 84 | 84 | - **Parked work**: the terminal's Flow dialog says how many issues the crew parked (an open issue whose newest comment is the crew's `Parked by the crew` note) in the last 24 h and 7 d, and names the newest three; the MCP `flow` tool returns the same as `parked`. The flow panel on `/boards` draws two lines under its numbers, each left out at 0: `N idle pulls` (open crew pulls whose head has not moved for 72 h; the oldest three linked, `and K more` after) and `N parked today, M this week` (linking the newest parked issue). The Flow dialog lists them too (`idle: N`, a row each, `+K more`). `/boards` is the owner's; the MCP `flow` tool, as an agent, reads public repositories only (sealed issues left out). `and K more` opens `/boards?idle=all`, a list of every idle pull. See `docs/TOUR.md`. |
| 85 | 85 | - **Issues**: labels, threaded comments, close/reopen, markdown. |
docs/features/boards-live.md deleted −15
| @@ -1,15 +0,0 @@ | ||
| 1 | --- | |
| 2 | topic: Tell the crew | |
| 3 | row: A live board moves its charts as events arrive | |
| 4 | --- | |
| 5 | # A live board moves its charts as events arrive (#3692) | |
| 6 | ||
| 7 | A board whose **Live** setting is on (`refresh` anything but `off`) opens one event stream, `GET /boards/<slug>/stream`, and never fetches its page again. Open `/boards/<slug>` as an admin: under the title it reads `live · updated Ns ago`, and when a run, pull, check, issue or usage event arrives the charts that moved are drawn again. Without JavaScript it reads "Moves as events arrive." and the page stays as it was served. | |
| 8 | ||
| 9 | - **What goes down**: only the points that are new or moved, a few hundred bytes a frame, at most every 750 ms and never while nothing moved. A burst of more than 24 points in one panel says "reload to redraw" instead. | |
| 10 | - **What is drawn**: line, bar and number charts of one series are drawn again from the points (the same scale, path and bars as the page). Area, heat, table and split charts keep what was served, and the header says "some charts changed a lot; reload to redraw" when one of them moved. | |
| 11 | - **Many tabs, one read**: every tab on a board shares one read of its panels (`src/boards/live_hub.ts`); ten tabs cost the queries of one. | |
| 12 | - **Who**: a person who is an admin. An agent or anyone else gets the not-found page, as for the board. | |
| 13 | - **In the terminal**: open the board from the Boards screen (`src/tui/screens/boards.ts`). While it is open, a panel that moved says `live HH:MM:SSZ: N points moved · latest X` under its data line, fed by the same frames (`deltaOf` in `src/boards/delta.ts`). | |
| 14 | ||
| 15 | The stream is `src/web/pages/boards-stream.ts`, which sends the frames and carries the client that draws them. |
scripts/unused-exports-allow.json −1
| @@ -14,7 +14,6 @@ | ||
| 14 | 14 | "src/billing/orders.ts bySession", |
| 15 | 15 | "src/billing/orders.ts recentOrders", |
| 16 | 16 | "src/billing/sync.ts setStripeFetch", |
| 17 | "src/boards/live_hub.ts hubsOpen", | |
| 18 | 17 | "src/boards/model_fill.ts useModel", |
| 19 | 18 | "src/checks/deepsec_plan.ts sweepArgvs", |
| 20 | 19 | "src/checks/doctor.ts isDoctorHold", |
src/boards/delta.ts deleted −55
| @@ -1,55 +0,0 @@ | ||
| 1 | /** | |
| 2 | * What changed in a board since the last look, as points: one panel's rows | |
| 3 | * against the rows last sent, giving only the points that are new or moved. | |
| 4 | * Plain data in, plain data out; the stream (`web/pages/boards-stream.ts`) | |
| 5 | * sends these instead of the page. | |
| 6 | */ | |
| 7 | import { formatValue } from "./chart.ts"; | |
| 8 | import { latestOf } from "./panel_data.ts"; | |
| 9 | import type { Row } from "./query.ts"; | |
| 10 | import type { Panel } from "./store.ts"; | |
| 11 | ||
| 12 | /** A point: its group, its value, and its series when the panel is split. */ | |
| 13 | export type DeltaPoint = [group: string, value: number] | [group: string, value: number, series: string]; | |
| 14 | /** | |
| 15 | * A panel's change: its place on the board, the points that are new or moved, and its latest value | |
| 16 | * as words. | |
| 17 | */ | |
| 18 | export type PanelDelta = { i: number; points: DeltaPoint[]; now?: string }; | |
| 19 | /** What was last sent for one panel: value by point key. */ | |
| 20 | export type Seen = Map<string, number>; | |
| 21 | ||
| 22 | /** | |
| 23 | * Most points one frame carries for one panel: a burst past it is not a delta, and the page is told | |
| 24 | * to reload. | |
| 25 | */ | |
| 26 | export const MAX_POINTS = 24; | |
| 27 | ||
| 28 | const keyOf = (r: Row): string => `${String(r.group ?? "all")}\u0000${r.series === undefined ? "" : String(r.series ?? "none")}`; | |
| 29 | ||
| 30 | /** The rows as what a later `deltaOf` compares against. */ | |
| 31 | export function seenOf(rows: readonly Row[]): Seen { | |
| 32 | return new Map(rows.map((r) => [keyOf(r), r.value ?? 0])); | |
| 33 | } | |
| 34 | ||
| 35 | /** | |
| 36 | * `rows` against `seen`: the new or moved points, or null when nothing changed. `next` is what to | |
| 37 | * remember. | |
| 38 | */ | |
| 39 | export function deltaOf(i: number, panel: Panel, rows: readonly Row[], seen: Seen): { delta: PanelDelta | null; next: Seen; tooMany: boolean } { | |
| 40 | const points: DeltaPoint[] = []; | |
| 41 | for (const r of rows) { | |
| 42 | const v = r.value ?? 0; | |
| 43 | if (seen.get(keyOf(r)) === v) continue; | |
| 44 | const g = String(r.group ?? "all"); | |
| 45 | points.push(r.series === undefined ? [g, v] : [g, v, String(r.series ?? "none")]); | |
| 46 | } | |
| 47 | const next = seenOf(rows); | |
| 48 | if (points.length === 0) return { delta: null, next, tooMany: false }; | |
| 49 | const latest = latestOf(panel, rows); | |
| 50 | return { | |
| 51 | delta: { i, points: points.slice(-MAX_POINTS), ...(latest === null ? {} : { now: formatValue(latest) }) }, | |
| 52 | next, | |
| 53 | tooMany: points.length > MAX_POINTS, | |
| 54 | }; | |
| 55 | } |
src/boards/live_hub.ts deleted −109
| @@ -1,109 +0,0 @@ | ||
| 1 | /** | |
| 2 | * One live read per open board, however many people watch it. The first watcher of a board starts | |
| 3 | * a hub: it listens to the bus once, and when a run, pull, check, issue or usage event arrives it | |
| 4 | * reads the panels' rows once (at most every `MIN_GAP_MS`), takes `deltaOf` against what it last | |
| 5 | * sent and hands the same frame to every watcher. The last one to leave stops it. The stream | |
| 6 | * (`web/pages/boards-stream.ts`) and the terminal board (`tui/screens/boards.ts`) both watch | |
| 7 | * through here, so ten tabs cost one set of queries per event. | |
| 8 | */ | |
| 9 | import type { App } from "../app.ts"; | |
| 10 | import { during } from "../perf/jobs.ts"; | |
| 11 | import { deltaOf, seenOf, type PanelDelta, type Seen } from "./delta.ts"; | |
| 12 | import { panelData } from "./panel_data.ts"; | |
| 13 | import type { Board } from "./store.ts"; | |
| 14 | ||
| 15 | /** The events a board's queries read: any of them may move a chart. */ | |
| 16 | export const STREAM_READS = ["run.", "pull.", "check.", "issue.", "usage."] as const; | |
| 17 | /** Rows are read at most this often, however many events arrive. */ | |
| 18 | export const MIN_GAP_MS = 750; | |
| 19 | ||
| 20 | /** What a watcher is told: the moved points, and whether a burst is too big to apply. */ | |
| 21 | export type Frame = { at: number; panels: PanelDelta[]; reload?: true }; | |
| 22 | /** A panel's points as the hub last read them, for a chart a page can redraw itself. */ | |
| 23 | export type Base = { i: number; points: [group: string, value: number][] }; | |
| 24 | ||
| 25 | const DRAWN = new Set(["line", "bar", "number"]); | |
| 26 | ||
| 27 | class Hub { | |
| 28 | private seen: Seen[]; | |
| 29 | private readonly watchers = new Set<(f: Frame) => void>(); | |
| 30 | private timer: ReturnType<typeof setTimeout> | undefined; | |
| 31 | private last = 0; | |
| 32 | private off: () => void; | |
| 33 | ||
| 34 | constructor(private readonly app: App, private readonly board: Board, private readonly drop: () => void) { | |
| 35 | this.seen = board.panels.map((p) => this.rowsOf(p)); | |
| 36 | this.off = app.bus.subscribe((event) => { | |
| 37 | if (this.timer !== undefined || !STREAM_READS.some((k) => event.kind.startsWith(k))) return; | |
| 38 | this.timer = setTimeout(() => during("boards-stream", () => this.send(), undefined, app), Math.max(0, MIN_GAP_MS - (Date.now() - this.last))); | |
| 39 | }, "ordered"); | |
| 40 | } | |
| 41 | ||
| 42 | private rowsOf(p: Board["panels"][number]): Seen { | |
| 43 | const d = panelData(this.app.db, this.board, p); | |
| 44 | return d.ok ? seenOf(d.rows) : new Map(); | |
| 45 | } | |
| 46 | ||
| 47 | /** The points of every panel a page redraws itself, as last read. */ | |
| 48 | base(): Base[] { | |
| 49 | const out: Base[] = []; | |
| 50 | this.board.panels.forEach((p, i) => { | |
| 51 | const keys = [...(this.seen[i] ?? new Map<string, number>())]; | |
| 52 | if (!DRAWN.has(p.chart) || keys.some(([k]) => !k.endsWith("\u0000"))) return; | |
| 53 | out.push({ i, points: keys.map(([k, v]) => [k.slice(0, -1), v]) }); | |
| 54 | }); | |
| 55 | return out; | |
| 56 | } | |
| 57 | ||
| 58 | private send(): void { | |
| 59 | this.timer = undefined; | |
| 60 | this.last = Date.now(); | |
| 61 | const panels: PanelDelta[] = []; | |
| 62 | let reload = false; | |
| 63 | this.board.panels.forEach((p, i) => { | |
| 64 | const d = panelData(this.app.db, this.board, p); | |
| 65 | if (!d.ok) return; | |
| 66 | const r = deltaOf(i, p, d.rows, this.seen[i] ?? new Map()); | |
| 67 | this.seen[i] = r.next; | |
| 68 | if (r.delta) panels.push(r.delta); | |
| 69 | reload ||= r.tooMany; | |
| 70 | }); | |
| 71 | if (panels.length === 0) return; | |
| 72 | const frame: Frame = { at: this.last, panels, ...(reload ? { reload: true as const } : {}) }; | |
| 73 | for (const w of this.watchers) w(frame); | |
| 74 | } | |
| 75 | ||
| 76 | join(onFrame: (f: Frame) => void): () => void { | |
| 77 | this.watchers.add(onFrame); | |
| 78 | return () => { | |
| 79 | this.watchers.delete(onFrame); | |
| 80 | if (this.watchers.size > 0) return; | |
| 81 | this.off(); | |
| 82 | if (this.timer !== undefined) clearTimeout(this.timer); | |
| 83 | this.drop(); | |
| 84 | }; | |
| 85 | } | |
| 86 | } | |
| 87 | ||
| 88 | const hubs = new WeakMap<object, Map<string, Hub>>(); | |
| 89 | ||
| 90 | /** | |
| 91 | * Watch a board: `onFrame` hears each frame of moved points; `base` is where the points stand now; | |
| 92 | * `stop` leaves (the last one out stops the hub). A board edited meanwhile is another hub: the key | |
| 93 | * holds the board itself. | |
| 94 | */ | |
| 95 | export function watchBoard(app: App, slug: string, board: Board, onFrame: (f: Frame) => void): { base: Base[]; stop: () => void } { | |
| 96 | let of = hubs.get(app.db); | |
| 97 | if (of === undefined) hubs.set(app.db, (of = new Map())); | |
| 98 | const key = `${slug}\u0000${JSON.stringify(board)}`; | |
| 99 | let hub = of.get(key); | |
| 100 | if (hub === undefined) { | |
| 101 | const made = new Hub(app, board, () => of.delete(key)); | |
| 102 | hub = made; | |
| 103 | of.set(key, made); | |
| 104 | } | |
| 105 | return { base: hub.base(), stop: hub.join(onFrame) }; | |
| 106 | } | |
| 107 | ||
| 108 | /** How many boards are being read live: for the test that watchers share one. */ | |
| 109 | export const hubsOpen = (app: App): number => hubs.get(app.db)?.size ?? 0; |
src/boards/panel_data.ts +3 −10
| @@ -136,19 +136,12 @@ export const cellsOf = (rows: readonly Row[], hrefs: readonly (string | null)[] | ||
| 136 | 136 | /** A panel as it is drawn: its chart's markup and, for one series over time, its latest value; or why it could not be read. */ |
| 137 | 137 | export type PanelDrawn = { ok: true; chart: string; latest: number | null } | { ok: false; error: string }; |
| 138 | 138 | |
| 139 | /** | |
| 140 | * One series drawn over time says its latest value beside its name; a split, a table or groups of | |
| 141 | * anything else have no one latest. | |
| 142 | */ | |
| 143 | export function latestOf(panel: Panel, rows: readonly Row[]): number | null { | |
| 144 | const newest = panel.chart === "line" || panel.chart === "bar" ? rows[rows.length - 1] : undefined; | |
| 145 | return newest !== undefined && newest.series === undefined && /^\d{4}-\d{2}-\d{2}/.test(String(newest.group)) ? (newest.value ?? 0) : null; | |
| 146 | } | |
| 147 | ||
| 148 | 139 | /** Draw `panel` from its rows: the chart is markup from here on, so whoever reads the rows off the serving thread draws them there too. */ |
| 149 | 140 | export function drawnPanel(panel: Panel, answer: PanelData): PanelDrawn { |
| 150 | 141 | if (!answer.ok) return answer; |
| 151 | const latest = latestOf(panel, answer.rows); | |
| 142 | const newest = panel.chart === "line" || panel.chart === "bar" ? answer.rows[answer.rows.length - 1] : undefined; | |
| 143 | // One series drawn over time says its latest value beside its name; a split, a table or groups of anything else have no one latest. | |
| 144 | const latest = newest !== undefined && newest.series === undefined && /^\d{4}-\d{2}-\d{2}/.test(String(newest.group)) ? (newest.value ?? 0) : null; | |
| 152 | 145 | return { ok: true, chart: drawChart(panel.chart, cellsOf(answer.rows), panel.title, typeof panel.query.source === "string" ? panel.query.source : undefined), latest }; |
| 153 | 146 | } |
| 154 | 147 |
src/http/marks/boards.json +1 −1
src/http/server.ts +2 −3
| @@ -73,8 +73,7 @@ import { nowPage } from "../web/pages/now.ts"; | ||
| 73 | 73 | import { myReposPage } from "../web/pages/my-repos.ts"; |
| 74 | 74 | import { displayChoose, displayPage } from "../web/pages/display.ts"; |
| 75 | 75 | import { displaysPage } from "../web/pages/displays.ts"; |
| 76 | import { boardStream } from "../web/pages/boards-stream.ts"; | |
| 77 | import { boardShow, boardsList } from "../web/pages/boards-view.ts"; | |
| 76 | import { boardLive, boardShow, boardsList } from "../web/pages/boards-view.ts"; | |
| 78 | 77 | import { actingVia } from "../core/acting_via.ts"; |
| 79 | 78 | import { |
| 80 | 79 | closeStreamsOf, |
| @@ -1312,7 +1311,7 @@ export function buildRouter(): Router<Handler> { | ||
| 1312 | 1311 | router.add("POST", "/boards/pin", boardPin); |
| 1313 | 1312 | for (const op of ["pin-panel", "unpin-panel", "move-pin"]) router.add("POST", `/boards/${op}`, pinPost); |
| 1314 | 1313 | router.add("GET", "/boards/:slug", boardShow); |
| 1315 | router.add("GET", "/boards/:slug/stream", boardStream); | |
| 1314 | router.add("GET", "/boards/:slug/live", boardLive); | |
| 1316 | 1315 | router.add("POST", "/boards/:slug/:op", boardPost); |
| 1317 | 1316 | router.add("GET", "/design/gallery", designComponentsPage); |
| 1318 | 1317 | router.add("GET", "/admin/data", adminDataPage); |
src/tui/screens/boards.ts +5 −30
| @@ -9,13 +9,10 @@ | ||
| 9 | 9 | * panel is said as its title, chart, size and the query that feeds it, then what `panelData` reads |
| 10 | 10 | * for it (the page's and the API's door): a time panel's last bucket and its step, else its row |
| 11 | 11 | * count. `[`/`]` mark a panel, `p` pins or unpins it to home and `<`/`>` move a pinned one |
| 12 | * (`actions/board-pins.ts`). A board that is live (`refresh` not `off`) keeps itself current while | |
| 13 | * its screen is open: it watches through the same hub as the page's stream (`boards/live_hub.ts`), | |
| 14 | * so a panel that moved says how many points and its latest value (`liveWords`). | |
| 12 | * (`actions/board-pins.ts`). | |
| 15 | 13 | */ |
| 16 | 14 | |
| 17 | 15 | import { formatValue } from "../../boards/chart.ts"; |
| 18 | import { watchBoard, type Frame } from "../../boards/live_hub.ts"; | |
| 19 | 16 | import { panelData, type PanelData } from "../../boards/panel_data.ts"; |
| 20 | 17 | import { RANGES, type Board } from "../../boards/store.ts"; |
| 21 | 18 | import { listPinned, movePinned, pinPanel, unpinPanel } from "../../actions/board-pins.ts"; |
| @@ -79,7 +76,7 @@ export function dataLine(d: PanelData): string { | ||
| 79 | 76 | * A board, panel by panel, as lines of text; the panel at `at` is marked, a |
| 80 | 77 | * pinned one says so, and each panel with its `data` read says what it holds. |
| 81 | 78 | */ |
| 82 | export function boardLines(board: Board, at = -1, pinned: readonly string[] = [], data: readonly PanelData[] = [], moved: ReadonlyMap<number, string> = new Map()): string[] { | |
| 79 | export function boardLines(board: Board, at = -1, pinned: readonly string[] = [], data: readonly PanelData[] = []): string[] { | |
| 83 | 80 | const lines = [ |
| 84 | 81 | plain(board.title), |
| 85 | 82 | `range ${board.range} · refresh ${board.refresh} · ${plural(board.panels.length, "panel")}`, |
| @@ -91,20 +88,10 @@ export function boardLines(board: Board, at = -1, pinned: readonly string[] = [] | ||
| 91 | 88 | lines.push("", `${i === at ? "▸ " : ""}${plain(p.title)}${pinned.includes(p.title) ? " [pinned to home]" : ""}`, ` ${p.chart} · ${p.w}×${p.h}`, ` ${query === "" ? "no query" : query}`); |
| 92 | 89 | const d = data[i]; |
| 93 | 90 | if (d !== undefined) lines.push(` ${dataLine(d)}`); |
| 94 | const m = moved.get(i); | |
| 95 | if (m !== undefined) lines.push(` ${m}`); | |
| 96 | 91 | } |
| 97 | 92 | return lines; |
| 98 | 93 | } |
| 99 | 94 | |
| 100 | /** What a live frame says of one panel: the points that moved and its latest value. */ | |
| 101 | export function liveWords(frame: Frame, i: number): string | undefined { | |
| 102 | const p = frame.panels.find((x) => x.i === i); | |
| 103 | if (p === undefined) return undefined; | |
| 104 | const clock = new Date(frame.at).toISOString().slice(11, 19); | |
| 105 | return `live ${clock}Z: ${plural(p.points.length, "point")} moved${p.now === undefined ? "" : ` · latest ${plain(p.now)}`}`; | |
| 106 | } | |
| 107 | ||
| 108 | 95 | export function boardScreen(ctx: Ctx, f: Session, slug: string, first: Board): Screen { |
| 109 | 96 | let board = first; |
| 110 | 97 | const scroll = new Scroll(); |
| @@ -116,13 +103,12 @@ export function boardScreen(ctx: Ctx, f: Session, slug: string, first: Board): S | ||
| 116 | 103 | // The gate is `changeBoard`'s, read once as the list's is. |
| 117 | 104 | const mayEdit = f.user?.isAdmin === true && f.user.kind !== "agent"; |
| 118 | 105 | let lines = boardLines(board, at, pinned); |
| 119 | const moved = new Map<number, string>(); | |
| 120 | 106 | const read = async (): Promise<void> => { |
| 121 | 107 | const listed = await listPinned(f.app, f.user); |
| 122 | 108 | pinned = listed.ok ? listed.value.filter((p) => p.slug === slug).map((p) => p.title) : []; |
| 123 | 109 | // Only an admin person reaches this screen (`showBoard` let them in), as `panelData` asks. |
| 124 | 110 | data = board.panels.map((p) => panelData(f.app.db, board, p)); |
| 125 | lines = boardLines(board, at, pinned, data, moved); | |
| 111 | lines = boardLines(board, at, pinned, data); | |
| 126 | 112 | ctx.invalidate(); |
| 127 | 113 | }; |
| 128 | 114 | /** Pin the marked panel, or unpin it when it is; `by` moves a pinned one in the home order. */ |
| @@ -175,18 +161,7 @@ export function boardScreen(ctx: Ctx, f: Session, slug: string, first: Board): S | ||
| 175 | 161 | binding(["esc", "q"], "back"), |
| 176 | 162 | ]; |
| 177 | 163 | }, |
| 178 | async load(signal) { | |
| 179 | await read(); | |
| 180 | if (board.refresh === "off" || !mayEdit || signal.aborted) return; | |
| 181 | const watch = watchBoard(f.app, slug, board, (frame) => { | |
| 182 | board.panels.forEach((_, i) => { | |
| 183 | const words = liveWords(frame, i); | |
| 184 | if (words !== undefined) moved.set(i, words); | |
| 185 | }); | |
| 186 | runAsync(ctx, read); | |
| 187 | }); | |
| 188 | signal.addEventListener("abort", watch.stop, { once: true }); | |
| 189 | }, | |
| 164 | load: read, | |
| 190 | 165 | render(area, s) { |
| 191 | 166 | const c = ctx.theme.c; |
| 192 | 167 | if (asking !== undefined) { |
| @@ -216,7 +191,7 @@ export function boardScreen(ctx: Ctx, f: Session, slug: string, first: Board): S | ||
| 216 | 191 | } |
| 217 | 192 | if (e.key === "[" || e.key === "]") { |
| 218 | 193 | if (board.panels.length > 0) at = (at + (e.key === "]" ? 1 : board.panels.length - 1)) % board.panels.length; |
| 219 | lines = boardLines(board, at, pinned, data, moved); | |
| 194 | lines = boardLines(board, at, pinned, data); | |
| 220 | 195 | return true; |
| 221 | 196 | } |
| 222 | 197 | if (e.key === "p") return act(), true; |
src/web/pages/boards-stream.ts deleted −160
| @@ -1,160 +0,0 @@ | ||
| 1 | /** | |
| 2 | * GET /boards/:slug/stream: a board kept live by points, not by pages. One SSE per open tab; the | |
| 3 | * panels are read once per board for every tab (`boards/live_hub.ts`), and only the points that are | |
| 4 | * new or moved go down, as `panels` frames of a few hundred bytes. Nothing is sent when nothing | |
| 5 | * moved. The `hello` frame carries the points of the charts the page redraws itself (line, bar, | |
| 6 | * number, one series). The client is `boardStreamJs`, which draws them. | |
| 7 | */ | |
| 8 | import { boardPicture, isFailed } from "../../flow/pages.ts"; | |
| 9 | import { watchBoard } from "../../boards/live_hub.ts"; | |
| 10 | import { isSlug } from "../../boards/store.ts"; | |
| 11 | import type { Ctx } from "../../http/context.ts"; | |
| 12 | import { eventStream } from "../../http/sse.ts"; | |
| 13 | import { notFoundPage } from "../chrome.ts"; | |
| 14 | ||
| 15 | export async function boardStream(ctx: Ctx): Promise<Response> { | |
| 16 | const u = ctx.auth.user; | |
| 17 | const slug = ctx.params.slug ?? ""; | |
| 18 | if (u?.isAdmin !== true || u.kind === "agent" || !isSlug(slug)) return notFoundPage(ctx); | |
| 19 | const picture = await boardPicture(ctx.app, slug); | |
| 20 | if (picture === undefined || isFailed(picture) || picture.board === null) return notFoundPage(ctx); | |
| 21 | const board = picture.board; | |
| 22 | ||
| 23 | return eventStream(ctx.app, ctx.request, (emit, _close, ready) => { | |
| 24 | const watch = watchBoard(ctx.app, slug, board, (frame) => { | |
| 25 | if (ready()) emit("panels", frame); | |
| 26 | }); | |
| 27 | emit("hello", { at: Date.now(), base: watch.base }); | |
| 28 | return watch.stop; | |
| 29 | }); | |
| 30 | } | |
| 31 | ||
| 32 | /** | |
| 33 | * The page's end of the stream. The header says "live · updated Ns ago" or "paused"; the latest | |
| 34 | * number moves in place; and a line, bar or number chart is drawn again from its points, with the | |
| 35 | * same scale, path and bars as `boards/chart.ts`. Area, heat, table and split charts are not drawn | |
| 36 | * here: a frame that moves one says so, and the page keeps what it was served. Every word set on | |
| 37 | * the page is set as text. | |
| 38 | */ | |
| 39 | export const boardStreamJs = /* js */ ` | |
| 40 | (function () { | |
| 41 | var grid = document.getElementById('board-grid'); | |
| 42 | var say = document.getElementById('board-live'); | |
| 43 | var src = grid && grid.getAttribute('data-stream'); | |
| 44 | if (!src || !say || typeof EventSource === 'undefined') return; | |
| 45 | var NS = 'http://www.w3.org/2000/svg'; | |
| 46 | var at = Date.now(), live = false, pts = {}, stale = false; | |
| 47 | var es = new EventSource(src); | |
| 48 | function group(n, d) { | |
| 49 | var s = Math.pow(10, d), r = Math.round(Math.abs(n) * s) / s, p = String(r).split('.'); | |
| 50 | var w = p[0].length > 3 && p[0].indexOf('e') < 0 ? p[0].replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',') : p[0]; | |
| 51 | return (n < 0 && r !== 0 ? '-' : '') + w + (p[1] === undefined ? '' : '.' + p[1]); | |
| 52 | } | |
| 53 | function fmt(v) { | |
| 54 | var a = Math.abs(v); | |
| 55 | if (a >= 1e9) return group(v / 1e9, a >= 1e10 ? 1 : 2) + 'G'; | |
| 56 | if (a >= 1e6) return group(v / 1e6, a >= 1e7 ? 1 : 2) + 'M'; | |
| 57 | if (a >= 1e4) return group(v / 1e3, a >= 1e5 ? 0 : 1) + 'k'; | |
| 58 | return group(v, a >= 100 ? 0 : a >= 10 ? 1 : 2); | |
| 59 | } | |
| 60 | function r2(n) { return String(Math.round(n * 100) / 100); } | |
| 61 | var STEPS = [1, 1.2, 1.5, 2, 2.5, 3, 4, 5, 6, 8, 10]; | |
| 62 | function nice(v) { | |
| 63 | if (!(v > 0)) return 1; | |
| 64 | var p = Math.pow(10, Math.floor(Math.log(v) / Math.LN10)); | |
| 65 | for (var i = 0; i < STEPS.length; i++) if (STEPS[i] * p >= v * 0.999999) return STEPS[i] * p; | |
| 66 | return 10 * p; | |
| 67 | } | |
| 68 | function scale(lo, hi) { | |
| 69 | var top = hi > 0 ? nice(hi) : 0, bottom = lo < 0 ? -nice(-lo) : 0, span = top - bottom || 1; | |
| 70 | return { top: bottom + span, bottom: bottom, y: function (v) { return 100 - ((v - bottom) / span) * 100; } }; | |
| 71 | } | |
| 72 | function line(vals, y) { | |
| 73 | var n = vals.length; | |
| 74 | if (n === 1) return 'M40 ' + r2(y(vals[0])) + ' L60 ' + r2(y(vals[0])); | |
| 75 | return vals.map(function (v, i) { return (i ? 'L' : 'M') + r2(n < 2 ? 50 : i * 100 / (n - 1)) + ' ' + r2(y(v)); }).join(' '); | |
| 76 | } | |
| 77 | function el(tag, attrs, title) { | |
| 78 | var e = document.createElementNS(NS, tag); | |
| 79 | for (var k in attrs) e.setAttribute(k, attrs[k]); | |
| 80 | if (title) { var t = document.createElementNS(NS, 'title'); t.textContent = title; e.appendChild(t); } | |
| 81 | return e; | |
| 82 | } | |
| 83 | function clear(plot, sel) { | |
| 84 | plot.querySelectorAll(sel).forEach(function (n) { var a = n.parentNode; if (a && a.nodeName === 'a') a.remove(); else n.remove(); }); | |
| 85 | } | |
| 86 | function words(card, list) { | |
| 87 | var vals = list.map(function (p) { return p[1]; }); | |
| 88 | var box = card.querySelector('.chart'), sr = card.querySelector('.chart .sr-only'); | |
| 89 | if (sr && box) sr.textContent = (box.getAttribute('aria-label') || '') + ': ' + list.length + ' points; lowest ' + fmt(Math.min.apply(null, vals)) + ', highest ' + fmt(Math.max.apply(null, vals)) + ', latest ' + fmt(vals[vals.length - 1]) + '.'; | |
| 90 | } | |
| 91 | function draw(card, kind, list) { | |
| 92 | var plot = card.querySelector('svg.chart-plot'); | |
| 93 | if (!plot || list.length === 0) return false; | |
| 94 | var vals = list.map(function (p) { return p[1]; }); | |
| 95 | var lo = Math.min.apply(null, vals), hi = Math.max.apply(null, vals), n = list.length; | |
| 96 | if (kind === 'number') { | |
| 97 | var span = hi - lo || 1, d = line(vals, function (v) { return 92 - ((v - lo) / span) * 84; }); | |
| 98 | var sp = plot.querySelector('.spark'); if (!sp) return false; | |
| 99 | sp.setAttribute('d', d); | |
| 100 | var big = card.querySelector('.chart-big .big'); if (big) big.textContent = fmt(vals[n - 1]); | |
| 101 | var note = card.querySelector('.chart-note'); if (note) note.textContent = list[n - 1][0] + ', the latest of ' + n; | |
| 102 | words(card, list); return true; | |
| 103 | } | |
| 104 | var s = scale(lo, hi); | |
| 105 | var ys = card.querySelectorAll('.chart-y span'); | |
| 106 | if (ys.length === 3) { ys[0].textContent = fmt(s.top); ys[1].textContent = fmt((s.top + s.bottom) / 2); ys[2].textContent = fmt(s.bottom); } | |
| 107 | if (kind === 'bar') { | |
| 108 | clear(plot, '.bar'); | |
| 109 | var slot = 100 / n; | |
| 110 | list.forEach(function (p, i) { | |
| 111 | var top = Math.min(s.y(p[1]), s.y(0)), h = Math.abs(s.y(p[1]) - s.y(0)); | |
| 112 | plot.appendChild(el('rect', { 'class': 'bar', x: r2(slot * i + slot * 0.15), y: r2(top), width: r2(slot * 0.7), height: r2(h) }, p[0] + ': ' + fmt(p[1]))); | |
| 113 | }); | |
| 114 | } else { | |
| 115 | var d2 = line(vals, s.y), ln = plot.querySelector('.chart-line'), wash = plot.querySelector('.chart-wash'); | |
| 116 | if (!ln) return false; | |
| 117 | ln.setAttribute('d', d2); | |
| 118 | if (wash && n > 1) wash.setAttribute('d', d2 + ' L100 ' + r2(s.y(0)) + ' L0 ' + r2(s.y(0)) + ' Z'); | |
| 119 | clear(plot, '.chart-hit'); | |
| 120 | list.forEach(function (p, i) { | |
| 121 | var l = i === 0 || n < 2 ? 0 : (i + i - 1) * 50 / (n - 1), rt = i === n - 1 ? 100 : (i + i + 1) * 50 / (n - 1); | |
| 122 | plot.appendChild(el('rect', { 'class': 'chart-hit', x: r2(l), y: '0', width: r2(rt - l), height: '100' }, p[0] + ': ' + fmt(p[1]))); | |
| 123 | }); | |
| 124 | } | |
| 125 | words(card, list); return true; | |
| 126 | } | |
| 127 | function paint() { | |
| 128 | var s = Math.max(0, Math.round((Date.now() - at) / 1000)); | |
| 129 | say.textContent = stale ? 'live \\u00b7 some charts changed a lot; reload to redraw' : live ? 'live \\u00b7 updated ' + (s < 2 ? 'just now' : s + 's ago') : 'paused \\u00b7 reconnecting'; | |
| 130 | say.setAttribute('data-state', live ? 'live' : 'paused'); | |
| 131 | } | |
| 132 | function parse(e) { try { return JSON.parse(e.data); } catch (_) { return null; } } | |
| 133 | es.addEventListener('hello', function (e) { | |
| 134 | var d = parse(e); live = true; at = Date.now(); | |
| 135 | if (d && d.base) d.base.forEach(function (b) { pts[b.i] = b.points; }); | |
| 136 | paint(); | |
| 137 | }); | |
| 138 | es.addEventListener('panels', function (e) { | |
| 139 | var d = parse(e); if (!d) return; | |
| 140 | at = Date.now(); live = true; | |
| 141 | var cards = grid.querySelectorAll('.bp'); | |
| 142 | d.panels.forEach(function (p) { | |
| 143 | var card = cards[p.i]; if (!card) return; | |
| 144 | var n = card.querySelector('.bp-now .num'); | |
| 145 | if (n && p.now) n.textContent = p.now; | |
| 146 | var list = pts[p.i], box = card.querySelector('.chart'), kind = box && box.getAttribute('data-chart'); | |
| 147 | if (!list || !kind) { stale = true; return; } | |
| 148 | p.points.forEach(function (q) { | |
| 149 | for (var i = 0; i < list.length; i++) if (list[i][0] === q[0]) { list[i][1] = q[1]; return; } | |
| 150 | list.push([q[0], q[1]]); | |
| 151 | }); | |
| 152 | if (!draw(card, kind, list)) stale = true; | |
| 153 | }); | |
| 154 | if (d.reload) stale = true; | |
| 155 | paint(); | |
| 156 | }); | |
| 157 | es.onerror = function () { live = false; paint(); }; | |
| 158 | setInterval(paint, 1000); | |
| 159 | })(); | |
| 160 | `; |
src/web/pages/boards-view.ts +25 −8
| @@ -2,8 +2,9 @@ | ||
| 2 | 2 | * Boards, drawn: `/boards` lists them and makes one, `/boards/:slug` is the |
| 3 | 3 | * grid with each panel's chart and, under it, the panels' management (edit, |
| 4 | 4 | * move, remove) and the board's own (rename, range, live, duplicate, |
| 5 | * delete). A live board's grid names a stream (`/boards/:slug/stream`, | |
| 6 | * `boards-stream.ts`) that carries new points; the page is never refetched. | |
| 5 | * delete). The grid is a live region with an address of its own | |
| 6 | * (`/boards/:slug/live`): a board that is live is refetched, by the same | |
| 7 | * swap the wall uses, when a run, pull, check, issue or usage event arrives. | |
| 7 | 8 | * No client framework. Every form posts to `boards-edit.ts`. Anyone but a |
| 8 | 9 | * person who is an admin gets the not-found page. |
| 9 | 10 | */ |
| @@ -14,10 +15,9 @@ import type { Ctx } from "../../http/context.ts"; | ||
| 14 | 15 | import { driftSection } from "./boards-drift.ts"; |
| 15 | 16 | import { notePhase, takeSessionTime, timePhase, timePhaseAsync } from "../../core/route_timing.ts"; |
| 16 | 17 | import { liveRegionsJs } from "../client.ts"; |
| 17 | import { boardStreamJs } from "./boards-stream.ts"; | |
| 18 | 18 | import { notFoundPage, signInFirst } from "../chrome.ts"; |
| 19 | 19 | import { html, when, type Html } from "../html.ts"; |
| 20 | import { page } from "../layout.ts"; | |
| 20 | import { fragment, page } from "../layout.ts"; | |
| 21 | 21 | import { btn, chartFrame, confirmAction, field, selectField } from "../ui.ts"; |
| 22 | 22 | import { emptyList } from "../empty_words.ts"; |
| 23 | 23 | import { fold, reading, readingFailed, readingJs } from "../figure.ts"; |
| @@ -31,6 +31,12 @@ import { drawnPanel, panelData, runFor, type PanelDrawn } from "../../boards/pan | ||
| 31 | 31 | import { readParams } from "../../boards/params.ts"; |
| 32 | 32 | import { paramsOf, queryFields } from "./boards.ts"; |
| 33 | 33 | |
| 34 | /** | |
| 35 | * The events the panels' queries read (runs, pulls, checks, issues, usage): any of them may change | |
| 36 | * a chart. | |
| 37 | */ | |
| 38 | const READS = "run.queued,run.started,run.finished,pull.*,check.*,issue.*,usage.*"; | |
| 39 | ||
| 34 | 40 | const sizes = (max: number, word: string, now: number) => |
| 35 | 41 | [1, 2, 3].slice(0, max).map((n) => ({ value: String(n), label: `${String(n)} ${word}`, selected: n === now })); |
| 36 | 42 | |
| @@ -66,14 +72,14 @@ export function drawPanel( | ||
| 66 | 72 | </div>`; |
| 67 | 73 | } |
| 68 | 74 | |
| 69 | /** The grid: each panel as drawn, naming the stream when the board is live. */ | |
| 75 | /** The grid alone: what the page shows and what the live address answers with. */ | |
| 70 | 76 | function grid(app: App, slug: string, board: Board, panels: readonly PanelDrawn[]): Html { |
| 71 | 77 | return html`<section |
| 72 | 78 | class="bgrid" |
| 73 | 79 | id="board-grid" |
| 74 | 80 | ${board.refresh === "off" |
| 75 | 81 | ? null |
| 76 | : html`data-stream="/boards/${slug}/stream"`} | |
| 82 | : html`data-live="${READS}" data-live-src="/boards/${slug}/live"`} | |
| 77 | 83 | > |
| 78 | 84 | ${board.panels.length === 0 |
| 79 | 85 | ? html`<p class="muted bp-w3">This board has no panel yet. Add the first one under "Add a panel" below, or pin a chart from <a href="/boards/data">Explore the data</a>.</p>` |
| @@ -272,14 +278,25 @@ export async function boardShow(ctx: Ctx): Promise<Response> { | ||
| 272 | 278 | wide: true, |
| 273 | 279 | body: html`<div class="hf bd"> |
| 274 | 280 | <header class="hf-head"> |
| 275 | <div class="hf-title"><h1>${board.title}</h1><p class="hf-live muted">${String(n)} ${n === 1 ? "chart" : "charts"} over ${RANGE_WORDS[board.range].toLowerCase()}. Times are UTC. ${board.refresh === "off" ? null : html`<span id="board-live" class="num" role="status" data-state="idle">Moves as events arrive.</span>`}</p></div> | |
| 281 | <div class="hf-title"><h1>${board.title}</h1><p class="hf-live muted">${String(n)} ${n === 1 ? "chart" : "charts"} over ${RANGE_WORDS[board.range].toLowerCase()}${board.refresh === "off" ? "" : ", redrawn as things happen"}. Times are UTC.</p></div> | |
| 276 | 282 | <nav class="bd-nav" aria-label="Elsewhere">${btn("All boards", { href: "/boards", variant: "ghost" })}${btn("Explore the data", { href: "/boards/data", variant: "ghost" })}</nav> |
| 277 | 283 | </header> |
| 278 | 284 | ${panels} |
| 279 | 285 | ${manage(slug, board, queryFields(readParams(ctx.url.searchParams)), listPins(ctx.app.db, ctx.auth.user?.id ?? ""))} |
| 280 | 286 | </div>`, |
| 281 | scriptJs: boardStreamJs, | |
| 287 | scriptJs: liveRegionsJs, | |
| 282 | 288 | }); |
| 283 | 289 | notePhase(ctx.request, "render", performance.now() - rendering); |
| 284 | 290 | return response; |
| 285 | 291 | } |
| 292 | ||
| 293 | // GET /boards/:slug/live | |
| 294 | export async function boardLive(ctx: Ctx): Promise<Response> { | |
| 295 | if (denied(ctx)) return fragment(html``, { status: 404 }); | |
| 296 | const slug = ctx.params.slug ?? ""; | |
| 297 | if (!isSlug(slug)) return fragment(html``, { status: 404 }); | |
| 298 | const picture = await boardPicture(ctx.app, slug); | |
| 299 | if (picture === undefined || isFailed(picture)) return fragment(html``, { status: 503 }); | |
| 300 | if (picture.board === null) return fragment(html``, { status: 404 }); | |
| 301 | return fragment(grid(ctx.app, slug, picture.board, picture.panels), { request: ctx.request }); | |
| 302 | } |
test/boards-doors.test.ts +2 −1
| @@ -77,12 +77,13 @@ describe("/boards doors", () => { | ||
| 77 | 77 | expect(page).toContain("<h1>Mine</h1>"); |
| 78 | 78 | expect(page).toContain("One"); |
| 79 | 79 | expect(await (await get("/boards", "alice")).text()).toContain("/boards/mine"); |
| 80 | expect((await get("/boards/mine/live", "alice")).status).toBe(200); | |
| 80 | 81 | }); |
| 81 | 82 | |
| 82 | 83 | for (const who of [null, "bob"]) { |
| 83 | 84 | const name = who ?? "a guest"; |
| 84 | 85 | test(`${name}: every board page is not found`, async () => { |
| 85 | for (const path of ["/boards", "/boards/mine", "/boards/mine/stream"]) { | |
| 86 | for (const path of ["/boards", "/boards/mine", "/boards/mine/live"]) { | |
| 86 | 87 | const r = await get(path, who); |
| 87 | 88 | // The list sends a guest to sign in first; it is never the list. |
| 88 | 89 | if (who === null && path === "/boards") { |
test/boards-store.test.ts +11 −7
| @@ -191,14 +191,18 @@ describe("/boards", () => { | ||
| 191 | 191 | const body = await (await asAdmin("/boards/fleet-health")).text(); |
| 192 | 192 | const grid = body.match(/<section[^>]*id="board-grid"[^>]*>/)?.[0] ?? ""; |
| 193 | 193 | expect(grid).not.toContain("data-live-every"); |
| 194 | expect(grid).not.toContain("data-live="); | |
| 195 | expect(grid).toContain('data-stream="/boards/fleet-health/stream"'); | |
| 194 | expect(grid).toMatch(/data-live="[^"]+"/); | |
| 195 | expect(grid).toContain('data-live="run.queued,run.started,run.finished,pull.*,check.*,issue.*,usage.*"'); | |
| 196 | expect(body).toContain('data-live-src="/boards/fleet-health/live"'); | |
| 196 | 197 | expect(body).toMatch(/<option\s+value="10s"\s+selected\s*>\s*on: redraw when events arrive\s*<\/option>/); |
| 197 | 198 | expect(body).not.toContain(">1m</option>"); |
| 198 | expect(body).toContain('data-state="idle">Moves as events arrive.'); | |
| 199 | expect(body).not.toContain("connecting"); | |
| 200 | expect(body.match(LINE)?.length).toBe(3); | |
| 201 | expect((await asAdmin("/boards/fleet-health/live")).status).toBe(405); // the HTML grid door is gone: the stream replaced it | |
| 199 | const live = await asAdmin("/boards/fleet-health/live"); | |
| 200 | expect(live.status).toBe(200); | |
| 201 | const text = await live.text(); | |
| 202 | expect(text.startsWith("<section")).toBe(true); | |
| 203 | expect(text.match(LINE)?.length).toBe(3); | |
| 204 | const again = await asAdmin("/boards/fleet-health/live", { headers: { "if-none-match": live.headers.get("etag")! } }); | |
| 205 | expect(again.status).toBe(304); | |
| 202 | 206 | expect((await post("/boards/fleet-health/settings", { range: "weeks", refresh: "10s" })).headers.get("set-cookie")).toContain("danger"); |
| 203 | 207 | }); |
| 204 | 208 | |
| @@ -264,7 +268,7 @@ describe("/boards", () => { | ||
| 264 | 268 | }); |
| 265 | 269 | |
| 266 | 270 | test("a non-admin and a stranger get 404 on every board route", async () => { |
| 267 | for (const path of ["/boards", "/boards/fleet-health", "/boards/fleet-health/stream"]) { | |
| 271 | for (const path of ["/boards", "/boards/fleet-health", "/boards/fleet-health/live"]) { | |
| 268 | 272 | expect((await fetch(servers.url + path, { headers: { authorization: `Bearer ${tok.bob}` } })).status).toBe(404); |
| 269 | 273 | const stranger = await fetch(servers.url + path, { redirect: "manual" }); |
| 270 | 274 | // The list sends a stranger to sign in (#6733, so /flow is no dead end); a board itself stays a 404. |
test/boards-stream.test.ts deleted −201
| @@ -1,201 +0,0 @@ | ||
| 1 | /** | |
| 2 | * A board is live by points (#3692): a new data point reaches an open board | |
| 3 | * within 2 s in under 2 KB, nothing is sent while idle, and the stream is an | |
| 4 | * admin's. `deltaOf` is checked on its own. | |
| 5 | */ | |
| 6 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 7 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 8 | import { tmpdir } from "node:os"; | |
| 9 | import { join } from "node:path"; | |
| 10 | import { writeBoard } from "../src/actions/boards.ts"; | |
| 11 | import { createApp } from "../src/app.ts"; | |
| 12 | import { deltaOf, MAX_POINTS, seenOf } from "../src/boards/delta.ts"; | |
| 13 | import type { Board, Panel } from "../src/boards/store.ts"; | |
| 14 | import { createRun } from "../src/core/runs.ts"; | |
| 15 | import { createToken } from "../src/core/tokens.ts"; | |
| 16 | import { createUser } from "../src/core/users.ts"; | |
| 17 | import { serve } from "../src/http/server.ts"; | |
| 18 | import { hubsOpen, watchBoard, type Frame } from "../src/boards/live_hub.ts"; | |
| 19 | import { boardStreamJs } from "../src/web/pages/boards-stream.ts"; | |
| 20 | ||
| 21 | const panel: Panel = { title: "Runs", chart: "bar", query: { source: "runs", aggregate: "count", groupBy: "kind" }, w: 1, h: 1 }; | |
| 22 | ||
| 23 | describe("deltaOf", () => { | |
| 24 | test("only new or moved points, and nothing when nothing moved", () => { | |
| 25 | const rows = [{ group: "check", value: 2 }, { group: "deploy", value: 1 }]; | |
| 26 | const seen = seenOf(rows); | |
| 27 | expect(deltaOf(0, panel, rows, seen).delta).toBeNull(); | |
| 28 | const r = deltaOf(0, panel, [{ group: "check", value: 3 }, { group: "deploy", value: 1 }, { group: "build", value: 1 }], seen); | |
| 29 | expect(r.delta?.points).toEqual([["check", 3], ["build", 1]]); | |
| 30 | }); | |
| 31 | test("a burst past the cap is cut and flagged", () => { | |
| 32 | const rows = Array.from({ length: MAX_POINTS + 5 }, (_, i) => ({ group: `g${String(i)}`, value: 1 })); | |
| 33 | const r = deltaOf(0, panel, rows, new Map()); | |
| 34 | expect(r.delta?.points.length).toBe(MAX_POINTS); | |
| 35 | expect(r.tooMany).toBe(true); | |
| 36 | }); | |
| 37 | }); | |
| 38 | ||
| 39 | describe("GET /boards/:slug/stream", () => { | |
| 40 | let dir: string; | |
| 41 | let app: ReturnType<typeof createApp>; | |
| 42 | let servers: Awaited<ReturnType<typeof serve>>; | |
| 43 | let admin = ""; | |
| 44 | let other = ""; | |
| 45 | beforeAll(async () => { | |
| 46 | dir = await mkdtemp(join(tmpdir(), "forge-boards-stream-")); | |
| 47 | app = createApp({ dataDir: dir, port: 0 }); | |
| 48 | servers = await serve(app); | |
| 49 | const mk = async (username: string, adminIfFirst?: boolean) => { | |
| 50 | const r = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase", ...(adminIfFirst ? { adminIfFirst } : {}) }); | |
| 51 | if (!r.ok) throw new Error(r.error); | |
| 52 | return r.value; | |
| 53 | }; | |
| 54 | const alice = await mk("alice", true); | |
| 55 | const bob = await mk("bob"); | |
| 56 | admin = createToken(app.db, alice.id, "t", "admin").token; | |
| 57 | other = createToken(app.db, bob.id, "t", "admin").token; | |
| 58 | app.db.run("INSERT INTO repo (id, owner_id, name) VALUES ('r1', ?, 'app')", [alice.id]); | |
| 59 | const w = await writeBoard(app, alice, "live", { title: "Live", range: "all", refresh: "10s", panels: [panel] }); | |
| 60 | if (!w.ok) throw new Error(JSON.stringify(w.error)); | |
| 61 | }); | |
| 62 | afterAll(async () => { | |
| 63 | await servers.stop?.(); | |
| 64 | await rm(dir, { recursive: true, force: true }); | |
| 65 | }); | |
| 66 | const open = (who: string, slug = "live", signal?: AbortSignal) => | |
| 67 | fetch(`${servers.url}/boards/${slug}/stream`, { headers: { authorization: `Bearer ${who}` }, ...(signal ? { signal } : {}) }); | |
| 68 | ||
| 69 | test("not an admin's, or not a board: not found", async () => { | |
| 70 | expect((await open(other)).status).toBe(404); | |
| 71 | expect((await open(admin, "nope")).status).toBe(404); | |
| 72 | }); | |
| 73 | ||
| 74 | test("a new point arrives within 2 s in under 2 KB, and an idle stream sends nothing", async () => { | |
| 75 | const stop = new AbortController(); | |
| 76 | const res = await open(admin, "live", stop.signal); | |
| 77 | expect(res.headers.get("content-type")).toContain("text/event-stream"); | |
| 78 | const reader = res.body!.getReader(); | |
| 79 | const dec = new TextDecoder(); | |
| 80 | let text = ""; | |
| 81 | let pending: ReturnType<typeof reader.read> | undefined; | |
| 82 | const until = async (needle: string, ms: number) => { | |
| 83 | const end = Date.now() + ms; | |
| 84 | while (!text.includes(needle) && Date.now() < end) { | |
| 85 | pending ??= reader.read(); | |
| 86 | const got = await Promise.race([pending, new Promise<null>((r) => setTimeout(() => r(null), Math.max(1, end - Date.now())))]); | |
| 87 | if (got === null) continue; | |
| 88 | pending = undefined; | |
| 89 | if (got.done) break; | |
| 90 | text += dec.decode(got.value); | |
| 91 | } | |
| 92 | return text.includes(needle); | |
| 93 | }; | |
| 94 | expect(await until("event: hello", 2000)).toBe(true); | |
| 95 | expect(text).toContain('"base":[{"i":0,"points":['); | |
| 96 | // Idle: an event the board does not read moves nothing. | |
| 97 | app.bus.append({ kind: "run.queued", repoId: "r1", payload: {} }); | |
| 98 | expect(await until("event: panels", 1200)).toBe(false); | |
| 99 | const sent = text.length; | |
| 100 | createRun(app.db, { repoId: "r1", kind: "check" }); | |
| 101 | app.bus.append({ kind: "run.queued", repoId: "r1", payload: {} }); | |
| 102 | const t0 = Date.now(); | |
| 103 | expect(await until("event: panels", 2000)).toBe(true); | |
| 104 | expect(Date.now() - t0).toBeLessThan(2000); | |
| 105 | const frame = text.slice(sent); | |
| 106 | expect(new TextEncoder().encode(frame).length).toBeLessThan(2048); | |
| 107 | expect(frame).toContain('"check"'); | |
| 108 | stop.abort(); | |
| 109 | }); | |
| 110 | }); | |
| 111 | ||
| 112 | describe("one read per board", () => { | |
| 113 | test("every watcher of a board shares one hub, hears the same frame, and the last one out stops it", async () => { | |
| 114 | const dir = await mkdtemp(join(tmpdir(), "forge-boards-hub-")); | |
| 115 | const app = createApp({ dataDir: dir, port: 0 }); | |
| 116 | const board: Board = { title: "Hub", range: "all", refresh: "10s", panels: [panel] }; | |
| 117 | const made = await createUser(app.db, { origin: "seed", trusted: true, username: "carol", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true }); | |
| 118 | if (!made.ok) throw new Error(made.error); | |
| 119 | app.db.run("INSERT INTO repo (id, owner_id, name) VALUES ('r1', ?, 'app')", [made.value.id]); | |
| 120 | const a: Frame[] = []; | |
| 121 | const b: Frame[] = []; | |
| 122 | let heard!: () => void; | |
| 123 | const both = new Promise<void>((r) => (heard = r)); | |
| 124 | const hear = (into: Frame[]) => (f: Frame) => { | |
| 125 | into.push(f); | |
| 126 | if (a.length > 0 && b.length > 0) heard(); | |
| 127 | }; | |
| 128 | const one = watchBoard(app, "hub", board, hear(a)); | |
| 129 | const two = watchBoard(app, "hub", board, hear(b)); | |
| 130 | expect(hubsOpen(app)).toBe(1); | |
| 131 | createRun(app.db, { repoId: "r1", kind: "check" }); | |
| 132 | app.bus.append({ kind: "run.queued", repoId: "r1", payload: {} }); | |
| 133 | await both; | |
| 134 | expect(a.length).toBe(1); | |
| 135 | expect(b).toEqual(a); | |
| 136 | one.stop(); | |
| 137 | expect(hubsOpen(app)).toBe(1); | |
| 138 | two.stop(); | |
| 139 | expect(hubsOpen(app)).toBe(0); | |
| 140 | await rm(dir, { recursive: true, force: true }); | |
| 141 | }); | |
| 142 | }); | |
| 143 | ||
| 144 | describe("the page's drawer", () => { | |
| 145 | /** A page of one bar panel, as little of a DOM as the client script asks of one. */ | |
| 146 | function drawnPage() { | |
| 147 | const mk = (cls = "") => { | |
| 148 | const e: any = { kids: [] as any[], attrs: { class: cls } as Record<string, string>, text: "", parentNode: null }; | |
| 149 | e.setAttribute = (k: string, v: string) => (e.attrs[k] = v); | |
| 150 | e.getAttribute = (k: string) => e.attrs[k] ?? null; | |
| 151 | e.appendChild = (c: any) => (c.parentNode = e, e.kids.push(c), c); | |
| 152 | e.remove = () => (e.parentNode.kids = e.parentNode.kids.filter((k: any) => k !== e)); | |
| 153 | e.querySelectorAll = (sel: string) => (sel === ".bar" ? e.kids.filter((k: any) => k.attrs.class === "bar") : sel === ".chart-hit" ? [] : []); | |
| 154 | Object.defineProperty(e, "textContent", { get: () => e.text + e.kids.map((k: any) => k.textContent).join(""), set: (v: string) => ((e.text = v), (e.kids = [])) }); | |
| 155 | return e; | |
| 156 | }; | |
| 157 | const plot = mk("chart-plot"); | |
| 158 | const ys = [mk(), mk(), mk()]; | |
| 159 | const now = mk(); | |
| 160 | const sr = mk(); | |
| 161 | const box = mk("chart"); | |
| 162 | box.attrs["data-chart"] = "bar"; | |
| 163 | box.attrs["aria-label"] = "Runs"; | |
| 164 | const card = mk("bp"); | |
| 165 | card.querySelector = (sel: string) => ({ ".bp-now .num": now, ".chart": box, ".chart .sr-only": sr, "svg.chart-plot": plot }[sel] ?? null); | |
| 166 | card.querySelectorAll = (sel: string) => (sel === ".chart-y span" ? ys : []); | |
| 167 | const grid = mk(); | |
| 168 | grid.attrs["data-stream"] = "/boards/x/stream"; | |
| 169 | grid.querySelectorAll = () => [card]; | |
| 170 | const say = mk(); | |
| 171 | const heard: Record<string, (e: { data: string }) => void> = {}; | |
| 172 | const run = new Function("document", "EventSource", "setInterval", boardStreamJs); | |
| 173 | run( | |
| 174 | { getElementById: (id: string) => (id === "board-grid" ? grid : say), createElementNS: (_: string, t: string) => mk(t) }, | |
| 175 | class { constructor() {} addEventListener(n: string, f: (e: { data: string }) => void) { heard[n] = f; } }, | |
| 176 | () => 0, | |
| 177 | ); | |
| 178 | return { heard, plot, ys, now, say, sr }; | |
| 179 | } | |
| 180 | ||
| 181 | test("a frame redraws the bars, the axis and the latest number, from the hello's points", () => { | |
| 182 | const p = drawnPage(); | |
| 183 | p.heard.hello!({ data: JSON.stringify({ at: 1, base: [{ i: 0, points: [["check", 2], ["deploy", 1]] }] }) }); | |
| 184 | p.heard.panels!({ data: JSON.stringify({ at: 2, panels: [{ i: 0, points: [["check", 5], ["build", 3]], now: "3" }] }) }); | |
| 185 | const bars = p.plot.kids.filter((k: any) => k.attrs.class === "bar"); | |
| 186 | expect(bars.length).toBe(3); | |
| 187 | expect(bars[0].textContent).toBe("check: 5"); | |
| 188 | expect(bars[2].textContent).toBe("build: 3"); | |
| 189 | expect(p.ys[0].textContent).toBe("5"); | |
| 190 | expect(p.now.textContent).toBe("3"); | |
| 191 | expect(p.sr.textContent).toContain("3 points; lowest 1, highest 5, latest 3"); | |
| 192 | expect(p.say.textContent).toContain("live"); | |
| 193 | }); | |
| 194 | ||
| 195 | test("a chart it cannot draw says so instead of going quiet", () => { | |
| 196 | const p = drawnPage(); | |
| 197 | p.heard.hello!({ data: JSON.stringify({ at: 1, base: [] }) }); | |
| 198 | p.heard.panels!({ data: JSON.stringify({ at: 2, panels: [{ i: 0, points: [["check", 5]] }] }) }); | |
| 199 | expect(p.say.textContent).toContain("reload to redraw"); | |
| 200 | }); | |
| 201 | }); |
test/job-slices.test.ts −1
| @@ -276,7 +276,6 @@ const UNTIMED: Record<string, string> = { | ||
| 276 | 276 | "drill-watch": "a /proc read of the drill child's memory and a state write every WATCH_MS, only while a restore drill runs in its own process; drill-job tests drive runDrillInChild directly", |
| 277 | 277 | "meter-watch": "one indexed read of held-full windows every 15 minutes, and a status fetch only while one is held full; meter-watch.test.ts drives it with a fake fetcher; the fixture holds no window", |
| 278 | 278 | "talk-live": "a one-shot timer in talkStream (web/pages/talk.ts), armed only while a person has /talk open and a reply is being written: it sends that one stream its latest live frame, at most one per 125 ms, drawing a block of at most 20,000 characters; talk-live.test.ts drives the stream and counts its frames", |
| 279 | "boards-stream": "a one-shot timer in boards/live_hub.ts, armed only while a person has /boards/<slug> open: one read per board for every tab, sent as the points newer than the last, at most one per MIN_GAP_MS; boards-stream.test.ts drives the stream and counts its frames", | |
| 280 | 279 | "view-stream-send": "re-reads the forge view for one open stream, at most once per VIEW_GAP_MS, only while an agent follows the view; the view is cached and forge-view-stream.test.ts drives it", |
| 281 | 280 | "view-stream-token-check": "one user read and one token read every 30 s per open stream; forge-view-stream.test.ts drives revocation", |
| 282 | 281 | desk: "expires notes past their time: one indexed delete on the desk table every 30 s (actions/desk.ts); the fixture has no notes", |
test/no-polling.test.ts +1 −2
| @@ -110,7 +110,6 @@ const ALLOWED: Record<string, { allow: string[]; why: string }> = { | ||
| 110 | 110 | "src/web/pages/talk.ts": { allow: ["setInterval"], why: "server side: the stream of one turn watches the run's row, which has no event to hear" }, |
| 111 | 111 | "src/web/client.ts": { allow: ["setInterval"], why: "clocks that only redraw text" }, |
| 112 | 112 | "src/web/space_client.ts": { allow: ["setInterval"], why: "the map clock label only redraws text; it fetches and reloads nothing" }, |
| 113 | "src/web/pages/boards-stream.ts": { allow: ["setInterval"], why: "the board's \"updated Ns ago\" label only redraws text; the stream carries the data" }, | |
| 114 | 113 | }; |
| 115 | 114 | |
| 116 | 115 | const PATTERNS: [string, RegExp][] = [ |
| @@ -323,7 +322,7 @@ const NOT_WALKED: Record<string, string> = { | ||
| 323 | 322 | "/:owner/:name/variants/:group": "needs a variant group of agent tries", |
| 324 | 323 | "/:owner/:name/waves/:version": "needs a wave of a milestone", |
| 325 | 324 | "/boards/:slug": "needs a board", |
| 326 | "/boards/:slug/stream": "needs a board; a stream, not a page", | |
| 325 | "/boards/:slug/live": "needs a board; a stream, not a page", | |
| 327 | 326 | "/bring/:id/:job": "needs a bring job", |
| 328 | 327 | "/claim/start/:token": "needs the one-time token an anonymous start returned", |
| 329 | 328 | "/join/:token": "needs a one-use link to work on a repository, which a repository's admin mints", |
test/pages-budget.test.ts +1 −1
| @@ -75,7 +75,7 @@ const MAX_UNFIXTURED = 158; // +1: /:owner/:name/large/:oid, a redirect to a pre | ||
| 75 | 75 | const NOT_PAGES = new Set([ |
| 76 | 76 | "/events", "/system/stream", "/settings/teams/stream", "/fleet/graph/live", |
| 77 | 77 | "/settings/traffic/scrapes/export", "/settings/backups/live", "/:owner/:name/stream", |
| 78 | "/settings/origins/flows/:id/stream", "/boards/:slug/stream", "/:owner/:name/archive/:file", // a tarball download, not a page | |
| 78 | "/settings/origins/flows/:id/stream", "/:owner/:name/archive/:file", // a tarball download, not a page | |
| 79 | 79 | "/api/v1/runner/jobs/:id/git/info/refs", // a runner's git door for one job (#13652), not a page |
| 80 | 80 | ]); |
| 81 | 81 |
test/tui-boards.test.ts −12
| @@ -18,7 +18,6 @@ import { boardRows, boardsScreen, dataLine, refusal, stepWords } from "../src/tu | ||
| 18 | 18 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; |
| 19 | 19 | import { quietLogs } from "./helpers/globals.ts"; |
| 20 | 20 | import { settleApp } from "./helpers/tui.ts"; |
| 21 | import type { Board, Panel } from "../src/boards/store.ts"; | |
| 22 | 21 | |
| 23 | 22 | quietLogs(); |
| 24 | 23 | |
| @@ -236,14 +235,3 @@ describe("tui boards", () => { | ||
| 236 | 235 | expect(refusal({ refused: "bad\u001b[2J" })).toBe("That was refused: bad [2J."); |
| 237 | 236 | }); |
| 238 | 237 | }); |
| 239 | ||
| 240 | test("a live frame says, under its panel, how many points moved and the latest value", async () => { | |
| 241 | const { boardLines, liveWords } = await import("../src/tui/screens/boards.ts"); | |
| 242 | const frame = { at: Date.UTC(2026, 10, 29, 16, 5, 9), panels: [{ i: 1, points: [["a", 1], ["b", 2]] as [string, number][], now: "2" }] }; | |
| 243 | expect(liveWords(frame, 0)).toBeUndefined(); | |
| 244 | expect(liveWords(frame, 1)).toBe("live 16:05:09Z: 2 points moved · latest 2"); | |
| 245 | const one: Panel = { title: "A", chart: "bar", query: { source: "runs", aggregate: "count", groupBy: "kind" }, w: 1, h: 1 }; | |
| 246 | const board: Board = { title: "T", range: "all", refresh: "10s", panels: [one, { ...one, title: "B" }] }; | |
| 247 | const lines = boardLines(board, -1, [], [], new Map([[1, liveWords(frame, 1)!]])); | |
| 248 | expect(lines.filter((l) => l.includes("live 16:05:09Z"))).toHaveLength(1); | |
| 249 | }); |
new above
offline