Public: anyone can read this; the crew can change it.

An app's page shows its last 30 days of p75 load as a sparkline #3228

Parked opened this
Closed without merging

scout/forge:scout/3202-an-app-s-page-shows-its-last-30-days-of → main 5 commits fork 5 threads · 5 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
10 files changed +159 −18
README.md +2
@@ -257,6 +257,8 @@ Every page links one static, immutable script (`src/web/beacon.ts`, under 2 KB,
257257
258258 An app made from the template ships the same beacon as `static/beacon.js`, posting to `POST /__forge/measure` on the app's own host. The forge answers that door itself (`src/apps/measure.ts`), before the app is woken: same-origin only, 30 reports a minute per client and 600 per app (429), a body over the cap is a 413, and a private app or a sealed pull's preview refuses anyone its gate refuses. The app is the host's, never the body's. Production reports are kept in `app_vital` (`src/apps/vitals.ts`, TTFB, load, LCP, INP and CLS, a visitor hashed under the day's salt, no address, kept 90 days and removed with the app, at most 20,000 rows per app a day); previews store nothing. Only Do-Not-Track opts a visitor out on an app's host: the `forge_measure=off` cookie is set on the forge's host and never reaches an app's. Read the numbers (visitors today and over 7 days, p75 TTFB, load, LCP, INP and CLS) on the app's settings page under **Visitors and speed**, or as `vitals` in an admin's `GET /api/v1/repos/:owner/:name/app`. Both doors show them only to people who administer the repository (`appVisitors` in `src/actions/apps.ts`), so a reader or an anonymous caller sees no `vitals`. In the terminal all five are on the second line of the app's **Deploys** screen over ssh.
259259
260 The 30-day load line (p75 load per UTC day, oldest first; a gap is a day with no reports) is drawn on the settings page, is `vitals.loadDays` in the API (30 numbers, `null` for a gap), and is a one-line text sparkline, a space for a gap, under the visitors line of the app's **Deploys** screen over ssh.
261
260262 The `app_vital` board source (`src/boards/sources.ts`) charts those reports: one row per app per day with `app` (the app's id), `day`, `load_p75`, `inp_p75` (ms) and `reports` (rows kept that day), the percentiles nearest-rank per app per day as `reach` does. `max` or `avg` over several days summarises daily percentiles, not the percentile of the whole range. Its rows belong to the app's repository, so a query sees only the repos in its scope. Today boards query with `repoIds: "all"` (`src/web/pages/boards.ts`) and only a site admin reaches them; no non-admin scope exists, so nothing yet applies the settings page's `canAdmin` gate per repository, and whoever builds one must. Days older than the 90-day trim are gone, not zero. The slug and the visitor hash are not columns. No dependency was added. Left out: a starting board for it; pick `app_vital` in the `/boards` source picker.
261263
262264 ## Live in the terminal
src/actions/apps.ts +3 −3
@@ -12,7 +12,7 @@ import { mayView } from "../core/sealed.ts";
1212 import { requireVerified } from "./verify.ts";
1313 import { requireAppRoom } from "./app_limit.ts";
1414 import type { App } from "../app.ts";
15 import { appVitals, type AppVitals } from "../apps/vitals.ts";
15 import { appVitals, loadDays, type AppVitals } from "../apps/vitals.ts";
1616 import { appsRuntime, envsFor, type EnvStatus } from "../apps/runtime.ts";
1717 import { grantUrl, originFor } from "../apps/proxy.ts";
1818 import { scaffoldFiles } from "../apps/scaffold.ts";
@@ -485,10 +485,10 @@ export function appView(
485485 * An app's visitors and speed, for those who administer its repository: the
486486 * same gate as the settings card, so every door shows them to the same people.
487487 */
488 export function appVisitors(app: App, actor: User | undefined, repo: Repo): AppVitals | undefined {
488 export function appVisitors(app: App, actor: User | undefined, repo: Repo): (AppVitals & { loadDays: (number | null)[] }) | undefined {
489489 if (!canAdmin(app.db, repo, actor)) return undefined;
490490 const record = getAppByRepo(app.db, repo.id);
491 return record === undefined ? undefined : appVitals(app.db, record.id);
491 return record === undefined ? undefined : { ...appVitals(app.db, record.id), loadDays: loadDays(app.db, record.id) };
492492 }
493493
494494 export type EnvError = "not_found" | "no_runtime" | "no_such_env";
src/apps/vitals.ts +26
@@ -87,6 +87,25 @@ export function appVitals(db: Database, appId: string, at: number = Date.now()):
8787 };
8888 }
8989
90 /** How many days the load sparkline covers. */
91 export const LOAD_DAYS = 30;
92
93 /** p75 load (nearest rank) per UTC day over the last 30 days, oldest first; null for a day with no reports. */
94 export function loadDays(db: Database, appId: string, at: number = Date.now()): (number | null)[] {
95 const first = dayOf(at - (LOAD_DAYS - 1) * DAY);
96 const rows = db
97 .query<{ day: string; load: number }, [string, string]>(
98 "SELECT day, load FROM app_vital WHERE app_id = ? AND day >= ? AND load IS NOT NULL ORDER BY day, load",
99 )
100 .all(appId, first);
101 const byDay = new Map<string, number[]>();
102 for (const r of rows) byDay.set(r.day, [...(byDay.get(r.day) ?? []), r.load]);
103 return Array.from({ length: LOAD_DAYS }, (_, i) => {
104 const loads = byDay.get(dayOf(at - (LOAD_DAYS - 1 - i) * DAY));
105 return loads === undefined ? null : loads[Math.ceil(0.75 * loads.length) - 1]!;
106 });
107 }
108
90109 /** A duration as a person reads it: "420 ms", "1.3 s", or a dash with no data. */
91110 export const speedText = (v: number | undefined): string =>
92111 v === undefined ? "–" : v < 1000 ? `${Math.round(v)} ms` : `${(v / 1000).toFixed(1)} s`;
@@ -97,3 +116,10 @@ export const shiftText = (v: number | undefined): string => (v === undefined ? "
97116 /** The one line the terminal shows. */
98117 export const visitorsLine = (v: AppVitals): string =>
99118 `visitors ${v.today} today, ${v.week} in 7 days · p75 TTFB ${speedText(v.ttfbP75)} · load ${speedText(v.loadP75)} · LCP ${speedText(v.lcpP75)} · INP ${speedText(v.inpP75)} · CLS ${shiftText(v.clsP75)}`;
119
120
121 /** The 30-day load series as one line of block characters, a space for a day with no reports. */
122 export function loadText(days: readonly (number | null)[]): string {
123 const top = Math.max(1, ...days.map((d) => d ?? 0));
124 return days.map((d) => (d === null ? " " : "▁▂▃▄▅▆▇█"[Math.min(7, Math.floor((d / top) * 8))]!)).join("");
125 }
src/tui/screens/deploys.ts +6 −2
@@ -8,7 +8,7 @@
88 */
99
1010 import { appVisitors } from "../../actions/apps.ts";
11 import { visitorsLine } from "../../apps/vitals.ts";
11 import { loadText, visitorsLine } from "../../apps/vitals.ts";
1212 import { listRepoRuns } from "../../actions/runs.ts";
1313 import { carriedByRuns, carriesText } from "../../core/carried.ts";
1414 import type { Repo } from "../../core/repos.ts";
@@ -40,6 +40,7 @@ export function deploysScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
4040 let carries = new Map<string, number[]>();
4141 let loaded = false;
4242 let visitors = "";
43 let load = "";
4344
4445 const read = (): void => {
4546 const runs = readDeploys(f, repo);
@@ -50,6 +51,7 @@ export function deploysScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
5051 );
5152 const seen = appVisitors(f.app, f.user, repo);
5253 visitors = seen === undefined ? "" : visitorsLine(seen);
54 load = seen === undefined ? "" : `p75 load, 30 days [${loadText(seen.loadDays)}] (a space is a day with no reports)`;
5355 loaded = true;
5456 ctx.invalidate();
5557 };
@@ -66,7 +68,7 @@ export function deploysScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
6668 load: async () => read(),
6769 render(area, s) {
6870 const c = ctx.theme.c;
69 const [head, body] = split(area, "v", [len(visitors === "" ? 1 : 2), fill(1)]);
71 const [head, body] = split(area, "v", [len(visitors === "" ? 1 : 3), fill(1)]);
7072 s.text(
7173 head!.x,
7274 head!.y,
@@ -76,6 +78,8 @@ export function deploysScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
7678 );
7779 if (visitors !== "")
7880 s.text(head!.x, head!.y + 1, truncate(visitors, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
81 if (load !== "")

This line has no test. Render the screen as an admin and assert it appears, and as a non-admin and assert it does not.

82 s.text(head!.x, head!.y + 2, truncate(load, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
7983 if (list.runs.length === 0) {
8084 emptyState(s, body!, c, {
8185 title: loaded ? "No deploys" : "Reading…",
src/web/pages/settings.ts +17 −4
@@ -51,7 +51,7 @@ import {
5151 updateRepoSettings,
5252 } from "../../actions/repos.ts";
5353 import { appsRuntime } from "../../apps/runtime.ts";
54 import { appVitals, shiftText, speedText as ms, type AppVitals } from "../../apps/vitals.ts";
54 import { appVitals, loadDays, shiftText, speedText as ms, type AppVitals } from "../../apps/vitals.ts";
5555 import type { PreviewData } from "../../apps/data.ts";
5656 import {
5757 getAppByRepo,
@@ -79,6 +79,7 @@ import {
7979 repoPalette,
8080 settingsLayout,
8181 } from "../chrome.ts";
82 import { loadSpark } from "../studio/kpi_row.ts";
8283 import { settingsLead } from "../studio/crew.ts";
8384 import { pageTitle } from "../studio/nouns.ts";
8485 import { appHref } from "./apps.ts";
@@ -584,7 +585,7 @@ function appSettingsView(
584585 const domains = listAppDomains(ctx.app, ctx.auth.user, repo);
585586 return html`${form}
586587 ${when(listed?.ok === true, () => html`<div class="mt">${appMembersView(base, values.access, named)}</div>`)}
587 <div class="mt">${appVisitorsView(appVitals(ctx.app.db, record.id))}</div>
588 <div class="mt">${appVisitorsView(appVitals(ctx.app.db, record.id), loadDays(ctx.app.db, record.id))}</div>
588589 <div class="mt">
589590 ${appEnvView(base, listAppEnvNames(ctx.app.db, record.id))}
590591 </div>
@@ -623,8 +624,19 @@ const SCOPE_WORDS: Record<AppEnvScope, string> = {
623624 preview: "previews",
624625 };
625626
627 /** The 30-day load line with its latest and worst day in words, or that nothing was reported. */
628 function loadLine(days: readonly (number | null)[]): Html {
outdated

The days = [] default is only here for the tests and is dead in production. Make days required. With the default, a caller who forgets it silently prints 'No reports in the last 30 days', which is a false claim about the data.

629 const seen = days.filter((d): d is number => d !== null);
630 if (seen.length === 0) return html`<p class="muted small mt">No reports in the last ${days.length} days.</p>`;
631 const last = days.findLast((d) => d !== null)!;
632 return html`<div class="mt">
633 <p class="muted small">p75 load per day, last ${days.length} days: ${ms(last)} latest, ${ms(Math.max(...seen))} worst; a break is a day with no reports.</p>
634 ${loadSpark(days)}
635 </div>`;
636 }
637
626638 /** Production's visitors and the speed they saw, from the app's own beacon. */
627 function appVisitorsView(v: AppVitals): Html {
639 export function appVisitorsView(v: AppVitals, days: readonly (number | null)[]): Html {
628640 return card(
629641 html`<p class="muted small mb">
outdated

The 30-day chart is a 96x24 icon with no values, axis or title, so it is a hint more than a reading. Show the latest and the worst day in words next to it, e.g. ${ms(last)} latest, ${ms(max)} worst. That also gives screen-reader and no-image readers the numbers. The inline html here is also long; move this block into a small named function.

630642 Counted by the beacon the template ships, through the forge: no
@@ -639,7 +651,8 @@ function appVisitorsView(v: AppVitals): Html {
639651 <div><dt>p75 LCP</dt><dd>${ms(v.lcpP75)}</dd></div>
640652 <div><dt>p75 INP</dt><dd>${ms(v.inpP75)}</dd></div>
641653 <div><dt>p75 CLS</dt><dd>${shiftText(v.clsP75)}</dd></div>
642 </dl>`,
654 </dl>
655 ${loadLine(days)}`,
643656 { head: html`${icon("rocket")}<h2>Visitors and speed</h2>` },
644657 );
645658 }
src/web/studio/feed_style.ts +1
@@ -26,6 +26,7 @@ export const feedCss = /* css */ `
2626 .kpi-value { font-size: 16px; line-height: 32px; font-weight: 600; }
2727 .kpi-note { line-height: 20px; overflow: hidden; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; line-clamp: 2; overflow-wrap: anywhere; }
2828 .kpi-spark { display: block; color: var(--muted-fg); max-width: 100%; }
29 .kpi-spark-wide { height: auto; }
2930 /* Your apps: a narrow column on a desk, a tab away on a phone. */
3031 .home-tabs { display: none; margin-bottom: 12px; }
3132 .home-app { gap: 8px; }
src/web/studio/kpi_row.ts +31 −8
@@ -18,16 +18,34 @@ import { sha, time } from "../ui.ts";
1818
1919 const W = 96;
2020 const H = 24;
21 const WIDE_W = 360;
22 const WIDE_H = 48;
outdated

spark is private, and the new code adds branching to a shared helper. The existing home visitors tile draws through this path too, and no test pins that its output is unchanged for a series with no nulls. Add one.

2123
22 /** A series oldest first as a fixed-size SVG polyline; the numbers are the only input. */
23 function spark(series: readonly number[], label: string): Html {
24 const top = Math.max(1, ...series);
25 const step = W / Math.max(1, series.length - 1);
26 const points = series
27 .map((v, i) => `${(i * step).toFixed(1)},${(H - 2 - (v / top) * (H - 4)).toFixed(1)}`)
28 .join(" ");
24 /**
25 * A series oldest first as a fixed-size SVG; the numbers are the only input.
26 * A null is a gap: the line breaks there, and a lone point is a dot.
27 */
28 function spark(series: readonly (number | null)[], label: string, w: number = W, h: number = H, cls = "kpi-spark"): Html {
29 const top = Math.max(1, ...series.map((v) => v ?? 0));
30 const step = w / Math.max(1, series.length - 1);
31 const runs: string[][] = [[]];
32 series.forEach((v, i) => {
33 if (v === null) {
34 if (runs[runs.length - 1]!.length > 0) runs.push([]);
35 return;
36 }
37 runs[runs.length - 1]!.push(`${(i * step).toFixed(1)},${(h - 2 - (v / top) * (h - 4)).toFixed(1)}`);
38 });
39 const marks = runs
40 .filter((r) => r.length > 0)
41 .map((r) => {
42 if (r.length > 1) return `<polyline points="${r.join(" ")}" fill="none" stroke="currentColor" stroke-width="1.5"/>`;
43 const [x, y] = r[0]!.split(",");
44 return `<circle cx="${x}" cy="${y}" r="1.5" fill="currentColor"/>`;
45 })
46 .join("");
2947 return raw(
30 `<svg class="kpi-spark" viewBox="0 0 ${W} ${H}" width="${W}" height="${H}" role="img" aria-label="${label}"><polyline points="${points}" fill="none" stroke="currentColor" stroke-width="1.5"/></svg>`,
48 `<svg class="${cls}" viewBox="0 0 ${w} ${h}" width="${w}" height="${h}" role="img" aria-label="${label}">${marks}</svg>`,
3149 );
3250 }
3351
@@ -41,6 +59,11 @@ export function visitorsSpark(days: readonly number[]): Html {
4159 return spark(days, `Distinct visitors each day over the last ${days.length} days`);
4260 }
4361
outdated

loadSpark inherits the 96px width made for the home tile. On a 360px phone 30 days is hard to read. Pass a wider size, or let the SVG scale.

62 /** An app's p75 page load per day, oldest first; a null day had no reports and is a gap. */
63 export function loadSpark(days: readonly (number | null)[]): Html {
64 return spark(days, `p75 page load each day over the last ${days.length} days, in milliseconds`, WIDE_W, WIDE_H, "kpi-spark kpi-spark-wide");
65 }
66
4467 function tile(label: string, href: string, value: Html | string, full: string, note: string | Html, title: string, extra: Html | null = null, tone: "attn" | null = null): Html {
4568 return html`<a class="card kpi" href="${href}"${tone === null ? "" : raw(` data-tone="${tone}"`)} aria-label="${label}: ${full}, ${title}">
4669 <span class="small muted">${label}</span>
test/app-load-spark.test.ts added +64
@@ -0,0 +1,64 @@
1 /** An app's page draws 30 days of p75 load as a sparkline; a day with no reports is a gap (#3202). */
2
3 import { expect, test } from "bun:test";
4 import { Database } from "bun:sqlite";
5 import { loadDays, loadText } from "../src/apps/vitals.ts";
6 import { appVisitorsView } from "../src/web/pages/settings.ts";
7 import { visitorsSpark } from "../src/web/studio/kpi_row.ts";
8 import { dayOf } from "../src/web/measure.ts";
9
10 const DAY = 86_400_000;
11 const NOW = Date.UTC(2026, 9, 20, 12);
12
13 function fixture(rows: [number, number | null][]): Database {
14 const db = new Database(":memory:");
15 db.run("CREATE TABLE app_vital (app_id TEXT, day TEXT, at INTEGER, visitor TEXT, load REAL, inp REAL)");
16 rows.forEach(([ago, load], i) =>
17 db.run("INSERT INTO app_vital VALUES ('a', ?, ?, ?, ?, NULL)", [dayOf(NOW - ago * DAY), NOW - ago * DAY, `v${i}`, load]),
18 );
19 return db;
20 }
21
22 const v = { today: 0, week: 0, ttfbP75: undefined, loadP75: undefined, lcpP75: undefined, inpP75: undefined, clsP75: undefined };
23
24 test("loadDays is p75 per day, oldest first, null where nothing was reported", () => {
25 const days = loadDays(fixture([[0, 100], [0, 200], [0, 300], [0, 400], [2, 500], [40, 900]]), "a", NOW);
26 expect(days).toHaveLength(30);
27 expect(days[29]).toBe(300);
28 expect(days[27]).toBe(500);
29 expect(days[28]).toBeNull();
30 expect(days.filter((d) => d !== null)).toHaveLength(2);
31 });
32
33 test("the section breaks the line at a day with no reports", () => {
34 const out = String(appVisitorsView(v, loadDays(fixture([[0, 100], [1, 200], [3, 300], [4, 400]]), "a", NOW)));
35 expect(out).toContain("kpi-spark");
36 expect(out).not.toContain("<script");
37 expect(out.match(/<polyline/g)).toHaveLength(2);
38 });
39
40 test("a lone day is a dot and no reports say so in words", () => {
41 const lone = String(appVisitorsView(v, loadDays(fixture([[5, 100]]), "a", NOW)));
42 expect(lone).toContain("<circle");
43 const none = String(appVisitorsView(v, loadDays(fixture([]), "a", NOW)));
44 expect(none).not.toContain("kpi-spark");
45 expect(none).toContain("No reports in the last 30 days");
46 });
47
48 test("the section words the latest and the worst day", () => {
49 const out = String(appVisitorsView(v, loadDays(fixture([[0, 300], [1, 900], [2, 100]]), "a", NOW)));
50 expect(out).toContain("300 ms latest, 900 ms worst");
51 });
52
53 test("the terminal line is one character a day, a space for a gap", () => {
54 const line = loadText(loadDays(fixture([[0, 800], [2, 100]]), "a", NOW));
55 expect(line).toHaveLength(30);
56 expect(line.slice(-3)).toBe("▂ █");
57 expect(loadText([null, null])).toBe(" ");
58 });
59
60 test("a series with no gaps draws as one plain polyline, as before", () => {
61 const out = String(visitorsSpark([0, 5, 10]));
62 expect(out).toContain('<polyline points="0.0,22.0 48.0,12.0 96.0,2.0" fill="none" stroke="currentColor" stroke-width="1.5"/>');
63 expect(out).not.toContain("<circle");
64 });
test/apps-measure.test.ts +3
@@ -149,6 +149,7 @@ describe("a report through the proxy", () => {
149149 if (!bob.ok) throw new Error(bob.error);
150150 expect(appVisitors(app, bob.value, repo)).toBeUndefined();
151151 expect(appVisitors(app, owner, repo)).toMatchObject({ today: 1 });
152 expect(appVisitors(app, owner, repo)!.loadDays).toHaveLength(30);
152153 const get = (token?: string) =>
153154 fetch(`${servers.url}/api/v1/repos/alice/notes/app`, {
154155 headers: token ? { authorization: `Bearer ${token}` } : {},
@@ -160,6 +161,8 @@ describe("a report through the proxy", () => {
160161 expect(await asBob.json()).not.toHaveProperty("vitals");
161162 const asAlice = await get(createToken(app.db, owner.id, "r", "ro").token);
162163 expect(await asAlice.json()).toMatchObject({ vitals: { today: 1 } });
164 const series = ((await get(createToken(app.db, owner.id, "r2", "ro").token).then((r) => r.json())) as { vitals: { loadDays: unknown[] } }).vitals.loadDays;
165 expect(series).toHaveLength(30);
163166 });
164167
165168 test("a sealed pull's preview refuses an anonymous report and stores nothing", async () => {
test/tui-deploys.test.ts +6 −1
@@ -132,7 +132,11 @@ test("an admin sees the app's visitors and speed above the deploys, and a reader
132132 const record = made.value;
133133 const at = Date.now();
134134 recordAppVital(forge.db, record.id, { path: "/", ttfb: 90, load: 420, lcp: 1300, inp: 80, cls: 0.05 }, "c", "u", at);
135 expect(await screenText(alice, r.value)).toContain("visitors 1 today, 1 in 7 days · p75 TTFB 90 ms · load 420 ms · LCP 1.3 s · INP 80 ms · CLS 0.05");
135 const admin = await screenText(alice, r.value);
136 expect(admin).toContain("visitors 1 today, 1 in 7 days · p75 TTFB 90 ms · load 420 ms · LCP 1.3 s · INP 80 ms · CLS 0.05");
137 expect(admin).toContain("p75 load, 30 days [");
138 expect(admin).toContain("█] (a space is a day with no reports)");
139 expect(admin).toContain("No deploys");
136140 const c = await signUp(forge, {
137141 username: "carol",
138142 email: "[email protected]",
@@ -140,4 +144,5 @@ test("an admin sees the app's visitors and speed above the deploys, and a reader
140144 }, { slot: fixtureSlot(forge) });
141145 if (!c.ok) throw new Error("signup failed");
142146 expect(await screenText(c.value, r.value)).not.toContain("visitors");
147 expect((await screenText(c.value, r.value))).not.toContain("p75 load, 30 days [");
143148 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs