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
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/14231-a-service-app-runs-its-process-starts-st → main 0 commits fork 1 thread · 1 unresolved
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 | ||
| 2046 | 2046 | refused), `placement` (`"metal"` or `"cloud"`, optional) and `volumes` |
| 2047 | 2047 | (`{ "path": "world", "sync": 300 }`, a relative path under the app's data and a |
| 2048 | 2048 | 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). | |
| 2051 | 2056 | |
| 2052 | 2057 | ## The access log |
| 2053 | 2058 |
src/apps/process.ts +20 −1
| @@ -26,6 +26,7 @@ import { endedLine, liveTree } from "../runs/ended.ts"; | ||
| 26 | 26 | import { CANCEL_GRACE_MS, graceKillLine } from "../runs/grace.ts"; |
| 27 | 27 | import { spellings, stripForgeDirs } from "../runs/paths.ts"; |
| 28 | 28 | import { seconds } from "./timing.ts"; |
| 29 | import { supervise } from "./supervise.ts"; | |
| 29 | 30 | import { toolchainUse, type ToolchainUse } from "./toolchain.ts"; |
| 30 | 31 | import { notFoundHint, shellCommand } from "./run_command.ts"; |
| 31 | 32 | import { floorRefusal } from "../spawn/disk_floor.ts"; |
| @@ -56,6 +57,8 @@ export interface ProcessHandle { | ||
| 56 | 57 | stop(): Promise<void>; |
| 57 | 58 | /** The cell limit it broke, once it has ended over one (`Cell.breach`). */ |
| 58 | 59 | breach?: () => string | undefined; |
| 60 | /** A service's restart count and pause (`apps/supervise.ts`). */ | |
| 61 | state?: () => import("./supervise.ts").ServiceState; | |
| 59 | 62 | } |
| 60 | 63 | |
| 61 | 64 | export interface StartInput { |
| @@ -828,6 +831,9 @@ export async function startProcess( | ||
| 828 | 831 | }, |
| 829 | 832 | }; |
| 830 | 833 | |
| 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 }; | |
| 831 | 837 | const ready = await waitUntilReady({ |
| 832 | 838 | port, |
| 833 | 839 | path: manifest.health, |
| @@ -859,7 +865,20 @@ export async function startProcess( | ||
| 859 | 865 | await tested.catch(() => {}); |
| 860 | 866 | return err(launched.error); |
| 861 | 867 | } |
| 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; | |
| 863 | 882 | log(`ready: ${input.url}`); |
| 864 | 883 | // How the process's own share of the start divides: the time until it |
| 865 | 884 | // 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( | ||
| 184 | 184 | }; |
| 185 | 185 | } |
| 186 | 186 | // 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; | |
| 188 | 188 | if (fault !== undefined) { |
| 189 | 189 | await started.value.handle.stop(); |
| 190 | 190 | revokeAppToken(rt.app.db, token.id); |
src/apps/runtime_status.ts +6 −1
| @@ -5,6 +5,7 @@ | ||
| 5 | 5 | */ |
| 6 | 6 | |
| 7 | 7 | import { cellHides, grantsHere } from "../spawn/hosted-mark.ts"; |
| 8 | import { serviceNote } from "./supervise.ts"; | |
| 8 | 9 | import { VERIFYING_NOTE } from "./env_phrase.ts"; |
| 9 | 10 | import { join } from "node:path"; |
| 10 | 11 | import type { AppRecord } from "../core/apps.ts"; |
| @@ -94,7 +95,11 @@ export function describe( | ||
| 94 | 95 | ...(state.live.deployStartedAt === null |
| 95 | 96 | ? {} |
| 96 | 97 | : { 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?.())! }), | |
| 98 | 103 | ...(state.live.testsFailed === undefined |
| 99 | 104 | ? {} |
| 100 | 105 | : { 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[] = [ | ||
| 70 | 70 | ...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", [ |
| 71 | 71 | ["src/spawn/cell.ts", "() => { if (isCell()) return;"], |
| 72 | 72 | ]), |
| 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 | ]), | |
| 73 | 76 | ...allow("setTimeout", "the boot warm-up's idle wait: one timer, cleared by cancel when the server stops", [ |
| 74 | 77 | ["src/http/warmup.ts", "() => (timers.delete(timer)"], |
| 75 | 78 | ]), |
new above
offline
Non-blocking: compute
serviceNote(state.live.handle.state?.())once and reuse it, rather than calling it twice and using!.