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 #3335

Parked opened this
Closed without merging

scout/forge:scout/3309-a-person-s-page-answers-under-50-ms-and → main 2 commits fork 1 thread · 1 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
3 files changed +104 −15
src/core/repos.ts +18
@@ -759,6 +759,24 @@ export function listReposByOwner(
759759 return withCounts(db, rows);
760760 }
761761
762 /** How many public repos one owner has, up to `cap`: one count, no rows built. */
763 export function countPublicReposByOwner(
764 db: Database,
765 ownerName: string,
766 cap: number,
767 ): number {
768 return (
769 db
770 .query<{ n: number }, [string, string, number]>(
771 `SELECT COUNT(*) AS n FROM (
772 SELECT repo.id FROM repo JOIN user ON user.id = repo.owner_id
773 WHERE user.username = ?2 COLLATE NOCASE AND ${PUBLIC_VISIBLE}
774 LIMIT ?3)`,
775 )
776 .get("", ownerName, cap)?.n ?? 0
777 );
778 }
779
762780 /**
763781 * Delete a repo. Row first, then disk — inverse of creation, same invariant.
764782 * Before removing the objects, detach every fork that borrows them (repack so
src/web/pages/org.ts +22 −15
@@ -28,9 +28,10 @@ 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";
3637 import { notFoundPage, pageHead, signInFirst } from "../chrome.ts";
@@ -180,12 +181,11 @@ async function appsSection(
180181 owner: User,
181182 isSelf: boolean,
182183 ): Promise<{ html: Html; count: number }> {
183 const repos = listReposByOwner(ctx.app.db, owner.username, ctx.auth.user, {
184 limit: 200,
185 });
186 const records = appsForRepos(
187 ctx.app.db,
188 repos.map((r) => r.id),
184 const repos = timePhase(ctx.request, "repos", () =>
outdated

This phase covers both the repo list and appsForRepos, so repos hides the apps read. Name it for what it times, or split it into two phases.

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)),
189189 );
190190 const appRepos = repos.filter((r) => records.has(r.id));
191191 const newAppHref = `/apps/new?owner=${owner.username}`;
@@ -203,7 +203,7 @@ async function appsSection(
203203 ),
204204 };
205205
206 const rows = await shelfRows(ctx, appRepos);
206 const rows = await timePhaseAsync(ctx.request, "apps", () => shelfRows(ctx, appRepos));
207207 return { count: appRepos.length, html: listCard(rows, {
208208 head: html`${icon("rocket")}
209209 <h2>Apps</h2>
@@ -310,7 +310,15 @@ export async function ownerProfile(ctx: Ctx): Promise<Response> {
310310 const canManage = isOrg && accessAllows(access, "admin");
311311 const isSelf =
312312 ctx.auth.user !== undefined && (ctx.auth.user.id === owner.id || canManage);
313 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
313314 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();
314322 // Said to the people it concerns: its members and the forge's owner.
315323 const ownerless =
316324 isOrg && access !== "none" && personOwners(ctx.app.db, owner.id).length === 0;
@@ -345,7 +353,7 @@ export async function ownerProfile(ctx: Ctx): Promise<Response> {
345353 )
346354 : null}
347355 ${apps.html}
348 ${repoSection(ctx, owner, isSelf, apps.count > 0)}
356 ${list}
349357 ${when(isOrg && accessAllows(access, "read"), () =>
350358 teamsSection(ctx, owner, canManage),
351359 )}
@@ -371,20 +379,19 @@ export async function ownerProfile(ctx: Ctx): Promise<Response> {
371379 )}
372380 ${isOrg ? orgSecrets(ctx, owner.username) : null}`;
373381
374 const listed = listReposByOwner(ctx.app.db, owner.username, undefined, {
375 limit: LIST_LIMIT_MAX,
376 });
377 return page({
382 const response = page({
378383 ctx,
379384 title: owner.username,
380385 description: ownerLine({
381386 org: isOrg,
382387 name: owner.username,
383 publicRepos: listed.length,
384 more: listed.length >= LIST_LIMIT_MAX,
388 publicRepos: listed,
389 more: listed >= LIST_LIMIT_MAX,
385390 }),
386391 body,
387392 });
393 notePhase(ctx.request, "render", performance.now() - rendering);
394 return response;
388395 }
389396
390397 function orgSecrets(ctx: Ctx, name: string): Html | null {
test/owner-timing.test.ts added +64
@@ -0,0 +1,64 @@
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 bearer = "";
13 let app: ReturnType<typeof createApp>;
14 let servers: Awaited<ReturnType<typeof serve>>;
15
16 beforeAll(async () => {
17 dir = await mkdtemp(join(tmpdir(), "forge-owner-timing-"));
18 app = createApp({ dataDir: dir, port: 0 });
19 servers = await serve(app);
20 const made = await createUser(app.db, {
21 origin: "seed", trusted: true, username: "alice", email: "[email protected]",
22 password: "a-good-passphrase", adminIfFirst: true,
23 });
24 if (!made.ok) throw new Error(made.error);
25 const owner = made.value.id;
26 bearer = createToken(app.db, owner, "t", "admin").token;
27 app.db.transaction(() => {
28 for (let i = 0; i < 200; i++) {
29 const id = `repo${String(i).padStart(4, "0")}`;
30 app.db
31 .query("INSERT INTO repo (id, owner_id, name, visibility, description, default_branch) VALUES (?1, ?2, ?3, ?4, ?5, 'main')")
32 .run(id, owner, `r${String(i)}`, i % 3 === 0 ? "private" : "public", `repo number ${String(i)}`);
33 if (i % 20 === 0)
34 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)}`);
35 if (i % 2 === 0)
36 app.db
37 .query("INSERT INTO issue (id, repo_id, number, kind, title, body, state, author_id) VALUES (?1, ?2, 1, 'issue', 't', '', 'open', ?3)")
38 .run(`iss${id}`, id, owner);
39 }
40 })();
41 });
42
43 afterAll(async () => {
44 servers.stop();
45 app.close();
46 await rm(dir, { recursive: true, force: true });
47 });
48
49 test("a stranger's view of a 200-repository owner names its phases and answers under 50 ms", async () => {
50 await (await fetch(servers.url + "/alice")).arrayBuffer(); // warm
51 const res = await fetch(servers.url + "/alice");
52 const text = await res.text();
53 expect(res.status).toBe(200);
54 expect(text).toContain("r1");
55 // 200 repositories, every third private: the description counts the 133 public ones, as the listing did.
56 expect(text).toContain("User @alice · 133 public repositories.");
57 const parts = (res.headers.get("server-timing") ?? "").split(", ");
58 const dur = (n: string) => Number(/dur=([\d.]+)/.exec(parts.find((p) => p.startsWith(`${n};`)) ?? "")?.[1]);
59 for (const n of ["session", "repos", "records", "apps", "list", "count", "render"]) {
60 expect(parts.filter((p) => p.startsWith(`${n};`)).length).toBe(1);
61 expect(dur(n)).not.toBeNaN();
62 }
63 expect(dur("app")).toBeLessThan(50);
64 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs