Public: anyone can read this; the crew can change it.
Observability 3b: the /boards index is live by streaming, like a board #3808
scout/forge:scout/3715-observability-3b-the-boards-index-is-liv → main 3 commits fork
11 files
changed +327
−15
README.md +2
| @@ -1245,6 +1245,8 @@ Where the whole forge waits is the owner's, on `/boards` (the old `/flow` redire | ||
| 1245 | 1245 | The terminal also has an Access command (`:` → Access), a site admin's: it reads the same last-day non-browser requests as Settings → Access and the `access` MCP tool, newest first, and filters them with `s` (since), `u` (user agent) and `p` (path), `c` to clear. |
| 1246 | 1246 | |
| 1247 | 1247 | `/system` is the machine, for the owner (#1789), laid out like btop (#2721): a meter and a 30-reading block-character history per core, memory and swap meters, load, hwmon temperatures, disk use per mount, disk and network rates (`/proc/diskstats`, `/proc/net/dev`), and a table of every process grouped forge / check (`check:<run>`) / app (`app:<slug>/<env>`) / host with CPU, memory and age, sortable by CPU (`c`) or memory (`m`) or the buttons (shown only with a script; without one the order is by CPU). It reads `/proc` and `/sys` and updates in place over one event stream, `/system/stream` (`?pause` holds it still; no reload, no polling); the 2 s push timer runs only while someone is subscribed, so it costs nothing unwatched. Its history is the `machine` board source. A test file running in more than one check at once is counted at the top of `/system` and the `/boards` flow panel, with the checks. Command lines are never kept — only `*.test.ts` arguments. |
| 1248 | ||
| 1249 | The `/boards` index follows its flow panel over one event stream, `/boards/stream` (#3715), as data and not markup: a flat map of `data-n` key → text (`landed.hour`, `stage.review.waiting`, `queue.<repo>.queued`, `verdict`; `src/flow/numbers.ts`). The first frame is every key; after that a frame holds only the keys that changed, read 100 ms after the forge's event bus says anything moved. Idle, nothing is sent and nothing is requested; the page shows `live · updated Ns ago` on its own clock, and `/boards?pause` opens no stream. No dependency was added. Left out: the panel's time-driven text (oldest wait, the sparklines, the lists under `?out=`) changes on reload, not by stream; a repository that appears in the merge queue after the page loaded shows on reload. | |
| 1248 | 1250 | In the terminal, `:` → System shows the same view (the owner's only): per-core CPU with a block-character history, memory, swap, disk and network rates, and each group's top two processes (no sort; the dialog is read-only), and `:` → Telemetry lists the agents and flips `telemetry:read` for the one you press Enter on. |
| 1249 | 1251 | An agent the owner grants `telemetry:read` (Settings → Telemetry, one switch per agent, revoked the same way) reads the same through `GET /api/v1/telemetry/{system,flow,sources,history}` and the MCP `flow` and `system` tools; private repositories' checks and apps are renamed `check:private-N` and lose their processes and test files, and `flow` (like `system`, an admin agent account needs the grant too: only a person who is an admin reads without it) names only public repositories' conflicted pulls, every read is listed on that page, and an agent without the grant is refused. `/contribute`, `GET /api/v1/contribute` and the MCP `contribute` tool are open to anyone: what the forge is, the bottleneck now, open issues labelled “help wanted” in public repositories, and how to propose (fork, pull, the same gate). The grant is a table, not a token scope, so no token has to be re-issued. |
| 1250 | 1252 |
src/boards/store.ts +1 −1
| @@ -49,7 +49,7 @@ const span = (v: unknown, max: number): v is number => | ||
| 49 | 49 | typeof v === "number" && Number.isInteger(v) && v >= 1 && v <= max; |
| 50 | 50 | |
| 51 | 51 | /** Names that belong to a page or an API door of their own, never a board's. */ |
| 52 | const TAKEN = new Set(["data", "sources", "query", "pins"]); | |
| 52 | const TAKEN = new Set(["data", "sources", "query", "pins", "stream"]); | |
| 53 | 53 | |
| 54 | 54 | /** A slug is a file name: lowercase, short, and never one of `TAKEN`. */ |
| 55 | 55 | export const isSlug = (s: unknown): s is string => |
src/flow/numbers.ts added +49
| @@ -0,0 +1,49 @@ | ||
| 1 | /** | |
| 2 | * The flow panel's numbers as plain data: a flat map from a key | |
| 3 | * (`landed.hour`, `stage.review.waiting`, `queue.alice/shop.queued`) to the | |
| 4 | * text the panel shows there. The page draws each at an element carrying that | |
| 5 | * key in `data-n`; the stream (`boards-index-stream.ts`) sends only the keys | |
| 6 | * that changed, and the client sets those elements' text. Plain strings in, | |
| 7 | * `textContent` out: nothing in it is markup. | |
| 8 | */ | |
| 9 | ||
| 10 | import { hoursSpan, type Throughput } from "./throughput.ts"; | |
| 11 | import { verdict, type PipelineStage } from "./pipeline.ts"; | |
| 12 | import type { QueueRow } from "./queue.ts"; | |
| 13 | ||
| 14 | export type Numbers = Record<string, string>; | |
| 15 | ||
| 16 | /** Every number the panel shows, keyed. */ | |
| 17 | export function flowNumbers( | |
| 18 | stages: readonly PipelineStage[], | |
| 19 | flow: Throughput, | |
| 20 | queue: readonly QueueRow[], | |
| 21 | now: number, | |
| 22 | ): Numbers { | |
| 23 | const n: Numbers = { verdict: verdict(stages, now) }; | |
| 24 | const out = new Map(flow.stages.map((t) => [t.key, t])); | |
| 25 | const landed = out.get("approved"); | |
| 26 | n["landed.hour"] = String(landed?.hours[0] ?? 0); | |
| 27 | n["landed.day"] = String(landed?.items.length ?? 0); | |
| 28 | n.median = flow.medianAskToLiveMs === null ? "—" : hoursSpan(flow.medianAskToLiveMs); | |
| 29 | for (const s of stages) { | |
| 30 | const t = out.get(s.key); | |
| 31 | n[`stage.${s.key}.waiting`] = String(s.waiting); | |
| 32 | n[`stage.${s.key}.active`] = String(s.active); | |
| 33 | n[`stage.${s.key}.hour`] = String(t?.hours[0] ?? 0); | |
| 34 | n[`stage.${s.key}.day`] = `${t?.items.length ?? 0} in 24 h`; | |
| 35 | } | |
| 36 | for (const q of queue) { | |
| 37 | n[`queue.${q.repo}.queued`] = String(q.queued); | |
| 38 | n[`queue.${q.repo}.gating`] = String(q.gating); | |
| 39 | n[`queue.${q.repo}.landed`] = String(q.landedHour); | |
| 40 | } | |
| 41 | return n; | |
| 42 | } | |
| 43 | ||
| 44 | /** The keys of `next` whose text differs from `before`'s. */ | |
| 45 | export function changed(before: Numbers, next: Numbers): Numbers { | |
| 46 | const delta: Numbers = {}; | |
| 47 | for (const [k, v] of Object.entries(next)) if (before[k] !== v) delta[k] = v; | |
| 48 | return delta; | |
| 49 | } |
src/http/server.ts +2
| @@ -27,6 +27,7 @@ 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 | 29 | import { boardLive, boardShow, boardsList } from "../web/pages/boards-view.ts"; |
| 30 | import { boardsIndexStream } from "../web/pages/boards-index-stream.ts"; | |
| 30 | 31 | import { |
| 31 | 32 | closeStreamsOf, |
| 32 | 33 | closeStreamsOfSession, |
| @@ -854,6 +855,7 @@ export function buildRouter(): Router<Handler> { | ||
| 854 | 855 | router.add("POST", "/boards/new", boardNew); |
| 855 | 856 | router.add("POST", "/boards/pin", boardPin); |
| 856 | 857 | for (const op of ["pin-panel", "unpin-panel", "move-pin"]) router.add("POST", `/boards/${op}`, pinPost); |
| 858 | router.add("GET", "/boards/stream", boardsIndexStream); | |
| 857 | 859 | router.add("GET", "/boards/:slug", boardShow); |
| 858 | 860 | router.add("GET", "/boards/:slug/live", boardLive); |
| 859 | 861 | router.add("POST", "/boards/:slug/:op", boardPost); |
src/web/boards-index-live.ts added +32
| @@ -0,0 +1,32 @@ | ||
| 1 | /** | |
| 2 | * The /boards index's client: one EventSource, each frame a map of | |
| 3 | * `data-n` key → text, set as text on the elements that carry the key. No | |
| 4 | * markup crosses the wire. "live · updated Ns ago" counts on the page's own | |
| 5 | * clock (no request); `?pause` opens nothing and says so. EventSource | |
| 6 | * reconnects by itself after a roll, and its first frame is the full map. | |
| 7 | */ | |
| 8 | export const boardsIndexLiveJs = /* js */ ` | |
| 9 | (function () { | |
| 10 | var status = document.getElementById('flow-live-state'); | |
| 11 | if (typeof EventSource === 'undefined' || /[?&]pause\\b/.test(location.search)) return; | |
| 12 | var at = null, shown = ''; | |
| 13 | function say() { | |
| 14 | if (!status) return; | |
| 15 | var s = at === null ? 'live' : 'live \\u00b7 updated ' + Math.max(0, Math.floor((Date.now() - at) / 1000)) + 's ago'; | |
| 16 | if (s !== shown) { shown = s; status.textContent = s; } | |
| 17 | } | |
| 18 | var es = new EventSource('/boards/stream'); | |
| 19 | es.addEventListener('flow', function (e) { | |
| 20 | var data; | |
| 21 | try { data = JSON.parse(e.data); } catch (_) { return; } | |
| 22 | if (!data || typeof data !== 'object') return; | |
| 23 | Array.prototype.forEach.call(document.querySelectorAll('[data-n]'), function (el) { | |
| 24 | var k = el.getAttribute('data-n'); | |
| 25 | if (Object.prototype.hasOwnProperty.call(data, k) && typeof data[k] === 'string' && el.textContent !== data[k]) el.textContent = data[k]; | |
| 26 | }); | |
| 27 | at = Date.now(); | |
| 28 | say(); | |
| 29 | }); | |
| 30 | setInterval(say, 1000); | |
| 31 | })(); | |
| 32 | `; |
src/web/pages/boards-index-stream.ts added +52
| @@ -0,0 +1,52 @@ | ||
| 1 | /** | |
| 2 | * GET /boards/stream: the index's flow numbers as data. One full frame on | |
| 3 | * connect, then a frame holding only the keys that changed, sent when the | |
| 4 | * forge's event bus says something moved (a burst is read once). While | |
| 5 | * nothing changes nothing is sent, and the server keeps no timer of its own | |
| 6 | * beyond the stream's heartbeat. Same door as the page: a person who is an | |
| 7 | * admin; anyone else gets the not-found page. | |
| 8 | */ | |
| 9 | import { queuesFor } from "../../system/telemetry.ts"; | |
| 10 | import { readPipeline } from "../../flow/pipeline.ts"; | |
| 11 | import { readThroughput } from "../../flow/throughput.ts"; | |
| 12 | import { changed, flowNumbers, type Numbers } from "../../flow/numbers.ts"; | |
| 13 | import type { App } from "../../app.ts"; | |
| 14 | import type { Ctx } from "../../http/context.ts"; | |
| 15 | import { eventStream } from "../../http/sse.ts"; | |
| 16 | import { notFoundPage } from "../chrome.ts"; | |
| 17 | ||
| 18 | /** A burst of events is read once, this long after the first. */ | |
| 19 | export const SETTLE_MS = 100; | |
| 20 | ||
| 21 | /** The panel's numbers now. */ | |
| 22 | export function readNumbers(app: App, now = Date.now()): Numbers { | |
| 23 | const stages = readPipeline(app.db, new Date(now)); | |
| 24 | const flow = readThroughput(app.db, stages.map((s) => s.key), new Date(now)); | |
| 25 | return flowNumbers(stages, flow, queuesFor(app, { kind: "owner" }, new Date(now)), now); | |
| 26 | } | |
| 27 | ||
| 28 | export function boardsIndexStream(ctx: Ctx): Response { | |
| 29 | const u = ctx.auth.user; | |
| 30 | if (u?.isAdmin !== true || u.kind === "agent") return notFoundPage(ctx); | |
| 31 | const { app } = ctx; | |
| 32 | return eventStream(app, ctx.request, (emit, _close, ready) => { | |
| 33 | let sent = readNumbers(app); | |
| 34 | emit("flow", sent); | |
| 35 | let timer: ReturnType<typeof setTimeout> | undefined; | |
| 36 | const off = app.bus.subscribe(() => { | |
| 37 | if (timer !== undefined) return; | |
| 38 | timer = setTimeout(() => { | |
| 39 | timer = undefined; | |
| 40 | if (!ready()) return; | |
| 41 | const next = readNumbers(app); | |
| 42 | const delta = changed(sent, next); | |
| 43 | sent = next; | |
| 44 | if (Object.keys(delta).length > 0) emit("flow", delta); | |
| 45 | }, SETTLE_MS); | |
| 46 | }); | |
| 47 | return () => { | |
| 48 | off(); | |
| 49 | if (timer !== undefined) clearTimeout(timer); | |
| 50 | }; | |
| 51 | }); | |
| 52 | } |
src/web/pages/boards-view.ts +10 −1
| @@ -19,6 +19,7 @@ import { notFoundPage } from "../chrome.ts"; | ||
| 19 | 19 | import { html, raw, when, type Html } from "../html.ts"; |
| 20 | 20 | import { fragment, page } from "../layout.ts"; |
| 21 | 21 | import { btn, card, empty } from "../ui.ts"; |
| 22 | import { boardsIndexLiveJs } from "../boards-index-live.ts"; | |
| 22 | 23 | import { flowPanel, flowPanelCss } from "./flow-panel.ts"; |
| 23 | 24 | import { isPinned, listPins } from "../../boards/pins.ts"; |
| 24 | 25 | import { cellsOf, chartBox, paramsOf, queryFields, readParams, runFor } from "./boards.ts"; |
| @@ -104,11 +105,19 @@ export async function boardsList(ctx: Ctx): Promise<Response> { | ||
| 104 | 105 | title: "Boards", |
| 105 | 106 | body: html`<div class="page-head"><h1>Boards</h1> |
| 106 | 107 | ${btn("Explore the data", { href: "/boards/data", variant: "ghost" })}</div> |
| 107 | ${card(make)} ${body} ${flowPanel(ctx.app, { kind: "owner" }, ctx.url, "/boards")}`, | |
| 108 | ${card(make)} ${body} ${liveLine(ctx.url.searchParams.has("pause"))} ${flowPanel(ctx.app, { kind: "owner" }, ctx.url, "/boards")}`, | |
| 108 | 109 | styleCss: flowPanelCss, |
| 110 | scriptJs: boardsIndexLiveJs, | |
| 109 | 111 | }); |
| 110 | 112 | } |
| 111 | 113 | |
| 114 | /** Whether the index is following its stream, and the one link that flips it. */ | |
| 115 | const liveLine = (paused: boolean): Html => | |
| 116 | html`<p class="muted small" id="flow-live" role="status"> | |
| 117 | <span id="flow-live-state">${paused ? "paused" : "live"}</span> · | |
| 118 | ${paused ? html`<a href="/boards">Resume</a>` : html`<a href="/boards?pause">Pause</a>`} | |
| 119 | </p>`; | |
| 120 | ||
| 112 | 121 | function panelForm(slug: string, op: string, p: Panel | undefined, index: number, fields: Html): Html { |
| 113 | 122 | return html`<form method="post" action="/boards/${slug}/${op}" class="bform"> |
| 114 | 123 | ${op === "edit" ? html`<input type="hidden" name="index" value="${String(index)}" />` : null} |
src/web/pages/flow-panel.ts +11 −11
| @@ -78,9 +78,9 @@ function outCell(base: string, t: StageThroughput): Html { | ||
| 78 | 78 | const day = t.items.length; |
| 79 | 79 | const passed = t.items.filter((i) => i.outcome === "passed").length; |
| 80 | 80 | return html`<span class="flow-out" data-out="${OUTFLOW[t.key].out}"> |
| 81 | <a class="mono" href="${outHref(base, t.key, 0)}" data-hour="0">${String(t.hours[0] ?? 0)}</a> | |
| 81 | <a class="mono" href="${outHref(base, t.key, 0)}" data-hour="0" data-n="stage.${t.key}.hour">${String(t.hours[0] ?? 0)}</a> | |
| 82 | 82 | ${sparkline(t)} |
| 83 | <a class="muted small" href="${outHref(base, t.key, null)}" data-day="${String(day)}">${String(day)} in 24 h</a> | |
| 83 | <a class="muted small" href="${outHref(base, t.key, null)}" data-day="${String(day)}" data-n="stage.${t.key}.day">${String(day)} in 24 h</a> | |
| 84 | 84 | </span> |
| 85 | 85 | <div class="muted small"> |
| 86 | 86 | ${OUTFLOW[t.key].label}${t.key === "checking" && day > 0 ? ` · ${passed} passed · ${day - passed} failed` : ""} |
| @@ -103,18 +103,18 @@ export function flowPanel(app: App, reader: Reader, url: URL, base: string): Htm | ||
| 103 | 103 | const listed = asked(url); |
| 104 | 104 | const shown = listed === null ? undefined : out.get(listed.key); |
| 105 | 105 | return html`<p id="bottleneck" data-stage="${worst?.key ?? ""}"> |
| 106 | <strong>${verdict(stages, now)}</strong> | |
| 106 | <strong data-n="verdict">${verdict(stages, now)}</strong> | |
| 107 | 107 | </p> |
| 108 | 108 | ${conflicted === null ? "" : html`<p id="conflicted">${conflicted}</p>`} |
| 109 | 109 | ${onBuilder === null ? "" : html`<p id="requested-builder">${onBuilder}</p>`} |
| 110 | 110 | ${onReviewer === null ? "" : html`<p id="requested-reviewer">${onReviewer}</p>`} |
| 111 | 111 | <p id="throughput"> |
| 112 | 112 | landed |
| 113 | <a href="${outHref(base, "approved", 0)}" data-landed-hour>${String(landed?.hours[0] ?? 0)}</a> | |
| 113 | <a href="${outHref(base, "approved", 0)}" data-landed-hour data-n="landed.hour">${String(landed?.hours[0] ?? 0)}</a> | |
| 114 | 114 | in the last hour · |
| 115 | <a href="${outHref(base, "approved", null)}" data-landed-day>${String(landed?.items.length ?? 0)}</a> | |
| 115 | <a href="${outHref(base, "approved", null)}" data-landed-day data-n="landed.day">${String(landed?.items.length ?? 0)}</a> | |
| 116 | 116 | in 24 h · median ask→live |
| 117 | <span data-median>${flow.medianAskToLiveMs === null ? "—" : hoursSpan(flow.medianAskToLiveMs)}</span> | |
| 117 | <span data-median data-n="median">${flow.medianAskToLiveMs === null ? "—" : hoursSpan(flow.medianAskToLiveMs)}</span> | |
| 118 | 118 | (24 h) |
| 119 | 119 | </p> |
| 120 | 120 | <p id="duplicate-work" data-count="${String(dups.length)}" class="${dups.length === 0 ? "muted" : ""}"> |
| @@ -153,8 +153,8 @@ export function flowPanel(app: App, reader: Reader, url: URL, base: string): Htm | ||
| 153 | 153 | ${s === worst ? badge("bottleneck", { tone: "danger" }) : null} |
| 154 | 154 | <div class="muted small">${STAGE_HOLDS[s.key]}</div> |
| 155 | 155 | </th> |
| 156 | <td class="mono">${String(s.waiting)}</td> | |
| 157 | <td class="mono">${String(s.active)}</td> | |
| 156 | <td class="mono" data-n="stage.${s.key}.waiting">${String(s.waiting)}</td> | |
| 157 | <td class="mono" data-n="stage.${s.key}.active">${String(s.active)}</td> | |
| 158 | 158 | <td class="mono">${waited(s, now) ?? "—"}</td> |
| 159 | 159 | <td class="small">${s.capacity ?? "—"}</td> |
| 160 | 160 | <td>${outCell(base, out.get(s.key)!)}</td> |
| @@ -195,9 +195,9 @@ function queueCard(rows: readonly QueueRow[]): Html { | ||
| 195 | 195 | (r) => |
| 196 | 196 | html`<tr data-queue="${r.repo}"> |
| 197 | 197 | <th scope="row"><a href="/${r.repo}/pulls">${r.repo}</a></th> |
| 198 | <td class="mono" data-queued>${String(r.queued)}</td> | |
| 199 | <td class="mono" data-gating>${String(r.gating)}</td> | |
| 200 | <td class="mono" data-landed>${String(r.landedHour)}</td> | |
| 198 | <td class="mono" data-queued data-n="queue.${r.repo}.queued">${String(r.queued)}</td> | |
| 199 | <td class="mono" data-gating data-n="queue.${r.repo}.gating">${String(r.gating)}</td> | |
| 200 | <td class="mono" data-landed data-n="queue.${r.repo}.landed">${String(r.landedHour)}</td> | |
| 201 | 201 | </tr>`, |
| 202 | 202 | )} |
| 203 | 203 | </tbody> |
test/boards-index-stream.test.ts added +165
| @@ -0,0 +1,165 @@ | ||
| 1 | /** | |
| 2 | * The /boards index is live over one stream (#3715): the flow panel's | |
| 3 | * numbers arrive as data, a change is sent as only the keys that changed, | |
| 4 | * and nothing is sent while nothing does. | |
| 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 { createApp, type App } from "../src/app.ts"; | |
| 11 | import { openIssue } from "../src/actions/issues.ts"; | |
| 12 | import { createRepo } from "../src/actions/repos.ts"; | |
| 13 | import type { Repo } from "../src/core/repos.ts"; | |
| 14 | import { createUser, type User } from "../src/core/users.ts"; | |
| 15 | import { changed } from "../src/flow/numbers.ts"; | |
| 16 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 17 | ||
| 18 | describe("/boards/stream", () => { | |
| 19 | let dataDir: string; | |
| 20 | let app: App; | |
| 21 | let servers: Servers; | |
| 22 | let alice: User; | |
| 23 | let repo: Repo; | |
| 24 | let cookie = ""; | |
| 25 | let bobCookie = ""; | |
| 26 | ||
| 27 | const login = async (username: string): Promise<string> => { | |
| 28 | const res = await fetch(`${servers.url}/signin`, { | |
| 29 | method: "POST", | |
| 30 | redirect: "manual", | |
| 31 | headers: { "content-type": "application/x-www-form-urlencoded", origin: servers.url }, | |
| 32 | body: new URLSearchParams({ username, password: "a-good-passphrase" }), | |
| 33 | }); | |
| 34 | return (res.headers.get("set-cookie") ?? "").split(";")[0] ?? ""; | |
| 35 | }; | |
| 36 | ||
| 37 | beforeAll(async () => { | |
| 38 | dataDir = await mkdtemp(join(tmpdir(), "forge-boards-index-")); | |
| 39 | app = createApp({ dataDir, port: 0 }); | |
| 40 | servers = await serve(app); | |
| 41 | const a = await createUser(app.db, { | |
| 42 | origin: "seed", trusted: true, username: "alice", email: "[email protected]", | |
| 43 | password: "a-good-passphrase", adminIfFirst: true, | |
| 44 | }); | |
| 45 | if (!a.ok) throw new Error(a.error); | |
| 46 | alice = a.value; | |
| 47 | const b = await createUser(app.db, { | |
| 48 | origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase", | |
| 49 | }); | |
| 50 | if (!b.ok) throw new Error(b.error); | |
| 51 | const made = await createRepo(app, alice, { name: "shop" }); | |
| 52 | if (!made.ok) throw new Error(String(made.error)); | |
| 53 | repo = made.value; | |
| 54 | cookie = await login("alice"); | |
| 55 | bobCookie = await login("bob"); | |
| 56 | }); | |
| 57 | ||
| 58 | afterAll(async () => { | |
| 59 | servers.stop(); | |
| 60 | app.close(); | |
| 61 | await rm(dataDir, { recursive: true, force: true }); | |
| 62 | }); | |
| 63 | ||
| 64 | /** Frames as they arrive: a reader that resolves each `flow` data line. */ | |
| 65 | function frames(res: Response) { | |
| 66 | const reader = res.body!.getReader(); | |
| 67 | const decoder = new TextDecoder(); | |
| 68 | let buf = ""; | |
| 69 | let bytes = 0; | |
| 70 | let pending: Promise<Awaited<ReturnType<ReadableStreamDefaultReader<Uint8Array>["read"]>>> | null = null; | |
| 71 | return { | |
| 72 | get bytes() { return bytes; }, | |
| 73 | async next(ms: number): Promise<Record<string, string> | null> { | |
| 74 | const deadline = Date.now() + ms; | |
| 75 | for (;;) { | |
| 76 | const at = buf.indexOf("\n\n"); | |
| 77 | if (at >= 0) { | |
| 78 | const block = buf.slice(0, at); | |
| 79 | buf = buf.slice(at + 2); | |
| 80 | const data = block.split("\n").find((l) => l.startsWith("data: ")); | |
| 81 | if (data !== undefined) return JSON.parse(data.slice(6)); | |
| 82 | continue; | |
| 83 | } | |
| 84 | const left = deadline - Date.now(); | |
| 85 | if (left <= 0) return null; | |
| 86 | // One read stays pending across timeouts, so a chunk is never lost. | |
| 87 | pending ??= reader.read(); | |
| 88 | const got = await Promise.race([ | |
| 89 | pending, | |
| 90 | new Promise<null>((r) => setTimeout(() => r(null), left)), | |
| 91 | ]); | |
| 92 | if (got === null) return null; | |
| 93 | pending = null; | |
| 94 | if (got.done) return null; | |
| 95 | bytes += got.value.length; | |
| 96 | buf += decoder.decode(got.value); | |
| 97 | } | |
| 98 | }, | |
| 99 | cancel: () => reader.cancel(), | |
| 100 | }; | |
| 101 | } | |
| 102 | ||
| 103 | test("the page names the stream, its numbers, and a Pause; ?pause says paused", async () => { | |
| 104 | const body = await (await fetch(`${servers.url}/boards`, { headers: { cookie } })).text(); | |
| 105 | expect(body).toContain("new EventSource('/boards/stream')"); | |
| 106 | expect(body).toContain('data-n="landed.day"'); | |
| 107 | expect(body).toContain('href="/boards?pause"'); | |
| 108 | expect(body).not.toContain("setTimeout("); | |
| 109 | const paused = await (await fetch(`${servers.url}/boards?pause`, { headers: { cookie } })).text(); | |
| 110 | expect(paused).toContain(">paused<"); | |
| 111 | expect(paused).toContain('href="/boards">Resume'); | |
| 112 | }); | |
| 113 | ||
| 114 | test("a stranger and a non-admin are refused", async () => { | |
| 115 | for (const headers of [{}, { cookie: bobCookie }]) { | |
| 116 | const res = await fetch(`${servers.url}/boards/stream`, { headers, redirect: "manual" }); | |
| 117 | expect(res.headers.get("content-type") ?? "").not.toContain("text/event-stream"); | |
| 118 | await res.body?.cancel(); | |
| 119 | } | |
| 120 | }); | |
| 121 | ||
| 122 | test("a pull landing changes the landed count within 2 s, in under 2 KB, and idle sends nothing", async () => { | |
| 123 | const res = await fetch(`${servers.url}/boards/stream`, { headers: { cookie } }); | |
| 124 | expect(res.headers.get("content-type")).toContain("text/event-stream"); | |
| 125 | const f = frames(res); | |
| 126 | const first = await f.next(2000); | |
| 127 | expect(first?.["landed.day"]).toBe("0"); | |
| 128 | expect(first?.["landed.hour"]).toBe("0"); | |
| 129 | ||
| 130 | // Idle: a quiet second sends nothing. | |
| 131 | expect(await f.next(1000)).toBeNull(); | |
| 132 | ||
| 133 | const before = f.bytes; | |
| 134 | const issue = openIssue(app, alice, repo, { title: "Add a cart", body: "" }); | |
| 135 | if (!issue.ok) throw new Error(String(issue.error)); | |
| 136 | app.db.query("UPDATE issue SET kind = 'pull', state = 'closed' WHERE id = ?1").run(issue.value.id); | |
| 137 | app.db | |
| 138 | .query( | |
| 139 | `INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid, merged_at) | |
| 140 | VALUES (?1, ?2, 'x', '', '', ?3)`, | |
| 141 | ) | |
| 142 | .run(issue.value.id, repo.defaultBranch, new Date().toISOString()); | |
| 143 | app.bus.append({ kind: "pull.merged", repoId: repo.id }); | |
| 144 | const t0 = Date.now(); | |
| 145 | let delta: Record<string, string> | null = null; | |
| 146 | while (Date.now() - t0 < 2000) { | |
| 147 | delta = await f.next(2000 - (Date.now() - t0)); | |
| 148 | if (delta?.["landed.day"] !== undefined) break; | |
| 149 | } | |
| 150 | expect(delta?.["landed.day"]).toBe("1"); | |
| 151 | expect(delta?.["landed.hour"]).toBe("1"); | |
| 152 | expect(f.bytes - before).toBeLessThan(2048); | |
| 153 | // Only what changed travels. | |
| 154 | expect(delta?.["stage.live.waiting"]).toBeUndefined(); | |
| 155 | ||
| 156 | // An event that changes nothing sends nothing. | |
| 157 | app.bus.append({ kind: "noop.event" }); | |
| 158 | expect(await f.next(600)).toBeNull(); | |
| 159 | await f.cancel(); | |
| 160 | }); | |
| 161 | ||
| 162 | test("changed() is the keys whose text differs", () => { | |
| 163 | expect(changed({ a: "1", b: "2" }, { a: "1", b: "3", c: "4" })).toEqual({ b: "3", c: "4" }); | |
| 164 | }); | |
| 165 | }); |
test/flow-throughput.test.ts +2 −2
| @@ -187,8 +187,8 @@ describe("/flow: actual throughput per stage", () => { | ||
| 187 | 187 | "landed 2 in the last hour · 6 in 24 h · median ask→live 3.5 h (24 h)", |
| 188 | 188 | ); |
| 189 | 189 | expect(headline).toContain('href="/boards?out=landed&hour=0#out"'); |
| 190 | expect(page).toMatch(/data-out="landed">\s*<a class="mono" href="\/boards\?out=landed&hour=0#out" data-hour="0">2<\/a>/); | |
| 191 | expect(page).toContain('data-day="6">6 in 24 h'); | |
| 190 | expect(page).toMatch(/data-out="landed">\s*<a class="mono" href="\/boards\?out=landed&hour=0#out" data-hour="0" data-n="stage\.approved\.hour">2<\/a>/); | |
| 191 | expect(page).toContain('data-day="6" data-n="stage.approved.day">6 in 24 h'); | |
| 192 | 192 | expect(page).toContain("2 passed · 1 failed"); |
| 193 | 193 | expect((page.match(/class="flow-bar"/g) ?? []).length).toBe(PIPELINE.length * 24); |
| 194 | 194 | }); |
test/no-polling.test.ts +1
| @@ -10,6 +10,7 @@ import { Glob } from "bun"; | ||
| 10 | 10 | /** file -> the patterns it may carry, and why */ |
| 11 | 11 | const ALLOWED: Record<string, { allow: string[]; why: string }> = { |
| 12 | 12 | "src/web/sw.ts": { allow: ['http-equiv="refresh"'], why: "the restart page: the forge is down, so there is no /events to hear" }, |
| 13 | "src/web/boards-index-live.ts": { allow: ["setInterval"], why: "the \"updated Ns ago\" clock: it only redraws text and requests nothing" }, | |
| 13 | 14 | "src/web/client.ts": { allow: ["data-live-every", "setInterval"], why: "the data-live-every mechanism itself, and clocks that only redraw text" }, |
| 14 | 15 | }; |
| 15 | 16 |
new above
offline