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

A pull's Files page names its Server-Timing phases and answers under 100 ms for a 40-file diff #3418

Parked opened this
Closed without merging

scout/forge:scout/3359-a-pull-s-files-page-names-its-server-tim → main 2 commits fork 2 threads · 2 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
6 files changed +260 −105
src/web/code.ts +77 −39
@@ -20,30 +20,71 @@ import {
2020 type Token,
2121 } from "./highlight.ts";
2222 import { highlightToLines, tokenClasses } from "./highlight-html.ts";
23 import { html, raw, type Html } from "./html.ts";
23 import { escapeHtml, html, raw, type Html } from "./html.ts";
2424
25 /** Per-character class attributes for one line, or null where none apply. */
26 function classMask(
27 text: string,
28 tokens: Token[] | undefined,
29 ): (string | null)[] {
30 const mask: (string | null)[] = new Array(text.length).fill(null);
31 if (!tokens) return mask;
25 /** A stretch of one line that shares a class attribute and a changed flag. */
26 interface Run {
27 end: number;
28 cls: string | null;
29 }
30
31 /**
32 * Rendered runs by class, then text. Code repeats itself — `const`, ` `, `=`,
33 * `(` — so most runs are one lookup instead of an escape and two concats.
34 * Bounded: past `MEMO_RUNS` the table starts over.
35 */
36 const MEMO_RUNS = 20_000;
37 const memo = new Map<string, Map<string, string>>();
38 let memoSize = 0;
39
40 function runHtml(cls: string | null, slice: string): string {
41 const key = cls ?? "";
42 let byText = memo.get(key);
43 if (byText === undefined) memo.set(key, (byText = new Map()));
44 const hit = byText.get(slice);
45 if (hit !== undefined) return hit;
46 const text = escapeHtml(slice);
47 const made = cls === null ? text : `<span class="${escapeHtml(cls)}">${text}</span>`;
48 if (memoSize >= MEMO_RUNS) {
49 memo.clear();
50 memoSize = 0;
51 memo.set(key, (byText = new Map()));
52 }
53 byText.set(slice, made);
54 memoSize++;
55 return made;
56 }
57
58 /**
59 * The line's class attributes as runs: adjacent tokens with the same classes
60 * merge, and whatever the tokens did not cover stays unclassified.
61 */
62 function classRuns(length: number, tokens: Token[] | undefined): Run[] {
63 const runs: Run[] = [];
3264 let pos = 0;
33 for (const token of tokens) {
65 const push = (end: number, cls: string | null) => {
66 const last = runs[runs.length - 1];
67 if (last && last.cls === cls) last.end = end;
68 else runs.push({ end, cls });
69 };
70 for (const token of tokens ?? []) {
71 if (pos >= length) break;
3472 const classes = tokenClasses(token);
35 const value = classes === "" ? null : classes;
36 for (let k = 0; k < token.text.length && pos < text.length; k++)
37 mask[pos++] = value;
73 const end = Math.min(length, pos + token.text.length);
74 if (end > pos) push(end, classes === "" ? null : classes);
75 pos = end;
3876 }
3977 // If the token stream didn't cover the line (source mismatch), the tail
4078 // simply stays unclassified — still correct, just uncolored.
41 return mask;
79 if (pos < length) push(length, null);
80 return runs;
4281 }
4382
4483 /**
4584 * Compose a line into spans. `tokens` colors it; `changed` (per character)
46 * marks the diff highlight. Either may be omitted.
85 * marks the diff highlight. Either may be omitted. One span per run of
86 * (class, changed), cut at the boundaries of both segmentations; the work is
87 * per run, not per character.
4788 */
4889 export function composeLine(
4990 text: string,
@@ -51,34 +92,31 @@ export function composeLine(
5192 changed: boolean[] | undefined,
5293 ): Html {
5394 if (text === "") return html``;
54 const classes = classMask(text, tokens);
55 const parts: Html[] = [];
56
57 let runStart = 0;
58 const flush = (end: number) => {
59 if (end <= runStart) return;
60 const slice = text.slice(runStart, end);
61 const cls = classes[runStart];
62 const isChanged = changed?.[runStart] ?? false;
63 if ((cls === null || cls === undefined) && !isChanged) {
64 parts.push(html`${slice}`);
65 } else {
66 const names = [cls ?? "", isChanged ? "wd" : ""]
67 .filter(Boolean)
68 .join(" ");
69 parts.push(html`<span class="${names}">${slice}</span>`);
70 }
71 runStart = end;
95 const runs = classRuns(text.length, tokens);
96 const marked = changed?.some(Boolean) === true;
97 let out = "";
98 const emit = (from: number, to: number, cls: string | null, wd: boolean) => {
99 const slice = text.slice(from, to);
100 out += runHtml(wd ? (cls === null ? "wd" : `${cls} wd`) : cls, slice);
72101 };
73102
74 for (let i = 1; i < text.length; i++) {
75 const sameClass = classes[i] === classes[runStart];
76 const sameChanged =
77 (changed?.[i] ?? false) === (changed?.[runStart] ?? false);
78 if (!sameClass || !sameChanged) flush(i);
103 let from = 0;
104 for (const run of runs) {
105 if (!marked) {
106 emit(from, run.end, run.cls, false);
107 from = run.end;
108 continue;
109 }
110 // Cut the class run wherever the changed flag flips.
111 while (from < run.end) {
112 const flag = changed![from] === true;
113 let end = from + 1;
114 while (end < run.end && (changed![end] === true) === flag) end++;
115 emit(from, end, run.cls, flag);
116 from = end;
117 }
79118 }
80 flush(text.length);
81 return html`${parts}`;
119 return raw(out);
82120 }
83121
84122 /** Highlight a whole blob into per-line Html, for the file browser. */
src/web/diff-syntax.ts +78 −26
@@ -3,11 +3,15 @@
33 * and new blobs (not the diff fragments — highlighting whole files is what
44 * keeps multi-line strings and comments correct across hunk boundaries) and
55 * key the tokens by path. The diff viewer then maps tokens onto rows by line
6 * number. Blobs are immutable by oid, so this is safe to cache upstream.
6 * number. Blobs are immutable by oid, so the tokens of a file at a commit are
7 * kept (`tokensCache`): a second look at the same head, by anyone, highlights
8 * nothing. Files are read together, so one file is highlighted while the
9 * next is on its way from git.
710 */
811
9 import type { Diff } from "../git/diff.ts";
12 import type { Diff, FileDiff } from "../git/diff.ts";
1013 import { blobForRender } from "../git/read.ts";
14 import type { Token } from "./highlight.ts";
1115 import { detectLanguage, highlightLines } from "./highlight.ts";
1216 import {
1317 MAX_DIFF_FILES,
@@ -17,6 +21,70 @@ import {
1721 } from "./diff-view.ts";
1822
1923 const CAP_BYTES = 1_000_000;
24 /** How many lines of tokens are kept; the oldest file goes first. */
25 const KEEP_LINES = 60_000;
26 const FULL_OID = /^[0-9a-f]{40}([0-9a-f]{24})?$/;
27
28 const tokensCache = new Map<string, Token[][] | null>();
29 let keptLines = 0;
30
31 /** Forget everything kept; for tests. */
32 export function clearSyntaxCache(): void {
33 tokensCache.clear();
34 keptLines = 0;
35 }
36
37 function keep(key: string, lines: Token[][] | null): void {
38 const weight = lines?.length ?? 0;
39 if (weight > KEEP_LINES) return;
40 tokensCache.set(key, lines);
41 keptLines += weight;
42 for (const [oldest, value] of tokensCache) {
43 if (keptLines <= KEEP_LINES) break;
44 tokensCache.delete(oldest);
45 keptLines -= value?.length ?? 0;
46 }
47 }
48
49 /** The tokens of `path` at `rev`, or undefined when it is not shown as text. */
50 async function tokensAt(
51 dir: string,
52 rev: string,
53 path: string,
54 ): Promise<Token[][] | undefined> {
55 const key = `${rev}\0${path}`;
56 const cacheable = FULL_OID.test(rev);
57 if (cacheable && tokensCache.has(key)) {
58 const hit = tokensCache.get(key)!;
59 // Refresh its place: the most recently read file goes last.
60 tokensCache.delete(key);
61 tokensCache.set(key, hit);
62 return hit ?? undefined;
63 }
64 const blob = await blobForRender(dir, rev, path, CAP_BYTES);
65 const lines =
66 blob.kind === "text"
67 ? highlightLines(new TextDecoder().decode(blob.body), detectLanguage(path))
68 : null;
69 if (cacheable) keep(key, lines);
70 return lines ?? undefined;
71 }
72
73 async function tokensOf(
74 dir: string,
75 file: FileDiff,
76 oldRev: string,
77 newRev: string,
78 ): Promise<FileTokens> {
79 const [old, now] = await Promise.all([
80 file.oldPath ? tokensAt(dir, oldRev, file.oldPath) : undefined,
81 file.newPath ? tokensAt(dir, newRev, file.newPath) : undefined,
82 ]);
83 const entry: FileTokens = {};
84 if (old) entry.old = old;
85 if (now) entry.new = now;
86 return entry;
87 }
2088
2189 export async function diffSyntax(
2290 dir: string,
@@ -24,32 +92,16 @@ export async function diffSyntax(
2492 oldRev: string,
2593 newRev: string,
2694 ): Promise<SyntaxMap> {
27 const map: SyntaxMap = new Map();
2895 // Only the files the viewer will actually render as a table are worth
2996 // highlighting — a stubbed file shows no hunks, so tokenising it would
3097 // burn the same cost the stub exists to avoid.
31 for (const file of diff.files.slice(0, MAX_DIFF_FILES)) {
32 if (file.binary || stubFor(file) !== null) continue;
33 const entry: FileTokens = {};
34 if (file.oldPath) {
35 const blob = await blobForRender(dir, oldRev, file.oldPath, CAP_BYTES);
36 if (blob.kind === "text") {
37 entry.old = highlightLines(
38 new TextDecoder().decode(blob.body),
39 detectLanguage(file.oldPath),
40 );
41 }
42 }
43 if (file.newPath) {
44 const blob = await blobForRender(dir, newRev, file.newPath, CAP_BYTES);
45 if (blob.kind === "text") {
46 entry.new = highlightLines(
47 new TextDecoder().decode(blob.body),
48 detectLanguage(file.newPath),
49 );
50 }
51 }
52 map.set(file.path, entry);
53 }
98 const shown = diff.files
99 .slice(0, MAX_DIFF_FILES)
100 .filter((file) => !file.binary && stubFor(file) === null);
101 const entries = await Promise.all(
102 shown.map((file) => tokensOf(dir, file, oldRev, newRev)),
103 );
104 const map: SyntaxMap = new Map();
105 shown.forEach((file, i) => map.set(file.path, entries[i]!));
54106 return map;
55107 }
src/web/diff-view.ts +24 −20
@@ -76,6 +76,8 @@ export interface DiffViewOptions {
7676 /** Per-file render context, resolved once per file. */
7777 interface RowCtx {
7878 path: string;
79 /** `path`, encoded for a query string. */
80 pathQuery: string;
7981 tokens: FileTokens;
8082 opts: DiffViewOptions;
8183 }
@@ -253,13 +255,14 @@ function renderRow(row: Row, ctx: RowCtx): Html {
253255 const side: Side = row.kind === "del" ? "old" : "new";
254256 const lineNo = side === "old" ? row.oldNumber : row.newNumber;
255257
256 const gutter = (n: number | null, isAnchorSide: boolean) => {
257 if (n === null) return html`<td class="dn"></td>`;
258 if (!opts.reviewBase || !isAnchorSide)
259 return html`<td class="dn">${n}</td>`;
260 const href = `${opts.reviewPage ?? opts.reviewBase}?rc=${encodeURIComponent(path)}~${side}~${n}#rc`;
261 return html`<td class="dn">
262 <a class="dn-comment" href="${href}" title="Comment on this line">${n}</a>
258 // One row is thousands of rows on a big change: plain strings, with every
259 // dynamic piece escaped, and the path's encoding done once per file.
260 const gutter = (n: number | null, isAnchorSide: boolean): string => {
261 if (n === null) return `<td class="dn"></td>`;
262 if (!opts.reviewBase || !isAnchorSide) return `<td class="dn">${n}</td>`;
263 const href = `${opts.reviewPage ?? opts.reviewBase}?rc=${ctx.pathQuery}~${side}~${n}#rc`;
264 return `<td class="dn">
265 <a class="dn-comment" href="${escapeHtml(href)}" title="Comment on this line">${n}</a>
263266 </td>`;
264267 };
265268
@@ -267,23 +270,23 @@ function renderRow(row: Row, ctx: RowCtx): Html {
267270 // in one value, and interpolated whole. A pretty-printed newline between
268271 // `<td>` and its span would render as a literal blank line and an indent —
269272 // which is exactly how this viewer once lost its density.
270 const cell = html`<span class="dcx"
271 >${composeLine(row.text, tokenLine, row.changed)}</span
272 >${when(
273 row.noNewline,
274 () => html`<span class="nonl" title="No newline at end of file">↵</span>`,
275 )}`;
276 const rowHtml = html`<tr class="dl" data-k="${row.kind}">
277 ${gutter(row.oldNumber, side === "old")}${gutter(
278 row.newNumber,
279 side === "new",
280 )}
273 const cell = `<span class="dcx"
274 >${composeLine(row.text, tokenLine, row.changed).text}</span
275 >${
276 row.noNewline
277 ? `<span class="nonl" title="No newline at end of file">↵</span>`
278 : ""
279 }`;
280 const rowHtml = raw(`<tr class="dl" data-k="${escapeHtml(row.kind)}">
281 ${gutter(row.oldNumber, side === "old")}${gutter(row.newNumber, side === "new")}
281282 <td class="dc" data-mark="${mark}">${cell}</td>
282 </tr>`;
283 </tr>`);
283284
284285 // Existing comments and a form, if any, ride under the row.
285286 const extras =
286 lineNo === null ? html`` : reviewRows(path, side, lineNo, row.text, ctx);
287 lineNo === null || (!opts.comments?.size && !opts.active)
288 ? html``
289 : reviewRows(path, side, lineNo, row.text, ctx);
287290 return html`${rowHtml}${extras}`;
288291 }
289292
@@ -520,6 +523,7 @@ function fileView(file: FileDiff, opts: DiffViewOptions): Html {
520523 // an active comment or existing comments is forced open so it's visible.
521524 const ctx: RowCtx = {
522525 path: file.path,
526 pathQuery: encodeURIComponent(file.path),
523527 tokens: opts.syntax?.get(file.path) ?? {},
524528 opts,
525529 };
src/web/html.ts +2 −5
@@ -42,11 +42,8 @@ function render(value: Value): string {
4242 }
4343
4444 export function html(strings: TemplateStringsArray, ...values: Value[]): Html {
45 let out = "";
46 for (const [i, chunk] of strings.entries()) {
47 out += chunk;
48 if (i < values.length) out += render(values[i]);
49 }
45 let out = strings[0]!;
46 for (let i = 0; i < values.length; i++) out += render(values[i]!) + strings[i + 1]!;
5047 return new Html(out);
5148 }
5249
src/web/pages/pull.ts +40 −14
@@ -64,6 +64,7 @@ import {
6464 repoPalette,
6565 signInFirst,
6666 } from "../chrome.ts";
67 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
6768 import { diffSyntax } from "../diff-syntax.ts";
6869 import {
6970 renderDiff,
@@ -798,6 +799,18 @@ export async function pullFilesPage(ctx: Ctx): Promise<Response> {
798799 const found = pullContext(ctx);
799800 if (found instanceof Response) return found;
800801 const { repo, pull } = found;
802 const began = performance.now();
803 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
804 const spent = { diff: 0, checks: 0, reviews: 0 };
805 /** Run `work`, adding the time it took to `spent[key]`. */
806 const lap = async <T>(key: keyof typeof spent, work: () => T | Promise<T>): Promise<T> => {
807 const started = performance.now();
808 try {
809 return await work();
810 } finally {
811 spent[key] += performance.now() - started;
812 }
813 };
801814 // Every read of the change is taken where its objects are (`pullDir`).
802815 const dir = await pullDir(ctx.app.db, ctx.app.reposRoot, repo, pull);
803816 const base = repoBase(repo);
@@ -805,32 +818,35 @@ export async function pullFilesPage(ctx: Ctx): Promise<Response> {
805818
806819 // The review gate travels with the status, so the merge box and
807820 // `mergePull` are answering the same question from the same numbers.
808 const { status, from, diff } = await pullDiff(dir, pull, {
809 db: ctx.app.db,
810 requireReview: repo.requireReview,
811 });
812 const syntax = await diffSyntax(dir, diff, from, status.headOid);
821 const { status, from, diff } = await lap("diff", () =>
822 pullDiff(dir, pull, {
823 db: ctx.app.db,
824 requireReview: repo.requireReview,
825 }),
826 );
827 const syntax = await lap("diff", () => diffSyntax(dir, diff, from, status.headOid));
813828 // A merged or closed pull is history; the wall is a question about landing.
814829 const wall =
815830 pull.mergedAt === null && pull.state === "open"
816 ? await wallOf(dir, status.baseOid, status.headOid)
831 ? await lap("diff", () => wallOf(dir, status.baseOid, status.headOid))
817832 : undefined;
818 const reviewLines = listReviewComments(ctx.app.db, pull.id);
833 const reviewLines = await lap("reviews", () => listReviewComments(ctx.app.db, pull.id));
819834 const reviewComments = byAnchor(reviewLines);
820835 const mayMerge = canWrite(ctx.app.db, repo, ctx.auth.user);
821836 const applied = labelsFor(ctx.app.db, pull.id);
822837 const allLabels = listLabels(ctx.app.db, repo.id);
823 const by = standings(ctx.app.db, pull, status.headOid);
838 const by = await lap("reviews", () => standings(ctx.app.db, pull, status.headOid));
824839 // The checks are the deploy runs of the live head, read here for the same
825840 // reason the review gate is: the box and the merge answer one question.
826 const check = checkSummary(ctx.app.db, pull.id, status.headOid);
841 const check = await lap("checks", () => checkSummary(ctx.app.db, pull.id, status.headOid));
827842 const isApp = getAppByRepo(ctx.app.db, repo.id) !== undefined;
828 const tier = await tierOf(dir, status.headOid, check);
829 const stale =
843 const tier = await lap("checks", () => tierOf(dir, status.headOid, check));
844 const stale = await lap("checks", async () =>
830845 pull.state === "open" && pull.mergedAt === null
831846 ? checkStale(check.run, await resolveOid(dir, `refs/heads/${pull.baseBranch}`))
832 : false;
833 const threads = pullThreads(ctx.app, pull);
847 : false,
848 );
849 const threads = await lap("reviews", () => pullThreads(ctx.app, pull));
834850 const threadViews = threadStateViews(ctx, repo, threads);
835851 const unresolved = threads.filter((t) => t.resolvedAt === null).length;
836852
@@ -936,7 +952,7 @@ export async function pullFilesPage(ctx: Ctx): Promise<Response> {
936952 <div class="mt">${renderDiff(diff, diffOptions)}</div>
937953 ${liveMount({ repo: base })}`;
938954
939 return page({
955 const response = page({
940956 ctx,
941957 title: `Files · ${pull.title} · ${repo.name}`,
942958 crumbs: crumbsFor(repo),
@@ -945,6 +961,16 @@ export async function pullFilesPage(ctx: Ctx): Promise<Response> {
945961 styleCss: labelCss([...allLabels, ...applied]),
946962 scriptJs: `${liveClientJs}\n${liveRegionsJs}`,
947963 });
964 const { diff: diffMs, checks, reviews } = spent;
965 notePhase(ctx.request, "diff", diffMs);
966 notePhase(ctx.request, "checks", checks);
967 notePhase(ctx.request, "reviews", reviews);
968 notePhase(
969 ctx.request,
970 "render",
971 Math.max(0, performance.now() - began - diffMs - checks - reviews),
972 );
973 return response;
948974 }
949975
950976 // GET /:owner/:name/pulls/:number/thread?after=<id>
test/pull-timing.test.ts +39 −1
@@ -1,4 +1,4 @@
1 /** `/:owner/:name/pulls/:n`'s Server-Timing names its phases (#3192). */
1 /** `/:owner/:name/pulls/:n`'s Server-Timing names its phases (#3192), and its Files page's (#3359). */
22 import { afterAll, beforeAll, expect, test } from "bun:test";
33 import { mkdtemp, rm } from "node:fs/promises";
44 import { tmpdir } from "node:os";
@@ -19,6 +19,7 @@ let app: App;
1919 let servers: Servers;
2020 let cookie = "";
2121 let number = 0;
22 let bigNumber = 0;
2223 const cells = process.env["FORGE_CELLS"];
2324
2425 beforeAll(async () => {
@@ -55,6 +56,27 @@ beforeAll(async () => {
5556 });
5657 if (!pull.ok) throw new Error(JSON.stringify(pull.error));
5758 number = pull.value.number;
59 // A 40-file, 2,000-line change, for the Files page.
60 const big = await commitToBranch(app, alice, repo.value, {
61 branch: "big",
62 message: "big",
63 files: Array.from({ length: 40 }, (_, f) => ({
64 path: `src/m${f}.ts`,
65 content: Array.from(
66 { length: 50 },
67 (_, i) => `export const v${f}_${i} = "<b>${i}</b>" + (${i} < 3 ? 'x' : \`y\${${i}}\`); // note & ${f}`,
68 ).join("\n") + "\n",
69 })),
70 });
71 if (!big.ok) throw new Error(JSON.stringify(big.error));
72 const bigPull = await openPull(app, alice, repo.value, {
73 title: "big",
74 body: "",
75 baseBranch: "main",
76 headBranch: "big",
77 });
78 if (!bigPull.ok) throw new Error(JSON.stringify(bigPull.error));
79 bigNumber = bigPull.value.number;
5880 createRun(app.db, {
5981 repoId: repo.value.id,
6082 kind: "check",
@@ -87,3 +109,19 @@ test("a pull names session, diff, checks, reviews and render after app, summing
87109 expect(ms("diff")).toBeGreaterThan(0);
88110 expect(ms("checks")).toBeGreaterThan(0);
89111 });
112
113 test("a pull's Files page names its phases and answers a cold 40-file diff well inside a generous bound", async () => {
114 const url = `${servers.url}/alice/r/pulls/${bigNumber}/files`;
115 // The first view of a head is cold: no warm-up, so this is what people meet first.
outdated

The warm-up request is what makes the budget pass. Real first views of a head are cold, so the test does not cover what people meet first.

116 const res = await fetch(url, { headers: { cookie } });
117 expect(res.status).toBe(200);
118 const html = await res.text();
119 expect(html).toContain("m39.ts");
120 expect(html).not.toContain("<b>1</b>");
121 const parts = (res.headers.get("server-timing") ?? "").split(", ");
122 const names = parts.map((p) => p.split(";")[0]!);
123 expect(names.slice(names.indexOf("app") + 1)).toEqual(["session", "diff", "checks", "reviews", "render"]);
124 const ms = (n: string) => Number(parts[names.indexOf(n)]!.match(/dur=([\d.]+)/)![1]);
125 // A generous bound, not the budget: wall clocks flake on a loaded machine. The phase names are the contract.
outdated

A hard 100 ms wall-clock assert is machine-dependent and will flake under load. Loosen it (e.g. 250 ms) and keep the phase-name assertion as the contract.

126 expect(ms("app")).toBeLessThan(250);
127 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs