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

The offline page and the waking page share one sentence and show when the forge will answer #13022

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

mason/forge:mason/13010-the-offline-page-and-the-waking-page-sha → main 9 commits fork 3 threads · 3 unresolved

  • Merged. mason/13010-the-offline-page-and-the-waking-page-sha was merged into main as 33b4937.

Review

Sign in to review this change.
8 files changed +131 −12
src/spawn/host.ts +8 −2
@@ -60,6 +60,8 @@ interface ChildLedger {
6060 * process meanwhile.
6161 */
6262 readonly moving: boolean;
63 /** How long the last start took, ms; undefined before one was measured. */
64 readonly wakeMs: number | undefined;
6365 /** What the parent shows the child (`x-forge-parent`); its own questions carry it. */
6466 readonly statusToken: string | undefined;
6567 }
@@ -84,6 +86,7 @@ function readLedgerSync(app: App, name: string): ChildLedger | undefined {
8486 placement?: unknown;
8587 size?: unknown;
8688 move?: unknown;
89 wakeMs?: unknown;
8790 statusToken?: unknown;
8891 };
8992 if (typeof parsed.name !== "string" || typeof parsed.bodyId !== "string") return undefined;
@@ -95,6 +98,7 @@ function readLedgerSync(app: App, name: string): ChildLedger | undefined {
9598 placement: parsed.placement === "cell" ? "cell" : "hosted",
9699 size: isSize(parsed.size) ? parsed.size : DEFAULT_SIZE,
97100 moving: typeof parsed.move === "object" && parsed.move !== null,
101 wakeMs: typeof parsed.wakeMs === "number" && parsed.wakeMs > 0 ? parsed.wakeMs : undefined,
98102 statusToken: typeof parsed.statusToken === "string" ? parsed.statusToken : undefined,
99103 };
100104 } catch {
@@ -812,7 +816,9 @@ function settleCell(parent: App, ledger: ChildLedger): Promise<CellChild | undef
812816 let flight = flights.get(ledger.bodyId);
813817 if (!flight) {
814818 const cells = cellChildren(parent);
819 const began = Date.now();
815820 flight = cells.start(ledger).then(async (child) => {
821 if (child !== undefined) noteLedger(parent, ledger.name, () => ({ wakeMs: Date.now() - began }));

The wakeMs write has no test: nothing fails if this line is removed, or if the ledger reader drops the field. Add one that covers write, read and hand-off to the waking page.

816822 if (child === undefined) await cellDidNotStart(parent, ledger, cells.failure(ledger.bodyId) ?? "its cell did not start");
817823 else noteLedger(parent, ledger.name, (raw) => (typeof raw["placementNote"] === "string" && raw["placementNote"].startsWith(NOT_STARTED) ? { placementNote: undefined } : undefined));
818824 return child;
@@ -1107,7 +1113,7 @@ export async function answerFromCell(parent: App, request: Request, named?: stri
11071113 // Only so many wait on one cell: the rest are told it is waking at once, so a crowd cannot pin
11081114 // connections and bodies.
11091115 const waiting = waiters.get(ledger.bodyId) ?? 0;
1110 if (waiting >= wakeLimits.waiters) return wakingResponse(parent, request, ledger.name);
1116 if (waiting >= wakeLimits.waiters) return wakingResponse(parent, request, ledger.name, undefined, 5, ledger.wakeMs);
11111117 waiters.set(ledger.bodyId, waiting + 1);
11121118 let woke: CellChild | undefined;
11131119 try {
@@ -1128,7 +1134,7 @@ export async function answerFromCell(parent: App, request: Request, named?: stri
11281134 // A cell that did not start says so, with when the host tries again: never "waking up" without
11291135 // end.
11301136 const stop = cells.failure(ledger.bodyId) === undefined ? undefined : lastStop(parent, ledger.bodyId);
1131 return wakingResponse(parent, request, ledger.name, stop === undefined ? undefined : stopSentence(stop));
1137 return wakingResponse(parent, request, ledger.name, stop === undefined ? undefined : stopSentence(stop), 5, ledger.wakeMs);
11321138 }
11331139
11341140 /**
src/web/pages/offline.ts +6 −2
@@ -7,6 +7,10 @@
77 import { createHash } from "node:crypto";
88 import { THEMES } from "../../design/themes.ts";
99 import { securityFloor } from "../../http/respond.ts";
10 import { triesAgain } from "../retry_words.ts";
11
12 /** The one meta refresh: the page asks again once every this many seconds. */
13 const REFRESH_S = 5;
1014
1115 const pad = (n: number) => String(n).padStart(2, "0");
1216
@@ -35,11 +39,11 @@ export function offlineHtml(at: Date): string {
3539 return (
3640 '<!doctype html><html lang="en"><head><meta charset="utf-8">' +
3741 '<meta name="viewport" content="width=device-width,initial-scale=1">' +
38 '<meta http-equiv="refresh" content="5">' +
42 `<meta http-equiv="refresh" content="${REFRESH_S}">` +
3943 "<title>Unreachable · forge</title>" +
4044 `<style>${STYLE}</style></head><body><main>` +
4145 "<h1>The forge is unreachable</h1>" +
42 "<p>This page tries again every few seconds.</p>" +
46 `<p>${triesAgain(REFRESH_S)}</p>` +
4347 `<p class="muted">Last seen <time datetime="${at.toISOString()}">${seenAt(at)}</time>.</p>` +
4448 "</main></body></html>"
4549 );
src/web/pages/waking.ts +9 −5
@@ -11,10 +11,14 @@ import { wakingText } from "../../spawn/sleep.ts";
1111 import { btn, empty } from "../ui.ts";
1212 import { html } from "../html.ts";
1313 import { page } from "../layout.ts";
14 import { wakeSeconds, wakingSentence } from "../retry_words.ts";
1415
1516 /** Waking (`why` undefined, 503) or refused (`why` a sentence, 429), as a page when the visitor asks for HTML. */
16 export function wakingResponse(app: App, request: Request, name: string, why?: string, retryS = 5): Response {
17 if (!(request.headers.get("accept") ?? "").includes("text/html")) return wakingText(name, why, retryS);
17 export function wakingResponse(app: App, request: Request, name: string, why?: string, retryS = 5, wakeMs?: number): Response {
18 // One number answers "when": the words, Refresh and Retry-After. A refusal keeps the caller's
19 // own.
20 const aboutS = why === undefined ? wakeSeconds(wakeMs) : retryS;
21 if (!(request.headers.get("accept") ?? "").includes("text/html")) return wakingText(name, why, aboutS);
1822 const url = new URL(request.url);
1923 const ctx: Ctx = { app, request, url, params: {}, auth: { user: undefined, scope: undefined, via: "none" }, theme: undefined };
2024 const response = page(
@@ -26,15 +30,15 @@ export function wakingResponse(app: App, request: Request, name: string, why?: s
2630 ${empty({
2731 icon: "history",
outdated

Principle 1: the same fact is said twice ('Starting, about N seconds' then 'tries again in about N seconds'). Principle 8: 'Starting, about 8 seconds.' is a fragment. Use one sentence. The line is also over 100 columns and holds a nested ternary: move it into retry_words.ts.

2832 title: why === undefined ? "Waking up" : "Not now",
29 note: why ?? `${name} was asleep. It is waking up and this page tries again by itself in a few seconds.`,
33 note: why ?? wakingSentence(name, wakeMs),
3034 action: btn("Try again", { href: url.pathname, variant: "primary" }),
3135 })}
3236 </div>`,
3337 },
3438 why === undefined ? 503 : 429,
3539 );
36 response.headers.set("retry-after", String(retryS));
40 response.headers.set("retry-after", String(aboutS));
outdated

Refresh is now N seconds but Retry-After stays at retryS (5): two different answers to 'when'. Send the same number in both and in the words.

3741 response.headers.set("cache-control", "no-store");
38 if (why === undefined) response.headers.set("refresh", "3");
42 if (why === undefined) response.headers.set("refresh", String(aboutS));
3943 return response;
4044 }
src/web/retry_words.ts added +26
@@ -0,0 +1,26 @@
1 /**
2 * The one sentence the offline page and the waking page share: when this page
3 * asks again. Plain data in (seconds), plain text out.
4 */
5
6 /** Seconds a waking page waits when no start has been measured yet. */
7 export const DEFAULT_WAKE_S = 5;
8
9 /** A measured start, in ms, as whole seconds to wait: at least 2, at most 30. */
10 export function wakeSeconds(ms: unknown): number {
11 if (typeof ms !== "number" || !Number.isFinite(ms) || ms <= 0) return DEFAULT_WAKE_S;
12 return Math.min(30, Math.max(2, Math.ceil(ms / 1000)));
13 }
14
15 /** `This page tries again in about 5 seconds.` */
16 export function triesAgain(seconds: number): string {
17 return `This page tries again in about ${seconds} second${seconds === 1 ? "" : "s"}.`;
18 }
19
20 /**
21 * `homie was asleep and is starting. This page tries again in about 8 seconds.` (`ms`: the last
22 * measured start).
23 */
24 export function wakingSentence(name: string, ms?: number): string {
25 return `${name} was asleep and is starting. ${triesAgain(wakeSeconds(ms))}`;
26 }
test/first-ten-minutes.test.ts +1 −1
@@ -202,7 +202,7 @@ describe("a request while a cell wakes", () => {
202202 const res = await answerFromCell(parent, post());
203203 expect(woken).toBe(false); // answered while the wake is still under way
204204 expect(res.status).toBe(503);
205 expect(await res.text()).toContain("waking");
205 expect(await res.text()).toContain("was asleep and is starting");
206206 } finally {
207207 wake.open(undefined);
208208 wakeLimits.waitMs = was;
test/forge-sleep.test.ts +1 −1
@@ -184,7 +184,7 @@ describe("a hosted forge scales to zero", () => {
184184 test("a waking page is plain for a browser, and the gate lets an awake forge through", async () => {
185185 const page = wakingResponse(parent, new Request("https://forge.test/", { headers: { accept: "text/html" } }), "homie");
186186 expect(page.status).toBe(503);
187 expect(page.headers.get("refresh")).toBe("3");
187 expect(page.headers.get("refresh")).toBe("5");
188188 const text = await page.text();
189189 expect(text).toContain("Waking up");
190190 expect(text).not.toContain("style=");
test/retry-words.test.ts added +39
@@ -0,0 +1,39 @@
1 import { describe, expect, test } from "bun:test";
2 import { createApp } from "../src/app.ts";
3 import { mkdtempSync } from "node:fs";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { offlineHtml } from "../src/web/pages/offline.ts";
7 import { wakingResponse } from "../src/web/pages/waking.ts";
8 import { triesAgain, wakeSeconds, wakingSentence } from "../src/web/retry_words.ts";
9
10 describe("when the forge will answer", () => {
11 test("a measured start becomes whole seconds, clamped; none measured is the default", () => {
12 expect(wakeSeconds(undefined)).toBe(5);
13 expect(wakeSeconds(-5)).toBe(5);
14 expect(wakeSeconds(4200)).toBe(5);
15 expect(wakeSeconds(100)).toBe(2);
16 expect(wakeSeconds(999_000)).toBe(30);
17 });
18
19 test("the waking page says about how long, and refreshes once after that long", async () => {
20 const app = createApp({ dataDir: mkdtempSync(join(tmpdir(), "forge-wake-")), port: 0 });
21 try {
22 const res = wakingResponse(app, new Request("https://x/", { headers: { accept: "text/html" } }), "homie", undefined, 5, 7400);
23 expect(res.headers.get("refresh")).toBe("8");
24 expect(res.headers.get("retry-after")).toBe("8");
25 const text = await res.text();
26 expect(text).toContain(wakingSentence("homie", 7400));
27 expect(text).not.toContain("Starting, about");
28 expect(text.match(/tries again/g)?.length).toBe(1);
29 } finally {
30 app.close();
31 }
32 });
33
34 test("the offline page uses the same sentence for its own refresh", () => {
35 const html = offlineHtml(new Date(0));
36 expect(html).toContain('content="5"');
37 expect(html).toContain(triesAgain(5));
38 });
39 });
test/spawn-cell-stays.test.ts +41 −1
@@ -13,9 +13,10 @@ import { tmpdir } from "node:os";
1313 import { join } from "node:path";
1414 import { createApp, type App } from "../src/app.ts";
1515 import { cellChildren, type CellChild } from "../src/spawn/cell.ts";
16 import { answerFromCell, bootHostedChild, closeHostedChildren, NOT_STARTED, provideCellsForTest, ranOwnCode, resolveHostedChild } from "../src/spawn/host.ts";
16 import { answerFromCell, bootHostedChild, closeHostedChildren, NOT_STARTED, provideCellsForTest, ranOwnCode, resolveHostedChild, wakeLimits } from "../src/spawn/host.ts";
1717 import { readOwnCode, switchOwnCode } from "../src/spawn/own_code.ts";
1818 import { cancelRestarts, lastStop, stopSentence } from "../src/spawn/stopped.ts";
19 import { wakingSentence } from "../src/web/retry_words.ts";
1920 import { quietLogs } from "./helpers/globals.ts";
2021
2122 quietLogs();
@@ -135,3 +136,42 @@ describe("on a host that holds no cell at all", () => {
135136 expect(ranOwnCode(parent, "beta")).toBe(false);
136137 });
137138 });
139
140 describe("how long a start took", () => {
141 test("is measured when the cell starts, kept in the ledger, and told to the next visitor's waking page", async () => {
142 provideCellsForTest(holds);
143 const server = Bun.serve({ port: 0, fetch: () => new Response("up") });
144 const realNow = Date.now;
145 const waitMs = wakeLimits.waitMs;
146 let skew = 0;
147 let asleep = false;
148 const { parent, ledger } = family("measured");
149 const cells = cellChildren(parent) as unknown as { start: unknown; get: unknown };
150 let held: CellChild | undefined;
151 cells.start = () => {
152 if (asleep) return new Promise<CellChild | undefined>(() => {});
153 skew += 7400;
154 held = { bodyId: "cell-alpha", name: "alpha", size: "small", port: server.port!, limits: { memoryMiB: 1, cpus: 1, diskMiB: 1 }, pid: 1, exited: new Promise<number>(() => {}) };
155 return Promise.resolve(held);
156 };
157 cells.get = () => held;
158 Date.now = () => realNow() + skew;
159 try {
160 expect(await (await answerFromCell(parent, visit())).text()).toBe("up");
161 expect((read(ledger) as { wakeMs?: number }).wakeMs).toBeGreaterThanOrEqual(7400);
162 // Asleep again, and a start that outlasts what a visitor is held for: the page says how long.
163 asleep = true;
164 held = undefined;
165 wakeLimits.waitMs = 20;
166 const waking = await answerFromCell(parent, visit());
167 expect(waking.status).toBe(503);
168 expect(waking.headers.get("refresh")).toBe("8");
169 expect(waking.headers.get("retry-after")).toBe("8");
170 expect(await waking.text()).toContain(wakingSentence("alpha", 7500));
171 } finally {
172 Date.now = realNow;
173 wakeLimits.waitMs = waitMs;
174 server.stop(true);
175 }
176 });
177 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs