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

The forge says plainly what is off on a small machine and why: Chromium, the AI tool, the page cache #12541

Merged opened this

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

Merged

scout/forge:scout/12522-the-forge-says-plainly-what-is-off-on-a → main 9 commits fork 1 thread · 1 unresolved

  • Merged. scout/12522-the-forge-says-plainly-what-is-off-on-a was merged into main as 0c7bfd1.

Review

Sign in to review this change.
21 files changed +257 −35
docs/features/footprint.md +13
@@ -9,6 +9,19 @@ Where it shows:
99 - `/system`, section "What the forge costs" (admins and granted telemetry readers, as the page's other sections). First view is one sentence: "Within budget: the forge is using 170 MiB; it should stay under 256 MiB.", or what is over. Open its disclosure for the measured facts (memory, first page, data on disk, machine and architecture) and one row per optional part, on or off and why.
1010 - The terminal: palette → System opens the System dialog; after the database lines it says the same sentence, then `off:` and the optional parts that are off. The dialog does not scroll, so the facts and the reasons are on `/system` only.
1111
12 ## What is off on a small machine (#12522)
13
14 Three parts are optional, and each is listed on or off with one line of why:
15
16 - **Chromium (looks)**: off when no Chromium is found (or `FORGE_CHROMIUM` names one that is not there). Pages are served without pictures.
17 - **Crew AI tool**: off when Claude Code is not on PATH or at `FORGE_CLAUDE`. Assigned work waits.
18 - **Large page cache**: off under 1 GiB of memory (the pod's limit, else the machine's). The caches behind code pages (kept pages, encoded bodies, page columns, folders and refs: 160 MiB at full size) each keep a quarter, so a page is rendered again more often but the forge fits.
19
20 Where to read it:
21
22 - `/system`, "What the forge costs": open the disclosure, one row per part.
23 - `GET /api/v1/health` signed in (any account, admin or not): `optional`, a list of `{ name, on, why }`. A stranger and an unauthenticated probe are not told it.
24
1225 The release proof reads the footprint once the new version answers `/healthz`, before the smoke checks load it, and keeps it in `release/proof.json` (`footprint`). `/system` shows this process's last reading, else the proof's.
1326
1427 Reading the disk figure walks the whole data directory (`treeBytes`), once per release proof and never on a page view; on a big data directory that walk can take seconds. It is asynchronous, so it does not hold the event loop.
src/actions/health.ts +15 −4
@@ -36,6 +36,7 @@ import {
3636 type VitalsInput,
3737 } from "../kernel/vitals.ts";
3838 import { snapshotsOf } from "../snapshot/service.ts";
39 import { optionals, type Optional } from "../system/footprint.ts";
3940 import { forgesMemory, memoryOverLine } from "../spawn/memory_fit.ts";
4041 import { forgeHasNoKey, NO_KEY_AT, NO_KEY_LINE } from "../crew/no_key.ts";
4142
@@ -113,6 +114,11 @@ export function withHeavyAskers(v: Vitals, app: App, now: number = Date.now()):
113114 */
114115 export type StrangerHealth = Pick<ForgeHealth, "ok" | "version" | "commit" | "draining">;
115116
117 /** The optional parts beside the health of anyone signed in (`system/footprint.ts`). */
118 export interface Parts {
119 readonly optional: readonly Optional[];
120 }
121
116122 /** The forge's overdue schedules as counts, on the health answer (#12512). */
117123 export interface ScheduleHealth {
118124 readonly schedules: { readonly overdue: number; readonly oldestSeconds: number };
@@ -136,13 +142,18 @@ export function readHealth(
136142 app: App,
137143 actor: User | undefined,
138144 probe = false,
139 ): StrangerHealth | ForgeHealth | (Vitals & ForgeHealth) {
140 const forge = forgeHealth();
145 ): StrangerHealth | ForgeHealth | (ForgeHealth & Parts) | (Vitals & ForgeHealth & Parts) {
146 const health = forgeHealth();
141147 if (actor === undefined && !probe) {
142 const { ok, version, commit, draining } = forge;
148 const { ok, version, commit, draining } = health;
143149 return { ok, version, commit, draining };
144150 }
145 if (!actor?.isAdmin) return forge;
151 // A probe without an actor keeps the forge's own shape: no parts, no memory class.
152 if (actor === undefined) return health;
153 // What is off on this machine and why, as /system says it (#12522): only someone signed in
154 // is told.
155 const forge = { ...health, optional: optionals() };
156 if (!actor.isAdmin) return forge;
146157 const v = forgeVitals(app);
147158 // Draining is the release's, not the vitals': it is broken all the same (#12167).
148159 // A broken cost-ledger chain is one more broken need, from the verdict kept in memory (#12273).
src/core/capacity.ts +2 −13
@@ -14,8 +14,9 @@
1414 import type { Database } from "bun:sqlite";
1515 import { readFileSync } from "node:fs";
1616 import { isIP } from "node:net";
17 import { availableParallelism, totalmem } from "node:os";
17 import { availableParallelism } from "node:os";
1818 import { PAYMENT_HOSTS } from "./egress_grants.ts";
19 import { memoryLimitBytes } from "../system/memory_limit.ts";
1920
2021 export type CapacityKey =
2122 | "crew.concurrency"
@@ -319,18 +320,6 @@ export function floorMiBForMemory(bytes: number): number {
319320 return Number.isFinite(n) && n > 0 ? n : 0;
320321 }
321322
322 /** The pod's memory limit (cgroup v2, then v1), else the machine's memory. */
323 export function memoryLimitBytes(): number {
324 for (const f of ["/sys/fs/cgroup/memory.max", "/sys/fs/cgroup/memory/memory.limit_in_bytes"]) {
325 try {
326 const n = Number(readFileSync(f, "utf8").trim());
327 if (Number.isFinite(n) && n > 0 && n < totalmem()) return n;
328 } catch {
329 // No such cgroup file: try the next.
330 }
331 }
332 return totalmem();
333 }
334323
335324 /**
336325 * What this pod's cgroup holds in memory now: `memory.current` less the inactive file cache
src/git/env.ts +1 −1
@@ -16,7 +16,7 @@ import { tmpdir } from "node:os";
1616 import { join } from "node:path";
1717 import { err, ok, type Result } from "../kernel/result.ts";
1818 import { cellProxy, PROXY_VARS } from "../apps/egress.ts";
19 import { memoryLimitBytes } from "../core/capacity.ts";
19 import { memoryLimitBytes } from "../system/memory_limit.ts";
2020 import { noteGit } from "../perf/git.ts";
2121 import { readerHold, namesOnlyOwn } from "./own_refs.ts";
2222 import { gitRecord } from "../perf/live.ts";
src/http/compress.ts +2 −1
@@ -12,6 +12,7 @@
1212
1313 import { brotliCompressSync, constants } from "node:zlib";
1414 import { ViewCache } from "../view/cache.ts";
15 import { cacheBytes } from "../system/cache_share.ts";
1516
1617 export type Encoding = "br" | "gzip";
1718
@@ -86,7 +87,7 @@ function encode(bytes: Uint8Array<ArrayBuffer>, encoding: Encoding, best: boolea
8687 * private markup for minutes and push out the pages strangers repeat.
8788 */
8889 /** Bytes `recent` may hold, source and encoded together; shown on /system. */
89 export const RECENT_BYTES = 48 * 1024 * 1024;
90 export const RECENT_BYTES = cacheBytes(48 * 1024 * 1024);
9091 const recent = new ViewCache({ maxEntries: 1024, maxBytes: RECENT_BYTES });
9192 /** How long an encoded body is kept unasked, ms. */
9293 const RECENT_TTL_MS = 5 * 60_000;
src/kernel/vitals.ts +2 −1
@@ -41,7 +41,8 @@ import { running as runningVersion } from "./version.ts";
4141 import { rollbackNeed } from "../release/launch.ts";
4242 import { behindStanding } from "../release/behind.ts";
4343 import { newestDrills } from "../core/domain_drills.ts";
44 import { capacityValue, memoryLimitBytes, podMemoryUsedBytes } from "../core/capacity.ts";
44 import { capacityValue, podMemoryUsedBytes } from "../core/capacity.ts";
45 import { memoryLimitBytes } from "../system/memory_limit.ts";
4546 import { limitValue } from "../settings/limits.ts";
4647 import { unwrittenFor, SILENT_AFTER_S } from "../http/access_log.ts";
4748 import { DOMAINS } from "./domains.ts";
src/looks/capture.ts +2 −1
@@ -109,7 +109,8 @@ const LOAD_MS = 3_000;
109109 /** The Chromium binary: `FORGE_CHROMIUM`, else the usual names on `PATH`, else the Mac's own. */
110110 export function findChromium(): string | undefined {
111111 const named = (process.env["FORGE_CHROMIUM"] ?? "").trim();
112 if (named !== "") return named;
112 // A named path that is not there is Chromium missing, said as off on /system (#12522).
113 if (named !== "") return existsSync(named) ? named : undefined;
113114 for (const name of [
114115 "chromium",
115116 "chromium-browser",
src/settings/limits.ts +1 −1
@@ -18,10 +18,10 @@ import {
1818 bootDefault,
1919 capacityValue,
2020 floorMiBForMemory,
21 memoryLimitBytes,
2221 setCapacity,
2322 type CapacityKey,
2423 } from "../core/capacity.ts";
24 import { memoryLimitBytes } from "../system/memory_limit.ts";
2525 import { err, ok, type Result } from "../kernel/result.ts";
2626 import { DEPLOY_PULL_KEEP_DAYS } from "../system/retention_deploys.ts";
2727 import { KEEP_DAYS as EVENT_KEEP_DAYS } from "../system/retention_events.ts";
src/spawn/memory_fit.ts +1 −1
@@ -8,7 +8,7 @@
88 */
99
1010 import type { App } from "../app.ts";
11 import { memoryLimitBytes } from "../core/capacity.ts";
11 import { memoryLimitBytes } from "../system/memory_limit.ts";
1212 import { limitValue } from "../settings/limits.ts";
1313 import { servedMemoryMiB } from "./clients.ts";
1414 import { mibWords } from "./usage.ts";
src/system/cache_share.ts added +23
@@ -0,0 +1,23 @@
1 /**
2 * How much of its page caches' full size a forge keeps (#12522). The caches behind
3 * strangers' code pages (kept pages, encoded bodies, page columns, folders and refs)
4 * hold 160 MiB at full size: more than half of a 512 MiB machine's budget. Under
5 * `LARGE_CACHE_MIN_BYTES` of memory each keeps a quarter, so a page is rendered
6 * again more often but the forge fits; /system and /api/v1/health say which.
7 */
8 import { memoryLimitBytes } from "./memory_limit.ts";
9
10 /** The memory from which the page caches keep their full size. */
11 export const LARGE_CACHE_MIN_BYTES = 1024 * 1024 * 1024;
12
13 /** The share of full size the page caches keep on a machine of `machineBytes`. */
14 export const cacheShare = (machineBytes: number): number => (machineBytes >= LARGE_CACHE_MIN_BYTES ? 1 : 1 / 4);
15
16 /** Read once at start: the caches are made at module load and keep their cap. */
17 const machine = memoryLimitBytes();
18
19 /** Whether this process's page caches keep their full size. */
20 export const largePageCache: boolean = cacheShare(machine) === 1;
21
22 /** A page cache's cap on this machine: `full` scaled by `cacheShare`, whole bytes. */
23 export const cacheBytes = (full: number, machineBytes: number = machine): number => Math.floor(full * cacheShare(machineBytes));
src/system/footprint.ts +12 −2
@@ -6,9 +6,10 @@
66 * /system shows the last one.
77 */
88 import { arch, availableParallelism } from "node:os";
9 import { memoryLimitBytes } from "../core/capacity.ts";
9 import { memoryLimitBytes } from "./memory_limit.ts";
1010 import { findChromium } from "../looks/capture.ts";
1111 import { treeBytes } from "./largest_dirs.ts";
12 import { largePageCache } from "./cache_share.ts";
1213
1314 const MIB = 1024 * 1024;
1415
@@ -60,10 +61,14 @@ export function clearReadyMark(): void {
6061 readyMs = null;
6162 }
6263
63 /** The optional parts and whether each is on. `chromium` and `crewTool` are a test's to hand in. */
64 /**
65 * The optional parts and whether each is on.
66 * `chromium`, `crewTool` and `largeCache` are a test's to hand in.
67 */
6468 export function optionals(
6569 chromium: string | null = findChromium() ?? null,
6670 crewTool: string | null = Bun.which(process.env["FORGE_CLAUDE"] ?? "claude"),
71 largeCache: boolean = largePageCache,
6772 ): Optional[] {
6873 return [
6974 {
@@ -76,6 +81,11 @@ export function optionals(
7681 on: crewTool !== null,
7782 why: crewTool === null ? "Claude Code is not on PATH or at FORGE_CLAUDE, so assigned work waits; pages and git do not need it" : "found, and run only while a crew run is working",
7883 },
84 {
85 name: "Large page cache",
86 on: largeCache,
87 why: largeCache ? "this machine has 1 GiB or more, so code pages keep 160 MiB of finished pages" : "this machine has under 1 GiB, so code pages keep a quarter as much and render again more often; pages and git do not need it",
88 },
7989 ];
8090 }
8191
src/system/live.ts +2 −1
@@ -9,7 +9,8 @@ import type { App } from "../app.ts";
99 import { cellRoots } from "../apps/contain.ts";
1010 import { HOST, readRaw, type Paths, type Raw } from "./proc.ts";
1111 import { buildSystem, forAgent, type PodLimits, type Roots, type SystemView } from "./view.ts";
12 import { cpuLimit, memoryLimitBytes, podMemoryUsedBytes } from "../core/capacity.ts";
12 import { cpuLimit, podMemoryUsedBytes } from "../core/capacity.ts";
13 import { memoryLimitBytes } from "./memory_limit.ts";
1314 import { during } from "../perf/jobs.ts";
1415
1516 const FRESH_MS = 1_000;
src/system/memory_limit.ts added +20
@@ -0,0 +1,20 @@
1 /**
2 * The memory this process may use: the pod's cgroup limit, else the machine's. Its own
3 * module, with nothing but node's, so the static web (`http/compress.ts`) can size its
4 * cache without loading `core/capacity.ts` and the data graph behind it (#12522, #8311).
5 */
6 import { readFileSync } from "node:fs";
7 import { totalmem } from "node:os";
8
9 /** The pod's memory limit (cgroup v2, then v1), else the machine's memory. */
10 export function memoryLimitBytes(): number {
11 for (const f of ["/sys/fs/cgroup/memory.max", "/sys/fs/cgroup/memory/memory.limit_in_bytes"]) {
12 try {
13 const n = Number(readFileSync(f, "utf8").trim());
14 if (Number.isFinite(n) && n > 0 && n < totalmem()) return n;
15 } catch {
16 // No such cgroup file: try the next.
17 }
18 }
19 return totalmem();
20 }
src/web/pages/kept_page.ts +2 −1
@@ -28,6 +28,7 @@ import { ViewCache } from "../../view/cache.ts";
2828 import { encodeOffThread } from "../code_rows_pool.ts";
2929 import { readFlash } from "../flash.ts";
3030 import { signInHref } from "../layout.ts";
31 import { cacheBytes } from "../../system/cache_share.ts";
3132
3233 interface KeptPage {
3334 readonly body: Uint8Array;
@@ -38,7 +39,7 @@ interface KeptPage {
3839 const TTL_MS = 60_000;
3940
4041 /** Bytes the kept pages may hold, shown on /system. */
41 export const KEPT_PAGE_BYTES = 64 * 1024 * 1024;
42 export const KEPT_PAGE_BYTES = cacheBytes(64 * 1024 * 1024);
4243 const store = new ViewCache({ maxEntries: 8192, maxBytes: KEPT_PAGE_BYTES });
4344
4445 /**
src/web/pages/tree_cache.ts +3 −2
@@ -20,6 +20,7 @@ import type { BlobForRender } from "../../git/read.ts";
2020 import type { RepoSource } from "../../view/source.ts";
2121 import type { RefSet } from "./refs.ts";
2222 import type { Html } from "../html.ts";
23 import { cacheBytes } from "../../system/cache_share.ts";
2324
2425 export const TTL_MS = 60_000;
2526
@@ -29,7 +30,7 @@ export interface RenderedTree {
2930 }
3031
3132 /** Bytes the page columns may hold; shown on /system. */
32 export const COLUMN_BYTES = 32 * 1024 * 1024;
33 export const COLUMN_BYTES = cacheBytes(32 * 1024 * 1024);
3334 const cache = new ViewCache({ maxEntries: 512, maxBytes: COLUMN_BYTES });
3435
3536 /** The commit `ref` names: a full id itself, a branch by its ref file; undefined for anything else (the caller reads git). */
@@ -70,7 +71,7 @@ export const clearTreeCache = (): void => {
7071 * `TTL_MS`, the staleness the kept pages already allow their switcher.
7172 */
7273 /** Bytes the folders and ref names may hold; shown on /system. */
73 export const PARTS_BYTES = 16 * 1024 * 1024;
74 export const PARTS_BYTES = cacheBytes(16 * 1024 * 1024);
7475 const parts = new ViewCache({ maxEntries: 8192, maxBytes: PARTS_BYTES });
7576 /** A folder at a commit cannot change: kept for as long as it fits. */
7677 const FOLDER_TTL_MS = 10 * 60_000;
test/boundary-tenancy-limits.test.ts +2 −1
@@ -23,7 +23,8 @@ import { join } from "node:path";
2323 import { BACKGROUND_CPU_WEIGHT } from "../src/apps/background.ts";
2424 import { enterArgv, floorHeld, FORGE_WEIGHT, keepFloor, prepare, type CgroupHost } from "../src/apps/cgroup.ts";
2525 import { cellOom, cellOomAdj, oomArgv, ownOom } from "../src/apps/oom.ts";
26 import { floorMiBForMemory, memoryLimitBytes } from "../src/core/capacity.ts";
26 import { floorMiBForMemory } from "../src/core/capacity.ts";
27 import { memoryLimitBytes } from "../src/system/memory_limit.ts";
2728 import { LIMITS } from "../src/settings/limits.ts";
2829 import { floorLine } from "../src/web/pages/system.ts";
2930 import { DISK_WALK_MAX, diskBytes, diskWalk } from "../src/apps/disk_walk.ts";
test/capacity-crew.test.ts +1 −1
@@ -16,9 +16,9 @@ import {
1616 capacityDefault,
1717 capacityValue,
1818 crewForMemory,
19 memoryLimitBytes,
2019 setCapacity,
2120 } from "../src/core/capacity.ts";
21 import { memoryLimitBytes } from "../src/system/memory_limit.ts";
2222 import { changedOf } from "../src/actions/capacity.ts";
2323
2424 const GiB = 1024 ** 3;
test/fixtures/cache-under.ts added +9
@@ -0,0 +1,9 @@
1 // Run by test/small-machine-off.test.ts: the page caches made on a machine of argv[2] bytes.
2 import { mock } from "bun:test";
3 import { join } from "node:path";
4
5 const src = join(import.meta.dir, "..", "..", "src");
6 mock.module(join(src, "system", "memory_limit.ts"), () => ({ memoryLimitBytes: () => Number(process.argv[2]) }));
7 const { KEPT_PAGE_BYTES } = await import(join(src, "web", "pages", "kept_page.ts"));
8 const { largePageCache } = await import(join(src, "system", "cache_share.ts"));
9 console.log(JSON.stringify({ KEPT_PAGE_BYTES, largePageCache }));
test/footprint.test.ts +3 −3
@@ -26,10 +26,10 @@ const reading = (over: Partial<Footprint> = {}): Footprint => ({
2626 afterEach(clearReadyMark);
2727
2828 test("a small machine says what is off and why", () => {
29 const o = optionals(null, null);
30 expect(o.map((x) => [x.name, x.on])).toEqual([["Chromium (looks)", false], ["Crew AI tool", false]]);
29 const o = optionals(null, null, false);
30 expect(o.map((x) => [x.name, x.on])).toEqual([["Chromium (looks)", false], ["Crew AI tool", false], ["Large page cache", false]]);
3131 expect(o[0]!.why).toContain("pages and git do not need it");
32 expect(optionals("/usr/bin/chromium", "/usr/bin/claude").every((x) => x.on)).toBe(true);
32 expect(optionals("/usr/bin/chromium", "/usr/bin/claude", true).every((x) => x.on)).toBe(true);
3333 });
3434
3535 test("a reading is measured: memory and the data directory on disk", async () => {
test/small-machine-off.test.ts added +139
@@ -0,0 +1,139 @@
1 // A small machine (#12522): what it cannot afford is off, the forge says so on /system
2 // and /api/v1/health, and with Chromium missing the home page and a push still work.
3 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
4 import { mkdtemp, rm } from "node:fs/promises";
5 import { tmpdir } from "node:os";
6 import { join } from "node:path";
7 import { createApp, type App } from "../src/app.ts";
8 import { serve, type Servers } from "../src/http/server.ts";
9 import { createRepo } from "../src/actions/repos.ts";
10 import { createToken } from "../src/core/tokens.ts";
11 import { cacheBytes, cacheShare, LARGE_CACHE_MIN_BYTES } from "../src/system/cache_share.ts";
12 import { findChromium } from "../src/looks/capture.ts";
13 import { optionals } from "../src/system/footprint.ts";
14 import { readHealth } from "../src/actions/health.ts";
15 import { signUpProven } from "./helpers/verified.ts";
16 import { gitClientEnv } from "./helpers/git-client.ts";
17 import { seedAdmin } from "./helpers/admin.ts";
18 import { proveAll } from "./helpers/verified.ts";
19
20 const MIB = 1024 * 1024;
21
22 test("under 1 GiB the page caches keep a quarter; from 1 GiB, all of it", () => {
23 expect(cacheShare(512 * MIB)).toBe(1 / 4);
24 expect(cacheShare(LARGE_CACHE_MIN_BYTES)).toBe(1);
25 expect(cacheBytes(64 * MIB, 512 * MIB)).toBe(16 * MIB);
26 expect(cacheBytes(64 * MIB, 4096 * MIB)).toBe(64 * MIB);
27 });
28
29 test("the kept-page cache is made a quarter of its size under 1 GiB, and whole from 1 GiB", async () => {
30 const made = async (bytes: number) => {
31 const p = Bun.spawn(["bun", join(import.meta.dir, "fixtures", "cache-under.ts"), String(bytes)], { stdout: "pipe", stderr: "pipe" });
32 const [out, code] = await Promise.all([new Response(p.stdout).text(), p.exited]);
33 expect(code).toBe(0);
34 return JSON.parse(out) as { KEPT_PAGE_BYTES: number; largePageCache: boolean };
35 };
36 expect(await made(512 * MIB)).toEqual({ KEPT_PAGE_BYTES: 16 * MIB, largePageCache: false });
37 expect(await made(4096 * MIB)).toEqual({ KEPT_PAGE_BYTES: 64 * MIB, largePageCache: true });
38 });
39
40 test("each optional part is listed on or off with its one-line reason", () => {
41 const small = optionals(null, null, false);
42 expect(small.map((o) => [o.name, o.on])).toEqual([
43 ["Chromium (looks)", false],
44 ["Crew AI tool", false],
45 ["Large page cache", false],
46 ]);
47 for (const o of small) expect(o.why).toContain("pages and git do not need it");
48 expect(optionals("/c", "/t", true).every((o) => o.on && !o.why.includes("\n"))).toBe(true);
49 });
50
51 describe("with Chromium missing", () => {
52 const before = process.env["FORGE_CHROMIUM"];
53 let dataDir: string;
54 let work: string;
55 let app: App;
56 let servers: Servers;
57 let token = "";
58 let readerToken = "";
59
60 beforeAll(async () => {
61 process.env["FORGE_CHROMIUM"] = "/nonexistent/chromium";
62 dataDir = await mkdtemp(join(tmpdir(), "small-"));
63 work = await mkdtemp(join(tmpdir(), "small-work-"));
64 app = createApp({ dataDir, port: 0 });
65 servers = await serve(app);
66 const admin = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "correct-horse-battery" });
67 if (!admin.ok) throw new Error("no admin");
68 proveAll(app);
69 const repo = await createRepo(app, admin.value, { name: "app" });
70 if (!repo.ok) throw new Error(`no repo: ${repo.error}`);
71 token = createToken(app.db, admin.value.id, "t", "admin").token;
72 const reader = await signUpProven(app, { username: "bob", email: "[email protected]", password: "correct-horse-battery" });
73 if (!reader.ok) throw new Error("no reader");
74 expect(reader.value.isAdmin).toBe(false);
75 readerToken = createToken(app.db, reader.value.id, "r", "ro").token;
76 });
77
78 afterAll(async () => {
79 if (before === undefined) delete process.env["FORGE_CHROMIUM"];
80 else process.env["FORGE_CHROMIUM"] = before;
81 servers.stop();
82 app.close();
83 await rm(dataDir, { recursive: true, force: true });
84 await rm(work, { recursive: true, force: true });
85 });
86
87 test("a named Chromium that is not there is missing, and said off", () => {
88 expect(findChromium()).toBeUndefined();
89 expect(optionals()[0]).toMatchObject({ name: "Chromium (looks)", on: false });
90 });
91
92 test("the home page answers", async () => {
93 const res = await fetch(`${servers.url}/`);
94 expect(res.status).toBe(200);
95 expect(await res.text()).toContain("<html");
96 });
97
98 test("a push lands", async () => {
99 const env = gitClientEnv();
100 const run = async (args: string[], cwd: string) => {
101 const p = Bun.spawn(args, { cwd, env, stdout: "pipe", stderr: "pipe" });
102 const [err, code] = await Promise.all([new Response(p.stderr).text(), p.exited]);
103 if (code !== 0) throw new Error(`${args.join(" ")}: ${err}`);
104 };
105 const remote = `${servers.url.replace("http://", `http://alice:${token}@`)}/alice/app.git`;
106 await run(["git", "clone", remote, "app"], work);
107 const dir = join(work, "app");
108 await Bun.write(join(dir, "README.md"), "# app\n");
109 await run(["git", "add", "."], dir);
110 await run(["git", "commit", "-m", "genesis"], dir);
111 await run(["git", "push", "origin", "HEAD:main"], dir);
112 const refs = await fetch(`${servers.url}/api/v1/repos/alice/app/branches`, { headers: { authorization: `Bearer ${token}` } });
113 expect(await refs.text()).toContain("main");
114 });
115
116 test("/api/v1/health lists the same parts to a signed-in reader, and nothing of them to a stranger", async () => {
117 const signed = (await (await fetch(`${servers.url}/api/v1/health`, { headers: { authorization: `Bearer ${token}` } })).json()) as {
118 optional?: { name: string; on: boolean; why: string }[];
119 };
120 expect(signed.optional?.map((o) => o.name)).toEqual(optionals().map((o) => o.name));
121 expect(signed.optional?.[0]).toMatchObject({ name: "Chromium (looks)", on: false });
122 const stranger = (await (await fetch(`${servers.url}/api/v1/health`)).json()) as Record<string, unknown>;
123 expect(stranger["optional"]).toBeUndefined();
124 });
125
126 test("a signed-in reader who is not an admin is told the parts too, without the vitals", async () => {
127 const res = await fetch(`${servers.url}/api/v1/health`, { headers: { authorization: `Bearer ${readerToken}` } });
128 expect(res.status).toBe(200);
129 const body = (await res.json()) as Record<string, unknown> & { optional?: { name: string; on: boolean }[] };
130 expect(body.optional?.map((o) => o.name)).toEqual(optionals().map((o) => o.name));
131 expect(body["broken"]).toBeUndefined();
132 });
133
134 test("a probe with no one signed in keeps the old shape: no optional parts", () => {
135 const probed = readHealth(app, undefined, true) as Record<string, unknown>;
136 expect(probed["ok"]).toBeDefined();
137 expect(probed["optional"]).toBeUndefined();
138 });
139 });
test/vitals.test.ts +2 −1
@@ -95,7 +95,8 @@ test("a site admin with a read-only token gets the shape; others get the short o
9595 [
9696 "accessLog",
9797 "apps", "at", "broken", "checkedAt", "commit", "degraded", "disk", "draining", "errors", "flakes",
98 "incidents", "lane", "memory", "needs", "ok", "queue", "rollout", "schedules", "stale", "stuck",
98 "incidents", "lane", "memory", "needs", "ok", "optional", "queue", "rollout", "schedules", "stale",
99 "stuck",
99100 "todo", "version",
100101 ].sort(),
101102 );

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs