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

A person's page answers under 50 ms and its Server-Timing names its phases: session, each read, render #5669

Parked opened this
Closed without merging

scout/forge:scout/3309-a-person-s-page-answers-under-50-ms-and → main 6 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
3 files changed +111 −16
src/core/repos.ts +18
@@ -762,6 +762,24 @@ export function listReposByOwner(
762762 return withCounts(db, rows);
763763 }
764764
765 /** How many public repos one owner has, up to `cap`: one count, no rows built. */
766 export function countPublicReposByOwner(
767 db: Database,
768 ownerName: string,
769 cap: number,
770 ): number {
771 return (
772 db
773 .query<{ n: number }, [string, string, number]>(
774 `SELECT COUNT(*) AS n FROM (
775 SELECT repo.id FROM repo JOIN user ON user.id = repo.owner_id
776 WHERE user.username = ?2 COLLATE NOCASE AND ${PUBLIC_VISIBLE}
777 LIMIT ?3)`,
778 )
779 .get("", ownerName, cap)?.n ?? 0
780 );
781 }
782
765783 /**
766784 * Delete a repo. Row first, then disk — inverse of creation, same invariant.
767785 * Before removing the objects, detach every fork that borrows them (repack so
src/web/pages/org.ts +22 −16
@@ -28,12 +28,12 @@ import {
2828 type Permission,
2929 type Team,
3030 } from "../../core/orgs.ts";
31 import { notePhase, takeSessionTime, timePhase, timePhaseAsync } from "../../core/route_timing.ts";
3132 import { appsForRepos } from "../../core/apps.ts";
3233 import { LIST_LIMIT_MAX } from "../../core/issues.ts";
33 import { listReposByOwner, type Repo } from "../../core/repos.ts";
34 import { countPublicReposByOwner, listReposByOwner, type Repo } from "../../core/repos.ts";
3435 import { getUserByName, hiddenFrom, type User } from "../../core/users.ts";
3536 import type { Ctx } from "../../http/context.ts";
36 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
3737 import { notFoundPage, pageHead, signInFirst } from "../chrome.ts";
3838 import { field, readForm, type Form } from "../form.ts";
3939 import { html, when, type Html } from "../html.ts";
@@ -181,12 +181,11 @@ async function appsSection(
181181 owner: User,
182182 isSelf: boolean,
183183 ): Promise<{ html: Html; count: number }> {
184 const repos = listReposByOwner(ctx.app.db, owner.username, ctx.auth.user, {
185 limit: 200,
186 });
187 const records = appsForRepos(
188 ctx.app.db,
189 repos.map((r) => r.id),
184 const repos = timePhase(ctx.request, "repos", () =>
185 listReposByOwner(ctx.app.db, owner.username, ctx.auth.user, { limit: 200 }),
186 );
187 const records = timePhase(ctx.request, "records", () =>
188 appsForRepos(ctx.app.db, repos.map((r) => r.id)),
190189 );
191190 const appRepos = repos.filter((r) => records.has(r.id));
192191 const newAppHref = `/apps/new?owner=${owner.username}`;
@@ -204,7 +203,7 @@ async function appsSection(
204203 ),
205204 };
206205
207 const rows = await shelfRows(ctx, appRepos);
206 const rows = await timePhaseAsync(ctx.request, "apps", () => shelfRows(ctx, appRepos));
208207 return { count: appRepos.length, html: listCard(rows, {
209208 head: html`${icon("rocket")}
210209 <h2>Apps</h2>
@@ -311,7 +310,15 @@ export async function ownerProfile(ctx: Ctx): Promise<Response> {
311310 const canManage = isOrg && accessAllows(access, "admin");
312311 const isSelf =
313312 ctx.auth.user !== undefined && (ctx.auth.user.id === owner.id || canManage);
313 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
314314 const apps = await appsSection(ctx, owner, isSelf);
315 const list = timePhase(ctx.request, "list", () =>
316 repoSection(ctx, owner, isSelf, apps.count > 0),
317 );
318 const listed = timePhase(ctx.request, "count", () =>
319 countPublicReposByOwner(ctx.app.db, owner.username, LIST_LIMIT_MAX),
320 );
321 const rendering = performance.now();
315322 // Said to the people it concerns: its members and the forge's owner.
316323 const ownerless =
317324 isOrg && access !== "none" && personOwners(ctx.app.db, owner.id).length === 0;
@@ -346,7 +353,7 @@ export async function ownerProfile(ctx: Ctx): Promise<Response> {
346353 )
347354 : null}
348355 ${apps.html}
349 ${repoSection(ctx, owner, isSelf, apps.count > 0)}
356 ${list}
350357 ${when(isOrg && accessAllows(access, "read"), () =>
351358 teamsSection(ctx, owner, canManage),
352359 )}
@@ -372,20 +379,19 @@ export async function ownerProfile(ctx: Ctx): Promise<Response> {
372379 )}
373380 ${isOrg ? orgSecrets(ctx, owner.username) : null}`;
374381
375 const listed = listReposByOwner(ctx.app.db, owner.username, undefined, {
376 limit: LIST_LIMIT_MAX,
377 });
378 return page({
382 const response = page({
379383 ctx,
380384 title: owner.username,
381385 description: ownerLine({
382386 org: isOrg,
383387 name: owner.username,
384 publicRepos: listed.length,
385 more: listed.length >= LIST_LIMIT_MAX,
388 publicRepos: listed,
389 more: listed >= LIST_LIMIT_MAX,
386390 }),
387391 body,
388392 });
393 notePhase(ctx.request, "render", performance.now() - rendering);
394 return response;
389395 }
390396
391397 function orgSecrets(ctx: Ctx, name: string): Html | null {
test/owner-timing.test.ts added +71
@@ -0,0 +1,71 @@
1 /** A person's page names its Server-Timing phases and answers fast for 200 repositories (#3309). */
2 import { afterAll, beforeAll, expect, test } from "bun:test";
3 import { mkdtemp, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { createApp } from "../src/app.ts";
7 import { createToken } from "../src/core/tokens.ts";
8 import { createUser } from "../src/core/users.ts";
9 import { serve } from "../src/http/server.ts";
10
11 let dir = "";
12 let app: ReturnType<typeof createApp>;
13 let servers: Awaited<ReturnType<typeof serve>>;
14
15 beforeAll(async () => {
16 dir = await mkdtemp(join(tmpdir(), "forge-owner-timing-"));
17 app = createApp({ dataDir: dir, port: 0 });
18 servers = await serve(app);
19 const made = await createUser(app.db, {
20 origin: "seed", trusted: true, username: "alice", email: "[email protected]",
21 password: "a-good-passphrase", adminIfFirst: true,
22 });
23 if (!made.ok) throw new Error(made.error);
24 const owner = made.value.id;
25 createToken(app.db, owner, "t", "admin");
26 app.db.transaction(() => {
27 for (let i = 0; i < 200; i++) {
28 const id = `repo${String(i).padStart(4, "0")}`;
29 app.db
30 .query("INSERT INTO repo (id, owner_id, name, visibility, description, default_branch) VALUES (?1, ?2, ?3, ?4, ?5, 'main')")
31 .run(id, owner, `r${String(i)}`, i % 3 === 0 ? "private" : "public", `repo number ${String(i)}`);
32 if (i % 20 === 0)
33 app.db.query("INSERT INTO app (id, repo_id, slug, access, preview_data) VALUES (?1, ?2, ?3, 'public', 'copy')").run(`app${id}`, id, `a${String(i)}`);
34 if (i % 2 === 0)
35 app.db
36 .query("INSERT INTO issue (id, repo_id, number, kind, title, body, state, author_id) VALUES (?1, ?2, 1, 'issue', 't', '', 'open', ?3)")
37 .run(`iss${id}`, id, owner);
38 }
39 })();
40 });
41
42 afterAll(async () => {
43 servers.stop();
44 app.close();
45 await rm(dir, { recursive: true, force: true });
46 });
47
48 test("a stranger's view of a 200-repository owner names its phases and answers under 50 ms", async () => {
49 await (await fetch(servers.url + "/alice")).arrayBuffer(); // warm
50 const res = await fetch(servers.url + "/alice");
51 const text = await res.text();
52 expect(res.status).toBe(200);
53 expect(text).toContain("r1");
54 // 200 repositories, every third private: the description counts the 133 public ones, as the listing did.
55 expect(text).toContain("User @alice · 133 public repositories.");
56 const parts = (res.headers.get("server-timing") ?? "").split(", ");
57 const dur = (n: string) => Number(/dur=([\d.]+)/.exec(parts.find((p) => p.startsWith(`${n};`)) ?? "")?.[1]);
58 for (const n of ["session", "repos", "records", "apps", "list", "count", "render"]) {
59 expect(parts.filter((p) => p.startsWith(`${n};`)).length).toBe(1);
60 expect(dur(n)).not.toBeNaN();
61 }
62 // The page's own time, best of five: a loaded check machine must not turn one slow sample into a failure.
63 let best = dur("app");
64 for (let i = 0; i < 4 && best >= 50; i++) {
65 const again = await fetch(servers.url + "/alice");
66 await again.arrayBuffer();
67 const m = /app;dur=([\d.]+)/.exec(again.headers.get("server-timing") ?? "");
68 best = Math.min(best, Number(m?.[1]));
69 }
70 expect(best).toBeLessThan(50);
71 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs