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

A service app runs: its process starts, stays up with backoff, and stops with the app (the `service` kind's first running piece) #16650

Merged opened this

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

Merged

scout/forge:scout/14231-a-service-app-runs-its-process-starts-st → main 0 commits fork 1 thread · 1 unresolved

  • Merged. scout/14231-a-service-app-runs-its-process-starts-st was merged into main as 77871b2.

Review

Sign in to review this change.
7 files changed +308 −5
docs/APPS.md +7 −2
@@ -2046,8 +2046,13 @@ an HTTP child: `ports` (TCP, 1024–65535, required), `always_on` (true; false i
20462046 refused), `placement` (`"metal"` or `"cloud"`, optional) and `volumes`
20472047 (`{ "path": "world", "sync": 300 }`, a relative path under the app's data and a
20482048 sync cadence in seconds, 10–86400). `src/apps/service.ts` validates it; the
2049 manifest carries it as `service`, `null` for a web app. Running it, exposing
2050 the ports and syncing volumes are not built yet (issue #391).
2049 manifest carries it as `service`, `null` for a web app. Its `run` starts under the same
2050 containment as a web app (a cell where the host has one), with no HTTP health
2051 wait: started is up. `src/apps/supervise.ts` restarts it when it exits, after
2052 1 s, 2 s, 4 s … never more than 60 s (a run of 60 s starts the count over), and
2053 the app page says so ("service restarting in 8 s after exit code 1"). Stopping
2054 or archiving the app stops the process and its children and ends the
2055 restarts. Exposing the ports and syncing volumes are not built yet (issue #391).
20512056
20522057 ## The access log
20532058
src/apps/process.ts +20 −1
@@ -26,6 +26,7 @@ import { endedLine, liveTree } from "../runs/ended.ts";
2626 import { CANCEL_GRACE_MS, graceKillLine } from "../runs/grace.ts";
2727 import { spellings, stripForgeDirs } from "../runs/paths.ts";
2828 import { seconds } from "./timing.ts";
29 import { supervise } from "./supervise.ts";
2930 import { toolchainUse, type ToolchainUse } from "./toolchain.ts";
3031 import { notFoundHint, shellCommand } from "./run_command.ts";
3132 import { floorRefusal } from "../spawn/disk_floor.ts";
@@ -56,6 +57,8 @@ export interface ProcessHandle {
5657 stop(): Promise<void>;
5758 /** The cell limit it broke, once it has ended over one (`Cell.breach`). */
5859 breach?: () => string | undefined;
60 /** A service's restart count and pause (`apps/supervise.ts`). */
61 state?: () => import("./supervise.ts").ServiceState;
5962 }
6063
6164 export interface StartInput {
@@ -828,6 +831,9 @@ export async function startProcess(
828831 },
829832 };
830833
834 // A service has no page to wait for: started is up, and the supervisor
835 // (`apps/supervise.ts`) answers for it ending.
836 if (manifest.service != null) return { handle, spawnedAt, firstOutputAt };
831837 const ready = await waitUntilReady({
832838 port,
833839 path: manifest.health,
@@ -859,7 +865,20 @@ export async function startProcess(
859865 await tested.catch(() => {});
860866 return err(launched.error);
861867 }
862 const { handle, spawnedAt, firstOutputAt } = launched;
868 const { handle: first, spawnedAt, firstOutputAt } = launched;
869 if (manifest.service != null) {
870 log("service started; no health wait, it is restarted with backoff if it exits");
871 const handle = supervise({
872 first,
873 log,
874 start: async () => {
875 const again = await launch(pick());
876 return "error" in again ? { ok: false, error: again.error.message } : { ok: true, handle: again.handle };
877 },
878 });
879 return ok({ handle, tested });
880 }
881 const handle = first;
863882 log(`ready: ${input.url}`);
864883 // How the process's own share of the start divides: the time until it
865884 // first said anything (the runtime loading the app, the app's own boot
src/apps/runtime_bringup.ts +1 −1
@@ -184,7 +184,7 @@ export async function bringUp(
184184 };
185185 }
186186 // The health path answered; the page people open must too.
187 const fault = await rootFault(started.value.handle.port);
187 const fault = manifest.value.service == null ? await rootFault(started.value.handle.port) : undefined;
188188 if (fault !== undefined) {
189189 await started.value.handle.stop();
190190 revokeAppToken(rt.app.db, token.id);
src/apps/runtime_status.ts +6 −1
@@ -5,6 +5,7 @@
55 */
66
77 import { cellHides, grantsHere } from "../spawn/hosted-mark.ts";
8 import { serviceNote } from "./supervise.ts";
89 import { VERIFYING_NOTE } from "./env_phrase.ts";
910 import { join } from "node:path";
1011 import type { AppRecord } from "../core/apps.ts";
@@ -94,7 +95,11 @@ export function describe(
9495 ...(state.live.deployStartedAt === null
9596 ? {}
9697 : { deployStartedAt: state.live.deployStartedAt }),
97 ...(swapped ? { note: VERIFYING_NOTE } : {}),
98 ...(swapped
99 ? { note: VERIFYING_NOTE }
100 : serviceNote(state.live.handle.state?.()) === undefined
101 ? {}
102 : { note: serviceNote(state.live.handle.state?.())! }),

Non-blocking: compute serviceNote(state.live.handle.state?.()) once and reuse it, rather than calling it twice and using !.

98103 ...(state.live.testsFailed === undefined
99104 ? {}
100105 : { error: `serving · tests failed: ${state.live.testsFailed}` }),
src/apps/supervise.ts added +133
@@ -0,0 +1,133 @@
1 /**
2 * Keeping a `service` app up: it has no HTTP page to wait for, so it is
3 * started, and when it ends on its own it is started again after a pause
4 * that doubles each time, up to a minute. A process that stayed up a full
5 * minute starts the count over. Stopping the supervisor stops the process
6 * (its group or cell tree, the handle's own `stop`) and ends the loop.
7 */
8
9 import type { ProcessHandle } from "./process.ts";
10
11 export const BACKOFF_FIRST_MS = 1_000;
12 export const BACKOFF_CAP_MS = 60_000;
13 /** Up this long, a process has earned a fresh count. */
14 export const STABLE_MS = 60_000;
15
16 /** The pause before restart number `restarts` (1 is the first): 1 s, 2 s, 4 s … 60 s. */
17 export function backoffMs(restarts: number): number {
18 const n = Math.max(1, Math.floor(restarts));
19 return Math.min(BACKOFF_CAP_MS, BACKOFF_FIRST_MS * 2 ** Math.min(n - 1, 16));
20 }
21
22 /** What the app page says about a service that is between processes or has been restarted. */
23 export interface ServiceState {
24 /** Restarts since the last stable run. */
25 readonly restarts: number;
26 /** When the next start happens, while waiting for it. */
27 readonly nextAt?: number | undefined;
28 readonly lastExit?: number | undefined;
29 }
30
31 export interface Supervised extends ProcessHandle {
32 state(): ServiceState;
33 }
34
35 export interface SuperviseInput {
36 /** One start of the process; it resolves with a handle, or an error message. */
37 readonly start: () => Promise<{ ok: true; handle: ProcessHandle } | { ok: false; error: string }>;
38 readonly first: ProcessHandle;
39 readonly log: (line: string) => void;
40 readonly now?: () => number;
41 readonly sleep?: (ms: number, wake: Promise<void>) => Promise<void>;
42 readonly stableMs?: number;
43 }
44
45 const napOf = (ms: number, wake: Promise<void>): Promise<void> =>
46 new Promise((resolve) => {
47 const timer = setTimeout(resolve, ms);
48 void wake.then(() => {
49 clearTimeout(timer);
50 resolve();
51 });
52 });
53
54 export function supervise(input: SuperviseInput): Supervised {
55 const now = input.now ?? Date.now;
56 const nap = input.sleep ?? napOf;
57 const stableMs = input.stableMs ?? STABLE_MS;
58 let current: ProcessHandle | undefined = input.first;
59 let restarts = 0;
60 let nextAt: number | undefined;
61 let lastExit: number | undefined;
62 let stopped = false;
63 let wakeNow: () => void = () => {};
64 const woken = new Promise<void>((resolve) => (wakeNow = resolve));
65 let done: (code: number) => void = () => {};
66 const exited = new Promise<number>((resolve) => (done = resolve));
67
68 const loop = async (): Promise<void> => {
69 let handle = input.first;
70 let startedAt = now();
71 for (;;) {
72 lastExit = await handle.exited;
73 current = undefined;
74 if (stopped) break;
75 if (now() - startedAt >= stableMs) restarts = 0;
76 // Pause, then start again; a start that fails is one more restart.
77 for (;;) {
78 restarts += 1;
79 const wait = backoffMs(restarts);
80 nextAt = now() + wait;
81 input.log(`service exited with code ${lastExit}; restart ${restarts} in ${Math.round(wait / 1000)} s`);
82 await nap(wait, woken);
83 nextAt = undefined;
84 if (stopped) break;
85 const started = await input.start();
86 if (stopped) {
87 if (started.ok) await started.handle.stop();
88 break;
89 }
90 if (started.ok) {
91 handle = started.handle;
92 current = handle;
93 startedAt = now();
94 input.log("service restarted");
95 break;
96 }
97 input.log(`service did not start: ${started.error}`);
98 }
99 if (stopped) break;
100 }
101 done(0);
102 };
103 void loop();
104
105 return {
106 get pid() {
107 return current?.pid ?? 0;
108 },
109 get port() {
110 return current?.port ?? input.first.port;
111 },
112 exited,
113 breach: () => current?.breach?.() ?? input.first.breach?.(),
114 state: () => ({ restarts, nextAt, lastExit }),
115 stop: async () => {
116 stopped = true;
117 wakeNow();
118 await current?.stop();
119 await exited;
120 },
121 };
122 }
123
124 /** The line the app page shows for a service that has had to restart. */
125 export function serviceNote(state: ServiceState | undefined, now: number = Date.now()): string | undefined {
126 if (state === undefined || state.restarts === 0) return undefined;
127 const after = state.lastExit === undefined ? "" : ` after exit code ${state.lastExit}`;
128 if (state.nextAt !== undefined) {
129 const s = Math.max(0, Math.ceil((state.nextAt - now) / 1000));
130 return `service restarting in ${s} s${after} (restart ${state.restarts}, pause doubles up to 60 s)`;
131 }
132 return `service restarted ${state.restarts} time${state.restarts === 1 ? "" : "s"}${after}`;
133 }
test/service-run.test.ts added +138
@@ -0,0 +1,138 @@
1 import { expect, test } from "bun:test";
2 import { mkdtempSync, readFileSync, existsSync } from "node:fs";
3 import { tmpdir } from "node:os";
4 import { join } from "node:path";
5 import { startProcess, type ProcessHandle, type StartInput } from "../src/apps/process.ts";
6 import { parseManifest } from "../src/apps/manifest.ts";
7 const until = async (ok: () => boolean): Promise<void> => {
8 for (const end = Date.now() + 10_000; !ok() && Date.now() < end; ) await new Promise((r) => setImmediate(r));
9 if (!ok()) throw new Error("never became true");
10 };
11 import { backoffMs, serviceNote, supervise } from "../src/apps/supervise.ts";
12
13 test("backoff doubles from one second and is capped at sixty", () => {
14 expect([1, 2, 3, 4, 5, 6, 7, 8, 40].map(backoffMs)).toEqual([1000, 2000, 4000, 8000, 16000, 32000, 60000, 60000, 60000]);
15 });
16
17 const fake = (): ProcessHandle & { end(code: number): void; stops: number } => {
18 let end: (code: number) => void = () => {};
19 const exited = new Promise<number>((r) => (end = r));
20 const h = {
21 pid: 1,
22 port: 1,
23 exited,
24 stops: 0,
25 end: (c: number) => end(c),
26 stop: async () => {
27 h.stops += 1;
28 end(0);
29 },
30 };
31 return h;
32 };
33
34 test("a service that exits is started again after the doubling pauses, and says so", async () => {
35 const waits: number[] = [];
36 const handles = [fake(), fake(), fake()];
37 let i = 0;
38 const sup = supervise({
39 first: handles[0]!,
40 log: () => {},
41 start: async () => ({ ok: true, handle: handles[++i]! }),
42 sleep: async (ms) => void waits.push(ms),
43 now: () => 0,
44 });
45 handles[0]!.end(1);
46 await until(() => i === 1);
47 handles[1]!.end(2);
48 await until(() => i === 2);
49 expect(waits).toEqual([1000, 2000]);
50 expect(sup.state().restarts).toBe(2);
51 expect(serviceNote(sup.state())).toContain("restarted 2 times after exit code 2");
52 await sup.stop();
53 expect(handles[2]!.stops).toBe(1);
54 });
55
56 test("a service that stayed up long enough starts the count over", async () => {
57 const waits: number[] = [];
58 let t = 0;
59 const hs = [fake(), fake()];
60 const sup = supervise({
61 first: hs[0]!,
62 log: () => {},
63 start: async () => ({ ok: true, handle: hs[1]! }),
64 sleep: async (ms) => void waits.push(ms),
65 now: () => t,
66 stableMs: 100,
67 });
68 t = 500;
69 hs[0]!.end(1);
70 await until(() => waits.length === 1);
71 expect(waits).toEqual([1000]);
72 expect(sup.state().restarts).toBe(1);
73 await sup.stop();
74 });
75
76 test("stopping during the pause ends it without another start", async () => {
77 const h = fake();
78 let starts = 0;
79 const sup = supervise({ first: h, log: () => {}, start: async () => (starts++, { ok: false, error: "x" }) });
80 h.end(1);
81 await until(() => sup.state().nextAt !== undefined);
82 expect(serviceNote(sup.state())).toContain("restarting in");
83 await sup.stop();
84 expect(starts).toBe(0);
85 expect(await sup.exited).toBe(0);
86 });
87
88 const input = (dir: string, run: string): StartInput => {
89 const m = parseManifest(JSON.stringify({ app: { kind: "service", ports: [25565], run } }), undefined);
90 if (!m.ok) throw new Error("manifest");
91 return {
92 dir,
93 dataDir: dir,
94 env: "production",
95 url: "http://localhost",
96 commitOid: "a".repeat(40),
97 forgeUrl: "http://localhost",
98 identityKey: "k".repeat(32),
99 manifest: m.value,
100 log: () => {},
101 signal: new AbortController().signal,
102 } as unknown as StartInput;
103 };
104
105 test("a service with no HTTP port starts without a health wait, and stop ends it and its children", async () => {
106 const dir = mkdtempSync(join(tmpdir(), "svc-"));
107 // A child that outlives a bare shell exit: the group must take it down.
108 const run = `(sleep 300 & echo $! > child.pid; wait)`;
109 const t0 = Date.now();
110 const started = await startProcess(input(dir, run));
111 expect(started.ok).toBe(true);
112 if (!started.ok) return;
113 expect(Date.now() - t0).toBeLessThan(5000);
114 await until(() => existsSync(join(dir, "child.pid")) && readFileSync(join(dir, "child.pid"), "utf8").endsWith("\n"));
115 const child = Number(readFileSync(join(dir, "child.pid"), "utf8"));
116 expect(() => process.kill(child, 0)).not.toThrow();
117 await started.value.handle.stop();
118 await until(() => {
119 try {
120 process.kill(child, 0);
121 return false;
122 } catch {
123 return true;
124 }
125 });
126 expect(existsSync(dir)).toBe(true);
127 });
128
129 test("a service that crashes is restarted by the real start path", async () => {
130 const dir = mkdtempSync(join(tmpdir(), "svc-"));
131 const started = await startProcess(input(dir, `echo x >> runs; exit 3`));
132 expect(started.ok).toBe(true);
133 if (!started.ok) return;
134 const state = started.value.handle.state!;
135 await until(() => state().restarts >= 1);
136 await until(() => existsSync(join(dir, "runs")) && readFileSync(join(dir, "runs"), "utf8").split("\n").length > 2);
137 await started.value.handle.stop();
138 });
test/timers-named.test.ts +3
@@ -70,6 +70,9 @@ const ALLOWED: readonly Allowed[] = [
7070 ...allow("setInterval", "an adopted cell's identity check: one kill(0) and a pid-file read a second per cell, ended when the cell is gone", [
7171 ["src/spawn/cell.ts", "() => { if (isCell()) return;"],
7272 ]),
73 ...allow("setTimeout", "a service's restart pause: one timer, only resolves a promise, cleared when the app stops", [
74 ["src/apps/supervise.ts", "resolve"],
75 ]),
7376 ...allow("setTimeout", "the boot warm-up's idle wait: one timer, cleared by cancel when the server stops", [
7477 ["src/http/warmup.ts", "() => (timers.delete(timer)"],
7578 ]),

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs