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

/signin answers without a stall on the serving thread #17835

opened this

Merged 4h 15m ago, live in production

scout/forge:scout/17822-signin-answers-without-a-stall-on-the-se → main 0 commits fork 2 threads · 2 unresolved

  • Merged. scout/17822-signin-answers-without-a-stall-on-the-se was merged into main as ff7b4dd.

Review

Sign in to review this change.
4 files changed +179 −2
src/http/lazy_routes.ts +27
@@ -26,6 +26,10 @@ export interface LazyFamily {
2626 }
2727
2828 const families = new WeakMap<Router<Handler>, LazyFamily[]>();
29 /**
30 * Each family's own cached loader, by table: what a request awaits, and what `loadFamilies` fills.
31 */
32 const loaders = new WeakMap<Router<Handler>, Map<string, () => Promise<Router<Handler>>>>();
2933
3034 /** The families registered on this table, in the order they were (`scripts/lazy-lists.ts`). */
3135 export function lazyFamilies(table: Router<Handler>): readonly LazyFamily[] {
@@ -59,6 +63,9 @@ export function lazyRoutes(
5963 throw error;
6064 },
6165 ));
66 const ownLoaders = loaders.get(table) ?? new Map<string, () => Promise<Router<Handler>>>();
67 loaders.set(table, ownLoaders);
68 ownLoaders.set(family, loaded);
6269 for (const [method, pattern] of routes)
6370 table.add(method, pattern, async (ctx) => {
6471 const handler = (await loaded()).handlerOf(method, pattern);
@@ -66,3 +73,23 @@ export function lazyRoutes(
6673 return handler(ctx);
6774 });
6875 }
76
77 /**
78 * Load `names` on `table` now, in turn, as their first request would: the module a request then
79 * meets is already in place (#17822). Answers the names that loaded; one that fails or is not on
80 * the table is left out, and its first request tries again.
81 */
82 export async function loadFamilies(table: Router<Handler>, names: readonly string[]): Promise<string[]> {
83 const loaded: string[] = [];
84 for (const name of names) {
85 const load = loaders.get(table)?.get(name);
86 if (load === undefined) continue;
87 try {
88 await load();
89 loaded.push(name);
90 } catch {
91 // Not kept by `lazyRoutes`: the first request retries and is answered with what it meets.
92 }
93 }
94 return loaded;
95 }
src/http/server.ts +21 −2
@@ -5,7 +5,7 @@
55 * verdict. Auth is resolved once per request and handed to handlers as data.
66 */
77
8 import { lazyRoutes } from "./lazy_routes.ts";
8 import { lazyRoutes, loadFamilies } from "./lazy_routes.ts";
99 import { boundedSignal } from "../kernel/fetch_timeout.ts";
1010 import { forgesRoutes } from "./routes/forges.ts";
1111 import { carrySent, InvalidJson } from "./json_body.ts";
@@ -65,7 +65,7 @@ import { runGate } from "./run_gate.ts";
6565 import { readGrantGate } from "./read_grant_gate.ts";
6666 import { viaGate } from "./via_gate.ts";
6767 import type { Database } from "bun:sqlite";
68 import { scheduleWarmUp, WARM, type Family } from "./warmup.ts";
68 import { BOOT, scheduleWarmUp, WARM, type Family } from "./warmup.ts";
6969 import { resourcePolicy } from "./corp.ts";
7070 import { createUsageCounter, type UsageCounter } from "../core/usage_count.ts";
7171 import { createRouteTiming, noteDbTime, noteSessionTime, notePhase, namesFrame, noteStart, takePhases, serverTiming, withLag, takeDbTime, type RouteTiming } from "../core/route_timing.ts";
@@ -575,6 +575,8 @@ const fromStored = (stored: StoredResponse, replay: boolean): Response => {
575575 export interface Servers {
576576 /** Resolves once the post-boot warm-up of the public families has run (#14662). */
577577 readonly warmed: Promise<void>;
578 /** The families loaded before the listener opened (`BOOT`, #17822): none unless warming. */
579 readonly booted: readonly string[];
578580 /**
579581 * The performance watcher's hourly probe (#16066): one GET answered through the routes without
580582 * the listener. Nothing in a request names it, so no client can reach or imitate it; it is
@@ -1205,6 +1207,22 @@ export async function serve(app: App, options: { warm?: { families?: readonly Fa
12051207 return withHeader(response, "connection", "close");
12061208 };
12071209
1210 // The sign-in door, loaded and drawn once before the port opens, so no first request pays the
1211 // import or the first render on the serving thread (#17822). Only where the warm-up runs.
1212 const booted = options.warm === undefined ? [] : await loadFamilies(router, BOOT.families);
1213 if (options.warm !== undefined)
1214 for (const path of BOOT.pages) {
1215 try {
1216 const drawn = await answer(app, router, apiRouter, probeLimiter, new Request(`http://localhost${path}`));
1217 await drawn.arrayBuffer();
1218 } catch (error) {
1219 app.log.warn("boot: a page did not draw; its first request will", {
1220 path,
1221 error: error instanceof Error ? error.message : String(error),
1222 });
1223 }
1224 }
1225
12081226 // Set by `stopAccepting`: the port is the release's now.
12091227 let handedOver = false;
12101228 // The warm-up waits for the first answer (#14662): boot to first answer is unchanged.
@@ -1265,6 +1283,7 @@ export async function serve(app: App, options: { warm?: { families?: readonly Fa
12651283 });
12661284 return {
12671285 warmed: warm.done,
1286 booted,
12681287 async probe(path) {
12691288 const started = performance.now();
12701289 const request = new Request(`http://localhost${path}`, { method: "GET" });
src/http/warmup.ts +12
@@ -10,6 +10,10 @@
1010 * (the request's origin is the canonical one, so the warmed copy is the one
1111 * served), and the render and the first JIT are paid here.
1212 *
13 * The sign-in door is not here: it is every person's way in and its module the costliest first
14 * import a signed-out visitor meets, so it is loaded and drawn before the listener opens (`BOOT`,
15 * #17822): no first request, however early, pays it.
16 *
1317 * The one list is `WARM`. /changelog, /search, /pricing and /templates are
1418 * static imports already loaded at boot and have no family to load.
1519 */
@@ -44,6 +48,14 @@ export const WARM: readonly Family[] = [
4448 },
4549 ];
4650
51 /**
52 * Loaded and drawn before the listener opens, in the booting process only (#17822). The accounts
53 * module took 120-485 ms to import and the form 25 ms to draw the first time, on the serving
54 * thread, while argon2 itself runs off it: so the first `/signin`, GET or POST, held every other
55 * request. The boot pays it once instead (`serve`).
56 */
57 export const BOOT = { families: ["accounts"], pages: ["/signin"] } as const;
58
4759 /** How long the listener is left alone after its first answer. */
4860 export const WARM_IDLE_MS = 500;
4961 /** A forge nobody has asked yet warms after this long. */
test/signin-loop-free.test.ts added +119
@@ -0,0 +1,119 @@
1 /**
2 * A sign-in never holds the serving thread (#17822). Argon2 at the forge's own cost runs off the
3 * thread, and the accounts module is loaded, and the form drawn, before the listener opens: so
4 * the very first request after a boot, a POST /signin with nothing before it, meets a loaded
5 * module. Nothing here times the loop; the load is read where it happens.
6 */
7 import { afterAll, beforeAll, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import { createUser } from "../src/core/users.ts";
13 import type { Ctx, Handler } from "../src/http/context.ts";
14 import { lazyRoutes, loadFamilies } from "../src/http/lazy_routes.ts";
15 import { Router } from "../src/http/router.ts";
16 import { serve, type Servers } from "../src/http/server.ts";
17 import { BOOT, WARM } from "../src/http/warmup.ts";
18 import { realHash } from "./helpers/cheap-hash.ts";
19 import { quietLogs } from "./helpers/globals.ts";
outdated

A 50 ms bound on a 1 ms setInterval gap is a flaky timing assertion on shared CI. Test the cold path deterministically, without awaiting servers.warmed first.

20
21 quietLogs();
22
23 let dir: string;
24 let app: App;
25 let servers: Servers;
26
27 beforeAll(async () => {
28 dir = await mkdtemp(join(tmpdir(), "forge-signin-boot-"));
29 app = createApp({ dataDir: dir, port: 0 });
30 const made = await createUser(app.db, {
31 origin: "seed",
32 trusted: true,
33 username: "alice",
34 email: "[email protected]",
35 password: "a-good-passphrase",
36 adminIfFirst: true,
37 });
38 if (!made.ok) throw new Error(made.error);
39 // The production cost, not the suite's cheap one.
40 const strong = await realHash("a-good-passphrase", "argon2id");
41 app.db.run("UPDATE user SET password_hash = ?1 WHERE username = 'alice'", [strong]);
42 // Warming, as the booting process does, but with no family after the first answer: the boot's
43 // own loads are what this file reads, and a warm-up left running would reach into the next file
44 // its worker runs (the check runs files `--no-isolate`).
45 servers = await serve(app, { warm: { families: [] } });
46 });
47 afterAll(async () => {
48 servers.stop();
49 app.close();
50 await rm(dir, { recursive: true, force: true });
51 });
52
53 async function signIn(username: string, password: string): Promise<Response> {
54 return fetch(`${servers.url}/signin`, {
55 method: "POST",
56 headers: { origin: servers.url },
57 body: new URLSearchParams({ username, password }),
58 redirect: "manual",
59 });
60 }
61
62 test("the accounts module is loaded before the listener answers anyone, and the warm list no longer waits for it", () => {
63 expect(BOOT.families).toContain("accounts");
64 expect(BOOT.pages).toContain("/signin");
65 expect(servers.booted).toEqual(["accounts"]);
66 expect(WARM.flatMap((f) => f.paths)).not.toContain("/signin");
67 });
68
69 test("the first request after a boot is a wrong password at full cost, and it is refused", async () => {
70 const wrong = await signIn("alice", "not-the-passphrase");
71 expect(wrong.status).toBe(422);
72 expect(await wrong.text()).toContain("That username and password don&#39;t match.");
73 });
74
75 test("a name with no account is refused with the same words", async () => {
76 const nobody = await signIn("nobody-here", "not-the-passphrase");
77 expect(nobody.status).toBe(422);
78 expect(await nobody.text()).toContain("That username and password don&#39;t match.");
79 });
80
81 test("the right password signs in", async () => {
82 expect((await signIn("alice", "a-good-passphrase")).status).toBe(303);
83 });
84
85 test("a forge served without the warm-up loads nothing at boot", async () => {
86 const other = createApp({ dataDir: await mkdtemp(join(tmpdir(), "forge-signin-cold-")), port: 0 });
87 const cold = await serve(other);
88 try {
89 expect(cold.booted).toEqual([]);
90 } finally {
91 cold.stop();
92 other.close();
93 await rm(other.config.dataDir, { recursive: true, force: true });
94 }
95 });
96
97 test("loadFamilies loads a family once, before its first request, and leaves out what it cannot load", async () => {
98 let loads = 0;
99 let failing = true;
100 const router = new Router<Handler>();
101 lazyRoutes(router, "door", async () => (loads++, (r) => void r.add("GET", "/door", () => new Response("in"))), [["GET", "/door"]]);
102 lazyRoutes(
103 router,
104 "broken",
105 async () => {
106 if (failing) throw new Error("not yet");
107 return (r) => void r.add("GET", "/broken", () => new Response("fixed"));
108 },
109 [["GET", "/broken"]],
110 );
111 expect(await loadFamilies(router, ["door", "broken", "absent"])).toEqual(["door"]);
112 expect(loads).toBe(1);
113 const door = router.match("GET", "/door");
114 if (door === undefined) throw new Error("no /door");
115 expect(await (await door.handler({} as Ctx)).text()).toBe("in");
116 expect(loads).toBe(1);
117 failing = false;
118 expect(await loadFamilies(router, ["broken"])).toEqual(["broken"]);
119 });

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

Keyboard shortcuts

Docs