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

A template page shows how long its last forge took from the click to a first live change, as one line #13454

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/13431-a-template-page-shows-how-long-its-last → main 11 commits fork 3 threads · 3 unresolved

  • Merged. scout/13431-a-template-page-shows-how-long-its-last was merged into main as 066c590.

Review

Sign in to review this change.
11 files changed +205 −8
docs/features/README.md +1
@@ -17,6 +17,7 @@ A new note gets a row here (`test/feature-orphans.test.ts`).
1717 Read with the guide page [What a forge is](../guide-what-a-forge-is.md).
1818
1919 - [A forge made from a template says so on its home](started-from.md)
20 - [How long the last forge from a template took, at /templates/<name>](template-timing.md)
2021 - [A look in the feed](feed-look.md)
2122 - [Empty lists](empty-words.md)
2223 - [An app with no description says its README](readme-description.md)
docs/features/template-timing.md added +7
@@ -0,0 +1,7 @@
1 # How long the last forge from a template took
2
3 `/templates/<name>` (a built-in template, for example `starter`) and `/templates/<owner>/<name>` (a template repository, readable by the viewer) say what the template is and, once a forge has been made from it, one muted line: `Last forge from this template reached its first change in <time>`. With no recorded spawn there is no line.
4
5 The time is the `ms` of the newest real `forge.spawn.live` event for that template (click to the child's first `/healthz` answer). `spawn/live.ts` records the template on that event; nothing is measured on the page request and no table was added. Drills and forges made before this was kept do not count. A forge's "Started from" line links here; the terminal's Template screen prints the same line.
6
7 Code: `src/actions/template_timing.ts`, `src/web/pages/template.ts`. Test: `test/template-timing.test.ts`.
src/actions/template_timing.ts added +48
@@ -0,0 +1,48 @@
1 /**
2 * How long the last forge made from a template took to come alive (#13431). Nothing is measured
3 * here and no table is added: `spawn/live.ts` already records `forge.spawn.live` with `ms` (the
4 * click to the first answer of the child's `/healthz`) and, from this change, the template; this
5 * reads the newest such event. A forge made with no template, or before this was kept, counts for
6 * none.
7 */
8
9 import type { Database } from "bun:sqlite";
10 import { DEFAULT_TEMPLATE, parseTemplate } from "../spawn/templates.ts";
11
12 /**
13 * The template a spawn asked for, as the field to record on its live event; none for blank or junk.
14 */
15 export function templateOfInput(v: unknown): { template?: string } {
16 const t = parseTemplate(v);
17 return t.ok && t.value !== DEFAULT_TEMPLATE ? { template: t.value } : {};
18 }
19
20 /**
21 * The ms the newest real (not a drill) forge from this template took to go live, read from the
22 * outbox (walks `event_kind`); undefined when there is none.
23 */
24 export function lastForgeMs(db: Database, template: string): number | undefined {
25 const row = db
26 .query<{ ms: number }, [string]>(
27 `SELECT json_extract(payload, '$.ms') AS ms FROM event
28 WHERE kind = 'forge.spawn.live' AND json_extract(payload, '$.template') = ?1
29 AND json_extract(payload, '$.drill') IS NULL AND json_extract(payload, '$.ms') IS NOT NULL
30 ORDER BY seq DESC LIMIT 1`,
31 )
32 .get(template);
33 return row !== null && typeof row.ms === "number" ? row.ms : undefined;
34 }
35
36 /** "850 ms", "12 s", "1 m 5 s": the time in the two units that read at a glance. */
37 export function spawnTimeWords(ms: number): string {
38 if (ms < 1000) return `${Math.max(0, Math.round(ms))} ms`;
39 const s = Math.round(ms / 1000);
40 if (s < 60) return `${s} s`;
41 return s % 60 === 0 ? `${s / 60} m` : `${Math.floor(s / 60)} m ${s % 60} s`;
42 }
43
44 /** The one line, or null when no forge from this template has come alive. */
45 export function templateTimingLine(db: Database, template: string): string | null {
46 const ms = lastForgeMs(db, template);
47 return ms === undefined ? null : `Last forge from this template reached its first change in ${spawnTimeWords(ms)}`;
48 }
src/http/server.ts +3
@@ -26,6 +26,7 @@ import { refusedByDatabase, shownRefusal } from "./refusal.ts";
2626 import { NOT_A_MEMBER } from "../core/roles.ts";
2727 import { privacyPage } from "../web/pages/privacy.ts";
2828 import { termsPage } from "../web/pages/terms.ts";
29 import { templatePage } from "../web/pages/template.ts";
2930 import { publicSecurityPage } from "../web/pages/security_public.ts";
3031 import { statusPage } from "../web/pages/status.ts";
3132 import { startClaimAccountSubmit, startClaimPage, startClaimSubmit } from "../web/pages/start_claim.ts";
@@ -1068,6 +1069,8 @@ export function buildRouter(): Router<Handler> {
10681069 // The forge's own documentation: a redirect built from configuration only.
10691070 router.add("GET", "/privacy", privacyPage);
10701071 router.add("GET", "/terms", termsPage);
1072 router.add("GET", "/templates/:name", templatePage);
1073 router.add("GET", "/templates/:owner/:name", templatePage);
10711074 router.add("GET", "/security", publicSecurityPage);
10721075 router.add("GET", "/status", statusPage);
10731076 router.add("GET", "/docs", docsFolder);
src/spawn/door.ts +2 −1
@@ -10,6 +10,7 @@ import { dropServed } from "./clients.ts";
1010 import { contributeAnswer, wantsToContribute } from "./contribute_words.ts";
1111 import { nameShapeVerdict } from "./name_verdict.ts";
1212 import { linkRequestVisitor } from "../perf/visitor_link.ts";
13 import { templateOfInput } from "../actions/template_timing.ts";
1314 import { startWatch, probeOf, type Probe } from "./live.ts";
1415 import { firstProof, reachWords, settleChild } from "./reach.ts";
1516 import {
@@ -458,7 +459,7 @@ export async function spawnDoor(
458459 // Its apps come up now, so the first visit after a claim finds them awake.
459460 if (!made.value.existed) {
460461 void bootHostedChild(ctx.app, made.value.name);
461 startWatch(ctx.app, { name: made.value.name, startedAt, probe: (probes.get(ctx.app) ?? probeOf)(made.value.url) });
462 startWatch(ctx.app, { name: made.value.name, startedAt, ...templateOfInput(raw["template"]), probe: (probes.get(ctx.app) ?? probeOf)(made.value.url) });
462463 }
463464 // Proven from outside before it is called done: the child's home and each
464465 // app's public address, each with what came back. What does not answer yet
src/spawn/live.ts +7 −1
@@ -43,6 +43,11 @@ export interface Watch {
4343 readonly startedAt: number;
4444 readonly probe: Probe;
4545 readonly drill?: boolean;
46 /**
47 * The template the forge was started from (`blank` or none left out), kept on the event for the
48 * template's page.
49 */
50 readonly template?: string;
4651 readonly pollMs?: number;
4752 readonly giveUpMs?: number;
4853 readonly now?: () => number;
@@ -66,6 +71,7 @@ export async function watchLive(app: App, w: Watch): Promise<"live" | "failed" |
6671 const poll = w.pollMs ?? POLL_MS;
6772 const until = w.startedAt + (w.giveUpMs ?? GIVE_UP_MS);
6873 const drill = w.drill === true ? { drill: 1 } : {};
74 const template = w.template === undefined ? {} : { template: w.template };
6975 const sleep = (ms: number) =>
7076 new Promise<void>((done) => {
7177 const t = setTimeout(done, ms);
@@ -82,7 +88,7 @@ export async function watchLive(app: App, w: Watch): Promise<"live" | "failed" |
8288 if (app.closing.signal.aborted) return "stopped";
8389 if (up) {
8490 const ms = Math.max(0, Math.round(now() - w.startedAt));
85 app.bus.append({ kind: "forge.spawn.live", payload: { ms, ...drill } });
91 app.bus.append({ kind: "forge.spawn.live", payload: { ms, ...template, ...drill } });
8692 return "live";
8793 }
8894 const t = now();
src/tui/screens/template.ts +6 −2
@@ -7,6 +7,7 @@
77 */
88
99 import { updateRepoSettings } from "../../actions/repos.ts";
10 import { templateTimingLine } from "../../actions/template_timing.ts";
1011 import { templateProblem } from "../../apps/template_problem.ts";
1112 import { canAdmin, getRepoById, type Repo } from "../../core/repos.ts";
1213 import { templateSaid } from "../../core/template_words.ts";
@@ -46,8 +47,11 @@ export function templateScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
4647 ? "New forges may start from this repository. t clears it."
4748 : "Not a template. t lets new forges start from this repository.";
4849 s.text(area.x, area.y, truncate(said, area.w), style(c.mutedFg, c.bg), area.x + area.w);
49 if (on && flag !== undefined && area.h > 1)
50 s.text(area.x, area.y + 1, truncate(`Flagged: ${flag}`, area.w), style(c.mutedFg, c.bg), area.x + area.w);
50 let row = area.y + 1;
51 if (on && flag !== undefined && row < area.y + area.h)
52 s.text(area.x, row++, truncate(`Flagged: ${flag}`, area.w), style(c.mutedFg, c.bg), area.x + area.w);
53 const took = templateTimingLine(f.db, `${repo.ownerName}/${repo.name}`);
54 if (took !== null && row < area.y + area.h) s.text(area.x, row, truncate(took, area.w), style(c.mutedFg, c.bg), area.x + area.w);
5155 },
5256 key(e) {
5357 if (e.ctrl || e.alt || e.key !== "t") return false;
src/web/pages/template.ts added +45
@@ -0,0 +1,45 @@
1 /**
2 * GET /templates/:name (a built-in template) and /templates/:owner/:name (a template repository):
3 * what it is and, when a forge has been made from it, one line on how long the last took from
4 * the click to its first live answer. The number is read from stored events
5 * (`actions/template_timing.ts`), never measured here; with no spawn there is no line.
6 */
7
8 import { templateTimingLine } from "../../actions/template_timing.ts";
9 import { canRead, getRepo } from "../../core/repos.ts";
10 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
11 import type { Ctx } from "../../http/context.ts";
12 import { DEFAULT_TEMPLATE, TEMPLATES, templateOf } from "../../spawn/templates.ts";
13 import { notFoundPage } from "../chrome.ts";
14 import { html } from "../html.ts";
15 import { page } from "../layout.ts";
16
17 export function templatePage(ctx: Ctx): Response {
18 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
19 const owner = ctx.params["owner"];
20 const name = ctx.params["name"] ?? "";
21 let id: string;
22 let link = html``;
23 if (owner === undefined) {
24 if (name === DEFAULT_TEMPLATE || !TEMPLATES.some((t) => t.id === name)) return notFoundPage(ctx);
25 id = name;
26 } else {
27 const repo = getRepo(ctx.app.db, owner, name);
28 if (repo === undefined || !repo.template || !canRead(ctx.app.db, repo, ctx.auth.user)) return notFoundPage(ctx);
29 id = `${repo.ownerName}/${repo.name}`;
30 link = html`<p><a href="/${id}">Open the repository</a></p>`;
31 }
32 const t = templateOf(id);
33 return timePhase(ctx.request, "render", () => {
34 const line = templateTimingLine(ctx.app.db, id);
35 return page({
36 ctx,
37 title: t.title,
38 description: t.says,
39 body: html`<div class="page-head"><h1>${t.title}</h1></div>
40 <p class="muted">${t.says}</p>
41 ${line === null ? null : html`<p class="small muted" id="template-timing">${line}</p>`}
42 ${link}`,
43 });
44 });
45 }
src/web/started_from.ts +4 −3
@@ -1,7 +1,8 @@
11 /**
22 * "Started from <template>": the one muted line a forge made from a template shows on its home.
3 * The stored name is printed; it links to the template's page only while that repository is
4 * still marked as a template here and the viewer can read it. Nothing for a forge with no template.
3 * The stored name is printed; it links to the template's page (`/templates/<owner>/<name>`) only
4 * while that repository is still marked as a template here and the viewer can read it. Nothing for
5 * a forge with no template.
56 */
67
78 import type { Database } from "bun:sqlite";
@@ -20,7 +21,7 @@ export function startedFromHtml(db: Database, from: StartedFrom, viewer: User |
2021 const [owner = "", name = ""] = from.repo.split("/");
2122 const repo = getRepo(db, owner, name);
2223 if (repo !== undefined && repo.template && canRead(db, repo, viewer)) {
23 shown = html`<a href="/${repo.ownerName}/${repo.name}">${from.name}</a>`;
24 shown = html`<a href="/templates/${repo.ownerName}/${repo.name}">${from.name}</a>`;
2425 }
2526 }
2627 return html`<p class="small muted" id="started-from">Started from ${shown}</p>`;
test/started-from-line.test.ts +1 −1
@@ -48,7 +48,7 @@ describe("started from", () => {
4848 await record({ id: "alice/kit", repo: "alice/kit", tip: "a".repeat(40) });
4949 const l = await line();
5050 expect(l).toContain("Started from");
51 expect(l).toContain('<a href="/alice/kit">alice/kit</a>');
51 expect(l).toContain('<a href="/templates/alice/kit">alice/kit</a>');
5252 const home = await (await fetch(`${servers.url}/`, { headers: { authorization: auth } })).text();
5353 expect(home).toContain('id="started-from"');
5454 });
test/template-timing.test.ts added +81
@@ -0,0 +1,81 @@
1 /**
2 * A template page says how long its last forge took to its first live answer, read from stored
3 * events (#13431).
4 */
5 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { commitToBranch, createRepo, updateRepoSettings } from "../src/actions/repos.ts";
11 import { getRepo } from "../src/core/repos.ts";
12 import { lastForgeMs, spawnTimeWords, templateOfInput } from "../src/actions/template_timing.ts";
13 import { createUser, type User } from "../src/core/users.ts";
14 import { watchLive } from "../src/spawn/live.ts";
15 import { serve, type Servers } from "../src/http/server.ts";
16 import { quietLogs } from "./helpers/globals.ts";
17
18 quietLogs();
19
20 describe("template timing", () => {
21 let dataDir: string;
22 let app: App;
23 let servers: Servers;
24 let alice: User;
25 const get = async (path: string) => fetch(`${servers.url}${path}`);
26
27 beforeAll(async () => {
28 dataDir = await mkdtemp(join(tmpdir(), "forge-template-timing-"));
29 app = createApp({ dataDir, port: 0 });
30 servers = await serve(app);
31 const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
32 if (!a.ok) throw new Error("user");
33 alice = a.value;
34 const kit = await createRepo(app, alice, { name: "kit", visibility: "public", description: "" });
35 if (!kit.ok) throw new Error("repo");
36 await commitToBranch(app, alice, kit.value, { message: "seed", files: [{ path: "forge.json", content: '{"app":{"run":"bun main.ts"}}' }] });
37 const marked = await updateRepoSettings(app, alice, getRepo(app.db, "alice", "kit") ?? kit.value, { template: true });
38 if (!marked.ok) throw new Error(`mark: ${marked.error}`);
39 }, 30_000);
40
41 afterAll(async () => {
42 servers.stop();
43 app.close();
44 await rm(dataDir, { recursive: true, force: true });
45 });
46
47 test("with no recorded spawn the page shows no timing line", async () => {
48 const res = await get("/templates/alice/kit");
49 expect(res.status).toBe(200);
50 const body = await res.text();
51 expect(body).not.toContain("template-timing");
52 expect(body).not.toContain("first change");
53 expect(lastForgeMs(app.db, "alice/kit")).toBeUndefined();
54 });
55
56 test("a recorded spawn shows its time, from the stored event", async () => {
57 const done = await watchLive(app, { name: "x", startedAt: 1_000, template: "alice/kit", probe: async () => true, now: () => 13_400 });
outdated

(t += 0) + 12_400 is a convoluted way to write a constant, and t is unused. Use now: () => 13_400 and delete t.

58 expect(done).toBe("live");
59 // A drill and another template's forge do not count.
60 await watchLive(app, { name: "y", startedAt: 0, template: "alice/kit", drill: true, probe: async () => true, now: () => 99_000 });
61 await watchLive(app, { name: "z", startedAt: 0, template: "starter", probe: async () => true, now: () => 5_000 });
62 expect(lastForgeMs(app.db, "alice/kit")).toBe(12_400);
63 const body = await (await get("/templates/alice/kit")).text();
64 expect(body).toContain("Last forge from this template reached its first change in 12 s");
65 const starter = await (await get("/templates/starter")).text();
66 expect(starter).toContain("in 5 s");
67 });
68
69 test("a repository that is not a template, and blank, have no page", async () => {
70 expect((await get("/templates/alice/nope")).status).toBe(404);
71 expect((await get("/templates/blank")).status).toBe(404);
72 });
73
74 test("the words and the recorded field", () => {
75 expect(spawnTimeWords(850)).toBe("850 ms");
76 expect(spawnTimeWords(65_000)).toBe("1 m 5 s");
77 expect(templateOfInput("blank")).toEqual({});
78 expect(templateOfInput("starter")).toEqual({ template: "starter" });
79 expect(templateOfInput(5)).toEqual({});
80 });
81 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs