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

A container's limits and start time are shown in the cloud tree #17731

opened this

Merged 10h 53m ago, live in production

sold/container-limits → main 0 commits

  • Merged. sold/container-limits was merged into main as 66aac7a.

Review

Sign in to review this change.
9 files changed +235 −16
docs/features/infra.md +1 −1
@@ -107,7 +107,7 @@ Every DigitalOcean and Hetzner account is read into provider ▸ account ▸ pro
107107 - **Changed with the shared language:** `!web` and `!machine:i-111` negate and a leading `"` quotes (both were part of the word); `sort:`, `group:` and `created:` were text; `cost:=10`, `cost:>10,=20` and `cost:>10,<5` were refused; a sign left out and a long line's rest are now said; over MCP `cost:abc` and `cost:none` listed everything and are refused. `test/cloud-filter-lines.test.ts` holds each, and every line that kept its rows.
108108 - **A resource** is at `/infra/-/<cloud>/<account>/<project>/<id>`, beside the tree, or full width on a phone: cost, state, what it is attached to and what it holds (an address its balancer, NAT gateway or task; an ECS service its balancer and cluster; a balancer the services known behind it, "Shared by" when there are several; a link AWS does not state is not drawn, which does not mean nothing uses it), an AWS list price's day, what it leaves out and whose file it is (or why there is none), the app an AWS resource is part of and how that is known (nothing when it is not), what it was made from, who made it, when it was created, when it was read, and Ask about this (a talk with those facts, fenced as data).
109109 - **Created.** An EC2 instance's is when its primary network interface was attached, which is its first launch: AWS's `launchTime` is its last start and is not shown. "not known" when the cloud does not state a date, or the forge does not read one (an AWS address, function, table, cluster or zone). An S3 bucket's is "Created, or last changed", because AWS moves it when the bucket changes, its policy for one; a filter by `created:` uses that date all the same.
110 - **Containers.** A machine that is a game box opens into its containers (`src/cloud/containers.ts`), at `/infra/-/<cloud>/<account>/<project>/machine:<id>/container:<name>`: state, health, CPU, memory, how long it has been up, its image (the box owner's only) and a link to its page under /games, where it is changed. It is what the box's last full sync wrote, and nothing is asked of the box. "not known" is said of a limit (the agent does not send one), of figures the box could not measure, and of everything once the box is silent for two minutes ("not known: running 3 hours ago"). A container is in no count and no sum. The machine is the one the box's own row names, never found by name. Who sees which follows the games roles, and nobody sees the waker.
110 - **Containers.** A machine that is a game box opens into its containers (`src/cloud/containers.ts`), at `/infra/-/<cloud>/<account>/<project>/machine:<id>/container:<name>`: state, health, CPU, memory, how long it has been up, its image (the box owner's only) and a link to its page under /games, where it is changed. It is what the box's last full sync wrote, and nothing is asked of the box. The sync carries `upSince`, `memLimitMiB` and `cpuLimit` for each service, from one `docker inspect` that asks for those fields by name and never the whole answer, which holds the env (`services` in `src/games/agent.sh`): a limit of 0 is "no limit set", and one left out (an older agent) is "not known", as is a value out of its range. Without `upSince` the uptime is the diagnosis' word. "not known" is also said of figures the box could not measure, and of everything once the box is silent for two minutes ("not known: running 3 hours ago"). A container is in no count and no sum. The machine is the one the box's own row names, never found by name. Who sees which follows the games roles, and nobody sees the waker.
111111 - **Keys.** j and k move, Enter opens, h and l (or the arrows) close and open, `/` filters and Enter goes to the first match.
112112 - **States.** No account (a link to /settings/cloud), not read yet, a failed read (one line: when, why, and how old what is shown is), a kind that could not be read with its reason (on its project and on the account, which says where; under the headline's sum, "Not everything is listed: 1 kind not read" links to that account, and text doors name it; a billed account's gaps count too, and change no sum), and a reading older than three of its duty's intervals. A project's note ("R2 is not switched on for this account") is a plain line and no trouble, on its account too when that has one project. **Check the account** (`a` in the terminal) opens the account: see [Cloud accounts](cloud.md#what-was-not-read-17637).
113113 - **Terminal.** `:` then Cloud resources, or `/` in Infra (`src/tui/screens/cloudtree.ts`): the same list, filter and facts, the List price, Old price, Price from and No price lines among them (both read `factsOf`); `tab` changes pane, `w` opens the web page, `P` reads every account.
src/cloud/containers.ts +12 −4
@@ -3,7 +3,8 @@
33 * sync wrote them. Nothing is asked of the box, and nothing here changes it. A person sees the ones
44 * their games role covers. What the sync did not say is null or empty, never 0: the agent sends 0
55 * when Docker's figures could not be read, and its `startedAt` is when the container was made, so
6 * how long it has been up is Docker's own word ("Up 3 hours") from the box's diagnosis.
6 * how long it has been up is from `upSince`, or, when an older agent sends none, Docker's own word
7 * ("Up 3 hours") in the box's diagnosis.
78 */
89
910 import type { Database } from "bun:sqlite";
@@ -37,6 +38,13 @@ const STOPPED = "none, it is not running";
3738
3839 const mib = (n: number): string => (n >= 1024 ? `${(n / 1024).toFixed(1)} GiB` : `${Math.round(n)} MiB`);
3940
41 /** "3 hours", for how long it has been up. */
42 const spanWords = (since: string, now: number): string => agoWords(since, now).replace("just now", "less than a minute").replace(/ ago$/, "");
43
44 /** ", limit 2.0 GiB": 0 is none set and null not known, which are not the same. */
45 const limitWords = (n: number | null, words: (n: number) => string): string => (n === null ? ", limit not known" : n === 0 ? ", no limit set" : `, limit ${words(n)}`);
46 const cores = (n: number): string => `${Number(n.toFixed(3))} ${n === 1 ? "core" : "cores"}`;
47
4048 /** Every container `viewer` may see, by its machine as the cloud tree names it: `<cloud>/<account>/machine:<id>`. */
4149 export function containersOf(db: Database, viewer: User | undefined, now = Date.now()): Map<string, readonly Container[]> {
4250 const out = new Map<string, readonly Container[]>();
@@ -66,9 +74,9 @@ export function containersOf(db: Database, viewer: User | undefined, now = Date.
6674 name: s.name,
6775 state: silent ? `${UNKNOWN}: ${state} ${agoWords(s.seenAt, now)}` : state,
6876 health: silent ? "" : s.health,
69 cpu: figure(measured ? `${s.cpuPct.toFixed(1)}% of one core, limit not known` : UNKNOWN),
70 memory: figure(measured ? `${mib(s.memMiB)}, limit not known${has > 0 ? `; its machine has ${mib(has)}` : ""}` : UNKNOWN),
71 uptime: figure(/^Up (.+?)(?: \(.*\))?$/.exec(ps?.status ?? "")?.[1] ?? UNKNOWN),
77 cpu: figure(measured || s.cpuLimit !== null ? `${measured ? `${s.cpuPct.toFixed(1)}% of one core` : UNKNOWN}${limitWords(s.cpuLimit, cores)}` : UNKNOWN),
78 memory: figure(measured || s.memLimitMiB !== null ? `${measured ? mib(s.memMiB) : UNKNOWN}${limitWords(s.memLimitMiB, mib)}${has > 0 && !s.memLimitMiB ? `; its machine has ${mib(has)}` : ""}` : UNKNOWN),
79 uptime: figure(s.upSince !== null ? spanWords(s.upSince, now) : (/^Up (.+?)(?: \(.*\))?$/.exec(ps?.status ?? "")?.[1] ?? UNKNOWN)),
7280 image: owner ? (ps?.image ?? "") || UNKNOWN : "",
7381 page: `/games/${box.name}/${s.name}`,
7482 readAt: s.seenAt,
src/core/migration-pins/20261203003100-game-container-limits.pin added +1
@@ -0,0 +1,1 @@
1 f1713828b73565437fb92cb8a833f0f12be05287a6dd0f3b00d5082957ebb7ad
src/core/migrations/20261203003100-game-container-limits.ts added +7
@@ -0,0 +1,7 @@
1 // When a container started and the limits set on it (#17532), as the box's newest full sync said:
2 // null is not known (an older agent sends none of them), and a limit of 0 is "none set". Additive.
3 export default `
4 ALTER TABLE game_service ADD COLUMN up_since TEXT;
5 ALTER TABLE game_service ADD COLUMN mem_limit_mib INTEGER;
6 ALTER TABLE game_service ADD COLUMN cpu_limit REAL;
7 `;
src/games/agent.sh +23 −5
@@ -378,25 +378,43 @@ json_or() {
378378 since="$(now)"
379379 [ -f "$DIR/.results" ] || echo '[]' >"$DIR/.results"
380380
381 # The services as compose sees them, with each one's CPU and memory from docker stats.
381 # What one inspect may say of a container: never the whole answer, which holds every env value.
382 INSPECT='{"name":{{json .Name}},"running":{{json .State.Running}},"started":{{json .State.StartedAt}},"memory":{{json .HostConfig.Memory}},"cpus":{{json .HostConfig.NanoCpus}},"quota":{{json .HostConfig.CpuQuota}},"period":{{json .HostConfig.CpuPeriod}}}'
383
384 # The services as compose sees them, with each one's CPU and memory from docker stats, and its start
385 # time and limits from one docker inspect: a limit of 0 is none set, and what it did not say is left out.
382386 services() {
383 local ps stats
387 local ps stats ids='' limits='[]'
384388 ps="$(capped 5 "${COMPOSE[@]}" ps -a --format json 2>/dev/null | jq -cs 'flatten' 2>/dev/null)" || ps='[]'
385389 [ -n "$ps" ] || ps='[]'
386390 stats="$(capped 5 "$DOCKER" stats --no-stream --format json 2>/dev/null | jq -cs '.' 2>/dev/null)" || stats='[]'
387391 [ -n "$stats" ] || stats='[]'
388 jq -cn --argjson ps "$ps" --argjson stats "$stats" '
392 ids="$(jq -r '[.[].ID | strings | select(test("^[0-9a-f]{12,64}$"))] | join(" ")' <<<"$ps" 2>/dev/null)"
393 # shellcheck disable=SC2086 # a list of ids
394 [ -z "$ids" ] || limits="$(capped 5 "$DOCKER" inspect --format "$INSPECT" $ids 2>/dev/null | jq -cRn '[inputs | fromjson? | objects]' 2>/dev/null | json_or '[]')"
395 jq -cn --argjson ps "$ps" --argjson stats "$stats" --argjson limits "$limits" '
389396 def mib: (capture("^(?<n>[0-9.]+)\\s*(?<u>[KMGT]?i?B)") // {n: "0", u: "MiB"})
390397 | (.n | tonumber) * ({"B": (1/1048576), "KiB": (1/1024), "KB": (1/1024), "MiB": 1, "MB": 1, "GiB": 1024, "GB": 1024, "TiB": 1048576}[.u] // 1);
398 def known: type == "number" and . >= 0;
399 # The CPU limit in cores: `cpus`, else `cpu_quota` over its period (Docker takes 100000 for 0); a quota of 0 or less is none.
400 def cores: if (.cpus | known | not) then empty
401 elif .cpus > 0 then .cpus / 1000000000
402 elif (.quota | type) != "number" then empty
403 elif .quota > 0 then .quota / (if (.period | known) and .period > 0 then .period else 100000 end)
404 else 0 end;
391405 ($stats | map({key: .Name, value: .}) | from_entries) as $s
392 | $ps | map({
406 | ($limits | map({key: (.name | tostring | ltrimstr("/")), value: .}) | from_entries) as $l
407 | $ps | map($l[.Name // ""] as $i | {
393408 name: .Service,
394409 state: (.State // ""),
395410 health: (.Health // ""),
396411 startedAt: (.CreatedAt // ""),
397412 cpuPct: (($s[.Name].CPUPerc // "0%") | rtrimstr("%") | tonumber? // 0),
398413 memMiB: (($s[.Name].MemUsage // "0MiB") | split(" / ")[0] | mib | floor)
399 })'
414 }
415 + (if $i.running == true and ($i.started | type) == "string" then {upSince: $i.started} else {} end)
416 + (if $i.memory | known then {memLimitMiB: ($i.memory / 1048576 | floor)} else {} end)
417 + ([$i // {} | cores | {cpuLimit: .}] | add // {}))'
400418 }
401419
402420 # New log lines since the last sync, at most 200 a service: "hub | text" split at the first bar.
src/games/store.ts +38 −5
@@ -67,6 +67,11 @@ export interface GameService {
6767 readonly startedAt: string;
6868 readonly cpuPct: number;
6969 readonly memMiB: number;
70 /** When the container last started; null when the box did not say. `startedAt` is when it was made. */
71 readonly upSince: string | null;
72 /** The memory limit set on it, MiB, and the CPU limit, in cores: 0 is none set, null not known. */
73 readonly memLimitMiB: number | null;
74 readonly cpuLimit: number | null;
7075 readonly seenAt: string;
7176 /** Stopped by its sleep right now (`games/sleep.ts`): the container is stopped, and starts when someone joins. */
7277 readonly asleep: boolean;
@@ -208,9 +213,9 @@ export function markAsleep(db: Database, boxId: string, sleepers: readonly strin
208213 export const servicesOf = (db: Database, boxId: string): GameService[] =>
209214 db
210215 .query<
211 { name: string; state: string; health: string; started_at: string; cpu_pct: number; mem_mib: number; seen_at: string; asleep: number },
216 { name: string; state: string; health: string; started_at: string; cpu_pct: number; mem_mib: number; up_since: string | null; mem_limit_mib: number | null; cpu_limit: number | null; seen_at: string; asleep: number },
212217 [string]
213 >("SELECT name, state, health, started_at, cpu_pct, mem_mib, seen_at, asleep FROM game_service WHERE box_id = ?1 ORDER BY name")
218 >("SELECT name, state, health, started_at, cpu_pct, mem_mib, up_since, mem_limit_mib, cpu_limit, seen_at, asleep FROM game_service WHERE box_id = ?1 ORDER BY name")
214219 .all(boxId)
215220 .map((r) => ({
216221 name: r.name,
@@ -219,6 +224,9 @@ export const servicesOf = (db: Database, boxId: string): GameService[] =>
219224 startedAt: r.started_at,
220225 cpuPct: r.cpu_pct,
221226 memMiB: r.mem_mib,
227 upSince: r.up_since,
228 memLimitMiB: r.mem_limit_mib,
229 cpuLimit: r.cpu_limit,
222230 seenAt: r.seen_at,
223231 asleep: r.asleep === 1,
224232 }));
@@ -587,6 +595,10 @@ export interface SyncBody {
587595 startedAt?: unknown;
588596 cpuPct?: unknown;
589597 memMiB?: unknown;
598 /** Docker's start time, and the limits set on it: left out by an older agent, or when not read. */
599 upSince?: unknown;
600 memLimitMiB?: unknown;
601 cpuLimit?: unknown;
590602 }[];
591603 readonly logs?: Record<string, unknown>;
592604 /** Per service, the raw RCON answers the agent read (`list`, `tps`, `mspt`): `games/metrics.ts` parses them. */
@@ -632,6 +644,26 @@ export interface SyncBody {
632644 const str = (v: unknown, max = 200): string => (typeof v === "string" ? v.slice(0, max) : "");
633645 const num = (v: unknown): number => (typeof v === "number" && Number.isFinite(v) ? v : 0);
634646
647 /** A limit as the box sent it: 0 (none set) or `least` to `most`; anything else is not known. */
648 const limit = (v: unknown, least: number, most: number): number | null => (typeof v === "number" && (v === 0 || (v >= least && v <= most)) ? v : null);
649
650 /** A memory limit in whole MiB, 64 TiB at most. */
651 const wholeMiB = (v: unknown): number | null => {
652 const n = limit(v, 1, 64 * 1024 * 1024);
653 return n === null ? null : Math.floor(n);
654 };
655
656 /** The oldest start believed (Docker writes year 1 for "never"), and how far ahead a box's clock may run. */
657 const OLDEST_START = Date.parse("2013-01-01T00:00:00Z");
658 const CLOCK_AHEAD_MS = 5 * 60_000;
659
660 /** Docker's RFC 3339 start time, to the millisecond in UTC; null when it is not one, or not a sane one. */
661 function startOf(v: unknown, at: string): string | null {
662 const m = /^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d)(\.\d{1,9})?(Z|[+-]\d\d:\d\d)$/.exec(str(v, 41));
663 const ms = m === null ? NaN : Date.parse(`${m[1]}${(m[2] ?? ".000").slice(0, 4).padEnd(4, "0")}${m[3]}`);
664 return ms >= OLDEST_START && ms <= Date.parse(at) + CLOCK_AHEAD_MS ? new Date(ms).toISOString() : null;
665 }
666
635667 /**
636668 * After a sync whose answer never came back (a timeout), the agent sends its lines again from the
637669 * older mark and says so (`retry`): how many of the first of `sent` are already the newest the
@@ -697,9 +729,10 @@ export function recordSync(
697729 const name = str(s.name, 64);
698730 if (!SERVICE_NAME.test(name)) continue;
699731 db.query(
700 `INSERT INTO game_service (box_id, name, state, health, started_at, cpu_pct, mem_mib, seen_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)
701 ON CONFLICT (box_id, name) DO UPDATE SET state = excluded.state, health = excluded.health, started_at = excluded.started_at, cpu_pct = excluded.cpu_pct, mem_mib = excluded.mem_mib, seen_at = excluded.seen_at`,
702 ).run(box.id, name, str(s.state, 20), str(s.health, 20), str(s.startedAt, 40), num(s.cpuPct), num(s.memMiB), at);
732 `INSERT INTO game_service (box_id, name, state, health, started_at, cpu_pct, mem_mib, seen_at, up_since, mem_limit_mib, cpu_limit) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)
733 ON CONFLICT (box_id, name) DO UPDATE SET state = excluded.state, health = excluded.health, started_at = excluded.started_at, cpu_pct = excluded.cpu_pct, mem_mib = excluded.mem_mib, seen_at = excluded.seen_at,
734 up_since = excluded.up_since, mem_limit_mib = excluded.mem_limit_mib, cpu_limit = excluded.cpu_limit`,
735 ).run(box.id, name, str(s.state, 20), str(s.health, 20), str(s.startedAt, 40), num(s.cpuPct), num(s.memMiB), at, startOf(s.upSince, at), wholeMiB(s.memLimitMiB), limit(s.cpuLimit, 0.001, 4_096));
703736 }
704737 for (const [service, lines] of Object.entries(body.logs ?? {}).slice(0, 64)) {
705738 if (!SERVICE_NAME.test(service) || !Array.isArray(lines)) continue;
test/cloud-containers.test.ts +35
@@ -124,6 +124,41 @@ test("what the last sync said, and not known where it did not", () => {
124124 expect(JSON.stringify(facts(HUB))).not.toContain("2026-11-01");
125125 });
126126
127 test("the agent's three fields: up since, and limits, where 0 is none set and a missing one is not known", () => {
128 const up = (ms: number): string => new Date(Date.now() - ms).toISOString().replace("Z", "123456Z");
129 const hub = (o: Record<string, unknown>): Record<string, string> => {
130 sync({ ...SYNC, services: [{ ...service("hub", "running", 12.5, 900), ...o }] });
131 return facts(HUB);
132 };
133 // Docker's own start time is believed before the words in the diagnosis ("Up 3 hours").
134 expect(hub({ upSince: up(26 * 3_600_000), memLimitMiB: 2048, cpuLimit: 1.5 })).toMatchObject({ CPU: "12.5% of one core, limit 1.5 cores", Memory: "900 MiB, limit 2.0 GiB", Uptime: "26 hours" });
135 // The terminal draws the same facts.
136 for (const words of ["12.5% of one core, limit 1.5 cores", "900 MiB, limit 2.0 GiB", "26 hours"]) expect(cloudLines(view(), at(HUB)).join("\n")).toContain(words);
137 expect(hub({ upSince: up(20_000), memLimitMiB: 512, cpuLimit: 1 })).toMatchObject({ CPU: "12.5% of one core, limit 1 core", Memory: "900 MiB, limit 512 MiB", Uptime: "less than a minute" });
138 expect(hub({ memLimitMiB: 0, cpuLimit: 0 })).toMatchObject({ CPU: "12.5% of one core, no limit set", Memory: "900 MiB, no limit set; its machine has 15.6 GiB" });
139 // Left out by this sync: what the last one said is not kept. An older agent shows what it did.
140 expect(hub({ upSince: "" })).toMatchObject({ CPU: "12.5% of one core, limit not known", Memory: "900 MiB, limit not known; its machine has 15.6 GiB", Uptime: "3 hours" });
141 // Figures that could not be read do not hide a limit that was.
142 expect(hub({ cpuPct: 0, memMiB: 0, memLimitMiB: 2048, cpuLimit: 2 })).toMatchObject({ CPU: "not known, limit 2 cores", Memory: "not known, limit 2.0 GiB" });
143 sync({ ...SYNC, services: [{ ...service("hub", "exited", 0, 0), upSince: up(3_600_000), memLimitMiB: 2048, cpuLimit: 1 }] });
144 expect(facts(HUB)).toMatchObject({ CPU: "none, it is not running", Memory: "none, it is not running", Uptime: "none, it is not running" });
145 });
146
147 test("the box is not trusted: a field out of its range is not known, and never 0 or an error", () => {
148 const day = 86_400_000;
149 const row = (o: Record<string, unknown>): unknown => {
150 sync({ ...SYNC, services: [{ ...service("hub", "running", 12.5, 900), ...o }] });
151 return app.db.query("SELECT up_since, mem_limit_mib, cpu_limit FROM game_service WHERE name = 'hub'").get();
152 };
153 const none = { up_since: null, mem_limit_mib: null, cpu_limit: null };
154 for (const v of [null, "", "yesterday", "2026-12-01", "0001-01-01T00:00:00Z", "2026-13-45T00:00:00Z", new Date(Date.now() + day).toISOString(), `${new Date().toISOString()}${"0".repeat(500)}`, 1_700_000_000_000, {}, ["2026-12-01T00:00:00Z"]]) expect(row({ upSince: v })).toEqual(none);
155 for (const v of [null, "2048", -1, 0.5, 1e12, true, {}, [5]]) expect(row({ memLimitMiB: v })).toEqual(none);
156 for (const v of [null, "1.5", -1, 1e-9, 1e6, true, {}, [1]]) expect(row({ cpuLimit: v })).toEqual(none);
157 // A box's clock may run a little ahead; a date is kept in one form.
158 expect(row({ upSince: "2026-12-01T10:00:00.123456789+02:00", memLimitMiB: 2048.9, cpuLimit: 0.25 })).toEqual({ up_since: "2026-12-01T08:00:00.123Z", mem_limit_mib: 2048, cpu_limit: 0.25 });
159 expect((row({ upSince: new Date(Date.now() + 60_000).toISOString() }) as { up_since: string | null }).up_since).not.toBeNull();
160 });
161
127162 test("a silent box: what runs now is not known, and what it last said is told as that", () => {
128163 app.db.run("DELETE FROM game_service");
129164 sync(SYNC, new Date(Date.now() - 3 * 3_600_000));
test/game-agent-limits.test.ts added +117
@@ -0,0 +1,117 @@
1 /**
2 * The game box's agent says when each container started and its limits (#17532): one docker inspect
3 * a full sync, with a format that names only those fields, since the whole answer holds every env
4 * value. An inspect that fails, hangs or names fewer containers costs those fields and nothing else.
5 */
6 import { expect, test } from "bun:test";
7 import { chmodSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
8 import { rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { quietLogs } from "./helpers/globals.ts";
12
13 quietLogs();
14
15 const AGENT = join(import.meta.dir, "../src/games/agent.sh");
16 const lacks = ["bash", "curl", "jq", "timeout"].filter((t) => Bun.which(t) === null);
17 const on = test.skipIf(lacks.length > 0);
18
19 const id = (n: number): string => `${n}f3c9a1b2d4e5`.repeat(5).slice(0, 64);
20 const NAMES = ["velocity", "hub", "survival", "game-hunting-1", "forge-waker"];
21 const PS = NAMES.map((Name, i) => JSON.stringify({ ID: id(i), Service: Name.replace(/^game-|-1$/g, ""), Name, State: i === 2 ? "exited" : "running", Health: "", CreatedAt: "2026-11-01 10:00:00 +0000 UTC" })).join("\n");
22 const line = (i: number, o: Record<string, unknown> = {}): string => JSON.stringify({ name: `/${NAMES[i]!}`, running: i !== 2, started: "2026-12-01T08:00:00.123456789Z", memory: 0, cpus: 0, quota: 0, period: 0, ...o });
23
24 type Sent = Record<string, unknown>;
25
26 /** One full sync of the agent with a docker whose `inspect` is `inspect`: what it sent, and every docker call. */
27 async function syncWith(inspect: string): Promise<{ services: Sent[]; body: string; calls: string[] }> {
28 const box = mkdtempSync(join(tmpdir(), "forge-game-limits-"));
29 const docker = join(box, "docker");
30 writeFileSync(join(box, "ps.json"), `${PS}\n`);
31 writeFileSync(join(box, "inspect.json"), NAMES.map((_, i) => line(i, i === 1 ? { memory: 2_147_483_648 + 700_000, cpus: 1_500_000_000 } : {})).join("\n"));
32 writeFileSync(
33 docker,
34 `#!/usr/bin/env bash
35 printf '%s\\n' "$*" >>"${box}/calls"
36 case "$*" in
37 *" ps -a --format json") cat "${box}/ps.json" ;;
38 "stats --no-stream --format json") echo '{"Name":"hub","CPUPerc":"12.5%","MemUsage":"812MiB / 7.8GiB"}' ;;
39 "inspect --format "*) ${inspect} ;;
40 inspect*) echo '[{"Config":{"Env":["RCON_PASSWORD=hunter2"]}}]' ;;
41 esac
42 `,
43 );
44 chmodSync(docker, 0o755);
45 // The agent's own cap, shorter for the inspect alone, so a hang is not 5 s of a test.
46 writeFileSync(join(box, "timeout"), `#!/usr/bin/env bash\ncase "$*" in *" inspect "*) shift; exec "${Bun.which("timeout") ?? ""}" 1 "$@" ;; esac\nexec "${Bun.which("timeout") ?? ""}" "$@"\n`);
47 chmodSync(join(box, "timeout"), 0o755);
48 const bodies: string[] = [];
49 const forge = Bun.serve({
50 port: 0,
51 hostname: "127.0.0.1",
52 async fetch(req) {
53 bodies.push(await req.text());
54 return Response.json({ composeSha: "", commands: [] });
55 },
56 });
57 try {
58 const p = Bun.spawn(["bash", AGENT], {
59 env: { PATH: `${box}:${process.env["PATH"] ?? ""}`, FORGE_URL: `http://127.0.0.1:${String(forge.port)}`, FORGE_GAME_TOKEN: "fgb_abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG", FORGE_GAME_DIR: box, FORGE_GAME_DOCKER: docker, FORGE_GAME_ONCE: "1" },
60 stdout: "ignore",
61 stderr: "pipe",
62 });
63 const said = await new Response(p.stderr).text();
64 await p.exited;
65 expect(bodies.length, `the agent said: ${said}`).toBe(1);
66 return { services: (JSON.parse(bodies[0]!) as { services: Sent[] }).services, body: bodies[0]!, calls: readFileSync(join(box, "calls"), "utf8").split("\n") };
67 } finally {
68 forge.stop(true);
69 await rm(box, { recursive: true, force: true });
70 }
71 }
72 const hasNone = (s: Sent): boolean => !("upSince" in s) && !("memLimitMiB" in s) && !("cpuLimit" in s);
73
74 on("one inspect over every container compose lists: start while running, limits in MiB and cores, 0 for none set", async () => {
75 const { services, body, calls } = await syncWith(`cat "\${0%/*}/inspect.json"`);
76 expect(services.map((s) => s["name"])).toEqual(["velocity", "hub", "survival", "hunting", "forge-waker"]);
77 expect(services[1]).toEqual({ name: "hub", state: "running", health: "", startedAt: "2026-11-01 10:00:00 +0000 UTC", cpuPct: 12.5, memMiB: 812, upSince: "2026-12-01T08:00:00.123456789Z", memLimitMiB: 2048, cpuLimit: 1.5 });
78 expect(services[3]).toMatchObject({ upSince: "2026-12-01T08:00:00.123456789Z", memLimitMiB: 0, cpuLimit: 0 });
79 // Stopped: its limits are still set on it, and it is not up since anything.
80 expect(services[2]).toMatchObject({ memLimitMiB: 0, cpuLimit: 0 });
81 expect("upSince" in services[2]!).toBe(false);
82 const asked = calls.filter((c) => c.startsWith("inspect"));
83 expect(asked.length).toBe(1);
84 for (let i = 0; i < NAMES.length; i++) expect(asked[0]).toContain(id(i));
85 // Only these fields, by name: the rest of an inspect is the env.
86 expect([...asked[0]!.matchAll(/\{\{(.*?)\}\}/g)].map((m) => m[1])).toEqual(["json .Name", "json .State.Running", "json .State.StartedAt", "json .HostConfig.Memory", "json .HostConfig.NanoCpus", "json .HostConfig.CpuQuota", "json .HostConfig.CpuPeriod"]);
87 expect(body).not.toContain("hunter2");
88 });
89
90 on("an inspect that fails, prints rubbish or hangs: the sync is whole, without the fields", async () => {
91 for (const broken of ["exit 1", "echo 'Error: template: no such field'; exit 1", `echo '{"name":"/hub","mem'; sleep 60`]) {
92 const { services } = await syncWith(broken);
93 expect(services.map((s) => [s["name"], s["state"]])).toEqual([["velocity", "running"], ["hub", "running"], ["survival", "exited"], ["hunting", "running"], ["forge-waker", "running"]]);
94 expect(services[1]).toMatchObject({ cpuPct: 12.5, memMiB: 812 });
95 expect(services.every(hasNone)).toBe(true);
96 }
97 }, 30_000);
98
99 on("a container gone before the inspect costs its own fields alone, and a figure that is none is left out", async () => {
100 const { services } = await syncWith(`echo '${line(1)}'; echo '${line(0, { memory: null, cpus: "2", started: 5 })}'; echo 'Error: No such object' >&2; exit 1`);
101 expect(services[1]).toMatchObject({ memLimitMiB: 0, cpuLimit: 0 });
102 expect([services[0]!, ...services.slice(2)].every(hasNone)).toBe(true);
103 });
104
105 on("the CPU limit: cpus, else the quota over its period, else none set; a quota it did not say is not known", async () => {
106 const cases: [Record<string, unknown>, number | undefined][] = [
107 [{ cpus: 1_500_000_000, quota: 50_000, period: 100_000 }, 1.5],
108 [{ quota: 50_000, period: 200_000 }, 0.25],
109 [{ quota: 250_000, period: 0 }, 2.5],
110 [{ quota: -1, period: 100_000 }, 0],
111 [{ quota: null }, undefined],
112 ];
113 const { services } = await syncWith(cases.map(([o], i) => `echo '${line(i, o)}'`).join("; "));
114 expect(services.map((s) => s["cpuLimit"])).toEqual(cases.map(([, cores]) => cores));
115 // The rest of each entry is there whatever the CPU said.
116 expect(services.every((s) => s["memLimitMiB"] === 0)).toBe(true);
117 });
test/game-topology.test.ts +1 −1
@@ -41,7 +41,7 @@ const COMPOSE = `services:
4141 forge-waker:
4242 image: wollomatic/socket-proxy:1.14.0
4343 `;
44 const svc = (state: string, health = "") => ({ name: "x", state, health, startedAt: "", cpuPct: 0, memMiB: 0, seenAt: "", asleep: false });
44 const svc = (state: string, health = "") => ({ name: "x", state, health, startedAt: "", cpuPct: 0, memMiB: 0, upSince: null, memLimitMiB: null, cpuLimit: null, seenAt: "", asleep: false });
4545
4646 describe("the pieces", () => {
4747 test("four states, and an old box's stop reads as stopped", () => {

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs