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) #16666

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 3 threads · 3 unresolved

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

Review

Sign in to review this change.
8 files changed +149 −13
docs/features/service-restart.md added +23
@@ -0,0 +1,23 @@
1 ---
2 topic: Your apps
3 row: A service app runs, restarts with backoff and stops with the app
4 ---
5 # A service app runs, restarts with backoff and stops with the app
6
7 This page is for app authors. An app whose `forge.json` declares a `service` has no web page, so the forge starts its `run` and keeps it up. It does not wait for an HTTP answer.
8
9 ## What happens
10
11 - **Start.** The forge starts `run` under the same containment as a web app. It does not wait for a health check, so a deploy is live as soon as the process is started.
12 - **Restart.** When the process exits on its own, the forge starts it again after a pause. The pause is 1 s the first time and doubles with each restart in a row: 1 s, 2 s, 4 s, up to 60 s. A start that fails counts as one more restart.
13 - **Reset.** A process that stays up a full 60 s starts the count over, so the next exit pauses 1 s again.
14 - **Stop.** Stopping or archiving the app stops the process and its children, and ends the restarting. A stop during a pause also ends it.
15
16 ## Where you see it
17
18 After a restart, the app page shows one line under "Deploy and log", and the terminal's Deploys screen shows the same line under the production heading:
19
20 - `service restarting in 4 s after exit code 2 (restart 3, pause doubles up to 60 s)` while it waits
21 - `service restarted 3 times after exit code 2` once it is running again
22
23 Nothing is shown for a service that has never restarted. The deploy's log also records each exit and restart.
src/apps/process.ts +3
@@ -101,6 +101,8 @@ export interface StartInput {
101101 readonly warm?: boolean | undefined;
102102 /** Chooses the app's port; tests hold one open to prove the retry. */
103103 readonly pickPort?: (() => number) | undefined;
104 /** A service's pause before a restart, given its length; tests make it short. */
105 readonly restartPause?: ((ms: number, wake: Promise<void>) => Promise<void>) | undefined;
104106 /**
105107 * The repository's shared bun cache (`checks/install.ts`
106108 * `checkInstallCache`), the one its checks fill (#7544). The forge fills
@@ -871,6 +873,7 @@ export async function startProcess(
871873 const handle = supervise({
872874 first,
873875 log,
876 ...(input.restartPause === undefined ? {} : { sleep: input.restartPause }),
874877 start: async () => {
875878 const again = await launch(pick());
876879 return "error" in again ? { ok: false, error: again.error.message } : { ok: true, handle: again.handle };
src/apps/runtime_status.ts +2 −5
@@ -75,6 +75,7 @@ export function describe(
7575 error: state.lastError,
7676 }
7777 : undefined;
78 const note = swapped ? VERIFYING_NOTE : serviceNote(state.live.handle.state?.());
7879 return {
7980 env: state.env,
8081 state: "running",
@@ -95,11 +96,7 @@ export function describe(
9596 ...(state.live.deployStartedAt === null
9697 ? {}
9798 : { deployStartedAt: state.live.deployStartedAt }),
98 ...(swapped
99 ? { note: VERIFYING_NOTE }
100 : serviceNote(state.live.handle.state?.()) === undefined
101 ? {}
102 : { note: serviceNote(state.live.handle.state?.())! }),
99 ...(note === undefined ? {} : { note }),
outdated

Compute serviceNote(state.live.handle.state?.()) once and spread { note } if defined. As written it runs twice and ends in a ! assertion.

103100 ...(state.live.testsFailed === undefined
104101 ? {}
105102 : { error: `serving · tests failed: ${state.live.testsFailed}` }),
src/apps/supervise.ts +8 −4
@@ -24,11 +24,11 @@ export interface ServiceState {
2424 /** Restarts since the last stable run. */
2525 readonly restarts: number;
2626 /** When the next start happens, while waiting for it. */
27 readonly nextAt?: number | undefined;
28 readonly lastExit?: number | undefined;
27 readonly nextAt?: number;
28 readonly lastExit?: number;
2929 }
3030
31 export interface Supervised extends ProcessHandle {
31 interface Supervised extends ProcessHandle {
3232 state(): ServiceState;
3333 }
3434
@@ -111,7 +111,11 @@ export function supervise(input: SuperviseInput): Supervised {
111111 },
112112 exited,
113113 breach: () => current?.breach?.() ?? input.first.breach?.(),
114 state: () => ({ restarts, nextAt, lastExit }),
114 state: () => ({
115 restarts,
116 ...(nextAt === undefined ? {} : { nextAt }),
117 ...(lastExit === undefined ? {} : { lastExit }),
118 }),
115119 stop: async () => {
116120 stopped = true;
117121 wakeNow();
src/tui/screens/deploys.ts +7 −3
@@ -166,6 +166,8 @@ interface Production {
166166 readonly stop: boolean;
167167 /** Its forge.json sets `app.always_on`: production never sleeps. */
168168 readonly alwaysOn: boolean;
169 /** What the deployment says of itself (a service's restarts), or "". */
170 readonly note: string;
169171 }
170172
171173 /**
@@ -175,7 +177,7 @@ interface Production {
175177 */
176178 function readProduction(f: Session, repo: Repo): Production {
177179 const view = appView(f.app, f.user, repo);
178 if (!view.ok) return { state: "", redeploy: false, stop: false, alwaysOn: false };
180 if (!view.ok) return { state: "", redeploy: false, stop: false, alwaysOn: false, note: "" };
179181 const env = view.value.environments.find((e) => e.env === "production");
180182 const state = env?.state ?? "";
181183 const writer = view.value.serving && f.user !== undefined && canWrite(f.db, repo, f.user);
@@ -184,6 +186,7 @@ function readProduction(f: Session, repo: Repo): Production {
184186 redeploy: writer,
185187 stop: writer && state !== "" && state !== "stopped",
186188 alwaysOn: env?.alwaysOn === true,
189 note: env?.note ?? "",
187190 };
188191 }
189192
@@ -243,7 +246,7 @@ export function deploysScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
243246 const previewState = new ListState();
244247 /** Which list the cursor is in: production's deploys, or the previews under them. */
245248 let inPreviews = false;
246 let production: Production = { state: "", redeploy: false, stop: false, alwaysOn: false };
249 let production: Production = { state: "", redeploy: false, stop: false, alwaysOn: false, note: "" };
247250 let members = false;
248251 // Inviting is the repository admin's (`inviteContributor` decides; this only shows the key).
249252 const mayInvite = (): boolean => f.user !== undefined && f.user.kind === "user" && canAdmin(f.db, repo, f.user);
@@ -469,6 +472,7 @@ export function deploysScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
469472 (pace === "" ? 0 : 1) +
470473 side.length +
471474 (onboarding === "" ? 0 : 1) +
475 (production.note === "" ? 0 : 1) +
472476 egress.length +
473477 (named === "" ? 0 : 1),
474478 ),
@@ -499,7 +503,7 @@ export function deploysScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
499503 style(c.mutedFg, c.bg),
500504 head!.x + head!.w,
501505 );
502 [onboarding, visitors, trend, pace, ...side, named, ...egress]
506 [onboarding, production.note, visitors, trend, pace, ...side, named, ...egress]
503507 .filter((line) => line !== "")
504508 .forEach((line, i) =>
505509 s.text(head!.x, head!.y + 1 + i, truncate(line, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w),
test/service-note-page.test.ts added +34
@@ -0,0 +1,34 @@
1 import { expect, test } from "bun:test";
2 import { describe } from "../src/apps/runtime_status.ts";
3 import type { AppsRuntime } from "../src/apps/runtime.ts";
4 import type { Environment } from "../src/apps/runtime_env.ts";
5 import type { ServiceState } from "../src/apps/supervise.ts";
6 import { envFacts } from "../src/web/ui.ts";
7
8 const status = (svc: ServiceState | undefined) => {
9 const rt = { urlFor: () => "https://x.test" } as unknown as AppsRuntime;
10 const live = {
11 commitOid: "a".repeat(40),
12 runId: "r1",
13 since: 1,
14 servingAt: 1,
15 createdAt: 1,
16 deployStartedAt: null,
17 manifest: {},
18 handle: { pid: 1, port: 1, state: svc === undefined ? undefined : () => svc },
19 };
20 return describe(rt, { env: "production", app: {}, live } as unknown as Environment);
21 };
22
23 test("the app page says a service restarted, and that the pause doubles up to 60 s", () => {
24 const waiting = String(envFacts("/a/b", status({ restarts: 3, nextAt: Date.now() + 4000, lastExit: 2 })));
25 expect(waiting).toContain("service restarting in");
26 expect(waiting).toContain("after exit code 2");
27 expect(waiting).toContain("pause doubles up to 60 s");
28 expect(String(envFacts("/a/b", status({ restarts: 1 })))).toContain("service restarted 1 time");
29 });
30
31 test("a service that never restarted, and a web app, show no restart note", () => {
32 expect(status({ restarts: 0 }).note).toBeUndefined();
33 expect(status(undefined).note).toBeUndefined();
34 });
test/service-run.test.ts +1 −1
@@ -128,7 +128,7 @@ test("a service with no HTTP port starts without a health wait, and stop ends it
128128
129129 test("a service that crashes is restarted by the real start path", async () => {
130130 const dir = mkdtempSync(join(tmpdir(), "svc-"));
131 const started = await startProcess(input(dir, `echo x >> runs; exit 3`));
131 const started = await startProcess({ ...input(dir, `echo x >> runs; exit 3`), restartPause: () => new Promise((r) => setImmediate(r)) });
132132 expect(started.ok).toBe(true);
133133 if (!started.ok) return;
134134 const state = started.value.handle.state!;
test/tui-deploys-service-note.test.ts added +71
@@ -0,0 +1,71 @@
1 /** The deploys screen says a service is restarting, in the app page's words. */
2 import { afterAll, beforeAll, expect, test } from "bun:test";
3 import { mkdtemp, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { createRepo } from "../src/actions/repos.ts";
7 import { createApp, type App as Forge } from "../src/app.ts";
8 import { AppsRuntime } from "../src/apps/runtime.ts";
9 import { createApp as createAppRecord } from "../src/core/apps.ts";
10 import type { Repo } from "../src/core/repos.ts";
11 import type { User } from "../src/core/users.ts";
12 import { createForgeApp } from "../src/tui/forge.ts";
13 import { deploysScreen } from "../src/tui/screens/deploys.ts";
14 import { headlessTerminal } from "../src/tui/term/terminal.ts";
15 import { quietLogs } from "./helpers/globals.ts";
16 import { settleApp } from "./helpers/tui.ts";
17 import { seedAdmin } from "./helpers/admin.ts";
18
19 quietLogs();
20
21 let dir: string;
22 let forge: Forge;
23 let alice: User;
24 let repo: Repo;
25 let runtime: AppsRuntime;
26 let note: string | undefined;
27
28 beforeAll(async () => {
29 dir = await mkdtemp(join(tmpdir(), "forge-tui-service-note-"));
30 forge = createApp({ dataDir: dir, port: 0 });
31 const a = await seedAdmin(forge, { username: "alice", email: "[email protected]", password: "a-long-passphrase" });
32 if (!a.ok) throw new Error("signup failed");
33 alice = a.value;
34 const r = await createRepo(forge, alice, { name: "worker", visibility: "public" });
35 if (!r.ok) throw new Error("repo failed");
36 repo = r.value;
37 const made = createAppRecord(forge.db, { repoId: repo.id, slug: "worker", access: "public" });
38 if (!made.ok) throw new Error(made.error);
39 runtime = new AppsRuntime(forge, { domain: "apps.test", scheme: "https", forgeUrl: "https://forge.test", concurrency: 1 });
40 runtime.status = (() => [
41 { env: "production", state: "running", ...(note === undefined ? {} : { note }) },
42 ]) as unknown as typeof runtime.status;
43 });
44
45 afterAll(async () => {
46 await runtime?.stop();
47 forge?.close?.();
48 await rm(dir, { recursive: true, force: true });
49 });
50
51 const frame = async (): Promise<string> => {
52 const { app, session } = createForgeApp(
53 forge,
54 { sshUsername: alice.username, remoteAddress: "127.0.0.1", user: alice },
55 { terminal: headlessTerminal(200, 40), exitHooks: false },
56 );
57 app.start();
58 await settleApp(app);
59 app.push(deploysScreen(session, app.ctx, repo));
60 await settleApp(app);
61 const text = app.screen.toText();
62 app.stop();
63 return text;
64 };
65
66 test("the terminal shows a service's restart note, and nothing when there is none", async () => {
67 note = undefined;
68 expect(await frame()).not.toContain("service restart");
69 note = "service restarted 2 times after exit code 2";
70 expect(await frame()).toContain("service restarted 2 times after exit code 2");
71 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs