Public: anyone can read this; the crew can change it.
Home opens with a KPI row: landings per hour, live version, median check time #2865
scout/forge:scout/2739-home-opens-with-a-kpi-row-landings-per-h → main 2 commits fork
7 files
changed +297
−12
README.md +1 −1
Diff not shown — a line 4,595 characters wide (limit 2,000). +1 −1
View filesrc/flow/kpis.ts added +93
| @@ -0,0 +1,93 @@ | ||
| 1 | /** | |
| 2 | * The home's KPI row (#2739), as plain data: real landings per hour on the | |
| 3 | * forge's own default branch with a 24-hour sparkline, and the median time a | |
| 4 | * check took over the same 24 hours. Which version is live is the process's | |
| 5 | * own stamp (`kernel/version.ts`); the page puts that beside these. | |
| 6 | * | |
| 7 | * A landing is a commit on the first-parent line of the default branch that | |
| 8 | * changed something: an empty commit (`--allow-empty`, a merge of a pull that | |
| 9 | * had already landed) is history, not a landing, and is not counted. Hours | |
| 10 | * count back from `now` as in `throughput.ts`: hour 0 is the last hour. | |
| 11 | */ | |
| 12 | ||
| 13 | import type { Database } from "bun:sqlite"; | |
| 14 | import type { App } from "../app.ts"; | |
| 15 | import { getRepo } from "../core/repos.ts"; | |
| 16 | import { runGit } from "../git/env.ts"; | |
| 17 | import { isSafeRef } from "../git/guard.ts"; | |
| 18 | import { repoDir } from "../git/repos.ts"; | |
| 19 | import { HOURS, median } from "./throughput.ts"; | |
| 20 | ||
| 21 | const HOUR_MS = 3_600_000; | |
| 22 | ||
| 23 | export interface Kpis { | |
| 24 | /** Landings per hour, hour 0 the last one; null when the forge names no code repository. */ | |
| 25 | readonly landings: readonly number[] | null; | |
| 26 | /** Median check duration in milliseconds over checks that finished in 24 h; null when none did. */ | |
| 27 | readonly medianCheckMs: number | null; | |
| 28 | } | |
| 29 | ||
| 30 | /** One commit as the log reports it: when it was committed (epoch seconds) and whether it changed any path. */ | |
| 31 | export interface LogEntry { | |
| 32 | readonly at: number; | |
| 33 | readonly changed: boolean; | |
| 34 | } | |
| 35 | ||
| 36 | /** Per hour back from `now`, the entries that changed something. */ | |
| 37 | export function landingsByHour(entries: readonly LogEntry[], now: number): number[] { | |
| 38 | const hours = new Array<number>(HOURS).fill(0); | |
| 39 | for (const e of entries) { | |
| 40 | if (!e.changed) continue; | |
| 41 | const h = Math.floor((now - e.at * 1000) / HOUR_MS); | |
| 42 | if (h >= 0 && h < HOURS) hours[h]! += 1; | |
| 43 | } | |
| 44 | return hours; | |
| 45 | } | |
| 46 | ||
| 47 | /** Parse `git log --format=%x01%ct%x02 --name-only`: a record per commit, its paths after the `\x02`. */ | |
| 48 | export function parseLog(out: string): LogEntry[] { | |
| 49 | const entries: LogEntry[] = []; | |
| 50 | for (const record of out.split("\x01")) { | |
| 51 | const [stamp, paths = ""] = record.split("\x02"); | |
| 52 | if (stamp === undefined || !/^\d{1,12}$/.test(stamp)) continue; | |
| 53 | entries.push({ at: Number(stamp), changed: paths.trim() !== "" }); | |
| 54 | } | |
| 55 | return entries; | |
| 56 | } | |
| 57 | ||
| 58 | async function readLandings(app: App, now: number): Promise<number[] | null> { | |
| 59 | const [owner, name] = (app.config.forgeRepo ?? "").split("/"); | |
| 60 | if (owner === undefined || name === undefined) return null; | |
| 61 | const repo = getRepo(app.db, owner, name); | |
| 62 | if (repo === undefined || !isSafeRef(repo.defaultBranch)) return null; | |
| 63 | const since = Math.floor(now / 1000) - HOURS * 3600; | |
| 64 | const log = await runGit( | |
| 65 | [ | |
| 66 | "log", "--first-parent", "-m", "--name-only", | |
| 67 | `--since=${since}`, "--format=%x01%ct%x02", | |
| 68 | `refs/heads/${repo.defaultBranch}`, "--", | |
| 69 | ], | |
| 70 | { cwd: repoDir(app.reposRoot, repo.ownerName, repo.name) }, | |
| 71 | ); | |
| 72 | return log.ok ? landingsByHour(parseLog(log.value), now) : null; | |
| 73 | } | |
| 74 | ||
| 75 | /** The median of how long each check that finished in the last 24 hours ran. */ | |
| 76 | export function medianCheckMs(db: Database, now: number): number | null { | |
| 77 | const rows = db | |
| 78 | .query<{ started_at: string; finished_at: string }, [string, string]>( | |
| 79 | `SELECT started_at, finished_at FROM run | |
| 80 | WHERE kind = 'check' AND state IN ('ok','failed') | |
| 81 | AND started_at IS NOT NULL AND finished_at >= ?1 AND finished_at <= ?2`, | |
| 82 | ) | |
| 83 | .all(new Date(now - HOURS * HOUR_MS).toISOString(), new Date(now).toISOString()); | |
| 84 | return median( | |
| 85 | rows | |
| 86 | .map((r) => Date.parse(r.finished_at) - Date.parse(r.started_at)) | |
| 87 | .filter((ms) => Number.isFinite(ms) && ms >= 0), | |
| 88 | ); | |
| 89 | } | |
| 90 | ||
| 91 | export async function readKpis(app: App, now = Date.now()): Promise<Kpis> { | |
| 92 | return { landings: await readLandings(app, now), medianCheckMs: medianCheckMs(app.db, now) }; | |
| 93 | } |
src/web/pages/releases.ts −9
| @@ -19,15 +19,6 @@ import { html, when, type Html } from "../html.ts"; | ||
| 19 | 19 | import { flashTo, page } from "../layout.ts"; |
| 20 | 20 | import { badge, btn, card, empty, sha, time } from "../ui.ts"; |
| 21 | 21 | |
| 22 | /** "live: <sha> since <time>" for the home, or nothing when no release is known to be live. */ | |
| 23 | export function liveLine(ctx: Ctx): Html | undefined { | |
| 24 | const live = running().commit; | |
| 25 | if (live === null || !mayRead(ctx.app, ctx.auth.user)) return undefined; | |
| 26 | return html`<p class="small muted" id="live-release"> | |
| 27 | <a href="/releases">live: <span class="sha">${live.slice(0, 7)}</span> since ${time(BOOTED)}</a> | |
| 28 | </p>`; | |
| 29 | } | |
| 30 | ||
| 31 | 22 | function pullCell(ctx: Ctx, r: Release): Html { |
| 32 | 23 | if (r.pullNumber === null) return html`—`; |
| 33 | 24 | const repo = getRepoById(ctx.app.db, r.repoId); |
src/web/studio/home.ts +3 −2
| @@ -6,7 +6,6 @@ | ||
| 6 | 6 | * best of what is public (`actions/front.ts`). |
| 7 | 7 | */ |
| 8 | 8 | |
| 9 | import { liveLine } from "../pages/releases.ts"; | |
| 10 | 9 | import { |
| 11 | 10 | frontPage, |
| 12 | 11 | frontPicksJson, |
| @@ -48,6 +47,7 @@ import { writableAppsOf } from "./asks.ts"; | ||
| 48 | 47 | import { needsYouSection } from "./asks_page.ts"; |
| 49 | 48 | import { flowCards } from "./flow_card.ts"; |
| 50 | 49 | import { composer, feedJs, feedNote, feedRegion } from "./feed.ts"; |
| 50 | import { kpiRow } from "./kpi_row.ts"; | |
| 51 | 51 | import { homeTabs } from "./home_tabs.ts"; |
| 52 | 52 | import { crewKeyNote } from "./crew.ts"; |
| 53 | 53 | import { everydayCard } from "../pages/everyday.ts"; |
| @@ -243,8 +243,9 @@ export async function studioHome( | ||
| 243 | 243 | }); |
| 244 | 244 | } |
| 245 | 245 | const ask = firstSteps ?? everydayCard(ctx, user); |
| 246 | const kpis = await kpiRow(ctx); | |
| 246 | 247 | const body = html`<h1 class="sr-only">Home</h1> |
| 247 | ${ask} ${address} ${liveLine(ctx)} | |
| 248 | ${ask} ${address} ${kpis} | |
| 248 | 249 | ${when( |
| 249 | 250 | steps, |
| 250 | 251 | () => html`<p class="small muted" id="lean-home"> |
src/web/studio/kpi_row.ts added +69
| @@ -0,0 +1,69 @@ | ||
| 1 | /** | |
| 2 | * The home's KPI row (#2739): shipped per hour with a day's sparkline, the | |
| 3 | * live version and since when, the median test time. Each tile is a link to | |
| 4 | * the page that explains it. Server-rendered at a fixed height, so nothing | |
| 5 | * moves when it arrives; shown to those who may read the releases, as the | |
| 6 | * live line is. | |
| 7 | */ | |
| 8 | ||
| 9 | import { readKpis } from "../../flow/kpis.ts"; | |
| 10 | import { HOURS } from "../../flow/throughput.ts"; | |
| 11 | import { running, runningLine } from "../../kernel/version.ts"; | |
| 12 | import { BOOTED, mayRead } from "../../release/gate.ts"; | |
| 13 | import type { Ctx } from "../../http/context.ts"; | |
| 14 | import { html, type Html } from "../html.ts"; | |
| 15 | import { time } from "../ui.ts"; | |
| 16 | ||
| 17 | export const kpiCss = /* css */ ` | |
| 18 | .kpis { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 200px), 1fr)); gap: 8px; margin: 0 0 16px; padding: 0; list-style: none; } | |
| 19 | .kpi { display: grid; gap: 2px; align-content: start; min-height: 76px; padding: 10px 12px; background: var(--card); border: 1px solid var(--border); border-radius: var(--radius); color: var(--fg); text-decoration: none; min-width: 0; overflow-wrap: anywhere; } | |
| 20 | .kpi:hover { border-color: var(--border-strong); } | |
| 21 | .kpi:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; } | |
| 22 | .kpi-value { font-size: 20px; font-weight: 600; font-variant-numeric: tabular-nums; } | |
| 23 | .kpi svg { width: 72px; height: 16px; } | |
| 24 | .kpi-bar { fill: var(--muted-fg); } | |
| 25 | .kpi-bar[data-empty] { fill: var(--muted); } | |
| 26 | `; | |
| 27 | ||
| 28 | /** "1.5/h": landings per hour over the day, one decimal. */ | |
| 29 | export const perHour = (day: number): string => `${(day / HOURS).toFixed(1)}/h`; | |
| 30 | ||
| 31 | /** A span in the unit it reads best in: "45 s", "3.5 min", "1.2 h". */ | |
| 32 | export function span(ms: number): string { | |
| 33 | if (ms < 60_000) return `${Math.round(ms / 1000)} s`; | |
| 34 | if (ms < 3_600_000) return `${(ms / 60_000).toFixed(1)} min`; | |
| 35 | return `${(ms / 3_600_000).toFixed(1)} h`; | |
| 36 | } | |
| 37 | ||
| 38 | function sparkline(hours: readonly number[]): Html { | |
| 39 | const max = Math.max(1, ...hours); | |
| 40 | const bars = hours.map((n, hour) => { | |
| 41 | const h = n === 0 ? 1 : Math.max(2, Math.round((n / max) * 16)); | |
| 42 | return html`<rect class="kpi-bar" ${n === 0 ? html`data-empty` : null} x="${String((HOURS - 1 - hour) * 3)}" y="${String(16 - h)}" width="2" height="${String(h)}" />`; | |
| 43 | }); | |
| 44 | return html`<svg viewBox="0 0 72 16" aria-hidden="true" focusable="false">${bars}</svg>`; | |
| 45 | } | |
| 46 | ||
| 47 | export async function kpiRow(ctx: Ctx): Promise<Html | null> { | |
| 48 | if (!mayRead(ctx.app, ctx.auth.user)) return null; | |
| 49 | const kpis = await readKpis(ctx.app); | |
| 50 | const day = kpis.landings?.reduce((a, b) => a + b, 0) ?? null; | |
| 51 | const live = running(); | |
| 52 | return html`<ul class="kpis" id="kpis" aria-label="Key numbers"> | |
| 53 | <li><a class="kpi" href="/boards"> | |
| 54 | <span class="kpi-label muted small">Shipped per hour</span> | |
| 55 | <span class="kpi-value">${day === null ? "—" : perHour(day)}</span> | |
| 56 | ${kpis.landings === null ? html`<span class="small muted">not set up</span>` : sparkline(kpis.landings)} | |
| 57 | </a></li> | |
| 58 | <li id="live-release"><a class="kpi" href="/releases"> | |
| 59 | <span class="kpi-label muted small">Live version</span> | |
| 60 | <span class="kpi-value">${runningLine(live)}</span> | |
| 61 | <span class="small muted">live since ${time(BOOTED)}</span> | |
| 62 | </a></li> | |
| 63 | <li><a class="kpi" href="/boards"> | |
| 64 | <span class="kpi-label muted small">Median test time (24 h)</span> | |
| 65 | <span class="kpi-value">${kpis.medianCheckMs === null ? "—" : span(kpis.medianCheckMs)}</span> | |
| 66 | <span class="small muted"> </span> | |
| 67 | </a></li> | |
| 68 | </ul>`; | |
| 69 | } |
src/web/studio/style.ts +2
| @@ -79,6 +79,7 @@ const phone = part(/* css */ ` | ||
| 79 | 79 | `); |
| 80 | 80 | |
| 81 | 81 | import { feedCss } from "./feed_style.ts"; |
| 82 | import { kpiCss } from "./kpi_row.ts"; | |
| 82 | 83 | |
| 83 | 84 | export const studioCss = `@layer components {\n${[ |
| 84 | 85 | tellBox, |
| @@ -88,5 +89,6 @@ export const studioCss = `@layer components {\n${[ | ||
| 88 | 89 | rows, |
| 89 | 90 | rowActions, |
| 90 | 91 | part(feedCss), |
| 92 | part(kpiCss), | |
| 91 | 93 | phone, |
| 92 | 94 | ].join("\n\n")}\n}`; |
test/home-kpis.test.ts added +129
| @@ -0,0 +1,129 @@ | ||
| 1 | /** | |
| 2 | * The home's KPI row (#2739): from seeded commits on the forge repository's | |
| 3 | * default branch and seeded checks, the numbers are the expected ones; an | |
| 4 | * empty commit is not a landing; the row is server-rendered with its links. | |
| 5 | */ | |
| 6 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 7 | import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; | |
| 8 | import { tmpdir } from "node:os"; | |
| 9 | import { join } from "node:path"; | |
| 10 | import { createRepo } from "../src/actions/repos.ts"; | |
| 11 | import { createApp, type App } from "../src/app.ts"; | |
| 12 | import { createRun } from "../src/core/runs.ts"; | |
| 13 | import { createUser } from "../src/core/users.ts"; | |
| 14 | import { landingsByHour, medianCheckMs, parseLog, readKpis } from "../src/flow/kpis.ts"; | |
| 15 | import { repoDir } from "../src/git/repos.ts"; | |
| 16 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 17 | import { span } from "../src/web/studio/kpi_row.ts"; | |
| 18 | import { quietLogs } from "./helpers/globals.ts"; | |
| 19 | import { proveAll } from "./helpers/verified.ts"; | |
| 20 | ||
| 21 | quietLogs(); | |
| 22 | ||
| 23 | const HOUR = 3_600_000; | |
| 24 | const NOW = Date.now(); | |
| 25 | ||
| 26 | describe("the home's KPI row", () => { | |
| 27 | let root = ""; | |
| 28 | let app: App; | |
| 29 | let servers: Servers; | |
| 30 | ||
| 31 | const git = (cwd: string, date: string | null, ...args: string[]) => { | |
| 32 | const r = Bun.spawnSync(["git", ...args], { | |
| 33 | cwd, | |
| 34 | env: { | |
| 35 | PATH: process.env["PATH"] ?? "", | |
| 36 | HOME: root, | |
| 37 | GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t", | |
| 38 | ...(date === null ? {} : { GIT_AUTHOR_DATE: date, GIT_COMMITTER_DATE: date }), | |
| 39 | }, | |
| 40 | }); | |
| 41 | if (r.exitCode !== 0) throw new Error(r.stderr.toString()); | |
| 42 | }; | |
| 43 | const login = async () => { | |
| 44 | const r = await fetch(`${servers.url}/signin`, { | |
| 45 | method: "POST", | |
| 46 | headers: { origin: servers.url }, | |
| 47 | body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }), | |
| 48 | redirect: "manual", | |
| 49 | }); | |
| 50 | return (r.headers.get("set-cookie") ?? "").split(";")[0]!; | |
| 51 | }; | |
| 52 | ||
| 53 | beforeAll(async () => { | |
| 54 | root = mkdtempSync(join(tmpdir(), "forge-kpis-")); | |
| 55 | app = createApp({ dataDir: root, port: 0, forgeRepo: "alice/forge" }); | |
| 56 | const u = await createUser(app.db, { | |
| 57 | origin: "seed", trusted: true, username: "alice", email: "[email protected]", | |
| 58 | password: "a-good-passphrase", adminIfFirst: true, | |
| 59 | }); | |
| 60 | if (!u.ok) throw new Error(u.error); | |
| 61 | proveAll(app); | |
| 62 | const made = await createRepo(app, u.value, { name: "forge" }); | |
| 63 | if (!made.ok) throw new Error(made.error); | |
| 64 | const bare = repoDir(app.reposRoot, "alice", "forge"); | |
| 65 | const work = join(root, "work"); | |
| 66 | git(root, null, "init", "-q", "-b", "main", work); | |
| 67 | const at = (hoursAgo: number) => new Date(NOW - hoursAgo * HOUR - 60_000).toISOString(); | |
| 68 | // Two real landings in the last hour, one 5 hours ago, one 30 hours ago, | |
| 69 | // and an empty commit in the last hour that is not a landing. | |
| 70 | for (const [file, hoursAgo] of [["a", 30], ["b", 5], ["c", 0], ["d", 0]] as const) { | |
| 71 | writeFileSync(join(work, file), file); | |
| 72 | git(work, at(hoursAgo), "add", file); | |
| 73 | git(work, at(hoursAgo), "commit", "-q", "-m", file); | |
| 74 | } | |
| 75 | git(work, at(0), "commit", "-q", "--allow-empty", "-m", "empty"); | |
| 76 | // The bare repository's pre-receive hook is the forge's own; fetch into it instead. | |
| 77 | git(bare, null, "fetch", "-q", work, "+main:refs/heads/main"); | |
| 78 | // Checks that finished in the last day: 30 s, 90 s and 60 s (median 60 s); a failed one counts; one 2 days old and one still running do not. | |
| 79 | const check = (state: string, start: number, end: number | null) => { | |
| 80 | const r = createRun(app.db, { repoId: (app.db.query("SELECT id FROM repo WHERE name='forge'").get() as { id: string }).id, kind: "check" }); | |
| 81 | app.db | |
| 82 | .query("UPDATE run SET state = ?1, started_at = ?2, finished_at = ?3 WHERE id = ?4") | |
| 83 | .run(state, new Date(start).toISOString(), end === null ? null : new Date(end).toISOString(), r.id); | |
| 84 | }; | |
| 85 | check("ok", NOW - 3 * HOUR, NOW - 3 * HOUR + 30_000); | |
| 86 | check("failed", NOW - 2 * HOUR, NOW - 2 * HOUR + 90_000); | |
| 87 | check("ok", NOW - HOUR, NOW - HOUR + 60_000); | |
| 88 | check("ok", NOW - 48 * HOUR, NOW - 48 * HOUR + 600_000); | |
| 89 | check("running", NOW - 1000, null); | |
| 90 | servers = await serve(app); | |
| 91 | }); | |
| 92 | afterAll(() => { | |
| 93 | servers?.stop(); | |
| 94 | rmSync(root, { recursive: true, force: true }); | |
| 95 | }); | |
| 96 | ||
| 97 | test("landings per hour count commits that changed something and skip the empty one", async () => { | |
| 98 | const { landings } = await readKpis(app, NOW); | |
| 99 | expect(landings).not.toBeNull(); | |
| 100 | expect(landings![0]).toBe(2); | |
| 101 | expect(landings![5]).toBe(1); | |
| 102 | expect(landings!.reduce((a, b) => a + b, 0)).toBe(3); | |
| 103 | }); | |
| 104 | ||
| 105 | test("the median check time is over checks that finished in 24 h", () => { | |
| 106 | expect(medianCheckMs(app.db, NOW)).toBe(60_000); | |
| 107 | expect(medianCheckMs(app.db, NOW - 100 * HOUR)).toBeNull(); | |
| 108 | }); | |
| 109 | ||
| 110 | test("pure pieces: the log parses and hours bucket", () => { | |
| 111 | const entries = parseLog(`\x01${Math.floor(NOW / 1000)}\x02\n\na\n\x01${Math.floor(NOW / 1000)}\x02\n\n`); | |
| 112 | expect(entries.map((e) => e.changed)).toEqual([true, false]); | |
| 113 | expect(landingsByHour(entries, NOW)[0]).toBe(1); | |
| 114 | expect(span(45_000)).toBe("45 s"); | |
| 115 | expect(span(210_000)).toBe("3.5 min"); | |
| 116 | }); | |
| 117 | ||
| 118 | test("home renders the row server-side, each tile a link, for an admin only", async () => { | |
| 119 | const cookie = await login(); | |
| 120 | const body = await (await fetch(`${servers.url}/`, { headers: { cookie } })).text(); | |
| 121 | const row = body.slice(body.indexOf('id="kpis"')); | |
| 122 | expect(row).toContain("0.1/h"); | |
| 123 | expect(row).toContain('href="/releases"'); | |
| 124 | expect(row).toContain('href="/boards"'); | |
| 125 | expect(row).toContain("1.0 min"); | |
| 126 | const anon = await (await fetch(`${servers.url}/`)).text(); | |
| 127 | expect(anon).not.toContain('id="kpis"'); | |
| 128 | }); | |
| 129 | }); |
new above
offline