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

A long-running services kind: declared ports, always on, placed on the owner's hardware, for a Minecraft network and its websites #1451

Closed opened this in answer to
Closed without merging

scout/forge:scout/1118-a-long-running-services-kind-declared-po → main 4 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
15 files changed +648 −25
README.md +14
@@ -273,6 +273,20 @@ environment. Browsers resolve `*.localhost` to loopback, so a laptop forge
273273 needs no DNS at all; elsewhere point a wildcard at it and set
274274 `FORGE_APP_DOMAIN`.
275275
276 A long-running thing that is not a web app — a Minecraft server — says
277 `"kind": "service"` under `app` in `forge.json`, with `ports` (TCP, 1024–65535),
278 and optionally `placement` (a node label this node must carry, from
279 `FORGE_NODE_LABELS`), `health_command` and `limits`. Production publishes
280 those ports on every address of the host, relayed byte for byte, and is never
281 put to sleep; a preview runs with its ports unpublished. A deploy is refused,
282 in a sentence, for a port the forge itself, its terminal
283 (`FORGE_SSH_PORT`), the operator (`FORGE_RESERVED_PORTS`) or another app's
284 service holds, for the range apps are handed ports from (32768 and up), for a
285 placement the node lacks, and for udp, which is not relayed yet. The app page
286 shows the service's placement, ports and whether they are published, and
287 `ssh` into it says the same instead of opening a terminal
288 ([docs/APPS.md](docs/APPS.md#the-service-kind)).
289
276290 With a sentence and **Pick for me**, the sentence becomes a plan before the
277291 page comes back: `src/crew/plan.ts` makes one non-interactive call to
278292 `claude` — the quickest model, a fixed JSON shape, at most 3 seconds — for a
docs/APPS.md +37 −6
@@ -1080,9 +1080,40 @@ as one column carried a domain of the app's own.
10801080 ## The `service` kind
10811081
10821082 `app.kind: "service"` in `forge.json` declares a long-running app that is not
1083 an HTTP child: `ports` (TCP, 1024–65535, required), `always_on` (true; false is
1084 refused), `placement` (`"metal"` or `"cloud"`, optional) and `volumes`
1085 (`{ "path": "world", "sync": 300 }`, a relative path under the app's data and a
1086 sync cadence in seconds, 10–86400). `src/apps/service.ts` validates it; the
1087 manifest carries it as `service`, `null` for a web app. Running it, exposing
1088 the ports and syncing volumes are not built yet (issue #391).
1083 an HTTP child, a game server for one:
1084
1085 ```json
1086 { "app": { "kind": "service", "run": "java -jar paper.jar nogui",
1087 "ports": [25565, 25566], "placement": "vxrail",
1088 "health_command": "nc -z 127.0.0.1 25565",
1089 "volumes": [{ "path": "world", "sync": 300 }],
1090 "limits": { "memory": 6144, "cpus": 4 } } }
1091 ```
1092
1093 - `ports`: required, 1–8 entries, 1024–65535. A bare number is TCP;
1094 `"25565/tcp"` or `{ "port": 25565 }` say the same. A udp port
1095 (`"19132/udp"`) is refused when the manifest is read, with the reason.
1096 A port the forge, its terminal (`FORGE_SSH_PORT`), `FORGE_RESERVED_PORTS`, a
1097 common host service (3306, 5432, 6379, 8080, …) or another app's production
1098 service holds, or one at 32768 and up, fails the deploy with a sentence.
1099 - `always_on`: true; false is refused. The sweep never puts a service to sleep.
1100 - `placement`: a node label. A node carries the labels in `FORGE_NODE_LABELS`
1101 (`metal,vxrail`); a service whose label the node lacks fails its deploy with
1102 that sentence in the log, rather than starting on the wrong body.
1103 - `limits`: the same `app.limits` every app has.
1104 - `health_command`: one line that exits 0 while the service is well. It runs
1105 in its own cell, reaching the service's published ports on `127.0.0.1`
1106 (`FORGE_SERVICE_PORTS` lists them); the deploy is ready when it succeeds,
1107 or fails after `ready` seconds (the last attempt is cut at that budget). Without it, a service that stays up a
1108 moment is ready.
1109 - `volumes`: relative paths under the app's data and a sync cadence.
1110
1111 In the cell, the production environment's TCP ports are published on every
1112 address of the host, relayed byte for byte (`publish` in `apps/contain.ts`),
1113 never proxied, and the forge does not relay HTTP to a service. A preview of a
1114 service runs without publishing: the ports are the host's, and production holds
1115 them.
1116
1117 Not built yet: relaying UDP (refused at parse), syncing volumes (issue #391), a companion app reaching a
1118 service by name (cells refuse private addresses; this needs a declared
1119 `uses`), and scheduling across nodes (the label is checked, not chosen).
src/apps/contain.ts +16 −1
@@ -101,6 +101,12 @@ export interface CellSpec {
101101 readonly limits: Limits;
102102 /** The port an app listens on; the forge relays `127.0.0.1:<port>` in. */
103103 readonly listen?: number | undefined;
104 /**
105 * TCP ports a service listens on inside the cell, published on every
106 * address of the host — relayed, never proxied, so a game client speaks
107 * its own protocol to the process.
108 */
109 readonly publish?: readonly number[] | undefined;
104110 /** Keep the controlling terminal (an app's `tty`). */
105111 readonly terminal?: boolean | undefined;
106112 /** Told of every undeclared host let through while egress is only reported. */
@@ -232,7 +238,8 @@ const INSIDE = "/run/forge";
232238 * the cell's init and never to the command — whose children are how the
233239 * forge tells a busy app from an idle one (`apps/busy.ts`).
234240 */
235 const WRAPPER = `s=${INSIDE}; listen=$1; shift; loops=$1; shift
241 const WRAPPER = `s=${INSIDE}; listen=$1; shift; loops=$1; shift; pubs=$1; shift
242 for p in $pubs; do (socat UNIX-LISTEN:$s/pub-$p.sock,fork,unlink-early TCP:127.0.0.1:$p >/dev/null 2>&1 &); done
236243 (socat TCP-LISTEN:${PROXY_PORT},bind=127.0.0.1,fork,reuseaddr UNIX-CONNECT:$s/out.sock >/dev/null 2>&1 &)
237244 for p in $loops; do (socat TCP-LISTEN:$p,bind=127.0.0.1,fork,reuseaddr UNIX-CONNECT:$s/loop-$p.sock >/dev/null 2>&1 &); done
238245 [ "$listen" = - ] || (socat UNIX-LISTEN:$s/in.sock,fork,unlink-early TCP:127.0.0.1:$listen >/dev/null 2>&1 &)
@@ -279,6 +286,13 @@ export function openCell(
279286 opened.push(
280287 relay({ unix: join(sockets, `loop-${port}.sock`) }, { tcp: port }),
281288 );
289 for (const port of new Set(spec.publish ?? []))
290 opened.push(
291 relay(
292 { tcp: port, host: "0.0.0.0" },
293 { unix: join(sockets, `pub-${port}.sock`) },
294 ),
295 );
282296 if (spec.listen !== undefined)
283297 opened.push(
284298 relay({ tcp: spec.listen }, { unix: join(sockets, "in.sock") }),
@@ -337,6 +351,7 @@ export function openCell(
337351 "cell",
338352 spec.listen === undefined ? "-" : String(spec.listen),
339353 [...new Set(loops)].join(" "),
354 [...new Set(spec.publish ?? [])].join(" "),
340355 "/bin/sh",
341356 "-c",
342357 command,
src/apps/egress.ts +2 −2
@@ -369,7 +369,7 @@ export function startEgress(
369369 * forge's own loopback port from inside one.
370370 */
371371 export function relay(
372 listen: { tcp: number } | { unix: string },
372 listen: { tcp: number; host?: string } | { unix: string },
373373 target: { unix: string } | { tcp: number },
374374 ): Egress {
375375 interface Pair {
@@ -452,7 +452,7 @@ export function relay(
452452 "unix" in listen
453453 ? Bun.listen<Pair>({ unix: listen.unix, socket: handlers })
454454 : Bun.listen<Pair>({
455 hostname: "127.0.0.1",
455 hostname: listen.host ?? "127.0.0.1",
456456 port: listen.tcp,
457457 socket: handlers,
458458 });
src/apps/placement.ts added +28
@@ -0,0 +1,28 @@
1 /**
2 * Where a service may run: the labels this node carries
3 * (`FORGE_NODE_LABELS`, comma separated; `FORGE_NODE_LABELS=metal,vxrail`)
4 * against the one label the service asks for (`app.placement`). A forge
5 * with no labels set carries none, so a service that names a placement is
6 * refused there rather than started on a body it did not ask for.
7 */
8
9 import type { ServiceSpec } from "./service.ts";
10
11 export function nodeLabels(
12 env: Record<string, string | undefined> = process.env,
13 ): string[] {
14 return (env["FORGE_NODE_LABELS"] ?? "")
15 .split(",")
16 .map((label) => label.trim().toLowerCase())
17 .filter((label) => label !== "");
18 }
19
20 /** `undefined` when the service fits here, else why it does not. */
21 export function placementProblem(
22 service: ServiceSpec,
23 labels: readonly string[] = nodeLabels(),
24 ): string | undefined {
25 if (service.placement === null || labels.includes(service.placement))
26 return undefined;
27 return `placement "${service.placement}" wants a node with that label; this node carries ${labels.length === 0 ? "none (FORGE_NODE_LABELS is unset)" : labels.join(", ")}`;
28 }
src/apps/ports.ts added +49
@@ -0,0 +1,49 @@
1 /**
2 * Which host ports a service may publish. A port is the host's, not the
3 * app's, so a manifest cannot take what the forge itself listens on, the
4 * range apps are handed their own ports from, or what another app's service
5 * already holds.
6 */
7
8 /** Ports the host's own daemons use by convention, refused to every manifest. */
9 const COMMON = [3306, 5432, 6379, 8080, 8443, 9090, 9100, 10250, 27017];
10 /** Linux hands outgoing connections and `freePort()` from here up. */
11 const EPHEMERAL_FROM = 32768;
12
13 /** Port -> who holds it, for every port a manifest may not publish. */
14 export function reservedPorts(
15 env: Record<string, string | undefined> = process.env,
16 ): Map<number, string> {
17 const out = new Map<number, string>();
18 for (const port of COMMON) out.set(port, "a common host service");
19 const number = (value: string | undefined, fallback: number): number =>
20 value === undefined || value.trim() === "" ? fallback : Number(value);
21 out.set(number(env["PORT"], 3000), "the forge's own listener");
22 const ssh = number(env["FORGE_SSH_PORT"], 2222);
23 if (ssh > 0) out.set(ssh, "the forge's terminal");
24 for (const raw of (env["FORGE_RESERVED_PORTS"] ?? "").split(",")) {
25 const port = Number(raw.trim());
26 if (Number.isInteger(port) && port > 0)
27 out.set(port, "reserved by the operator");
28 }
29 return out;
30 }
31
32 /** `undefined` when every port is free to publish, else a plain sentence. */
33 export function publishProblem(
34 ports: readonly number[],
35 reserved: ReadonlyMap<number, string>,
36 held: ReadonlyMap<number, string>,
37 ): string | undefined {
38 for (const port of ports) {
39 if (port >= EPHEMERAL_FROM)
40 return `port ${port} is in the range the forge hands to apps (${EPHEMERAL_FROM} and up); choose a lower one`;
41 const by = reserved.get(port);
42 if (by !== undefined)
43 return `port ${port} is not available to publish: it belongs to ${by}`;
44 const other = held.get(port);
45 if (other !== undefined)
46 return `port ${port} is already published by ${other}'s service; choose another`;
47 }
48 return undefined;
49 }
src/apps/process.ts +104 −8
@@ -18,6 +18,7 @@ import { isReservedAppEnvName } from "../core/app_env.ts";
1818 import { err, ok, type Result } from "../kernel/result.ts";
1919 import { spellings, stripForgeDirs } from "../runs/paths.ts";
2020 import { seconds } from "./timing.ts";
21 import { placementProblem } from "./placement.ts";
2122 import {
2223 commandPid,
2324 killTree,
@@ -332,6 +333,16 @@ export async function startProcess(
332333 input: StartInput,
333334 ): Promise<Result<StartedProcess, StartError>> {
334335 const { manifest, log } = input;
336 const service = manifest.service;
337 if (service !== null) {
338 const problem = placementProblem(service);
339 if (problem !== undefined) return err({ stage: "start", message: problem });
340 }
341 // Ports are the host's: one environment holds them, the production one.
342 const publish =
343 service !== null && input.env === "production"
344 ? service.ports.map((p) => p.port)
345 : undefined;
335346 const stepEnv = childEnv({
336347 CI: "1",
337348 FORGE_APP_ENV: input.env === "production" ? "production" : "preview",
@@ -387,7 +398,9 @@ export async function startProcess(
387398 egress: manifest.egress ?? [],
388399 reach: [input.forgeUrl],
389400 limits: resolveLimits("app", manifest.limits),
390 listen: port,
401 // A service is reached on its own ports, never through the proxy.
402 listen: service === null ? port : undefined,
403 publish,
391404 onUndeclared: input.cell.onUndeclared,
392405 egressMode: input.cell.egressMode,
393406 },
@@ -458,13 +471,25 @@ export async function startProcess(
458471 },
459472 };
460473
461 const ready = await waitUntilReady({
462 port,
463 path: manifest.health,
464 timeoutMs: manifest.ready * 1000,
465 exited: proc.exited,
466 signal: input.signal,
467 });
474 const ready =
475 service === null
476 ? await waitUntilReady({
477 port,
478 path: manifest.health,
479 timeoutMs: manifest.ready * 1000,
480 exited: proc.exited,
481 signal: input.signal,
482 })
483 : await waitUntilServiceReady({
484 command: publish === undefined ? null : service.healthCommand,
485 spec: stepCell(input),
486 ports: publish ?? [],
487 env: { ...stepEnv, FORGE_SERVICE_PORTS: (publish ?? []).join(",") },
488 log,
489 timeoutMs: manifest.ready * 1000,
490 exited: proc.exited,
491 signal: input.signal,
492 });
468493 if (!ready.ok) {
469494 await handle.stop();
470495 // The app never came up: the test step running beside it has nothing
@@ -487,6 +512,77 @@ export async function startProcess(
487512 return ok({ handle, tested });
488513 }
489514
515 /**
516 * A service is ready when its health command exits 0, run in a cell that
517 * reaches the service's published ports on 127.0.0.1 (`FORGE_SERVICE_PORTS`
518 * names them). With no command — or in a preview, which publishes nothing —
519 * it is ready once it has stayed up for a moment.
520 */
521 export async function waitUntilServiceReady(input: {
522 command: string | null;
523 spec: CellSpec | undefined;
524 ports: readonly number[];
525 env: Record<string, string>;
526 log: (line: string) => void;
527 timeoutMs: number;
528 exited: Promise<number>;
529 signal: AbortSignal;
530 }): Promise<Result<void, StartError>> {
531 const deadline = Date.now() + input.timeoutMs;
532 let exitCode: number | undefined;
533 void input.exited.then((code) => {
534 exitCode = code;
535 });
536 const down = (): Result<void, StartError> | undefined => {
537 if (input.signal.aborted)
538 return err({ stage: "start", message: "cancelled" });
539 if (exitCode !== undefined)
540 return err({
541 stage: "start",
542 message: `exited with code ${exitCode} before it was well`,
543 });
544 return undefined;
545 };
546 if (input.command === null) {
547 await Bun.sleep(SERVICE_SETTLE_MS);
548 return down() ?? ok();
549 }
550 const cell =
551 input.spec === undefined
552 ? undefined
553 : {
554 ...input.spec,
555 reach: [
556 ...input.spec.reach,
557 ...input.ports.map((p) => `http://127.0.0.1:${p}`),
558 ],
559 };
560 let last = "";
561 while (Date.now() < deadline) {
562 const gone = down();
563 if (gone !== undefined) return gone;
564 const tried = await runStep("health", input.command, {
565 cwd: input.spec?.dir ?? ".",
566 env: input.env,
567 log: () => {},
568 signal: input.signal,
569 // Never past the ready budget: the last attempt is cut short, not run on.
570 timeoutMs: Math.max(1, Math.min(HEALTH_ATTEMPT_MS, deadline - Date.now())),
571 cell,
572 });
573 if (tried.ok) return ok();
574 last = tried.error;
575 await Bun.sleep(HEALTH_INTERVAL_MS);
576 }
577 return err({
578 stage: "ready",
579 message: `health command did not succeed within ${Math.round(input.timeoutMs / 1000)}s — ${last}`,
580 });
581 }
582
583 const SERVICE_SETTLE_MS = 1_500;
584 const HEALTH_ATTEMPT_MS = 10_000;
585
490586 /**
491587 * Poll the health path until the app answers. Any HTTP answer below 500
492588 * counts — a 404 on `/` is an app that is up and has no root page — and an
src/apps/runtime.ts +53
@@ -13,6 +13,8 @@
1313 * commit, once.
1414 */
1515
16 import { publishProblem, reservedPorts } from "./ports.ts";
17 import { mayIdle, type ServiceSpec } from "./service.ts";
1618 import { pullDir, runDir } from "../core/pulls.ts";
1719 import { accountActive } from "../core/accounts.ts";
1820 import { sshCommand } from "../ssh/command.ts";
@@ -154,6 +156,29 @@ const BUSY_GRACE_MS = 45 * 60_000;
154156 * the studio reads the same constant to word its badge. */
155157 export const VERIFYING_NOTE = "serving — still verifying its tests";
156158
159 /** What a service environment shows: its ports, where it runs, whether they are published. */
160 export interface ServiceStatus {
161 readonly ports: readonly number[];
162 readonly placement: string | null;
163 /** Only production publishes; a preview runs with its ports unpublished. */
164 readonly published: boolean;
165 }
166
167 function serviceOf(
168 manifest: { readonly service: ServiceSpec | null },
169 env: EnvName,
170 ): { service?: ServiceStatus } {
171 const s = manifest.service;
172 if (s === null) return {};
173 return {
174 service: {
175 ports: s.ports.map((p) => p.port),
176 placement: s.placement,
177 published: env === "production",
178 },
179 };
180 }
181
157182 export interface EnvStatus {
158183 readonly env: EnvName;
159184 readonly state: EnvState;
@@ -161,6 +186,8 @@ export interface EnvStatus {
161186 readonly commitOid: string;
162187 readonly url: string;
163188 readonly port?: number | undefined;
189 /** Set for a `service` kind: its published ports and placement. */
190 readonly service?: ServiceStatus | undefined;
164191 /** The run that produced this state — a link to its log. */
165192 readonly runId?: string | undefined;
166193 readonly since?: string | undefined;
@@ -454,6 +481,18 @@ export class AppsRuntime {
454481 );
455482 }
456483
484 /** Port -> app slug, for every port another app's live service publishes. */
485 private heldServicePorts(except: string): Map<number, string> {
486 const held = new Map<number, string>();
487 for (const other of this.envs.values()) {
488 const service = other.live?.manifest.service;
489 if (other.env !== "production" || other.app.id === except || !service)
490 continue;
491 for (const p of service.ports) held.set(p.port, other.app.slug);
492 }
493 return held;
494 }
495
457496 private describe(state: Environment): EnvStatus {
458497 const url = this.urlFor(state.app, state.env);
459498 // Once a deploy's own commit has answered and swapped in, it is
@@ -514,6 +553,7 @@ export class AppsRuntime {
514553 createdAt: state.live.createdAt,
515554 tty: state.live.manifest.tty,
516555 looks: state.live.manifest.looks,
556 ...serviceOf(state.live.manifest, state.env),
517557 ...(state.live.deployStartedAt === null
518558 ? {}
519559 : { deployStartedAt: state.live.deployStartedAt }),
@@ -1152,6 +1192,17 @@ export class AppsRuntime {
11521192 : manifest.error.message,
11531193 };
11541194 }
1195 // Ports are the host's: refuse a claim on one that is not free, before
1196 // any work is spent on the checkout.
1197 const service = manifest.value.service;
1198 if (service !== null && state.env === "production") {
1199 const problem = publishProblem(
1200 service.ports.map((p) => p.port),
1201 reservedPorts(),
1202 this.heldServicePorts(state.app.id),
1203 );
1204 if (problem !== undefined) return { ok: false, error: problem };
1205 }
11551206 const dir = join(
11561207 envDir(this.app.config.dataDir, state.app.id, state.env),
11571208 run.commitOid.slice(0, 7),
@@ -1712,6 +1763,8 @@ export class AppsRuntime {
17121763 state.keptAwake = undefined;
17131764 if (
17141765 live === undefined ||
1766 // A service is always on: nothing asks it for pages to keep it awake.
1767 !mayIdle(live.manifest) ||
17151768 state.deploying !== undefined ||
17161769 state.queued !== undefined ||
17171770 state.waking !== undefined
src/apps/service.ts +54 −5
@@ -8,7 +8,8 @@
88
99 import { err, ok, type Result } from "../kernel/result.ts";
1010
11 export type Placement = "metal" | "cloud";
11 /** A node label (`metal`, `vxrail`, `eu-west`): the node it runs on must carry it. */
12 export type Placement = string;
1213
1314 export interface ServicePort {
1415 readonly port: number;
@@ -29,8 +30,17 @@ export interface ServiceSpec {
2930 /** Where it would rather run; `null` leaves it to the forge. */
3031 readonly placement: Placement | null;
3132 readonly volumes: readonly ServiceVolume[];
33 /**
34 * A command that exits 0 while the service is well, run in a cell that
35 * reaches the service's own published ports on 127.0.0.1. `null`: up
36 * means the process is still running.
37 */
38 readonly healthCommand: string | null;
3239 }
3340
41 const LABEL_RE = /^[a-z0-9]([a-z0-9._-]{0,38}[a-z0-9])?$/;
42 const HEALTH_MAX = 1_000;
43
3444 const PORTS_MAX = 8;
3545 const VOLUMES_MAX = 8;
3646 const PATH_MAX = 200;
@@ -52,12 +62,31 @@ export function parseService(app: Json): Result<ServiceSpec, { message: string }
5262 if (rawPorts.length > PORTS_MAX)
5363 return invalid(`app.ports may name at most ${PORTS_MAX} ports`);
5464 const ports: ServicePort[] = [];
55 for (const p of rawPorts) {
65 for (const raw of rawPorts) {
66 // 25565 (tcp), "25565/udp", or { port, protocol }.
67 let p: unknown = raw;
68 let protocol: unknown = "tcp";
69 if (typeof raw === "string") {
70 const m = /^(\d{1,5})\/(tcp|udp)$/.exec(raw);
71 if (m === null)
72 return invalid('app.ports strings must look like "19132/udp"');
73 p = Number(m[1]);
74 protocol = m[2];
75 } else if (isObject(raw)) {
76 p = raw["port"];
77 protocol = raw["protocol"] ?? "tcp";
78 }
5679 if (typeof p !== "number" || !Number.isInteger(p) || p < 1024 || p > 65535)
5780 return invalid("app.ports entries must be whole numbers, 1024–65535");
81 if (protocol === "udp")
82 return invalid(
83 `app.ports names ${p}/udp, but the forge cannot relay udp yet; only tcp ports can be published`,
84 );
85 if (protocol !== "tcp")
86 return invalid('app.ports protocol must be "tcp"');
5887 if (ports.some((q) => q.port === p))
5988 return invalid(`app.ports names ${p} twice`);
60 ports.push({ port: p, protocol: "tcp" });
89 ports.push({ port: p, protocol });
6190 }
6291
6392 const alwaysOn = app["always_on"];
@@ -67,8 +96,22 @@ export function parseService(app: Json): Result<ServiceSpec, { message: string }
6796 return invalid("app.always_on cannot be false for a service");
6897
6998 const placement = app["placement"];
70 if (placement !== undefined && placement !== "metal" && placement !== "cloud")
71 return invalid('app.placement must be "metal" or "cloud"');
99 if (
100 placement !== undefined &&
101 (typeof placement !== "string" || !LABEL_RE.test(placement))
102 )
103 return invalid(
104 "app.placement must be a node label: lowercase letters, digits, . _ -",
105 );
106 const health = app["health_command"];
107 if (
108 health !== undefined &&
109 (typeof health !== "string" ||
110 health.trim() === "" ||
111 health.length > HEALTH_MAX ||
112 /[\0\n]/.test(health))
113 )
114 return invalid("app.health_command must be one line of at most 1000 characters");
72115
73116 const rawVolumes = app["volumes"] ?? [];
74117 if (!Array.isArray(rawVolumes))
@@ -110,5 +153,11 @@ export function parseService(app: Json): Result<ServiceSpec, { message: string }
110153 alwaysOn: true,
111154 placement: placement ?? null,
112155 volumes,
156 healthCommand: health === undefined ? null : health.trim(),
113157 });
114158 }
159
160 /** A service is always on: only a web app is ever put to sleep. */
161 export function mayIdle(manifest: { readonly service: ServiceSpec | null }): boolean {
162 return manifest.service === null;
163 }
src/apps/service_line.ts added +13
@@ -0,0 +1,13 @@
1 /**
2 * A service in words: the one sentence the app page and the terminal both
3 * say, so neither knows less than the other.
4 */
5
6 import type { ServiceStatus } from "./runtime.ts";
7
8 export function serviceLine(service: ServiceStatus): string {
9 const ports = service.ports.map((p) => `${p}/tcp`).join(", ");
10 const where =
11 service.placement === null ? "any node" : `node "${service.placement}"`;
12 return `service on ${where} · ports ${ports} ${service.published ? "published" : "not published (a preview never takes the host's ports)"} · always on`;
13 }
src/apps/tty.ts +11 −2
@@ -18,6 +18,7 @@
1818 * one.
1919 */
2020
21 import { serviceLine } from "./service_line.ts";
2122 import { killTree, openCell } from "./contain.ts";
2223 import type { App as Forge } from "../app.ts";
2324 import { getAppBySlug, type AppRecord } from "../core/apps.ts";
@@ -97,7 +98,9 @@ export function ttyRefusalText(
9798 case "private":
9899 return `${name} is private: sign in to the forge first, so your key is known`;
99100 case "no_tty":
100 return `${name} has no terminal interface — give it one with "tty" in forge.json`;
101 return detail === ""
102 ? `${name} has no terminal interface — give it one with "tty" in forge.json`
103 : `${name} is a service, running and without a terminal interface: ${detail}`;
101104 case "not_running":
102105 return `${name} is not running: ${detail}`;
103106 case "no_pty":
@@ -142,7 +145,13 @@ export async function runAppTty(
142145 : (status.error ?? `it is ${status.state}`);
143146 return err({ refusal: "not_running", detail });
144147 }
145 if (live.tty === null) return err({ refusal: "no_tty", detail: "" });
148 if (live.tty === null) {
149 const service = runtime.envStatus(target.app, target.env)?.service;
150 return err({
151 refusal: "no_tty",
152 detail: service === undefined ? "" : serviceLine(service),
153 });
154 }
146155
147156 const terminal = new Bun.Terminal({
148157 cols: Math.max(1, host.cols || 80),
src/web/ui.ts +6
@@ -10,6 +10,7 @@
1010 * reaches for an inline `style` attribute, because the CSP forbids it.
1111 */
1212
13 import { serviceLine } from "../apps/service_line.ts";
1314 import { VERIFYING_NOTE, type EnvState, type EnvStatus } from "../apps/runtime.ts";
1415 import type { PreviewData } from "../apps/data.ts";
1516 import type { Mark } from "../core/marks.ts";
@@ -453,6 +454,11 @@ export function envFacts(
453454 </p>`,
454455 )}
455456 ${when(env.note, (note) => html`<p class="muted small">${note}</p>`)}
457 ${when(
458 env.service,
459 (service) =>
460 html`<p class="muted small" data-service>${serviceLine(service)}</p>`,
461 )}
456462 ${when(dormantNote(env), (note) => html`<p class="muted small" data-dormant>${note}</p>`)}
457463 ${when(
458464 env.busy,
test/apps-adversarial.test.ts +43 −1
@@ -2129,8 +2129,46 @@ describe("manifest: service kind", () => {
21292129 alwaysOn: true,
21302130 placement: "metal",
21312131 volumes: [{ path: "world", sync: 60 }],
2132 healthCommand: null,
21322133 });
21332134 });
2135 test("a service declares a node label and a health command; udp is refused with its reason", () => {
2136 const r = svc({
2137 ports: [25565, "25566/tcp", { port: 24454 }],
2138 placement: "vxrail",
2139 health_command: "nc -z 127.0.0.1 25565",
2140 });
2141 expect(r.ok && r.value.service?.ports).toEqual([
2142 { port: 25565, protocol: "tcp" },
2143 { port: 25566, protocol: "tcp" },
2144 { port: 24454, protocol: "tcp" },
2145 ]);
2146 expect(r.ok && r.value.service?.placement).toBe("vxrail");
2147 expect(r.ok && r.value.service?.healthCommand).toBe("nc -z 127.0.0.1 25565");
2148 expect(svc({ ports: [25565, "25565/tcp"] }).ok).toBe(false);
2149 for (const udp of ["19132/udp", { port: 19132, protocol: "udp" }]) {
2150 const refused = svc({ ports: [udp] });
2151 expect(refused.ok).toBe(false);
2152 expect(
2153 !refused.ok && refused.error.kind === "invalid"
2154 ? refused.error.message
2155 : "",
2156 ).toContain(
2157 "19132/udp, but the forge cannot relay udp yet",
2158 );
2159 }
2160 });
2161 test("a service is never put to sleep and its placement is checked", async () => {
2162 const { placementProblem, nodeLabels } = await import("../src/apps/placement.ts");
2163 const r = svc({ ports: [25565], placement: "vxrail" });
2164 const spec = r.ok ? r.value.service! : (undefined as never);
2165 expect(placementProblem(spec, ["metal", "vxrail"])).toBeUndefined();
2166 expect(placementProblem(spec, [])).toContain("FORGE_NODE_LABELS");
2167 expect(nodeLabels({ FORGE_NODE_LABELS: " Metal, vxrail,," })).toEqual([
2168 "metal",
2169 "vxrail",
2170 ]);
2171 });
21342172 test("a web app has no service", () => {
21352173 const r = parseManifest(JSON.stringify({ app: { run: "x" } }), undefined);
21362174 expect(r.ok && r.value.service).toBeNull();
@@ -2143,7 +2181,11 @@ describe("manifest: service kind", () => {
21432181 { ports: [25565, 25565] },
21442182 { ports: ["25565"] },
21452183 { ports: [25565], always_on: false },
2146 { ports: [25565], placement: "moon" },
2184 { ports: [25565], placement: "Moon Base" },
2185 { ports: [25565], placement: 7 },
2186 { ports: ["25565/sctp"] },
2187 { ports: [25565], health_command: "a\nb" },
2188 { ports: [25565], health_command: "" },
21472189 { ports: [25565], volumes: [{ path: "../etc" }] },
21482190 { ports: [25565], volumes: [{ path: "/abs" }] },
21492191 { ports: [25565], volumes: [{ path: "w", sync: 1 }] },
test/contain-publish.test.ts added +69
@@ -0,0 +1,69 @@
1 import { expect, test } from "bun:test";
2 import { mkdtempSync } from "node:fs";
3 import { tmpdir } from "node:os";
4 import { join } from "node:path";
5 import { cellsAvailable, openCell, resolveLimits } from "../src/apps/contain.ts";
6 import { freePort } from "../src/apps/process.ts";
7
8 // Visible as skipped, never silently green, where there is no bubblewrap.
9 const cells = await cellsAvailable();
10 const can = cells.ok && canListenOnUnixSockets();
11
12 function canListenOnUnixSockets(): boolean {
13 try {
14 const probe = join(mkdtempSync(join(tmpdir(), "sock-")), "p.sock");
15 Bun.listen({ unix: probe, socket: { data() {} } }).stop(true);
16 return true;
17 } catch {
18 return false; // some sandboxes refuse unix sockets
19 }
20 }
21
22 test.skipIf(!can)("a published port reaches a process inside the cell, byte for byte", async () => {
23 const dir = mkdtempSync(join(tmpdir(), "pub-"));
24 const port = freePort();
25 let cell: ReturnType<typeof openCell>;
26 try {
27 cell = openCell({
28 dir,
29 writable: [],
30 home: join(dir, "home"),
31 hide: [],
32 egress: [],
33 reach: [],
34 limits: resolveLimits("app", undefined),
35 publish: [port],
36 });
37 } catch (error) {
38 throw new Error(`the cell could not open its sockets: ${error}`);
39 }
40 const server = `Bun.listen({hostname:"127.0.0.1",port:${port},socket:{data(s,d){s.write("echo:"+d);s.end()}}});setInterval(()=>{},1e3)`;
41 const proc = Bun.spawn(
42 cell.argv(`exec ${process.execPath} -e '${server}'`),
43 { env: cell.env({ PATH: process.env["PATH"] ?? "" }), stdout: "ignore", stderr: "ignore" },
44 );
45 try {
46 let got = "";
47 for (let i = 0; i < 100 && got === ""; i++) {
48 await Bun.sleep(100);
49 got = await new Promise<string>((resolve) => {
50 let out = "";
51 Bun.connect({
52 hostname: "127.0.0.1",
53 port,
54 socket: {
55 open: (s) => void s.write("hi"),
56 data: (_s, d) => void (out += d.toString()),
57 close: () => resolve(out),
58 error: () => resolve(""),
59 connectError: () => resolve(""),
60 },
61 }).catch(() => resolve(""));
62 });
63 }
64 expect(got).toBe("echo:hi");
65 } finally {
66 proc.kill("SIGKILL");
67 cell.close();
68 }
69 }, 30_000);
test/service-kind.test.ts added +149
@@ -0,0 +1,149 @@
1 import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2 import { parseManifest } from "../src/apps/manifest.ts";
3 import { publishProblem, reservedPorts } from "../src/apps/ports.ts";
4 import {
5 startProcess,
6 waitUntilServiceReady,
7 type StartInput,
8 } from "../src/apps/process.ts";
9 import { mayIdle } from "../src/apps/service.ts";
10 import { serviceLine } from "../src/apps/service_line.ts";
11 import { ttyRefusalText } from "../src/apps/tty.ts";
12
13 const manifestOf = (app: object) => {
14 const r = parseManifest(
15 JSON.stringify({ app: { kind: "service", run: "x", ...app } }),
16 undefined,
17 );
18 if (!r.ok)
19 throw new Error(r.error.kind === "invalid" ? r.error.message : r.error.kind);
20 return r.value;
21 };
22
23 describe("which ports a service may publish", () => {
24 const reserved = reservedPorts({ PORT: "3000", FORGE_SSH_PORT: "2222" });
25 const none = new Map<number, string>();
26
27 test("the forge's own listener, its terminal and common host ports are refused", () => {
28 expect(publishProblem([3000], reserved, none)).toBe(
29 "port 3000 is not available to publish: it belongs to the forge's own listener",
30 );
31 expect(publishProblem([2222], reserved, none)).toContain("the forge's terminal");
32 expect(publishProblem([5432], reserved, none)).toContain("common host service");
33 expect(
34 publishProblem([7777], reservedPorts({ FORGE_RESERVED_PORTS: "7777, x" }), none),
35 ).toContain("reserved by the operator");
36 });
37
38 test("a port with the terminal switched off is free", () => {
39 const hosted = reservedPorts({ PORT: "3000", FORGE_SSH_PORT: "0" });
40 expect(publishProblem([2222], hosted, none)).toBeUndefined();
41 });
42
43 test("the range apps are handed ports from is refused", () => {
44 expect(publishProblem([40000], reserved, none)).toContain("range the forge hands to apps");
45 });
46
47 test("a port another app's service holds is refused, by that app's name", () => {
48 expect(
49 publishProblem([25565], reserved, new Map([[25565, "minecraft"]])),
50 ).toBe("port 25565 is already published by minecraft's service; choose another");
51 });
52
53 test("free ports pass", () => {
54 expect(publishProblem([25565, 25566], reserved, none)).toBeUndefined();
55 });
56 });
57
58 describe("a service at deploy", () => {
59 const saved = process.env["FORGE_NODE_LABELS"];
60 beforeEach(() => delete process.env["FORGE_NODE_LABELS"]);
61 afterEach(() => {
62 if (saved === undefined) delete process.env["FORGE_NODE_LABELS"];
63 else process.env["FORGE_NODE_LABELS"] = saved;
64 });
65
66 test("a placement this node does not carry fails the start, in words", async () => {
67 const lines: string[] = [];
68 const started = await startProcess({
69 manifest: manifestOf({ ports: [25565], placement: "vxrail" }),
70 log: (l: string) => lines.push(l),
71 } as unknown as StartInput);
72 expect(started.ok).toBe(false);
73 expect(!started.ok && started.error.message).toContain(
74 'placement "vxrail" wants a node with that label',
75 );
76 });
77
78 test("a service is never put to sleep; a web app is", () => {
79 expect(mayIdle(manifestOf({ ports: [25565] }))).toBe(false);
80 const web = parseManifest(JSON.stringify({ app: { run: "x" } }), undefined);
81 expect(web.ok && mayIdle(web.value)).toBe(true);
82 });
83 });
84
85 describe("waitUntilServiceReady", () => {
86 const base = {
87 spec: undefined,
88 ports: [25565],
89 env: { PATH: process.env["PATH"] ?? "" },
90 log: () => {},
91 exited: new Promise<number>(() => {}),
92 signal: new AbortController().signal,
93 };
94
95 test("is ready when the health command succeeds", async () => {
96 const r = await waitUntilServiceReady({ ...base, command: "true", timeoutMs: 5_000 });
97 expect(r.ok).toBe(true);
98 });
99
100 test("fails in the ready stage, with the command's reason, when it never does", async () => {
101 const r = await waitUntilServiceReady({ ...base, command: "false", timeoutMs: 1_200 });
102 expect(!r.ok && r.error.stage).toBe("ready");
103 expect(!r.ok && r.error.message).toContain("health command did not succeed within 1s");
104 });
105
106 test("a slow attempt is cut at the ready budget, not at its own ten seconds", async () => {
107 const t0 = Date.now();
108 const r = await waitUntilServiceReady({ ...base, command: "sleep 30", timeoutMs: 1_000 });
109 expect(r.ok).toBe(false);
110 expect(Date.now() - t0).toBeLessThan(5_000);
111 }, 15_000);
112
113 test("a process that exits first fails with its code", async () => {
114 const r = await waitUntilServiceReady({
115 ...base,
116 command: "false",
117 exited: Promise.resolve(3),
118 timeoutMs: 5_000,
119 });
120 expect(!r.ok && r.error.message).toBe("exited with code 3 before it was well");
121 });
122
123 test("with no command it is ready once it has stayed up", async () => {
124 const r = await waitUntilServiceReady({ ...base, command: null, timeoutMs: 5_000 });
125 expect(r.ok).toBe(true);
126 });
127 });
128
129 describe("a service on the page and in the terminal", () => {
130 const status = { ports: [25565, 25566], placement: "vxrail", published: true };
131
132 test("says its placement, ports and that they are published", () => {
133 const line = serviceLine(status);
134 expect(line).toContain('node "vxrail"');
135 expect(line).toContain("25565/tcp, 25566/tcp published");
136 expect(line).toContain("always on");
137 });
138
139 test("a preview says its ports are not published", () => {
140 expect(serviceLine({ ...status, published: false })).toContain("not published");
141 });
142
143 test("the terminal tells a service apart from an app that lacks a tty", () => {
144 expect(ttyRefusalText("no_tty", "mc", serviceLine(status))).toContain(
145 "mc is a service",
146 );
147 expect(ttyRefusalText("no_tty", "notes")).toContain('"tty" in forge.json');
148 });
149 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs