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

A request to the preview or app that hangs is refused at 30 seconds with a plain page, not left open #15847

Merged opened this

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

Merged

scout/forge:scout/15836-a-request-to-the-preview-or-app-that-han → main 0 commits fork 1 thread · 1 unresolved

  • Merged. scout/15836-a-request-to-the-preview-or-app-that-han was merged into main as 86f1d47.

Review

Sign in to review this change.
6 files changed +167 −1
src/apps/proxy.ts +16 −1
@@ -15,6 +15,7 @@
1515 * directory — so guessing a hostname yields the forge's own "not found".
1616 */
1717
18 import { during } from "../perf/jobs.ts";
1819 import { landedChange } from "./landed.ts";
1920 import { expireCookie, setCookie } from "../auth/cookies.ts";
2021 import { compressBytes, MIN_BYTES, negotiate } from "../http/compress.ts";
@@ -66,6 +67,7 @@ import { openPulls } from "./door_pulls.ts";
6667 import { notePhase, startedAt, takePhases, timePhase } from "../core/route_timing.ts";
6768 import { readServing } from "./serving.ts";
6869 import { notFound, securityFloor } from "../http/respond.ts";
70 import { UPSTREAM_WAIT_MS, slowAnswer } from "./upstream_wait.ts";
6971 import { appMeasure } from "./measure.ts";
7072 import { holdPortRequest, holdPortSocket } from "./handoff.ts";
7173 import { secureFor } from "../http/cookie_secure.ts";
@@ -1328,6 +1330,13 @@ export async function proxyApp(
13281330 };
13291331 let response: Response;
13301332 const sent = performance.now();
1333 // No headers within the wait: the connection to the app is aborted and the
1334 // visitor gets a 504, not an open request (#15836). Cleared once they arrive.
1335 const hung = new AbortController();
1336 const timer = setTimeout(
1337 () => during("upstream-wait", () => hung.abort()),
1338 runtime.options.upstreamWaitMs ?? UPSTREAM_WAIT_MS,
1339 );
13311340 try {
13321341 response = await fetch(upstream, {
13331342 method: request.method,
@@ -1337,13 +1346,19 @@ export async function proxyApp(
13371346 ? null
13381347 : request.body,
13391348 redirect: "manual",
1340 signal: request.signal,
1349 signal: AbortSignal.any([request.signal, hung.signal]),
13411350 // Bytes through, untouched: the app chose its encoding.
13421351 decompress: false,
13431352 } as RequestInit);
1353 clearTimeout(timer);
13441354 } catch {
1355 clearTimeout(timer);
13451356 answered();
13461357 relayUpstream(runtime, request, target, performance.now() - sent, vouched?.who);
1358 if (hung.signal.aborted && !request.signal.aborted) {
1359 const here = new URL(request.url);
1360 return relayAnswer(request, slowAnswer(target.app.slug, here.pathname + here.search));
1361 }
13471362 return relayAnswer(request, unavailable(runtime, target, status, "the app stopped answering"));
13481363 }
13491364 // A bare 400 from a deployment the environment has moved off (being replaced, or no
src/apps/runtime_env.ts +2
@@ -22,6 +22,8 @@ import type { ProcessHandle, StartError } from "./process.ts";
2222 export const log = createLog("apps");
2323
2424 export interface RuntimeOptions {
25 /** Milliseconds an app may take to begin an answer before a 504 (`apps/upstream_wait.ts`). */
26 readonly upstreamWaitMs?: number | undefined;
2527 /** The domain app hostnames hang off: `<slug>.<domain>`. */
2628 readonly domain: string;
2729 /** `http` or `https` — what the public URL of an app starts with. */
src/apps/upstream_wait.ts added +43
@@ -0,0 +1,43 @@
1 /**
2 * How long the proxy waits for an app to begin its answer, and the page it
3 * gives when the app does not (#15836). A hung app must not hold a visitor's
4 * connection open for ever: fail fast and loud.
5 */
6 import { securityFloor } from "../http/respond.ts";
7 import { escapeHtml as escape } from "../web/html.ts";
8
9 /**
10 * Milliseconds without response headers before the proxy answers 504 and
11 * closes its connection to the app. 30 s: longer than any page a person
12 * waits for, shorter than the 60 s edges and browsers give up at, so the
13 * forge's words arrive rather than an edge's. Streams are unaffected: the
14 * clock stops when the headers arrive. `RuntimeOptions.upstreamWaitMs`
15 * overrides it (tests).
16 */
17 export const UPSTREAM_WAIT_MS = 30_000;
18
19 /** The policy of the forge's own holding pages: inline style, nothing that runs. */
20 const POLICY =
21 "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'; " +
22 "base-uri 'none'; form-action 'none'";
23
24 /** The 504: one line naming the app, and a link to try again. */
25 export function slowAnswer(slug: string, retry: string): Response {
26 const html = `<!doctype html>
27 <meta charset="utf-8">
28 <meta name="viewport" content="width=device-width, initial-scale=1">
29 <title>${escape(slug)} — not answering</title>
30 <style>:root{color-scheme:light dark;font:16px/1.5 system-ui,sans-serif}body{max-width:34rem;margin:20vh auto;padding:0 1.5rem}</style>
31 <p><strong>${escape(slug)}</strong> did not answer in time. <a href="${escape(retry)}">Try again</a>.</p>
32 `;
33 return securityFloor(

retry may start with // (pathname of //host/x); collapse leading slashes so the link stays on this origin.

34 new Response(html, {
35 status: 504,
36 headers: {
37 "content-type": "text/html; charset=utf-8",
38 "cache-control": "no-store",
39 "content-security-policy": POLICY,
40 },
41 }),
42 );
43 }
src/main.ts +2
@@ -59,6 +59,7 @@ import { warmPlans } from "./web/pages/milestones.ts";
5959 import { warmBoards } from "./web/pages/boards-view.ts";
6060 import { AppsRuntime, IDLE_PULL_DAYS } from "./apps/runtime.ts";
6161 import { previewIdleMs } from "./apps/sleep_window.ts";
62 import { UPSTREAM_WAIT_MS } from "./apps/upstream_wait.ts";
6263 import { listApps } from "./core/apps.ts";
6364 import { holdAppHosts, releaseAppHosts } from "./apps/holding.ts";
6465 import { resolveAppDomain } from "./apps/host.ts";
@@ -574,6 +575,7 @@ const apps = appDomain?.ok
574575 forgeUrl,
575576 concurrency: positive(process.env.FORGE_APPS_CONCURRENCY, 2),
576577 busyGraceMs: crewRunMs,
578 upstreamWaitMs: positive(process.env.FORGE_UPSTREAM_WAIT_MS, UPSTREAM_WAIT_MS),
577579 // Days a pull may sit untouched before its preview sleeps; 0 keeps
578580 // every preview warm. Unset follows the profit slider, live.
579581 idlePullMs: previewIdleMs(process.env.FORGE_PREVIEW_IDLE_DAYS, IDLE_PULL_DAYS),
test/app-proxy-timeout.test.ts added +103
@@ -0,0 +1,103 @@
1 /**
2 * An app that never answers is refused with a 504 after the configured wait
3 * (#15836), its connection closed; an app that answers in time is untouched.
4 */
5 import { afterAll, beforeAll, describe, expect, spyOn, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { AppsRuntime, type EnvStatus } from "../src/apps/runtime.ts";
11 import { UPSTREAM_WAIT_MS, slowAnswer } from "../src/apps/upstream_wait.ts";
12 import { newApp } from "../src/actions/apps.ts";
13 import { createUser } from "../src/core/users.ts";
14 import { serve, type Servers } from "../src/http/server.ts";
15 import { quietLogs } from "./helpers/globals.ts";
16
17 quietLogs();
18
19 const DOMAIN = "apps.test";
20
21 test("the default wait is 30 seconds", () => {
22 expect(UPSTREAM_WAIT_MS).toBe(30_000);
23 });
24
25 test("the page names the app, escaped, and links to retry", async () => {
26 const res = slowAnswer("<b>x", "/a?b=1&c=<2>");
27 expect(res.status).toBe(504);
28 const html = await res.text();
29 expect(html).toContain("&lt;b&gt;x");
30 expect(html).not.toContain("<b>x");
31 expect(html).toContain('href="/a?b=1&amp;c=&lt;2&gt;"');
32 expect(res.headers.get("x-content-type-options")).toBe("nosniff");
33 });
34
35 describe("through the proxy", () => {
36 let dataDir: string;
37 let app: App;
38 let servers: Servers;
39 let runtime: AppsRuntime;
40 let backend: ReturnType<typeof Bun.serve>;
41 let status: ReturnType<typeof spyOn>;
42 let aborted: Promise<void> = Promise.resolve();
43 let sawAbort!: () => void;
44
45 const get = (path: string) =>
46 fetch(`${servers.url}${path}`, { headers: { host: `hello.${DOMAIN}`, accept: "text/plain" }, redirect: "manual" });
47
48 beforeAll(async () => {
49 backend = Bun.serve({
50 port: 0,
51 fetch(request) {
52 if (new URL(request.url).pathname === "/hang")
53 return new Promise<Response>(() => {
54 request.signal.addEventListener("abort", () => sawAbort());
55 });
56 return new Response("ok", { headers: { "content-type": "text/plain" } });
57 },
58 });
59 dataDir = await mkdtemp(join(tmpdir(), "forge-timeout-"));
60 app = createApp({ dataDir, port: 0 });
61 servers = await serve(app);
62 runtime = new AppsRuntime(app, {
63 domain: DOMAIN, scheme: "http", publicPort: servers.port, forgeUrl: servers.url,
64 concurrency: 1, upstreamWaitMs: 200,
65 });
66 await runtime.start();
67 status = spyOn(AppsRuntime.prototype, "envStatus").mockImplementation(
68 () => ({ env: "production", state: "running", port: backend.port, commitOid: "a".repeat(40) }) as EnvStatus,
69 );
70 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice",
71 email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
72 if (!made.ok) throw new Error(made.error);
73 const created = await newApp(app, made.value, { name: "hello", description: "d", visibility: "public" });
74 if (!created.ok) throw new Error(String(created.error));
75 }, 30_000);
76
77 afterAll(async () => {
78 status.mockRestore();
79 await runtime.stop();
80 servers.stop();
81 backend.stop(true);
82 app.close();
83 await rm(dataDir, { recursive: true, force: true });
84 });
85
86 test("an app that never answers gets a 504 within the wait, and its connection is closed", async () => {
87 aborted = new Promise<void>((r) => (sawAbort = r));
88 const started = performance.now();
89 const res = await get("/hang?x=1");
90 expect(res.status).toBe(504);
91 expect(performance.now() - started).toBeLessThan(2_000);
92 const html = await res.text();
93 expect(html).toContain("hello");
94 expect(html).toContain('href="/hang?x=1"');
95 await aborted; // the app saw its connection close
96 });
97
98 test("an app that answers is not refused", async () => {
99 const res = await get("/fast");
100 expect(res.status).toBe(200);
101 expect(await res.text()).toBe("ok");
102 });
103 });
test/job-slices.test.ts +1
@@ -261,6 +261,7 @@ function jobs(): Record<string, () => unknown> {
261261 * on.
262262 */
263263 const UNTIMED: Record<string, string> = {
264 "upstream-wait": "a one-shot timer that only aborts one proxied request when its app sends no headers in 30 s; no work of its own, cleared when the headers arrive; the upstream-wait tests drive it with a short wait",
264265 "runner-wait": "one-shot timers that only resolve a promise: a runner's claim held open, a check's look at its job each second (checks/runner_jobs.ts, runner_step.ts) and the runner program's own pauses; off unless FORGE_CHECKS_PLACEMENT=runner, and checks-runner-placement.test.ts drives all three",
265266 "git-pace": "a one-shot timer in git/pace.ts that only resolves the promise a paced pack write waits on: no work of its own, armed per pack chunk while a page response is in flight; git-pace.test.ts drives the pacer with a fake clock",
266267 "drill-watch": "a /proc read of the drill child's memory and a state write every WATCH_MS, only while a restore drill runs in its own process; drill-job tests drive runDrillInChild directly",

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs