Public: anyone can read this; the crew can change it.
Observability 3: boards are live by streaming per-panel points, never by re-fetching HTML #3714
mason/forge:mason/3692-observability-3-boards-are-live-by-strea → main 4 commits fork
14 files
changed +665
−71
README.md +1 −2
| @@ -1721,8 +1721,7 @@ work here. | ||
| 1721 | 1721 | - `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); |
| 1722 | 1722 | - the `board_pins` MCP tool (no `op` lists; `op` pin, unpin or move changes). `pins` is therefore not a board slug. |
| 1723 | 1723 | The first boot also writes seven starting boards, **Usage**, **Crew**, **Releases**, **Apps**, **Security**, **Throughput** and **Forges**. 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. |
| 1724 | 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 | |
| 1725 | (`/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` | |
| 1724 | A live board (any `refresh` but `off`; the form offers off or on, and `10s` and `1m` are still accepted and mean the same) streams its panels' new points, never HTML: one event stream (`/boards/:slug/stream`) whose `points` frames carry, per changed panel, the cells that are new or moved and the keys that left (`boards/delta.ts`; a panel whose order changed is sent whole), read again when any event lands or the machine is sampled, a burst settling into one read at most once a second, and nothing sent when nothing changed. Each frame's id is the board's version (a digest per panel), so a page just drawn or a stream resumed is sent only what it does not hold. The browser applies a frame and redraws the panel with the server's own chart code (`web/board-live-client.ts`, bundled once per process and served content-addressed), and the head of the board says `live · updated Ns ago`, with Pause / Resume (`?pause` opens nothing); a board saved meanwhile says so and offers a reload. The same doors are in the API: `GET /api/v1/boards`, `GET|PUT|DELETE /api/v1/boards/:slug` | |
| 1726 | 1725 | (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, for the same person, a **Boards** screen in the terminal that lists boards and shows a board's panels as text. No dependency was added. |
| 1727 | 1726 | - **Issues** — labels, threaded comments, close/reopen, markdown. |
| 1728 | 1727 | - **Pull requests** — open from a branch, a **beautiful diff viewer** (syntax |
src/boards/chart.ts +11 −1
| @@ -7,7 +7,7 @@ | ||
| 7 | 7 | * `currentColor` (series are told apart by opacity and named in a legend); |
| 8 | 8 | * every label is stripped of what XML cannot carry, clamped, then escaped. |
| 9 | 9 | */ |
| 10 | import { escapeXml } from "../web/og/card.ts"; | |
| 10 | import { escapeXml } from "../web/og/xml.ts"; | |
| 11 | 11 | |
| 12 | 12 | export type Point = { label: string; value: number; href?: string }; |
| 13 | 13 | /** A point of a grouped query: `label` is the x (a time bucket), `series` the category. */ |
| @@ -274,3 +274,13 @@ export function drawChart(chart: Chart, cells: readonly Cell[], title: string): | ||
| 274 | 274 | case "table": return tableChart(cells, title); |
| 275 | 275 | } |
| 276 | 276 | } |
| 277 | ||
| 278 | /** | |
| 279 | * A panel's body: its chart in the box that holds its space, or why its | |
| 280 | * query did not run. The page draws it on the server and the live board | |
| 281 | * (`web/board-live-client.ts`) redraws it in the browser, from the same code. | |
| 282 | */ | |
| 283 | export function panelBody(chart: Chart, reading: { cells: readonly Cell[] } | { error: string }, title: string): string { | |
| 284 | if ("error" in reading) return `<p class="muted small">${escapeXml(reading.error)}</p>`; | |
| 285 | return `<div class="chart-box${chart === "table" ? " is-table" : ""}">${drawChart(chart, reading.cells, title)}</div>`; | |
| 286 | } |
src/boards/delta.ts added +91
| @@ -0,0 +1,91 @@ | ||
| 1 | /** | |
| 2 | * What changed in a panel between two readings, small enough to stream: the | |
| 3 | * cells that are new or moved (`set`) and the keys that left (`drop`). A | |
| 4 | * cell's key is its x label and its series. Pure, no I/O: the server diffs | |
| 5 | * with it and the browser (`web/board-live-client.ts`) applies with it, so | |
| 6 | * the two never disagree about what a delta means. | |
| 7 | * | |
| 8 | * Order is part of a chart (x labels are drawn in the order first seen), so | |
| 9 | * applying keeps a set cell where it was, appends a new one, and removes a | |
| 10 | * dropped one. When that would not give the next reading's order, the delta | |
| 11 | * is a `reset`: the whole next reading. | |
| 12 | */ | |
| 13 | import type { Cell } from "./chart.ts"; | |
| 14 | ||
| 15 | /** A panel's reading: its cells, or why its query did not run. */ | |
| 16 | export type Reading = { cells: Cell[] } | { error: string }; | |
| 17 | ||
| 18 | export type Delta = { set: Cell[]; drop: string[] } | { reset: Cell[] } | { error: string }; | |
| 19 | ||
| 20 | export const keyOf = (c: Cell): string => (c.series === undefined ? c.label : `${c.label}\u0000${c.series}`); | |
| 21 | ||
| 22 | const same = (a: Cell, b: Cell) => | |
| 23 | a.label === b.label && a.value === b.value && a.series === b.series && a.href === b.href; | |
| 24 | ||
| 25 | /** The reading after `delta`. A delta that does not apply (an error) is the reading it names. */ | |
| 26 | export function applyDelta(prev: Reading, delta: Delta): Reading { | |
| 27 | if ("error" in delta) return { error: delta.error }; | |
| 28 | if ("reset" in delta) return { cells: delta.reset }; | |
| 29 | const cells = "cells" in prev ? prev.cells : []; | |
| 30 | const set = new Map(delta.set.map((c) => [keyOf(c), c])); | |
| 31 | const drop = new Set(delta.drop); | |
| 32 | const out: Cell[] = []; | |
| 33 | for (const c of cells) { | |
| 34 | const k = keyOf(c); | |
| 35 | if (drop.has(k)) continue; | |
| 36 | out.push(set.get(k) ?? c); | |
| 37 | set.delete(k); | |
| 38 | } | |
| 39 | return { cells: [...out, ...set.values()] }; | |
| 40 | } | |
| 41 | ||
| 42 | const sameReading = (a: Reading, b: Reading) => | |
| 43 | "error" in a || "error" in b | |
| 44 | ? "error" in a && "error" in b && a.error === b.error | |
| 45 | : a.cells.length === b.cells.length && a.cells.every((c, i) => same(c, b.cells[i]!)); | |
| 46 | ||
| 47 | /** The delta from `prev` to `next`, or null when nothing changed. */ | |
| 48 | export function deltaOf(prev: Reading, next: Reading): Delta | null { | |
| 49 | if (sameReading(prev, next)) return null; | |
| 50 | if ("error" in next) return { error: next.error }; | |
| 51 | if ("error" in prev) return { reset: next.cells }; | |
| 52 | const before = new Map(prev.cells.map((c) => [keyOf(c), c])); | |
| 53 | const keys = new Set(next.cells.map(keyOf)); | |
| 54 | const set = next.cells.filter((c) => { | |
| 55 | const was = before.get(keyOf(c)); | |
| 56 | return was === undefined || !same(was, c); | |
| 57 | }); | |
| 58 | const drop = [...before.keys()].filter((k) => !keys.has(k)); | |
| 59 | const delta: Delta = { set, drop }; | |
| 60 | // A delta that would land in another order, or say more than the reading itself, is the reading. | |
| 61 | if (!sameReading(applyDelta(prev, delta), next) || set.length >= next.cells.length) return { reset: next.cells }; | |
| 62 | return delta; | |
| 63 | } | |
| 64 | ||
| 65 | /** FNV-1a over a string, as 8 hex digits. */ | |
| 66 | function fnv(text: string): string { | |
| 67 | let h = 0x811c9dc5; | |
| 68 | for (let i = 0; i < text.length; i++) h = Math.imul(h ^ text.charCodeAt(i), 0x01000193); | |
| 69 | return (h >>> 0).toString(16).padStart(8, "0"); | |
| 70 | } | |
| 71 | ||
| 72 | /** The digest of one panel's reading. */ | |
| 73 | export const digestOf = (r: Reading): string => fnv(JSON.stringify(r)); | |
| 74 | ||
| 75 | /** | |
| 76 | * What a board's readings were, short: one digest per panel, joined by dots. | |
| 77 | * The stream sends it as each frame's id, so a reconnect (or a page just | |
| 78 | * drawn) says what it holds and is sent a panel whole only when that panel | |
| 79 | * moved on since. Not a security boundary: a collision costs one stale panel. | |
| 80 | */ | |
| 81 | export const versionOf = (readings: readonly Reading[]): string => | |
| 82 | readings.map(digestOf).join("."); | |
| 83 | ||
| 84 | /** A version as sent back: one digest per panel, or nothing for a panel it does not name. */ | |
| 85 | export function parseVersion(text: string | null, panels: number): (string | undefined)[] { | |
| 86 | const parts = text !== null && text.length <= panels * 9 ? text.split(".") : []; | |
| 87 | return Array.from({ length: panels }, (_, i) => { | |
| 88 | const d = parts[i]; | |
| 89 | return d !== undefined && /^[0-9a-f]{8}$/.test(d) ? d : undefined; | |
| 90 | }); | |
| 91 | } |
src/boards/ring.ts +15
| @@ -77,6 +77,14 @@ type FineRow = { | ||
| 77 | 77 | at: string; target: string; cpu_cores: number | null; memory_bytes: number | null; load: number | null; celsius: number | null; |
| 78 | 78 | }; |
| 79 | 79 | |
| 80 | const recorded = new Set<(db: Database) => void>(); | |
| 81 | ||
| 82 | /** Hear every write to a ring, with the database written: a live board redraws its machine panels then. */ | |
| 83 | export function onRecorded(listener: (db: Database) => void): () => void { | |
| 84 | recorded.add(listener); | |
| 85 | return () => recorded.delete(listener); | |
| 86 | } | |
| 87 | ||
| 80 | 88 | /** Keep `points` (taken at `now`), roll up the windows that closed, drop what is past its window. One transaction. */ |
| 81 | 89 | export function record(db: Database, points: readonly Point[], now: number): void { |
| 82 | 90 | const put = db.query( |
| @@ -111,4 +119,11 @@ export function record(db: Database, points: readonly Point[], now: number): voi | ||
| 111 | 119 | db.query("DELETE FROM machine_sample WHERE step = 15 AND at < ?").run(iso(now - FINE_KEEP_MS)); |
| 112 | 120 | db.query("DELETE FROM machine_sample WHERE step = 300 AND at < ?").run(iso(now - COARSE_KEEP_MS)); |
| 113 | 121 | })(); |
| 122 | for (const listener of [...recorded]) { | |
| 123 | try { | |
| 124 | listener(db); | |
| 125 | } catch { | |
| 126 | // one broken listener never stops the sampler | |
| 127 | } | |
| 128 | } | |
| 114 | 129 | } |
src/http/server.ts +9 −5
| @@ -26,7 +26,8 @@ import { limitsPage, limitsSet, quotasSet, signupSet, inviteMint, inviteRevoke } | ||
| 26 | 26 | import { measureSubmit } from "./measure.ts"; |
| 27 | 27 | import { boardsPage } from "../web/pages/boards.ts"; |
| 28 | 28 | import { boardNew, boardPin, boardPost, pinPost } from "../web/pages/boards-edit.ts"; |
| 29 | import { boardLive, boardShow, boardsList } from "../web/pages/boards-view.ts"; | |
| 29 | import { boardShow, boardsList } from "../web/pages/boards-view.ts"; | |
| 30 | import { boardStream } from "../web/pages/boards-stream.ts"; | |
| 30 | 31 | import { |
| 31 | 32 | closeStreamsOf, |
| 32 | 33 | closeStreamsOfSession, |
| @@ -104,6 +105,7 @@ import { sha256 } from "../kernel/hash.ts"; | ||
| 104 | 105 | import { |
| 105 | 106 | assetResponse, |
| 106 | 107 | highlightAsset, |
| 108 | boardLiveAsset, | |
| 107 | 109 | beaconAsset, |
| 108 | 110 | shellAsset, |
| 109 | 111 | stylesheetAsset, |
| @@ -661,7 +663,7 @@ export function buildRouter(): Router<Handler> { | ||
| 661 | 663 | router.add("GET", "/manifest.webmanifest", webManifest); |
| 662 | 664 | router.add("GET", "/opensearch.xml", openSearch); |
| 663 | 665 | router.add("GET", "/icons/:spec.png", iconPng); |
| 664 | // The highlighter bundle, content-addressed. A stale hash is a 404 rather | |
| 666 | // The highlighter and live-board bundles, content-addressed. A stale hash is a 404 rather | |
| 665 | 667 | // than a redirect: the page that asked for it names the hash it was built |
| 666 | 668 | // with, so a miss means an old tab, and an old tab should reload. |
| 667 | 669 | router.add("GET", "/assets/:name.js", async (ctx) => { |
| @@ -670,8 +672,10 @@ export function buildRouter(): Router<Handler> { | ||
| 670 | 672 | if (ctx.params.name === beaconAsset().name) |
| 671 | 673 | return assetResponse(ctx.request, beaconAsset()); |
| 672 | 674 | if (ctx.params.name === TOOLBAR_NAME) return toolbarResponse(ctx.request); |
| 673 | const asset = await highlightAsset(); | |
| 674 | if (asset === null || ctx.params.name !== asset.name) return notFound(); | |
| 675 | // The two bundles: built on first ask, so neither is built for a name that is neither's. | |
| 676 | const name = ctx.params.name ?? ""; | |
| 677 | const asset = name.startsWith("board-live-") ? await boardLiveAsset() : await highlightAsset(); | |
| 678 | if (asset === null || name !== asset.name) return notFound(); | |
| 675 | 679 | return assetResponse(ctx.request, asset); |
| 676 | 680 | }); |
| 677 | 681 | // The service worker: root scope needs a root path, and it must never be |
| @@ -855,7 +859,7 @@ export function buildRouter(): Router<Handler> { | ||
| 855 | 859 | router.add("POST", "/boards/pin", boardPin); |
| 856 | 860 | for (const op of ["pin-panel", "unpin-panel", "move-pin"]) router.add("POST", `/boards/${op}`, pinPost); |
| 857 | 861 | router.add("GET", "/boards/:slug", boardShow); |
| 858 | router.add("GET", "/boards/:slug/live", boardLive); | |
| 862 | router.add("GET", "/boards/:slug/stream", boardStream); | |
| 859 | 863 | router.add("POST", "/boards/:slug/:op", boardPost); |
| 860 | 864 | router.add("GET", "/settings/flags", flagsPage); |
| 861 | 865 | router.add("POST", "/settings/flags", flagsSet); |
src/web/asset.ts +24 −9
| @@ -1,5 +1,5 @@ | ||
| 1 | 1 | /** |
| 2 | * The one script this forge ships as a file. | |
| 2 | * The scripts this forge ships as files. | |
| 3 | 3 | * |
| 4 | 4 | * Everything else on the web is server-rendered HTML plus a nonce'd inline |
| 5 | 5 | * script, and that is the right shape for a page: nothing to fetch, nothing to |
| @@ -35,33 +35,48 @@ export interface BuiltAsset { | ||
| 35 | 35 | etag: string; |
| 36 | 36 | } |
| 37 | 37 | |
| 38 | let pending: Promise<BuiltAsset | null> | null = null; | |
| 38 | const pending = new Map<string, Promise<BuiltAsset | null>>(); | |
| 39 | 39 | |
| 40 | 40 | /** The highlighter bundle, built once per process. */ |
| 41 | 41 | export function highlightAsset(): Promise<BuiltAsset | null> { |
| 42 | pending ??= build(); | |
| 43 | return pending; | |
| 42 | return bundle("highlight", "highlight-client.ts"); | |
| 44 | 43 | } |
| 45 | 44 | |
| 46 | async function build(): Promise<BuiltAsset | null> { | |
| 45 | /** | |
| 46 | * The live board's bundle (`web/board-live-client.ts`): the board's own chart | |
| 47 | * code, so a streamed point is drawn in the browser exactly as the server | |
| 48 | * draws it. Built once per process; without it the board is still drawn, and | |
| 49 | * simply is not live. | |
| 50 | */ | |
| 51 | export function boardLiveAsset(): Promise<BuiltAsset | null> { | |
| 52 | return bundle("board-live", "board-live-client.ts"); | |
| 53 | } | |
| 54 | ||
| 55 | function bundle(prefix: string, entry: string): Promise<BuiltAsset | null> { | |
| 56 | let built = pending.get(prefix); | |
| 57 | if (built === undefined) pending.set(prefix, (built = build(prefix, entry))); | |
| 58 | return built; | |
| 59 | } | |
| 60 | ||
| 61 | async function build(prefix: string, entry: string): Promise<BuiltAsset | null> { | |
| 47 | 62 | try { |
| 48 | 63 | const built = await Bun.build({ |
| 49 | entrypoints: [`${import.meta.dir}/highlight-client.ts`], | |
| 64 | entrypoints: [`${import.meta.dir}/${entry}`], | |
| 50 | 65 | target: "browser", |
| 51 | 66 | format: "esm", |
| 52 | 67 | minify: true, |
| 53 | 68 | }); |
| 54 | 69 | const first = built.outputs[0]; |
| 55 | 70 | if (!built.success || first === undefined) { |
| 56 | log.warn("web.highlight_asset_failed", { logs: built.logs.length }); | |
| 71 | log.warn(`web.${prefix}_asset_failed`, { logs: built.logs.length }); | |
| 57 | 72 | return null; |
| 58 | 73 | } |
| 59 | 74 | const code = await first.text(); |
| 60 | 75 | const hash = sha256(code); |
| 61 | const name = `highlight-${hash.slice(0, 16)}`; | |
| 76 | const name = `${prefix}-${hash.slice(0, 16)}`; | |
| 62 | 77 | return { path: `/assets/${name}.js`, name, code, etag: `"${hash}"` }; |
| 63 | 78 | } catch (error) { |
| 64 | log.warn("web.highlight_asset_failed", { error: String(error) }); | |
| 79 | log.warn(`web.${prefix}_asset_failed`, { error: String(error) }); | |
| 65 | 80 | return null; |
| 66 | 81 | } |
| 67 | 82 | } |
src/web/board-live-client.ts added +27
| @@ -0,0 +1,27 @@ | ||
| 1 | /** | |
| 2 | * The browser entry point for a live board: the board's own delta and chart | |
| 3 | * code (`boards/delta.ts`, `boards/chart.ts` — pure string work, nothing | |
| 4 | * that reaches for a server API), bundled by `web/asset.ts` and served from | |
| 5 | * `/assets/board-live-<hash>.js`. A streamed point is applied and drawn here | |
| 6 | * by the same functions the server drew the page with, so a redrawn panel is | |
| 7 | * the panel the server would have sent. | |
| 8 | * | |
| 9 | * It publishes one global, `window.forgeBoard`, for the board's inline | |
| 10 | * script (`boardLiveJs` in `web/client.ts`), which owns the stream and the | |
| 11 | * DOM. Everything is exported too, so a test can import the built module. | |
| 12 | */ | |
| 13 | import { panelBody } from "../boards/chart.ts"; | |
| 14 | import { applyDelta } from "../boards/delta.ts"; | |
| 15 | ||
| 16 | const api = { applyDelta, panelBody }; | |
| 17 | ||
| 18 | declare global { | |
| 19 | // The board's inline script reaches for exactly this, and nothing else. | |
| 20 | // eslint-disable-next-line no-var | |
| 21 | var forgeBoard: typeof api | undefined; | |
| 22 | } | |
| 23 | ||
| 24 | globalThis.forgeBoard = api; | |
| 25 | ||
| 26 | export { applyDelta, panelBody }; | |
| 27 | export default api; |
src/web/client.ts +93
| @@ -2152,3 +2152,96 @@ export const liveRegionsJs = /* js */ ` | ||
| 2152 | 2152 | }); |
| 2153 | 2153 | })(); |
| 2154 | 2154 | `; |
| 2155 | ||
| 2156 | /** | |
| 2157 | * A live board (`/boards/:slug`): one EventSource on the board's own stream | |
| 2158 | * (`/boards/:slug/stream`), whose frames are per-panel deltas — the new | |
| 2159 | * points, never HTML. Each is applied to the panel's cells (the page's | |
| 2160 | * `#board-points` data block) and the panel redrawn by the board's bundle | |
| 2161 | * (`window.forgeBoard`, `web/board-live-client.ts`), the server's own chart | |
| 2162 | * code. The status line says "live · updated Ns ago", counted here, no | |
| 2163 | * request behind it; Pause closes the stream and Resume reopens it from the | |
| 2164 | * last version heard, so nothing in between is lost. `?pause` opens nothing. | |
| 2165 | * Without the bundle or EventSource the board is the page it was drawn as. | |
| 2166 | */ | |
| 2167 | export const boardLiveJs = /* js */ ` | |
| 2168 | (function () { | |
| 2169 | var grid = document.getElementById('board-grid'); | |
| 2170 | var status = document.getElementById('board-live'); | |
| 2171 | var data = document.getElementById('board-points'); | |
| 2172 | var lib = window.forgeBoard; | |
| 2173 | if (!grid || !status || !data || !lib || typeof EventSource === 'undefined') return; | |
| 2174 | var src = grid.getAttribute('data-stream'); | |
| 2175 | var text = status.querySelector('[data-live-text]'); | |
| 2176 | var toggle = status.querySelector('[data-live-toggle]'); | |
| 2177 | if (!src || !text || !toggle) return; | |
| 2178 | var panels; | |
| 2179 | try { panels = JSON.parse(data.textContent || '[]'); } catch (err) { return; } | |
| 2180 | var cards = grid.querySelectorAll(':scope > .card'); | |
| 2181 | var version = grid.getAttribute('data-v') || ''; | |
| 2182 | var at = Number(status.getAttribute('data-at')) || Date.now(); | |
| 2183 | var paused = /[?&]pause\\b/.test(location.search); | |
| 2184 | var state = paused ? 'paused' : 'connecting'; | |
| 2185 | var changed = false; | |
| 2186 | var source = null; | |
| 2187 | var retry = null; | |
| 2188 | function ago() { | |
| 2189 | var s = Math.max(0, Math.round((Date.now() - at) / 1000)); | |
| 2190 | return s < 60 ? s + 's' : s < 3600 ? Math.floor(s / 60) + 'm' : Math.floor(s / 3600) + 'h'; | |
| 2191 | } | |
| 2192 | function paint() { | |
| 2193 | status.setAttribute('data-state', changed ? 'changed' : state); | |
| 2194 | text.textContent = changed ? 'this board changed · reload to see it' : state + ' · updated ' + ago() + ' ago'; | |
| 2195 | toggle.textContent = paused ? 'Resume' : 'Pause'; | |
| 2196 | toggle.setAttribute('aria-pressed', String(paused)); | |
| 2197 | } | |
| 2198 | function apply(frame) { | |
| 2199 | (frame.panels || []).forEach(function (d) { | |
| 2200 | var p = panels[d.i]; | |
| 2201 | var card = cards[d.i]; | |
| 2202 | if (!p || !card) return; | |
| 2203 | var next = lib.applyDelta(p, d); | |
| 2204 | panels[d.i] = { chart: p.chart, title: p.title, cells: next.cells, error: next.error }; | |
| 2205 | if (!next.cells) delete panels[d.i].cells; | |
| 2206 | if (next.error === undefined) delete panels[d.i].error; | |
| 2207 | var body = card.querySelector('.card-body'); | |
| 2208 | if (body) body.innerHTML = lib.panelBody(p.chart, next, p.title); | |
| 2209 | }); | |
| 2210 | at = Date.now(); | |
| 2211 | paint(); | |
| 2212 | } | |
| 2213 | function close() { | |
| 2214 | if (source) { source.close(); source = null; } | |
| 2215 | if (retry) { clearTimeout(retry); retry = null; } | |
| 2216 | } | |
| 2217 | function open() { | |
| 2218 | if (source || paused || changed) return; | |
| 2219 | source = new EventSource(src + '?v=' + encodeURIComponent(version)); | |
| 2220 | source.addEventListener('open', function () { state = 'live'; paint(); }); | |
| 2221 | source.addEventListener('points', function (e) { | |
| 2222 | var frame; | |
| 2223 | try { frame = JSON.parse(e.data); } catch (err) { return; } | |
| 2224 | if (e.lastEventId) version = e.lastEventId; | |
| 2225 | apply(frame); | |
| 2226 | }); | |
| 2227 | source.addEventListener('board', function () { changed = true; close(); paint(); }); | |
| 2228 | // The browser resumes a dropped stream by itself, from the last id it | |
| 2229 | // heard; when it gives up we open a new one, from that same version. | |
| 2230 | source.addEventListener('error', function () { | |
| 2231 | if (!source) return; | |
| 2232 | state = 'reconnecting'; | |
| 2233 | if (source.readyState === 2) { source = null; retry = setTimeout(open, 5000); } | |
| 2234 | paint(); | |
| 2235 | }); | |
| 2236 | } | |
| 2237 | toggle.hidden = false; | |
| 2238 | toggle.addEventListener('click', function () { | |
| 2239 | paused = !paused; | |
| 2240 | if (paused) { close(); state = 'paused'; } else { state = 'connecting'; open(); } | |
| 2241 | paint(); | |
| 2242 | }); | |
| 2243 | setInterval(paint, 1000); | |
| 2244 | paint(); | |
| 2245 | open(); | |
| 2246 | })(); | |
| 2247 | `; |
src/web/highlight-client.ts +3 −3
| @@ -1,7 +1,7 @@ | ||
| 1 | 1 | /** |
| 2 | * The browser entry point for syntax highlighting — the *only* file in this | |
| 3 | * repository that is built for the client. `Bun.build` bundles it with | |
| 4 | * `highlight.ts`, `highlight-html.ts` and `html.ts` (all pure string work, | |
| 2 | * The browser entry point for syntax highlighting — one of the two files in | |
| 3 | * this repository built for the client (`board-live-client.ts` is the | |
| 4 | * other). `Bun.build` bundles it with `highlight.ts`, `highlight-html.ts` and `html.ts` (all pure string work, | |
| 5 | 5 | * zero dependencies, nothing that reaches for a server API) into one ES |
| 6 | 6 | * module served from `/assets/highlight-<hash>.js`. |
| 7 | 7 | * |
src/web/pages/boards-stream.ts added +87
| @@ -0,0 +1,87 @@ | ||
| 1 | /** | |
| 2 | * A board, live: `GET /boards/:slug/stream` is one event stream whose frames | |
| 3 | * are the panels' new points, never HTML. A `points` frame is | |
| 4 | * `{ panels: [{ i, set, drop } | { i, reset } | { i, error }] }` | |
| 5 | * (`boards/delta.ts`) for the panels that changed, and its id is the | |
| 6 | * board's version after it, so a reconnect — or the page that was just drawn, | |
| 7 | * with `?v=` — is sent only what it does not hold. | |
| 8 | * | |
| 9 | * Nothing is read on a clock. The panels are read again when the forge | |
| 10 | * says something happened (any event on the bus) or the machine was sampled | |
| 11 | * (`boards/ring.ts`), a burst settling into one read, at most one a | |
| 12 | * second; a read that changed nothing sends nothing, so a quiet forge is a | |
| 13 | * quiet stream. A `board` frame says the board itself was saved (a panel | |
| 14 | * added, a range changed): the page offers a reload and the stream ends. | |
| 15 | * Only a person who is an admin may open it; anyone else gets not-found. | |
| 16 | */ | |
| 17 | import { showBoard } from "../../actions/boards.ts"; | |
| 18 | import { deltaOf, digestOf, parseVersion, versionOf, type Delta, type Reading } from "../../boards/delta.ts"; | |
| 19 | import { onRecorded } from "../../boards/ring.ts"; | |
| 20 | import type { Ctx } from "../../http/context.ts"; | |
| 21 | import { eventStream } from "../../http/sse.ts"; | |
| 22 | import { notFoundPage } from "../chrome.ts"; | |
| 23 | import { readPanel } from "./boards-view.ts"; | |
| 24 | ||
| 25 | /** How long a burst of events has to settle before the panels are read. */ | |
| 26 | export const SETTLE_MS = 200; | |
| 27 | /** The least time between two reads of one stream's panels. */ | |
| 28 | export const GAP_MS = 1_000; | |
| 29 | ||
| 30 | type Frame = { panels: ({ i: number } & Delta)[] }; | |
| 31 | ||
| 32 | // GET /boards/:slug/stream | |
| 33 | export async function boardStream(ctx: Ctx): Promise<Response> { | |
| 34 | const slug = ctx.params.slug ?? ""; | |
| 35 | const shown = await showBoard(ctx.app, ctx.auth.user, slug); | |
| 36 | if (!shown.ok) return notFoundPage(ctx); | |
| 37 | const board = shown.value; | |
| 38 | const read = (): Reading[] => board.panels.map((p) => readPanel(ctx.app, board, p)); | |
| 39 | const held = parseVersion( | |
| 40 | ctx.request.headers.get("last-event-id") ?? ctx.url.searchParams.get("v"), | |
| 41 | board.panels.length, | |
| 42 | ); | |
| 43 | return eventStream(ctx.app, ctx.request, (emit, close) => { | |
| 44 | let readings = read(); | |
| 45 | // What the client does not hold, whole: nothing, for a page drawn a moment ago. | |
| 46 | const behind: Frame["panels"] = []; | |
| 47 | readings.forEach((r, i) => { | |
| 48 | if (digestOf(r) !== held[i]) behind.push("error" in r ? { i, error: r.error } : { i, reset: r.cells }); | |
| 49 | }); | |
| 50 | if (behind.length > 0) emit("points", { panels: behind } satisfies Frame, versionOf(readings)); | |
| 51 | ||
| 52 | let timer: ReturnType<typeof setTimeout> | undefined; | |
| 53 | let last = 0; | |
| 54 | const tick = () => { | |
| 55 | timer = undefined; | |
| 56 | last = Date.now(); | |
| 57 | const next = read(); | |
| 58 | const changed: Frame["panels"] = []; | |
| 59 | next.forEach((r, i) => { | |
| 60 | const delta = deltaOf(readings[i]!, r); | |
| 61 | if (delta !== null) changed.push({ i, ...delta }); | |
| 62 | }); | |
| 63 | readings = next; | |
| 64 | if (changed.length > 0) emit("points", { panels: changed } satisfies Frame, versionOf(readings)); | |
| 65 | }; | |
| 66 | const soon = () => { | |
| 67 | if (timer !== undefined) return; | |
| 68 | timer = setTimeout(tick, Math.max(SETTLE_MS, last + GAP_MS - Date.now())); | |
| 69 | }; | |
| 70 | const offBus = ctx.app.bus.subscribe((event) => { | |
| 71 | if (event.kind === "board.saved" && event.payload.slug === slug) { | |
| 72 | emit("board", { slug }); | |
| 73 | close(); | |
| 74 | return; | |
| 75 | } | |
| 76 | soon(); | |
| 77 | }); | |
| 78 | const offRing = onRecorded((db) => { | |
| 79 | if (db === ctx.app.db) soon(); | |
| 80 | }); | |
| 81 | return () => { | |
| 82 | offBus(); | |
| 83 | offRing(); | |
| 84 | if (timer !== undefined) clearTimeout(timer); | |
| 85 | }; | |
| 86 | }); | |
| 87 | } |
src/web/pages/boards-view.ts +49 −37
| @@ -2,9 +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). 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. | |
| 5 | * delete). A board that is live streams its panels' new points over | |
| 6 | * `/boards/:slug/stream` (`boards-stream.ts`) and redraws each panel in the | |
| 7 | * browser with the server's own chart code; no HTML is fetched again. | |
| 8 | 8 | * No client framework. Every form posts to `boards-edit.ts`. Anyone but a |
| 9 | 9 | * person who is an admin gets the not-found page. |
| 10 | 10 | */ |
| @@ -14,18 +14,19 @@ import { MAX_H, MAX_PANELS, MAX_TITLE, MAX_W, RANGES, type Board, type Panel } f | ||
| 14 | 14 | import type { App } from "../../app.ts"; |
| 15 | 15 | import type { Ctx } from "../../http/context.ts"; |
| 16 | 16 | import { notePhase, takeSessionTime, timePhase, timePhaseAsync } from "../../core/route_timing.ts"; |
| 17 | import { liveRegionsJs } from "../client.ts"; | |
| 17 | import { boardLiveJs } from "../client.ts"; | |
| 18 | import { boardLiveAsset } from "../asset.ts"; | |
| 19 | import { panelBody } from "../../boards/chart.ts"; | |
| 20 | import { versionOf, type Reading } from "../../boards/delta.ts"; | |
| 18 | 21 | import { notFoundPage } from "../chrome.ts"; |
| 19 | 22 | import { html, raw, when, type Html } from "../html.ts"; |
| 20 | import { fragment, page } from "../layout.ts"; | |
| 23 | import { page } from "../layout.ts"; | |
| 21 | 24 | import { btn, card, empty } from "../ui.ts"; |
| 22 | 25 | import { flowPanel, flowPanelCss } from "./flow-panel.ts"; |
| 23 | 26 | import { isPinned, listPins } from "../../boards/pins.ts"; |
| 24 | import { cellsOf, chartBox, paramsOf, queryFields, readParams, runFor } from "./boards.ts"; | |
| 27 | import { cellsOf, paramsOf, queryFields, readParams, runFor } from "./boards.ts"; | |
| 25 | 28 | |
| 26 | 29 | const RANGE_MS = { "1h": 3_600_000, "24h": 86_400_000, "7d": 604_800_000, "30d": 2_592_000_000 } as const; |
| 27 | /** The events the panels' queries read (runs, pulls, checks, issues, usage): any of them may change a chart. */ | |
| 28 | const READS = "run.queued,run.started,run.finished,pull.*,check.*,issue.*,usage.*"; | |
| 29 | 30 | |
| 30 | 31 | const option = (value: string, selected: boolean) => |
| 31 | 32 | html`<option value="${value}" ${selected ? raw("selected") : null}>${value}</option>`; |
| @@ -36,6 +37,12 @@ function ranged(query: Record<string, unknown>, range: Board["range"]): Record<s | ||
| 36 | 37 | return { ...query, from: new Date(Date.now() - RANGE_MS[range]).toISOString() }; |
| 37 | 38 | } |
| 38 | 39 | |
| 40 | /** A panel's points now: its query over the board's range. */ | |
| 41 | export function readPanel(app: App, board: Board, panel: Panel, run: typeof runFor = runFor): Reading { | |
| 42 | const answer = run(app.db, panel.chart, ranged(panel.query, board.range)); | |
| 43 | return answer.ok ? { cells: cellsOf(answer.rows) } : { error: answer.error }; | |
| 44 | } | |
| 45 | ||
| 39 | 46 | export function drawPanel( |
| 40 | 47 | app: App, |
| 41 | 48 | board: Board, |
| @@ -43,11 +50,12 @@ export function drawPanel( | ||
| 43 | 50 | aside: Html | null = null, |
| 44 | 51 | run: typeof runFor = runFor, |
| 45 | 52 | ): Html { |
| 46 | const answer = run(app.db, panel.chart, ranged(panel.query, board.range)); | |
| 53 | return panelCard(panel, readPanel(app, board, panel, run), aside); | |
| 54 | } | |
| 55 | ||
| 56 | function panelCard(panel: Panel, reading: Reading, aside: Html | null = null): Html { | |
| 47 | 57 | const q = paramsOf(panel.query, panel.chart); |
| 48 | const body = !answer.ok | |
| 49 | ? html`<p class="muted small">${answer.error}</p>` | |
| 50 | : chartBox(panel.chart, cellsOf(answer.rows), panel.title); | |
| 58 | const body = raw(panelBody(panel.chart, reading, panel.title)); | |
| 51 | 59 | const explore = new URLSearchParams(Object.entries(q).filter(([k, v]) => v !== "" && k !== "rows")); |
| 52 | 60 | return html`<div class="card bp-w${String(panel.w)} bp-h${String(panel.h)}"> |
| 53 | 61 | <div class="card-head"><h2>${panel.title}</h2> |
| @@ -57,25 +65,36 @@ export function drawPanel( | ||
| 57 | 65 | </div>`; |
| 58 | 66 | } |
| 59 | 67 | |
| 60 | /** The grid alone: what the page shows and what the live address answers with. */ | |
| 68 | /** | |
| 69 | * The grid, and for a live board its stream's address, the version of what | |
| 70 | * it drew (`data-v`), and the points themselves as a data block the browser | |
| 71 | * applies deltas to. `<` is escaped so the block cannot close itself. | |
| 72 | */ | |
| 61 | 73 | function grid(app: App, slug: string, board: Board): Html { |
| 74 | const readings = board.panels.map((p) => readPanel(app, board, p)); | |
| 75 | const live = board.refresh !== "off"; | |
| 76 | const points = board.panels.map((p, i) => ({ chart: p.chart, title: p.title, ...readings[i]! })); | |
| 62 | 77 | return html`<section |
| 63 | class="bgrid" | |
| 64 | id="board-grid" | |
| 65 | ${board.refresh === "off" | |
| 66 | ? null | |
| 67 | : html`data-live="${READS}" data-live-src="/boards/${slug}/live"`} | |
| 68 | > | |
| 69 | ${board.panels.length === 0 | |
| 70 | ? html`<p class="muted">No panels yet. Add one below.</p>` | |
| 71 | : board.panels.map((p) => drawPanel(app, board, p))} | |
| 72 | </section>`; | |
| 78 | class="bgrid" | |
| 79 | id="board-grid" | |
| 80 | ${live ? html`data-stream="/boards/${slug}/stream" data-v="${versionOf(readings)}"` : null} | |
| 81 | > | |
| 82 | ${board.panels.length === 0 | |
| 83 | ? html`<p class="muted">No panels yet. Add one below.</p>` | |
| 84 | : board.panels.map((p, i) => panelCard(p, readings[i]!))} | |
| 85 | </section> | |
| 86 | ${live ? raw(`<script type="application/json" id="board-points">${JSON.stringify(points).replaceAll("<", "\\u003c")}</script>`) : null}`; | |
| 73 | 87 | } |
| 74 | 88 | |
| 75 | const denied = (ctx: Ctx) => { | |
| 76 | const u = ctx.auth.user; | |
| 77 | return u?.isAdmin !== true || u.kind === "agent"; | |
| 78 | }; | |
| 89 | /** "live · updated 0s ago" and Pause, counted on by the page's script; a board that is not live says so. */ | |
| 90 | function liveStatus(board: Board, paused: boolean): Html { | |
| 91 | if (board.refresh === "off") | |
| 92 | return html`<p class="muted small board-live" id="board-live" data-state="off">not live · turn Live on under Board below</p>`; | |
| 93 | return html`<p class="muted small board-live" id="board-live" data-state="${paused ? "paused" : "live"}" data-at="${String(Date.now())}"> | |
| 94 | <span data-live-text>${paused ? "paused" : "live"} · updated 0s ago</span> | |
| 95 | <button type="button" class="btn btn-sm" data-live-toggle hidden>${paused ? "Resume" : "Pause"}</button> | |
| 96 | </p>`; | |
| 97 | } | |
| 79 | 98 | |
| 80 | 99 | // GET /boards |
| 81 | 100 | export async function boardsList(ctx: Ctx): Promise<Response> { |
| @@ -183,25 +202,18 @@ export async function boardShow(ctx: Ctx): Promise<Response> { | ||
| 183 | 202 | if (!shown.ok) return notFoundPage(ctx); |
| 184 | 203 | const board = shown.value; |
| 185 | 204 | const panels = timePhase(ctx.request, "grid", () => grid(ctx.app, slug, board)); |
| 205 | const live = board.refresh === "off" ? null : await boardLiveAsset(); | |
| 186 | 206 | const rendering = performance.now(); |
| 187 | 207 | const response = page({ |
| 188 | 208 | ctx, |
| 189 | 209 | title: board.title, |
| 190 | 210 | body: html`<div class="page-head"><h1>${board.title}</h1> |
| 211 | ${liveStatus(board, ctx.url.searchParams.has("pause"))} | |
| 191 | 212 | ${btn("All boards", { href: "/boards", variant: "ghost" })}</div> |
| 192 | 213 | ${panels} |
| 193 | 214 | ${manage(slug, board, queryFields(readParams(ctx.url.searchParams)), listPins(ctx.app.db, ctx.auth.user?.id ?? ""))}`, |
| 194 | scriptJs: liveRegionsJs, | |
| 215 | ...(live === null ? {} : { scriptAsset: live.path, scriptJs: boardLiveJs }), | |
| 195 | 216 | }); |
| 196 | 217 | notePhase(ctx.request, "render", performance.now() - rendering); |
| 197 | 218 | return response; |
| 198 | 219 | } |
| 199 | ||
| 200 | // GET /boards/:slug/live | |
| 201 | export async function boardLive(ctx: Ctx): Promise<Response> { | |
| 202 | if (denied(ctx)) return fragment(html``, { status: 404 }); | |
| 203 | const slug = ctx.params.slug ?? ""; | |
| 204 | const shown = await showBoard(ctx.app, ctx.auth.user, slug); | |
| 205 | if (!shown.ok) return fragment(html``, { status: 404 }); | |
| 206 | return fragment(grid(ctx.app, slug, shown.value), { request: ctx.request }); | |
| 207 | } |
src/web/style/content.ts +3
| @@ -393,6 +393,9 @@ a.origin-chip:hover { border-color: var(--border-strong); color: var(--fg); } | ||
| 393 | 393 | .bt-group th, .bt-group td { background: var(--muted); font-weight: 600; } |
| 394 | 394 | .sys-pair { display: grid; grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); gap: 16px; margin-bottom: 16px; } |
| 395 | 395 | .sys-pair .chart-box { max-width: none; } |
| 396 | .board-live { display: flex; align-items: center; gap: 8px; margin: 0 0 0 auto; font-size: 12px; font-variant-numeric: tabular-nums; } | |
| 397 | .board-live::before { content: ""; width: 8px; height: 8px; border-radius: 50%; background: var(--muted-fg); flex: none; } | |
| 398 | .board-live[data-state="live"]::before { background: var(--success); } | |
| 396 | 399 | .bgrid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; margin-bottom: 16px; } |
| 397 | 400 | .bp-w2 { grid-column: span 2; } |
| 398 | 401 | .bp-w3 { grid-column: span 3; } |
test/boards-live.test.ts added +245
| @@ -0,0 +1,245 @@ | ||
| 1 | /** | |
| 2 | * A live board streams points, never HTML (#3692): the page carries its | |
| 3 | * panels' points and the version of them; `/boards/:slug/stream` is quiet | |
| 4 | * while nothing happens, sends a new point within 2 s in well under 2 KB, | |
| 5 | * sends a panel whole only to a client that does not hold it, says when the | |
| 6 | * board itself was saved, and answers not-found to anyone but an admin. The | |
| 7 | * delta both ends share applies to exactly the next reading, and the bundle | |
| 8 | * the browser draws with is the server's own chart code. | |
| 9 | */ | |
| 10 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 11 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 12 | import { tmpdir } from "node:os"; | |
| 13 | import { join } from "node:path"; | |
| 14 | import { changeBoard, makeBoard } from "../src/actions/boards.ts"; | |
| 15 | import { createApp } from "../src/app.ts"; | |
| 16 | import { panelBody, type Cell } from "../src/boards/chart.ts"; | |
| 17 | import { applyDelta, deltaOf, parseVersion, versionOf, type Reading } from "../src/boards/delta.ts"; | |
| 18 | import { createToken } from "../src/core/tokens.ts"; | |
| 19 | import { createUser, type User } from "../src/core/users.ts"; | |
| 20 | import { serve } from "../src/http/server.ts"; | |
| 21 | import { boardLiveAsset } from "../src/web/asset.ts"; | |
| 22 | import { boardLiveJs } from "../src/web/client.ts"; | |
| 23 | ||
| 24 | let dir: string; | |
| 25 | let app: ReturnType<typeof createApp>; | |
| 26 | let servers: Awaited<ReturnType<typeof serve>>; | |
| 27 | let alice: User; | |
| 28 | const tok: Record<string, string> = {}; | |
| 29 | const PANELS = [ | |
| 30 | { title: "Runs by kind", chart: "bar", query: { source: "runs", aggregate: "count", groupBy: "kind" }, w: 1, h: 1 }, | |
| 31 | { title: "Turns by state", chart: "table", query: { source: "runs", aggregate: "sum", column: "turns", groupBy: "state" }, w: 1, h: 1 }, | |
| 32 | ]; | |
| 33 | ||
| 34 | const asAdmin = (path: string, init: RequestInit = {}) => | |
| 35 | fetch(servers.url + path, { redirect: "manual", ...init, headers: { authorization: `Bearer ${tok.admin}`, ...init.headers } }); | |
| 36 | let runs = 0; | |
| 37 | const addRun = (kind: string, state = "ok") => | |
| 38 | app.db.run("INSERT INTO run (id, repo_id, kind, state, turns, created_at) VALUES (?, 'rb', ?, ?, 1, ?)", [ | |
| 39 | `r${++runs}`, kind, state, new Date().toISOString(), | |
| 40 | ]); | |
| 41 | ||
| 42 | /** An open stream: every frame as it comes, and the bytes it has cost. */ | |
| 43 | async function open(path: string, headers: Record<string, string> = {}) { | |
| 44 | const stop = new AbortController(); | |
| 45 | const res = await asAdmin(path, { signal: stop.signal, headers }); | |
| 46 | const frames: { event: string; id?: string; data: unknown }[] = []; | |
| 47 | let bytes = 0; | |
| 48 | let text = ""; | |
| 49 | const reader = res.body!.getReader(); | |
| 50 | void (async () => { | |
| 51 | try { | |
| 52 | for (;;) { | |
| 53 | const { value, done } = await reader.read(); | |
| 54 | if (done) return; | |
| 55 | bytes += value.byteLength; | |
| 56 | text += new TextDecoder().decode(value); | |
| 57 | let end: number; | |
| 58 | while ((end = text.indexOf("\n\n")) >= 0) { | |
| 59 | const block = text.slice(0, end); | |
| 60 | text = text.slice(end + 2); | |
| 61 | const field = (n: string) => block.split("\n").find((l) => l.startsWith(`${n}: `))?.slice(n.length + 2); | |
| 62 | const event = field("event"); | |
| 63 | if (event !== undefined) frames.push({ event, ...(field("id") ? { id: field("id")! } : {}), data: JSON.parse(field("data") ?? "null") }); | |
| 64 | } | |
| 65 | } | |
| 66 | } catch { | |
| 67 | // aborted | |
| 68 | } | |
| 69 | })(); | |
| 70 | return { res, frames, bytes: () => bytes, close: () => stop.abort() }; | |
| 71 | } | |
| 72 | ||
| 73 | const until = async (ok: () => boolean, ms = 3_000) => { | |
| 74 | const end = Date.now() + ms; | |
| 75 | while (!ok() && Date.now() < end) await Bun.sleep(20); | |
| 76 | return ok(); | |
| 77 | }; | |
| 78 | ||
| 79 | beforeAll(async () => { | |
| 80 | dir = await mkdtemp(join(tmpdir(), "forge-boards-live-")); | |
| 81 | app = createApp({ dataDir: dir, port: 0 }); | |
| 82 | servers = await serve(app); | |
| 83 | const made = await createUser(app.db, { | |
| 84 | origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true, | |
| 85 | }); | |
| 86 | if (!made.ok) throw new Error(made.error); | |
| 87 | alice = made.value; | |
| 88 | const bob = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" }); | |
| 89 | if (!bob.ok) throw new Error(bob.error); | |
| 90 | tok.admin = createToken(app.db, alice.id, "t", "admin").token; | |
| 91 | tok.bob = createToken(app.db, bob.value.id, "t", "admin").token; | |
| 92 | app.db.run("INSERT INTO repo (id, owner_id, name) VALUES ('rb', ?, 'n')", [alice.id]); | |
| 93 | addRun("agent"); | |
| 94 | addRun("check", "failed"); | |
| 95 | expect(await makeBoard(app, alice, "Live")).toEqual({ ok: true, value: "live" }); | |
| 96 | for (const panel of PANELS) expect((await changeBoard(app, alice, "live", { kind: "add", panel })).ok).toBe(true); | |
| 97 | expect((await changeBoard(app, alice, "live", { kind: "settings", range: "24h", refresh: "10s" })).ok).toBe(true); | |
| 98 | expect(await makeBoard(app, alice, "Still")).toEqual({ ok: true, value: "still" }); | |
| 99 | }); | |
| 100 | ||
| 101 | afterAll(async () => { | |
| 102 | servers.stop(); | |
| 103 | app.close(); | |
| 104 | await rm(dir, { recursive: true, force: true }); | |
| 105 | }); | |
| 106 | ||
| 107 | describe("the delta both ends share", () => { | |
| 108 | const cell = (label: string, value: number, series?: string): Cell => ({ label, value, ...(series ? { series } : {}) }); | |
| 109 | ||
| 110 | test("one new point is one cell, applied to exactly the next reading", () => { | |
| 111 | const prev: Reading = { cells: [cell("a", 1), cell("b", 2)] }; | |
| 112 | const next: Reading = { cells: [cell("a", 1), cell("b", 2), cell("c", 3)] }; | |
| 113 | const d = deltaOf(prev, next); | |
| 114 | expect(d).toEqual({ set: [cell("c", 3)], drop: [] }); | |
| 115 | expect(applyDelta(prev, d!)).toEqual(next); | |
| 116 | expect(deltaOf(next, next)).toBeNull(); | |
| 117 | }); | |
| 118 | ||
| 119 | test("a window that slides drops the oldest and appends the newest; series are told apart", () => { | |
| 120 | const prev: Reading = { cells: [cell("1", 1, "x"), cell("1", 2, "y"), cell("2", 3, "x"), cell("2", 4, "y")] }; | |
| 121 | const next: Reading = { cells: [cell("2", 3, "x"), cell("2", 4, "y"), cell("3", 5, "x")] }; | |
| 122 | const d = deltaOf(prev, next)!; | |
| 123 | expect(d).toEqual({ set: [cell("3", 5, "x")], drop: ["1\u0000x", "1\u0000y"] }); | |
| 124 | expect(applyDelta(prev, d)).toEqual(next); | |
| 125 | }); | |
| 126 | ||
| 127 | test("a reorder, an error and a recovery are sent whole", () => { | |
| 128 | const prev: Reading = { cells: [cell("a", 1), cell("b", 2), cell("c", 3)] }; | |
| 129 | const swapped: Reading = { cells: [cell("b", 2), cell("a", 1), cell("c", 3)] }; | |
| 130 | expect(deltaOf(prev, swapped)).toEqual({ reset: swapped.cells }); | |
| 131 | expect(deltaOf(prev, { error: "no such column" })).toEqual({ error: "no such column" }); | |
| 132 | expect(deltaOf({ error: "x" }, prev)).toEqual({ reset: prev.cells }); | |
| 133 | expect(applyDelta(prev, { error: "x" })).toEqual({ error: "x" }); | |
| 134 | }); | |
| 135 | ||
| 136 | test("a version is one digest per panel; a forged one names nothing", () => { | |
| 137 | const v = versionOf([{ cells: [] }, { error: "e" }]); | |
| 138 | expect(v).toMatch(/^[0-9a-f]{8}\.[0-9a-f]{8}$/); | |
| 139 | expect(parseVersion(v, 2)).toEqual(v.split(".")); | |
| 140 | expect(parseVersion("<script>.zz", 2)).toEqual([undefined, undefined]); | |
| 141 | expect(parseVersion("x".repeat(10_000), 2)).toEqual([undefined, undefined]); | |
| 142 | }); | |
| 143 | }); | |
| 144 | ||
| 145 | describe("/boards/:slug", () => { | |
| 146 | test("a live board carries its stream, its version, its points and a live status, drawn by the bundle", async () => { | |
| 147 | const body = await (await asAdmin("/boards/live")).text(); | |
| 148 | const v = body.match(/data-v="([^"]+)"/)?.[1] ?? ""; | |
| 149 | expect(body).toContain('data-stream="/boards/live/stream"'); | |
| 150 | expect(v.split(".").length).toBe(2); | |
| 151 | expect(body).toMatch(/<script type="application\/json" id="board-points">\[\{"chart":"bar","title":"Runs by kind","cells":/); | |
| 152 | expect(body).toContain('id="board-live"'); | |
| 153 | expect(body).toContain("live · updated 0s ago"); | |
| 154 | const asset = (await boardLiveAsset())!; | |
| 155 | expect(body).toContain(`src="${asset.path}"`); | |
| 156 | const served = await asAdmin(asset.path); | |
| 157 | expect(served.status).toBe(200); | |
| 158 | expect(await served.text()).toContain("forgeBoard"); | |
| 159 | // The page asks for nothing again: no live regions to refetch, no fetch in its script. | |
| 160 | expect(body).not.toContain("data-live="); | |
| 161 | expect(boardLiveJs).not.toMatch(/fetch\(|XMLHttpRequest|location\.reload/); | |
| 162 | expect((await asAdmin("/boards/live?pause")).status).toBe(200); | |
| 163 | expect(await (await asAdmin("/boards/live?pause")).text()).toContain("paused · updated 0s ago"); | |
| 164 | }); | |
| 165 | ||
| 166 | test("the browser's bundle draws a panel as the server does", async () => { | |
| 167 | const asset = (await boardLiveAsset())!; | |
| 168 | const file = join(dir, "board-live.mjs"); | |
| 169 | await Bun.write(file, asset.code); | |
| 170 | const built = (await import(file)) as { panelBody: typeof panelBody; applyDelta: typeof applyDelta }; | |
| 171 | const reading: Reading = { cells: [{ label: "<b>x</b>", value: 3, href: "/a?b=1&c=2" }, { label: "y", value: 4 }] }; | |
| 172 | for (const chart of ["line", "bar", "area", "number", "table", "heat"] as const) | |
| 173 | expect(built.panelBody(chart, reading, "T <i>")).toBe(panelBody(chart, reading, "T <i>")); | |
| 174 | expect(built.panelBody("line", { error: "<bad>" }, "t")).toBe('<p class="muted small"><bad></p>'); | |
| 175 | }); | |
| 176 | ||
| 177 | test("a board that is not live opens no stream and says so", async () => { | |
| 178 | const body = await (await asAdmin("/boards/still")).text(); | |
| 179 | expect(body).not.toContain("data-stream"); | |
| 180 | expect(body).not.toContain("board-points"); | |
| 181 | expect(body).toContain("not live"); | |
| 182 | expect(body).not.toContain("board-live-"); | |
| 183 | }); | |
| 184 | }); | |
| 185 | ||
| 186 | describe("/boards/:slug/stream", () => { | |
| 187 | test("idle, nothing is sent; a new run reaches the open board within 2 s, in under 2 KB, as points not HTML", async () => { | |
| 188 | const v = (await (await asAdmin("/boards/live")).text()).match(/data-v="([^"]+)"/)![1]!; | |
| 189 | const s = await open(`/boards/live/stream?v=${v}`); | |
| 190 | expect(s.res.status).toBe(200); | |
| 191 | expect(s.res.headers.get("content-type")).toContain("text/event-stream"); | |
| 192 | // An event that changes no panel is read and sends nothing. | |
| 193 | app.bus.append({ kind: "issue.opened", actorId: alice.id, payload: {} }); | |
| 194 | await Bun.sleep(1_500); | |
| 195 | expect(s.frames).toEqual([]); | |
| 196 | const before = s.bytes(); | |
| 197 | const at = Date.now(); | |
| 198 | addRun("deploy"); | |
| 199 | app.bus.append({ kind: "run.finished", actorId: alice.id, payload: {} }); | |
| 200 | expect(await until(() => s.frames.length > 0)).toBe(true); | |
| 201 | expect(Date.now() - at).toBeLessThan(2_000); | |
| 202 | const sent = s.bytes() - before; | |
| 203 | expect(sent).toBeLessThan(2_048); | |
| 204 | const frame = s.frames[0]!; | |
| 205 | expect(frame.event).toBe("points"); | |
| 206 | expect(JSON.stringify(frame.data)).not.toContain("<"); | |
| 207 | const panels = (frame.data as { panels: { i: number; set?: Cell[]; drop?: string[] }[] }).panels; | |
| 208 | expect(panels.find((p) => p.i === 0)).toEqual({ i: 0, set: [{ label: "deploy", value: 1 }], drop: [] }); | |
| 209 | // Its id is the version now: the page drawn now holds the same. | |
| 210 | const now = (await (await asAdmin("/boards/live")).text()).match(/data-v="([^"]+)"/)![1]!; | |
| 211 | expect(frame.id).toBe(now); | |
| 212 | s.close(); | |
| 213 | }); | |
| 214 | ||
| 215 | test("a client that holds an older version is sent the panels it lacks, whole, and nothing more", async () => { | |
| 216 | const v = (await (await asAdmin("/boards/live")).text()).match(/data-v="([^"]+)"/)![1]!; | |
| 217 | const [first, second] = v.split("."); | |
| 218 | const s = await open(`/boards/live/stream?v=00000000.${second}`); | |
| 219 | expect(await until(() => s.frames.length > 0)).toBe(true); | |
| 220 | const panels = (s.frames[0]!.data as { panels: { i: number; reset?: Cell[] }[] }).panels; | |
| 221 | expect(panels.map((p) => p.i)).toEqual([0]); | |
| 222 | expect(panels[0]!.reset?.length).toBeGreaterThan(0); | |
| 223 | expect(s.frames[0]!.id).toBe(`${first}.${second}`); | |
| 224 | s.close(); | |
| 225 | // Last-Event-ID wins over the address, as a browser resuming sends it. | |
| 226 | const r = await open(`/boards/live/stream?v=00000000.00000000`, { "last-event-id": v }); | |
| 227 | await Bun.sleep(300); | |
| 228 | expect(r.frames).toEqual([]); | |
| 229 | r.close(); | |
| 230 | }); | |
| 231 | ||
| 232 | test("the board saved says so, and the stream ends", async () => { | |
| 233 | const s = await open("/boards/live/stream"); | |
| 234 | expect(await until(() => s.frames.length > 0)).toBe(true); | |
| 235 | expect((await changeBoard(app, alice, "live", { kind: "title", title: "Live two" })).ok).toBe(true); | |
| 236 | expect(await until(() => s.frames.some((f) => f.event === "board"))).toBe(true); | |
| 237 | s.close(); | |
| 238 | }); | |
| 239 | ||
| 240 | test("anyone but an admin person gets not-found", async () => { | |
| 241 | expect((await fetch(`${servers.url}/boards/live/stream`)).status).toBe(404); | |
| 242 | expect((await fetch(`${servers.url}/boards/live/stream`, { headers: { authorization: `Bearer ${tok.bob}` } })).status).toBe(404); | |
| 243 | expect((await asAdmin("/boards/nope/stream")).status).toBe(404); | |
| 244 | }); | |
| 245 | }); |
test/boards-store.test.ts +7 −14
| @@ -165,27 +165,20 @@ describe("/boards", () => { | ||
| 165 | 165 | const body = await res.text(); |
| 166 | 166 | expect(body.match(LINE)?.length).toBe(3); |
| 167 | 167 | expect(body).toContain("bp-w2"); |
| 168 | expect(body).not.toContain('data-live-src="/boards'); | |
| 168 | expect(body).not.toContain('data-stream="/boards'); | |
| 169 | 169 | }); |
| 170 | 170 | |
| 171 | test("settings turn on refresh, and the grid answers alone with an etag", async () => { | |
| 171 | test("settings turn on refresh, and the grid names its stream instead of an HTML address", async () => { | |
| 172 | 172 | const saved = await post("/boards/fleet-health/settings", { range: "24h", refresh: "10s" }); |
| 173 | 173 | expect(saved.status).toBe(303); |
| 174 | 174 | const body = await (await asAdmin("/boards/fleet-health")).text(); |
| 175 | 175 | const grid = body.match(/<section[^>]*id="board-grid"[^>]*>/)?.[0] ?? ""; |
| 176 | expect(grid).not.toContain("data-live-every"); | |
| 177 | expect(grid).toMatch(/data-live="[^"]+"/); | |
| 178 | expect(grid).toContain('data-live="run.queued,run.started,run.finished,pull.*,check.*,issue.*,usage.*"'); | |
| 179 | expect(body).toContain('data-live-src="/boards/fleet-health/live"'); | |
| 176 | expect(grid).not.toContain("data-live"); | |
| 177 | expect(grid).toContain('data-stream="/boards/fleet-health/stream"'); | |
| 178 | expect(body.match(LINE)?.length).toBe(3); | |
| 180 | 179 | expect(body).toMatch(/<option value="10s" selected>on: redraw when events arrive<\/option>/); |
| 181 | 180 | expect(body).not.toContain(">1m</option>"); |
| 182 | const live = await asAdmin("/boards/fleet-health/live"); | |
| 183 | expect(live.status).toBe(200); | |
| 184 | const text = await live.text(); | |
| 185 | expect(text.startsWith("<section")).toBe(true); | |
| 186 | expect(text.match(LINE)?.length).toBe(3); | |
| 187 | const again = await asAdmin("/boards/fleet-health/live", { headers: { "if-none-match": live.headers.get("etag")! } }); | |
| 188 | expect(again.status).toBe(304); | |
| 181 | expect((await asAdmin("/boards/fleet-health/live")).status).toBe(404); | |
| 189 | 182 | expect((await post("/boards/fleet-health/settings", { range: "weeks", refresh: "10s" })).headers.get("set-cookie")).toContain("danger"); |
| 190 | 183 | }); |
| 191 | 184 | |
| @@ -251,7 +244,7 @@ describe("/boards", () => { | ||
| 251 | 244 | }); |
| 252 | 245 | |
| 253 | 246 | test("a non-admin and a stranger get 404 on every board route", async () => { |
| 254 | for (const path of ["/boards", "/boards/fleet-health", "/boards/fleet-health/live"]) { | |
| 247 | for (const path of ["/boards", "/boards/fleet-health", "/boards/fleet-health/stream"]) { | |
| 255 | 248 | expect((await fetch(servers.url + path, { headers: { authorization: `Bearer ${tok.bob}` } })).status).toBe(404); |
| 256 | 249 | expect((await fetch(servers.url + path)).status).toBe(404); |
| 257 | 250 | } |
new above
offline