Public: anyone can read this; the crew can change it.
/signin answers without a stall on the serving thread #17835
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
4 files
changed +179
−2
src/http/lazy_routes.ts +27
| @@ -26,6 +26,10 @@ export interface LazyFamily { | ||
| 26 | 26 | } |
| 27 | 27 | |
| 28 | 28 | 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>>>>(); | |
| 29 | 33 | |
| 30 | 34 | /** The families registered on this table, in the order they were (`scripts/lazy-lists.ts`). */ |
| 31 | 35 | export function lazyFamilies(table: Router<Handler>): readonly LazyFamily[] { |
| @@ -59,6 +63,9 @@ export function lazyRoutes( | ||
| 59 | 63 | throw error; |
| 60 | 64 | }, |
| 61 | 65 | )); |
| 66 | const ownLoaders = loaders.get(table) ?? new Map<string, () => Promise<Router<Handler>>>(); | |
| 67 | loaders.set(table, ownLoaders); | |
| 68 | ownLoaders.set(family, loaded); | |
| 62 | 69 | for (const [method, pattern] of routes) |
| 63 | 70 | table.add(method, pattern, async (ctx) => { |
| 64 | 71 | const handler = (await loaded()).handlerOf(method, pattern); |
| @@ -66,3 +73,23 @@ export function lazyRoutes( | ||
| 66 | 73 | return handler(ctx); |
| 67 | 74 | }); |
| 68 | 75 | } |
| 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 @@ | ||
| 5 | 5 | * verdict. Auth is resolved once per request and handed to handlers as data. |
| 6 | 6 | */ |
| 7 | 7 | |
| 8 | import { lazyRoutes } from "./lazy_routes.ts"; | |
| 8 | import { lazyRoutes, loadFamilies } from "./lazy_routes.ts"; | |
| 9 | 9 | import { boundedSignal } from "../kernel/fetch_timeout.ts"; |
| 10 | 10 | import { forgesRoutes } from "./routes/forges.ts"; |
| 11 | 11 | import { carrySent, InvalidJson } from "./json_body.ts"; |
| @@ -65,7 +65,7 @@ import { runGate } from "./run_gate.ts"; | ||
| 65 | 65 | import { readGrantGate } from "./read_grant_gate.ts"; |
| 66 | 66 | import { viaGate } from "./via_gate.ts"; |
| 67 | 67 | 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"; | |
| 69 | 69 | import { resourcePolicy } from "./corp.ts"; |
| 70 | 70 | import { createUsageCounter, type UsageCounter } from "../core/usage_count.ts"; |
| 71 | 71 | 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 => { | ||
| 575 | 575 | export interface Servers { |
| 576 | 576 | /** Resolves once the post-boot warm-up of the public families has run (#14662). */ |
| 577 | 577 | readonly warmed: Promise<void>; |
| 578 | /** The families loaded before the listener opened (`BOOT`, #17822): none unless warming. */ | |
| 579 | readonly booted: readonly string[]; | |
| 578 | 580 | /** |
| 579 | 581 | * The performance watcher's hourly probe (#16066): one GET answered through the routes without |
| 580 | 582 | * 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 | ||
| 1205 | 1207 | return withHeader(response, "connection", "close"); |
| 1206 | 1208 | }; |
| 1207 | 1209 | |
| 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 | ||
| 1208 | 1226 | // Set by `stopAccepting`: the port is the release's now. |
| 1209 | 1227 | let handedOver = false; |
| 1210 | 1228 | // 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 | ||
| 1265 | 1283 | }); |
| 1266 | 1284 | return { |
| 1267 | 1285 | warmed: warm.done, |
| 1286 | booted, | |
| 1268 | 1287 | async probe(path) { |
| 1269 | 1288 | const started = performance.now(); |
| 1270 | 1289 | const request = new Request(`http://localhost${path}`, { method: "GET" }); |
src/http/warmup.ts +12
| @@ -10,6 +10,10 @@ | ||
| 10 | 10 | * (the request's origin is the canonical one, so the warmed copy is the one |
| 11 | 11 | * served), and the render and the first JIT are paid here. |
| 12 | 12 | * |
| 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 | * | |
| 13 | 17 | * The one list is `WARM`. /changelog, /search, /pricing and /templates are |
| 14 | 18 | * static imports already loaded at boot and have no family to load. |
| 15 | 19 | */ |
| @@ -44,6 +48,14 @@ export const WARM: readonly Family[] = [ | ||
| 44 | 48 | }, |
| 45 | 49 | ]; |
| 46 | 50 | |
| 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 | ||
| 47 | 59 | /** How long the listener is left alone after its first answer. */ |
| 48 | 60 | export const WARM_IDLE_MS = 500; |
| 49 | 61 | /** 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"; | |
| 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'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'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 | }); |
new above
offline
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.warmedfirst.