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

Games: spark profile call tree and flame graph on the forge #18211

opened this

Merged 5h 47m ago, live in production

torque/forge:torque/18208-games-spark-profile-call-tree-and-flame → main 0 commits fork 3 threads · 3 unresolved

  • Merged. torque/18208-games-spark-profile-call-tree-and-flame was merged into main as 5ce50ab.

Review

Sign in to review this change.
12 files changed +365 −83
docs/features/game-spark.md +5 −1
@@ -6,8 +6,12 @@ row: Game spark profiles
66
77 A box stores the profiles its servers' spark plugin posts, so a lag report is read from the forge, not a public paste. The box's owner makes an upload address on `/games/<box>` (Profiles, "Make an upload address"; `p` on the terminal's box screen opens `src/tui/screens/game_spark.ts`, where `u`), shown once: `<forge>/games/@spark/<secret>/`. Set it as spark's `bytebin-url`. spark posts `<address>post` (a gzipped protobuf, `Content-Type: application/x-spark-*`) and is answered `201` with `Location: <key>` and no body; a wrong secret is a `403`, a body past 8 MiB a `413`, anything not gzip or not a spark type a `400`. The secret only allows writes and only its hash is kept; a new address ends the old.
88
9 `GET <address><key>` returns the bytes and type to a forge session with any grant on the box (forge admins too), and `403` to anyone else; no grant table is new. The box's page and the terminal's box screen list what is stored (newest 50, type, time, size); the page's link opens one without the secret. A profile is kept 14 days and a box keeps its newest 50 (`SPARK_KEEP_DAYS`, `SPARK_KEEP_COUNT`, `BODY_CAPS.gameSpark`, each with its reason). `/games/<box>/spark/<key>` (#18058) opens a stored sampler profile on the forge for the same grants, a hidden or missing one a `404`: its threads, busiest first, with the time sampled in each, names escaped, read by the one decoder `src/games/spark_profile.ts` (`sparkThreads`). It unpacks at most 8 MiB, builds at most a million fields and reads at most 200 threads, so a hostile profile is refused ("download it"), not inflated. On the terminal, `p` on the box screen opens the profiles; `j`/`k` choose one and `enter` lists its threads, for any grant. Any other kind, or a profile too large to read here, is kept and offered as a download. Nothing is fetched elsewhere. **Not done: spark's viewer is not hosted.** This is a thread list; the call tree and flame graph are still opened in spark's own viewer from the downloaded file (#18208), and the gzip is checked by its magic bytes only. Code: `src/games/spark.ts`, `src/web/pages/games_spark.ts`.
9 `GET <address><key>` returns the bytes and type to a forge session with any grant on the box (forge admins too), and `403` to anyone else; no grant table is new. The box's page and the terminal's box screen list what is stored (newest 50, type, time, size); the page's link opens one without the secret. A profile is kept 14 days and a box keeps its newest 50 (`SPARK_KEEP_DAYS`, `SPARK_KEEP_COUNT`, `BODY_CAPS.gameSpark`, each with its reason). `/games/<box>/spark/<key>` (#18058) opens a stored sampler profile on the forge for the same grants, a hidden or missing one a `404`: per thread, in order of time, its time sampled, a flame graph (SVG drawn on the server, no script) and the call tree as text (at most 12 deep and 8 wide, the heaviest calls), names escaped, read by the one decoder `src/games/spark_profile.ts` (`decodeSparkProfile`) and drawn by `src/games/spark_view.ts`. It unpacks at most 8 MiB, builds at most a million fields and reads at most 200 threads, so a hostile profile is refused ("download it"), not inflated. On the terminal, `p` on the box screen opens the profiles; `j`/`k` choose one and `enter` shows the same call tree as indented lines, for any grant. Any other kind, or a profile too large to read here, is kept and offered as a download. Nothing is fetched elsewhere. The gzip is checked by its magic bytes at upload only. Not done: spark's own viewer's other tabs (heap, slowest ticks per window) are not drawn. Code: `src/games/spark.ts`, `src/web/pages/games_spark.ts`.
1010
1111 ## Installed with the mod (#18138)
1212
1313 Installing spark (`mods_install spark`, or as a plugin of a new server) writes spark's config in the same commit: `config/spark/config.json` on a mod server, `plugins/spark/config.json` on a plugin server. Its `bytebinUrl` is the placeholder `${CFG_SPARK_BYTEBIN_URL}`, which the image fills from the service's environment (`${SPARK_BASE}`), and `SPARK_BASE` is written to the box's sealed `.env` at each check-in: the upload address with its secret, which the repository never holds. Its `viewerUrl` is the box's profile page (`<forge>/games/<box>/@spark/`). No author-hosted address is in the file, so with the placeholder unfilled spark has no address to post to rather than a public paste. The box's `.env` address is the box's upload address: one made by hand on the page works until the box's next check-in, which sets it back. Not done: a spark already installed is not rewritten, and a hand-edited config is replaced on a reinstall.
14
15 ## The call tree and flame graph (#18208)
16
17 A listed profile opens `/games/<box>/spark/<key>` (the bytes stay at `/games/<box>/@spark/<key>`): `decodeSparkProfile` reads it per request, and each thread shows its time sampled (milliseconds), a flame graph (an SVG drawn on the server, no script; a box is as wide as its share of the thread, the call and time in its tooltip) and the call tree as text with shares. The terminal shows the same lines: on a box's Profiles screen (`p`), `j`/`k` pick a profile and Enter opens `src/tui/screens/game_spark_view.ts`. Only the 10 heaviest threads are drawn, on both doors; the rest are named as "N more threads not drawn, download the profile". Only a grant on the box reads it; a body that is not a profile says why and links the download. The tree is the decoder's pruned one: 12 deep, 8 wide, at most 2,000 nodes a thread, from a body of at most 8 MiB (64 MiB unpacked). Not done: slowest ticks, time per mod, GC and memory are decoded but not shown; a flame box is not zoomable. Code: `src/games/spark_view.ts` (layout), `src/web/pages/games_spark_view.ts`.
scripts/unused-exports-allow.json −6
@@ -90,8 +90,6 @@
9090 "src/git/read.ts sweepReaderPool",
9191 "src/http/archive_limit.ts forgetArchives",
9292 "src/http/crawl.ts crawlAgentCount",
93 "src/http/crawl.ts pinCrawlLag",
94 "src/http/crawl.ts setCrawlClock",
9593 "src/http/mcp.ts toolRegistry",
9694 "src/http/sse.ts resetSseDroppedCount",
9795 "src/http/sse.ts sseDroppedCount",
@@ -108,7 +106,6 @@
108106 "src/kernel/full_disk.ts forgetFull",
109107 "src/kernel/full_disk.ts provideWriterForTest",
110108 "src/kernel/log.ts clearErrors",
111 "src/kernel/migrate.ts notAdditive",
112109 "src/kernel/result.ts andThen",
113110 "src/kernel/result.ts unwrapOr",
114111 "src/looks/main_looks.ts mainLook",
@@ -134,7 +131,6 @@
134131 "src/snapshot/drill_job.ts markerLeft",
135132 "src/spawn/births.ts provideHoldForTest",
136133 "src/spawn/births.ts provideMemoryForTest",
137 "src/spawn/watch_probe_default.ts useWatchProbeByDefault",
138134 "src/spawn/child-apps.ts childRuntime",
139135 "src/spawn/child_db.ts childDbReaders",
140136 "src/spawn/clients.ts monthsSettled",
@@ -145,7 +141,6 @@
145141 "src/spawn/parent_credential.ts keepParentCredential",
146142 "src/spawn/pod.ts renderPod",
147143 "src/spawn/rate.ts resetAnonSpawns",
148 "src/spawn/reach_default.ts useReachByDefault",
149144 "src/spawn/usage.ts forgetSelfCpu",
150145 "src/story/records.ts isKnownRecord",
151146 "src/story/records.ts parseRecords",
@@ -186,6 +181,5 @@
186181 "src/spawn/machines.ts registerMachine",
187182 "src/spawn/routes.ts forgetRoutes",
188183 "src/maintain/lockfiles.ts lockfileDependencies",
189 "src/games/spark_profile.ts decodeSparkProfile",
190184 "src/trace/import.ts readImported"
191185 ]
src/games/spark_profile.ts −10
@@ -343,13 +343,3 @@ export function decodeSparkProfile(body: Uint8Array, unpacked = MAX_UNPACKED): S
343343
344344 /** What the forge unpacks to show a profile on a page or in the terminal: the upload cap. */
345345 export const READ_UNPACKED = 8 * 1024 * 1024;
346
347 /**
348 * The threads of a stored sampler profile, busiest first, for the page and the terminal; undefined
349 * when it is another kind, or too large or damaged to read here (the bytes are still kept).
350 */
351 export function sparkThreads(profile: { type: string; body: Uint8Array }): { name: string; ms: number }[] | undefined {
352 if (profile.type !== "application/x-spark-sampler") return undefined;
353 const r = decodeSparkProfile(profile.body, READ_UNPACKED);
354 return r.ok && r.summary.threads.length > 0 ? r.summary.threads.map((t) => ({ name: t.name.slice(0, 120), ms: t.ms })) : undefined;
355 }
src/games/spark_view.ts added +83
@@ -0,0 +1,83 @@
1 /**
2 * A decoded spark profile's call tree laid out for the two doors (#18208): `flameRects` for the
3 * page's flame graph, `treeLines` for the same tree as text (the terminal's, and the page's
4 * outline). Pure: the summary's tree in, plain data out. The tree is already pruned by
5 * `spark_profile.ts` (depth `TREE_DEPTH`, width `TREE_WIDTH`, at most 2,000 nodes a thread), so
6 * both are bounded by that.
7 *
8 * Units: `ms` is sampled time in milliseconds, as spark reports it; a share is a node's `ms`
9 * over the thread's `ms` (what the sampler spent in the thread), a fraction of 1.
10 */
11 import type { SparkSummary, TreeNode } from "./spark_profile.ts";
12
13 export interface FlameRect { readonly x: number; readonly w: number; readonly depth: number; readonly name: string; readonly ms: number; readonly share: number }
14
15 /** Widths are in this many units across (the SVG's viewBox width). */
16 export const FLAME_WIDTH = 1000;
17 /** A box narrower than this many units is left out: it cannot be seen or pointed at. */
18 const FLAME_MIN = 1.5;
19
20 /**
21 * A flame graph's boxes: each root starts where the last ended, a node's children sit under it from
22 * its left edge, and a box is `ms / total` of the width. Children whose times sum past their
23 * parent's (shared nodes) are clipped to the parent's right edge so a box never overhangs.
24 */
25 export function flameRects(tree: readonly TreeNode[], total: number): FlameRect[] {
26 const out: FlameRect[] = [];
27 if (!(total > 0)) return out;
28 const place = (nodes: readonly TreeNode[], from: number, to: number, depth: number): void => {
29 let x = from;
30 for (const n of nodes) {
31 const w = Math.min((Math.max(0, n.ms) / total) * FLAME_WIDTH, to - x);
32 if (w < FLAME_MIN) continue;
33 out.push({ x: round(x), w: round(w), depth, name: n.name, ms: n.ms, share: n.ms / total });
34 place(n.children, x, x + w, depth + 1);
35 x += w;
36 }
37 };
38 place(tree, 0, FLAME_WIDTH, 0);
39 return out;
40 }
41
42 const round = (x: number): number => Math.round(x * 100) / 100;
43 const percent = (share: number): string => `${(share * 100).toFixed(1)}%`;
44 export const millis = (ms: number): string => `${ms.toFixed(1)} ms`;
45
46 /** The tree as indented lines: ` 61.0% 60.0 ms net.minecraft.Level.tickEntities`. */
47 export function treeLines(tree: readonly TreeNode[], total: number): string[] {
48 const out: string[] = [];
49 const walk = (nodes: readonly TreeNode[], depth: number): void => {
50 for (const n of nodes) {
51 out.push(`${" ".repeat(depth)}${total > 0 ? percent(n.ms / total) : "-"} ${millis(n.ms)} ${n.name}`);
52 walk(n.children, depth + 1);
53 }
54 };
55 walk(tree, 0);
56 return out;
57 }
58
59 /**
60 * At most this many threads are drawn, the heaviest first: a profile may hold 200, each up to 2,000
61 * nodes.
62 */
63 export const MAX_THREADS = 10;
64
65 /**
66 * The heaviest `MAX_THREADS` threads by time sampled, and the sentence for those left out ("" when
67 * none).
68 */
69 export function heaviest<T extends { readonly ms: number }>(threads: readonly T[]): { drawn: T[]; note: string } {
70 const drawn = [...threads].sort((a, b) => b.ms - a.ms).slice(0, MAX_THREADS);
71 const left = threads.length - drawn.length;
72 return { drawn, note: left > 0 ? `${String(left)} more thread${left === 1 ? "" : "s"} not drawn, download the profile.` : "" };
73 }
74
75 /** The profile's header and thread list in the words both doors use. */
76 export function sparkHeadLines(s: SparkSummary): string[] {
77 const p = s.platform;
78 const secs = s.endTime > s.startTime ? Math.round((s.endTime - s.startTime) / 1000) : 0;
79 return [
80 `${p.name || p.type} ${p.version}${p.minecraft ? `, Minecraft ${p.minecraft}` : ""}${secs > 0 ? `, sampled ${String(secs)} s` : ""}`,
81 ...s.threads.map((t) => `${t.name || "(unnamed thread)"}: ${millis(t.ms)} sampled`),
82 ];
83 }
src/http/games_routes.ts +2 −1
@@ -26,7 +26,8 @@ import {
2626 } from "../web/pages/games.ts";
2727 import { gamePackDownload, gamePackLink, gamePackRevoke } from "../web/pages/games_client_pack.ts";
2828 import { gameMap, gameMapSlash } from "./games_map.ts";
29 import { gameSparkLink, gameSparkOpen, gameSparkPost, gameSparkRead, gameSparkView } from "../web/pages/games_spark.ts";
29 import { gameSparkView } from "../web/pages/games_spark_view.ts";
30 import { gameSparkLink, gameSparkOpen, gameSparkPost, gameSparkRead } from "../web/pages/games_spark.ts";
3031 import { gameConfigCommit, gameConfigPage, gameConfigPreview } from "../web/pages/games_config.ts";
3132 import { publicOrigin } from "../core/public_origin.ts";
3233 import type { Ctx, Handler } from "./context.ts";
src/tui/screens/game_spark.ts +17 −34
@@ -2,19 +2,19 @@
22 * A box's stored spark profiles in the terminal (#18137), as /games/<box>'s Profiles block: what is
33 * kept (type, time, size, key) in the same words, and `u`, for the box's owner, makes the upload
44 * address (shown once, here, until the screen closes: only its hash is kept). `j`/`k` choose a
5 * profile and `enter` lists a sampler profile's threads (#18058), for any grant on the box, as the
6 * page does.
5 * profile and `enter` opens a sampler profile's call tree (#18058, #18208), for any grant on the
6 * box, as the page does.
77 */
88
99 import { publicOrigin } from "../../core/public_origin.ts";
10 import { SPARK_WORDS, newSparkSecret, profileOf, profilesOf, sparkBase } from "../../games/spark.ts";
11 import { sparkThreads } from "../../games/spark_profile.ts";
10 import { SPARK_WORDS, newSparkSecret, profilesOf, sparkBase } from "../../games/spark.ts";
1211 import { mayDo, roleOn, type GameBox } from "../../games/store.ts";
1312 import type { Ctx, Screen } from "../app/app.ts";
1413 import { binding } from "../app/keys.ts";
1514 import { style } from "../term/style.ts";
1615 import { truncate, wrap } from "../term/width.ts";
1716 import type { Session } from "../session.ts";
17 import { gameSparkViewScreen } from "./game_spark_view.ts";
1818
1919 export function gameSparkScreen(f: Session, ctx: Ctx, box: GameBox): Screen {
2020 let address = "";
@@ -25,12 +25,12 @@ export function gameSparkScreen(f: Session, ctx: Ctx, box: GameBox): Screen {
2525 ...wrap(SPARK_WORDS, w),
2626 "",
2727 ...(address === "" ? [] : [`bytebin-url: ${address}`, "This is the only time it is shown.", ""]),
28 ...(stored.length === 0 ? ["None stored yet."] : stored.map((p) => `${p.at.slice(0, 16).replace("T", " ")} ${p.type.replace("application/x-spark-", "spark ")} ${String(Math.ceil(p.size / 1024))} KiB ${p.key}`)),
28 ...(stored.length === 0 ? ["None stored yet."] : stored.map((p, i) => `${i === at ? ">" : " "} ${p.at.slice(0, 16).replace("T", " ")} ${p.type.replace("application/x-spark-", "spark ")} ${String(Math.ceil(p.size / 1024))} KiB ${p.key}`)),
2929 ];
3030 };
3131 return {
3232 title: `${box.name}: spark profiles`,
33 keys: [binding(["j", "k"], "choose a profile"), binding(["enter"], "list its threads"), binding(["u"], "new upload address (owner)")],
33 keys: [binding(["j", "k"], "pick a profile"), binding(["enter"], "call tree"), binding(["u"], "new upload address (owner)")],
3434 render(area, s) {
3535 const c = ctx.theme.c;
3636 lines(Math.max(10, area.w)).slice(0, area.h).forEach((l, i) => s.text(area.x, area.y + i, truncate(l, area.w), style(c.fg, c.bg), area.x + area.w));
@@ -38,39 +38,22 @@ export function gameSparkScreen(f: Session, ctx: Ctx, box: GameBox): Screen {
3838 key(e) {
3939 if (e.ctrl || e.alt) return false;
4040 const stored = profilesOf(f.app.db, box.id);
41 if (e.key === "j" || e.key === "down" || e.key === "k" || e.key === "up") {
42 at = Math.max(0, Math.min(stored.length - 1, at + (e.key === "j" || e.key === "down" ? 1 : -1)));
41 if (e.key === "j" || e.key === "down") {
42 at = Math.min(at + 1, Math.max(0, stored.length - 1));
43 } else if (e.key === "k" || e.key === "up") {
44 at = Math.max(0, at - 1);
4345 } else if (e.key === "enter") {
44 const chosen = stored[at];
45 if (chosen === undefined || !mayDo(roleOn(f.app.db, f.user, box.id), "viewer")) return false;
46 ctx.push(profileScreen(f, ctx, box, chosen.key));
46 if (stored[at] === undefined || !mayDo(roleOn(f.app.db, f.user, box.id), "viewer")) return false;
47 ctx.push(gameSparkViewScreen(f, ctx, box, stored[at]!.key));
4748 return true;
48 } else if (e.key === "u" && mayDo(roleOn(f.app.db, f.user, box.id), "owner")) {
49 } else if (e.key === "u") {
50 if (!mayDo(roleOn(f.app.db, f.user, box.id), "owner")) return false;
4951 address = sparkBase(publicOrigin(f.app.config.url, `http://localhost:${String(f.app.config.port)}`), newSparkSecret(f.app.db, box.id));
50 } else return false;
52 } else {
53 return false;
54 }
5155 ctx.invalidate();
5256 return true;
5357 },
5458 };
5559 }
56
57 /** One stored profile's threads, busiest first: the page's list, in the same words. */
58 function profileScreen(f: Session, ctx: Ctx, box: GameBox, key: string): Screen {
59 const lines = (w: number): string[] => {
60 const profile = profileOf(f.app.db, box.id, key);
61 if (profile === undefined) return ["This profile is gone: it is kept 14 days."];
62 const threads = sparkThreads(profile);
63 return threads === undefined
64 ? wrap("The forge can list the threads of a sampler profile only, and this one is not a readable one: download it from the box's page.", w)
65 : ["The threads, busiest first. The call tree and flame graph are not shown here.", "", ...threads.map((t) => `${String(Math.round(t.ms))} ms sampled ${t.name}`)];
66 };
67 return {
68 title: `${box.name}: profile ${key}`,
69 keys: [],
70 render(area, s) {
71 const c = ctx.theme.c;
72 lines(Math.max(10, area.w)).slice(0, area.h).forEach((l, i) => s.text(area.x, area.y + i, truncate(l, area.w), style(c.fg, c.bg), area.x + area.w));
73 },
74 key: () => false,
75 };
76 }
src/tui/screens/game_spark_view.ts added +52
@@ -0,0 +1,52 @@
1 /**
2 * One stored spark profile in the terminal (#18208): what /games/<box>/spark/<key> shows, in
3 * the same words (`games/spark_view.ts`): the head, then per thread its time sampled and the call
4 * tree as indented lines. j/k scroll.
5 */
6
7 import { READ_UNPACKED, decodeSparkProfile } from "../../games/spark_profile.ts";
8 import { profileOf } from "../../games/spark.ts";
9 import { heaviest, millis, sparkHeadLines, treeLines } from "../../games/spark_view.ts";
10 import type { GameBox } from "../../games/store.ts";
11 import type { Ctx, Screen } from "../app/app.ts";
12 import { binding } from "../app/keys.ts";
13 import { style } from "../term/style.ts";
14 import { truncate } from "../term/width.ts";
15 import type { Session } from "../session.ts";
16
17 export function gameSparkViewScreen(f: Session, ctx: Ctx, box: GameBox, key: string): Screen {
18 let top = 0;
19 let cached: string[] | undefined;
20 // A stored profile never changes, so its lines are built once per screen, not on every render.
21 const lines = (): string[] => {
22 cached ??= build();
23 return cached;
24 };
25 const build = (): string[] => {
26 const stored = profileOf(f.app.db, box.id, key);
27 if (stored === undefined) return ["This profile is gone: profiles are kept 14 days."];
28 const read = stored.type === "application/x-spark-sampler" ? decodeSparkProfile(stored.body, READ_UNPACKED) : undefined;
29 if (read === undefined || !read.ok) return ["The forge draws a sampler profile only, and this one is not a readable one: download it from the box's page."];
30 const { drawn, note } = heaviest(read.summary.threads);
31 const [head = ""] = sparkHeadLines(read.summary);
32 return [head, "Times are milliseconds sampled, shares are of the thread; trees keep the heaviest calls.", ...drawn.flatMap((t) => ["", `== ${t.name || "(unnamed thread)"}: ${millis(t.ms)} sampled`, ...(t.tree.length === 0 ? ["Nothing was sampled in this thread."] : treeLines(t.tree, t.ms))]), ...(note === "" ? [] : ["", note])];
33 };
34 return {
35 title: `${box.name}: profile ${key}`,
36 keys: [binding(["j", "k"], "scroll")],
37 render(area, s) {
38 const c = ctx.theme.c;
39 const all = lines();
40 top = Math.max(0, Math.min(top, all.length - area.h));
41 all.slice(top, top + area.h).forEach((l, i) => s.text(area.x, area.y + i, truncate(l, area.w), style(l.startsWith("== ") ? c.mutedFg : c.fg, c.bg), area.x + area.w));
42 },
43 key(e) {
44 if (e.ctrl || e.alt) return false;
45 if (e.key === "j" || e.key === "down") top++;
46 else if (e.key === "k" || e.key === "up") top = Math.max(0, top - 1);
47 else return false;
48 ctx.invalidate();
49 return true;
50 },
51 };
52 }
src/web/pages/games_spark.ts +1 −29
@@ -8,11 +8,7 @@ import { BODY_CAPS, readBounded } from "../../http/limits.ts";
88 import type { Ctx } from "../../http/context.ts";
99 import { seesBox } from "../../games/store.ts";
1010 import { boxOfSparkSecret, keepProfile, newSparkSecret, profileOf, sparkBase } from "../../games/spark.ts";
11 import { sparkThreads } from "../../games/spark_profile.ts";
12 import { notFoundPage, pageHead } from "../chrome.ts";
13 import { html } from "../html.ts";
14 import { flashTo, page } from "../layout.ts";
15 import { row, rowList } from "../ui.ts";
11 import { flashTo } from "../layout.ts";
1612 import { readForm } from "../form.ts";
1713 import { boxOf } from "./games.ts";
1814
@@ -61,27 +57,3 @@ export async function gameSparkLink(ctx: Ctx): Promise<Response> {
6157 const base = sparkBase(publicOrigin(ctx.app.config.url, `http://localhost:${String(ctx.app.config.port)}`), newSparkSecret(ctx.app.db, got.box.id));
6258 return flashTo(ctx, `/games/${got.box.name}#spark`, { message: "Set this as spark's bytebin-url on the server. It allows uploads only; this is the only time it is shown, and the last address no longer works.", code: base });
6359 }
64
65 // GET /games/:box/spark/:key: a profile opened on the forge (#18058), decoded here, nothing
66 // fetched elsewhere. A sampler profile lists its threads; any other kind is kept and offered as a
67 // download. A missing and a hidden profile are alike a 404.
68 export function gameSparkView(ctx: Ctx): Response {
69 const got = boxOf(ctx, "viewer");
70 if (got instanceof Response) return got;
71 const key = ctx.params.key ?? "";
72 const profile = profileOf(ctx.app.db, got.box.id, key);
73 if (profile === undefined) return notFoundPage(ctx);
74 const threads = sparkThreads(profile);
75 const taken = profile.type.replace("application/x-spark-", "");
76 return page({
77 ctx,
78 title: `Profile · ${got.box.name}`,
79 body: html`${pageHead(`Profile ${key}`, { sub: `A spark ${taken} profile from ${got.box.name}, taken ${profile.at.slice(0, 16).replace("T", " ")} UTC, ${String(Math.ceil(profile.body.length / 1024))} KiB.` })}
80 <section class="settings-block">
81 <p class="muted small"><a href="/games/${got.box.name}/@spark/${key}" download="${key}.sparkprofile">Download the profile</a> to open it in spark's own viewer.</p>
82 ${threads === undefined
83 ? html`<p class="muted">The forge can list the threads of a sampler profile only, and this one is not a readable one: download it.</p>`
84 : html`<p class="muted small">The threads, busiest first. The call tree and flame graph are not shown here.</p>${rowList(threads.map((t) => row({ title: html`${t.name}`, meta: html`${String(Math.round(t.ms))} ms sampled` })))}`}
85 </section>`,
86 });
87 }
src/web/pages/games_spark_view.ts added +62
@@ -0,0 +1,62 @@
1 /**
2 * One stored spark profile as a page (#18208): per thread, its time sampled, a flame graph (SVG
3 * drawn here from `flameRects`, no script) and the call tree as text. The same tree, in the same
4 * words, is the terminal's (`tui/screens/game_spark_view.ts`).
5 */
6 import type { Ctx } from "../../http/context.ts";
7 import { READ_UNPACKED, decodeSparkProfile, type SparkSummary } from "../../games/spark_profile.ts";
8 import { profileOf } from "../../games/spark.ts";
9 import { FLAME_WIDTH, flameRects, heaviest, millis, sparkHeadLines, treeLines } from "../../games/spark_view.ts";
10 import { notFoundPage, pageHead } from "../chrome.ts";
11 import { html, type Html } from "../html.ts";
12 import { page } from "../layout.ts";
13 import { boxOf } from "./games.ts";
14
15 const SAMPLER = "application/x-spark-sampler";
16 const ROW = 18;
17 /** Roughly the width of one character of the 11-unit label, to cut a name to its box. */
18 const CHAR = 6;
19
20 /**
21 * A thread's flame graph: boxes by time, the name inside when it fits, the whole in the tooltip.
22 */
23 function flameSvg(thread: SparkSummary["threads"][number]): Html {
24 const rects = flameRects(thread.tree, thread.ms);
25 const depth = rects.reduce((m, r) => Math.max(m, r.depth), 0) + 1;
26 return html`<svg viewBox="0 0 ${String(FLAME_WIDTH)} ${String(depth * ROW)}" width="100%" role="img" aria-label="Flame graph of ${thread.name || "the thread"}" focusable="false">
27 ${rects.map((r) => {
28 const fit = Math.floor((r.w - 4) / CHAR);
29 const short = r.name.length <= fit ? r.name : fit > 3 ? `${r.name.slice(0, fit - 1)}…` : "";
30 return html`<g><title>${r.name}: ${millis(r.ms)} (${(r.share * 100).toFixed(1)}% of the thread)</title><rect x="${String(r.x)}" y="${String(r.depth * ROW)}" width="${String(r.w)}" height="${String(ROW - 1)}" fill="currentColor" fill-opacity="${String(Math.max(0.12, 0.4 - r.depth * 0.03))}"/>${short === "" ? null : html`<text x="${String(r.x + 3)}" y="${String(r.depth * ROW + 13)}" font-size="11" fill="currentColor">${short}</text>`}</g>`;
outdated

Principle 6: each box gets its own stroke, which draws a box around every thing. Drop the stroke and let the fill-opacity and width show the shape.

31 })}
32 </svg>`;
33 }
34
35 // GET /games/:box/spark/:key: a stored profile's call tree and flame graph, decoded here, nothing
36 // fetched elsewhere, for a session with a grant on the box. A missing and a hidden profile are
37 // alike a 404.
38 export function gameSparkView(ctx: Ctx): Response {
39 const got = boxOf(ctx, "viewer");
40 if (got instanceof Response) return got;
41 const key = ctx.params.key ?? "";
42 const stored = profileOf(ctx.app.db, got.box.id, key);
43 if (stored === undefined) return notFoundPage(ctx);
44 const read = stored.type === SAMPLER ? decodeSparkProfile(stored.body, READ_UNPACKED) : undefined;
45 const href = `/games/${got.box.name}/@spark/${key}`;
46 const shown = read !== undefined && read.ok ? heaviest(read.summary.threads) : undefined;
47 const body: Html = read === undefined || !read.ok
48 ? html`<p role="alert">The forge draws a sampler profile only, and this one is not a readable one: download it.</p><p><a href="${href}">Download it</a> and open it in spark's own viewer.</p>`
outdated

Principle 1: this paragraph explains units and pruning again after the page head's sub and the aria-label. Say it once, in plain words (principle 8).

49 : html`<p class="muted small">${sparkHeadLines(read.summary)[0]}. Times are milliseconds sampled, shares are of the thread; trees keep the heaviest calls. <a href="${href}">Download the profile</a>.</p>
50 ${read.summary.threads.length === 0 ? html`<p class="muted small">This profile holds no threads.</p>` : null}
outdated

High, denial of service: this maps over all threads (up to 200), each with up to 2,000 nodes drawn as an SVG and again as a <pre>, synchronously on every request. Cap the drawn threads (heaviest first, about 10), say how many were left out and link the download, and test the cap. Apply the same cap in the terminal screen.

51 ${(shown?.drawn ?? []).map((t, i) => html`<section class="settings-block">
52 <h2>${t.name || "(unnamed thread)"} <span class="muted small">${millis(t.ms)} sampled</span></h2>
53 ${t.tree.length === 0 ? html`<p class="muted small">Nothing was sampled in this thread.</p>` : html`${flameSvg(t)}
54 <details ${i === 0 ? html`open` : null}><summary>Call tree</summary><pre>${treeLines(t.tree, t.ms).join("\n")}</pre></details>`}
55 </section>`)}
56 ${shown?.note ? html`<p class="muted small">${shown.note} <a href="${href}">Download it</a>.</p>` : null}`;
57 return page({
58 ctx,
59 title: `Games · ${got.box.name} · profile`,
60 body: html`${pageHead("Spark profile", { sub: `${got.box.name} · ${key}` })}${body}`,
61 });
62 }
test/game-spark.test.ts +1 −1
@@ -109,7 +109,7 @@ describe("spark profiles in a game box", () => {
109109 expect(body).toContain("Server thread");
110110 expect(body).toContain("&lt;img src=x");
111111 expect(body).not.toContain("<img src=x");
112 expect(body).toContain("The call tree and flame graph are not shown here");
112 expect(body).toContain("Nothing was sampled in this thread");
113113 expect((await http.handle(new Request(`${ORIGIN}/games/net/spark/${key}`, { headers: cookie("carol") }))).status).toBe(404);
114114 const out = await http.handle(new Request(`${ORIGIN}/games/net/spark/${key}`));
115115 expect(out.status).toBe(303);
test/games-spark-view.test.ts added +116
@@ -0,0 +1,116 @@
1 /**
2 * The call tree and flame graph of a stored spark profile (#18208): the layout checked by hand,
3 * the page drawing it for a grant (and escaping a hostile name), the terminal showing the same
4 * tree lines.
5 */
6 import { afterAll, beforeAll, 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 { gzipSync } from "node:zlib";
11 import { createApp, type App } from "../src/app.ts";
12 import { createSession } from "../src/core/sessions.ts";
13 import { createUser, getUserByName } from "../src/core/users.ts";
14 import { keepProfile } from "../src/games/spark.ts";
15 import { decodeSparkProfile, type TreeNode } from "../src/games/spark_profile.ts";
16 import { FLAME_WIDTH, flameRects, treeLines } from "../src/games/spark_view.ts";
17 import { boxNamed, createGameBox, grant } from "../src/games/store.ts";
18 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
19 import { quietLogs } from "./helpers/globals.ts";
20
21 quietLogs();
22
23 const varint = (n: number): number[] => { const o: number[] = []; while (n > 127) { o.push((n % 128) | 128); n = Math.floor(n / 128); } o.push(n); return o; };
24 const key = (n: number, t: number) => varint(n * 8 + t);
25 const bytes = (n: number, b: number[]) => [...key(n, 2), ...varint(b.length), ...b];
26 const text = (n: number, s: string) => bytes(n, [...new TextEncoder().encode(s)]);
27 const dbl = (v: number) => [...new Uint8Array(new Float64Array([v]).buffer)];
28 // A data version 1 node: time (1), nested children (2).
29 const node = (cls: string, method: string, ms: number, kids: number[][] = []) => [...text(3, cls), ...text(4, method), ...key(1, 1), ...dbl(ms), ...kids.flatMap((k) => bytes(2, k))];
30 const profile = (rootName: string): Uint8Array => {
31 const tree = node("a.Server", rootName, 100, [node("a.Level", "tickEntities", 60, [node("a.Algo", "run", 40)]), node("a.Task", "step", 25)]);
32 return gzipSync(Uint8Array.from([...bytes(2, [...text(1, "Server thread"), ...key(2, 1), ...dbl(100), ...bytes(3, tree)])]));
33 };
34
35 const t = (name: string, ms: number, children: TreeNode[] = []): TreeNode => ({ name, ms, children });
36
37 test("flame boxes are as wide as their share of the thread, children under their parent's left edge", () => {
38 const rects = flameRects([t("root", 100, [t("a", 60, [t("a1", 40)]), t("b", 25)])], 100);
39 expect(rects.map((r) => [r.name, r.x, r.w, r.depth])).toEqual([
40 ["root", 0, FLAME_WIDTH, 0], ["a", 0, 600, 1], ["a1", 0, 400, 2], ["b", 600, 250, 1],
41 ]);
42 // A child past its parent is clipped, a sliver is dropped, a zero total draws nothing.
43 expect(flameRects([t("p", 50, [t("big", 80)])], 100).map((r) => r.w)).toEqual([500, 500]);
44 expect(flameRects([t("p", 100, [t("tiny", 0.1)])], 100).length).toBe(1);
45 expect(flameRects([t("p", 5)], 0)).toEqual([]);
46 });
47
48 test("the tree as lines, with shares of the thread", () => {
49 expect(treeLines([t("root", 100, [t("a", 60)])], 100)).toEqual(["100.0% 100.0 ms root", " 60.0% 60.0 ms a"]);
50 });
51
52 let dir: string;
53 let app: App;
54 let http: ForgeHttp;
55 let tree: string;
56 let evil: string;
57 const cookie = (name: string) => ({ cookie: `forge_session=${createSession(app.db, getUserByName(app.db, name)!.id).token}` });
58 const get = (path: string, who: string) => http.handle(new Request(`http://forge.test${path}`, { headers: cookie(who) }));
59
60 beforeAll(async () => {
61 dir = await mkdtemp(join(tmpdir(), "forge-spark-view-"));
62 app = createApp({ dataDir: dir, port: 0 });
63 http = forgeHttp(app);
64 for (const [username, adminIfFirst] of [["alice", true], ["bob", false], ["carol", false]] as const) {
65 const made = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@f.test`, password: "a-good-passphrase", adminIfFirst });
66 if (!made.ok) throw new Error(made.error);
67 }
68 createGameBox(app.db, { name: "net", repo: "alice/mc-network", path: "net/docker-compose.yml" });
69 const box = boxNamed(app.db, "net")!;
70 grant(app.db, box.id, getUserByName(app.db, "bob")!.id, "viewer");
71 const keep = (b: Uint8Array) => { const k = keepProfile(app.db, box.id, "application/x-spark-sampler", b); if (!k.ok) throw new Error(k.error); return k.value; };
72 tree = keep(profile("tick"));
73 evil = keep(profile("<script>alert(1)</script>"));
74 });
75 afterAll(async () => { await rm(dir, { recursive: true, force: true }); });
76
77 test("the page draws the thread's flame graph and call tree for a grant, and escapes names", async () => {
78 const r = await get(`/games/net/spark/${tree}`, "bob");
79 expect(r.status).toBe(200);
80 const body = await r.text();
81 expect(body).toContain("<svg");
82 expect(body).toContain("Server thread");
83 expect(body).toContain("100.0 ms sampled");
84 expect(body).toContain("60.0% 60.0 ms a.Level.tickEntities");
85 expect(body).toContain(`width="600"`);
86 const bad = await (await get(`/games/net/spark/${evil}`, "bob")).text();
87 expect(bad).not.toContain("<script>alert(1)");
88 expect(bad).toContain("&lt;script&gt;");
89 });
90
91 test("no grant, or another box's key, is a 404; a body that is not a profile is said plainly", async () => {
92 expect((await get(`/games/net/spark/${tree}`, "carol")).status).toBe(404);
93 expect((await get(`/games/net/spark/nothingnothing00`, "bob")).status).toBe(404);
94 const box = boxNamed(app.db, "net")!;
95 const k = keepProfile(app.db, box.id, "application/x-spark-sampler", new Uint8Array(Bun.gzipSync(new Uint8Array([1, 2, 3]))));
96 if (!k.ok) throw new Error(k.error);
97 const r = await get(`/games/net/spark/${k.value}`, "bob");
98 expect(r.status).toBe(200);
99 expect(await r.text()).toContain("is not a readable one");
100 expect(decodeSparkProfile(profile("tick")).ok).toBe(true);
101 });
102
103 test("only the heaviest threads are drawn, and the rest are counted, on both doors (#18208)", async () => {
104 const thread = (name: string, ms: number) => bytes(2, [...text(1, name), ...key(2, 1), ...dbl(ms), ...bytes(3, node("a.C", "m", ms))]);
105 const many = gzipSync(Uint8Array.from(Array.from({ length: 13 }, (_, i) => thread(`T${String(i)}`, i + 1)).flat()));
106 const box = boxNamed(app.db, "net")!;
107 const k = keepProfile(app.db, box.id, "application/x-spark-sampler", many);
108 if (!k.ok) throw new Error(k.error);
109 const body = await (await get(`/games/net/spark/${k.value}`, "bob")).text();
110 expect((body.match(/aria-label="Flame graph of/g) ?? []).length).toBe(10);
111 expect(body).toContain("3 more threads not drawn, download the profile.");
112 expect(body).toContain("T12");
113 expect(body).not.toContain("T0<");
114 const { heaviest } = await import("../src/games/spark_view.ts");
115 expect(heaviest([{ ms: 1 }, { ms: 5 }]).note).toBe("");
116 });
test/tui-games.test.ts +26 −1
@@ -390,7 +390,7 @@ test("enter on a stored sampler profile lists its threads, for a viewer (#18058)
390390 await settleApp(viewer.tui);
391391 await viewer.type("\r");
392392 await settleUntil(viewer.tui, "Zeta thread");
393 expect(viewer.tui.screen.toText()).toContain("The call tree and flame graph are not shown here");
393 expect(viewer.tui.screen.toText()).toContain("Nothing was sampled in this thread");
394394 } finally {
395395 viewer.tui.stop?.();
396396 }
@@ -435,6 +435,31 @@ test("the terminal's box screen lists stored spark profiles and u makes the uplo
435435 }
436436 });
437437
438 test("Enter on a stored spark profile opens its call tree in the terminal, as the page shows it (#18208)", async () => {
439 const box = boxNamed(app.db, "net")!;
440 const text = (n: number, s: string) => [n * 8 + 2, s.length, ...new TextEncoder().encode(s)];
441 const dbl = (x: number) => [...new Uint8Array(new Float64Array([x]).buffer)];
442 const node = (m: string, ms: number) => [...text(4, m), 9, ...dbl(ms)];
443 const tree = node("tick", 100);
444 const thread = [...text(1, "Main thread"), 2 * 8 + 1, ...dbl(100), 3 * 8 + 2, tree.length, ...tree];
445 const body = new Uint8Array(Bun.gzipSync(new Uint8Array([2 * 8 + 2, thread.length, ...thread])));
446 app.db.query("DELETE FROM game_spark_profile WHERE box_id = ?").run(box.id);
447 const kept = keepProfile(app.db, box.id, "application/x-spark-sampler", body);
448 if (!kept.ok) throw new Error(kept.error);
449 const owner = drive(alice, 200);
450 try {
451 owner.tui.ctx.push(gameBoxScreen(owner.session, owner.tui.ctx, box));
452 await settleApp(owner.tui);
453 await owner.type("p");
454 await settleApp(owner.tui);
455 await owner.type("\r");
456 await settleUntil(owner.tui, "Main thread");
457 expect(owner.tui.screen.toText()).toContain("100.0% 100.0 ms tick");
458 } finally {
459 owner.tui.stop?.();
460 }
461 });
462
438463 test("the Games list says tick time after TPS when a Fabric exporter gave it, and no tick segment when it did not", async () => {
439464 const box = boxNamed(app.db, "net")!;
440465 const line = async () => {

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs