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

Game servers sleep while empty and wake when someone joins (AutoStopper on Velocity) #17290

opened this

Merged 35h 42m ago, live in production

sold/game-sleep → main 0 commits 7 threads · 7 unresolved

  • Merged. sold/game-sleep was merged into main as cdf0f4f.

Review

Sign in to review this change.
15 files changed +796 −40
docs/features/games.md +12
@@ -21,6 +21,18 @@ Adding a Modrinth slug to a service whose `TYPE` and `VERSION` are set (Paper, F
2121
2222 The agent sends every string plain: terminal colour escapes and control bytes (which itzg images and `rcon-cli` print) are taken out, and every part is checked as JSON and passed through a file, never a command line, so a large sync still goes. The forge cleans the same from what an older agent sends (`boundedMachineBody`), and refuses only a body that is not JSON, with where it broke; its log holds the first 200 bytes.
2323
24 ## Sleep and wake
25
26 Each game server is warm or sleeps when empty. A sleeping server container stops after 10 minutes with nobody on it, which frees all its memory, and starts again when a player joins through the proxy: the player waits on the join screen while it boots (measured 13.9 to 15.2 s for Paper 1.21.6 once its world exists, 30 s on its first boot). The Minecraft client gives up on a silent join after about 30 s, so a boot that takes longer means one rejoin.
27
28 The policy is the label `forge.sleep: "true"` with `restart: "no"` in the compose file. Changing it on a service page (Sleep), with `z` on the terminal Games screen, or with the `games` tool `sleep` action is a commit by the person, who needs write access to the repository. From the labels the forge writes the rest of the file (`src/games/sleep.ts`):
29
30 - AutoStopper 3.0.0 (a Velocity plugin) in the proxy `MODRINTH_PROJECTS`, pinned to its Modrinth version id (`PG4gqnzX:EclCtvWk`): the image downloads that one version and checks the jar against its sha512 (`066bbc8b…d265361c`, in full in `AUTOSTOPPER_SHA512`), refusing a jar that differs. The proxy gets `MINECRAFT_VERSION` too when it has none, which the image needs beside `MODRINTH_PROJECTS`. Its settings as the compose config `forge_sleep` (the sleeping servers, a readiness probe, the empty time), and the sleepers in the proxy `FORGE_SLEEP`, so compose recreates the proxy when they change.
31 - Velocity `read-timeout` at 120 s while anything sleeps (30 s again when nothing does), so the proxy holds a joining player through a boot.
32 - `forge-waker`, a Docker socket proxy and the boundary: the proxy may inspect, start and stop the sleeping servers' containers and nothing else, and it never holds the Docker socket. Its image is pinned by digest (`wollomatic/socket-proxy:1.14.0@sha256:fead157c…`), since it holds the socket as root. A sleeping server's container name must be letters, digits, `_`, `.` and `-` (anything else is refused before a commit), and each name is escaped in the allowlist, so no name can widen it.
33
34 Warm again takes all of it away; the same labels always give the same file. Only an itzg/minecraft-server server can sleep; the proxy never does. Nothing chosen means warm. `/games/<box>` says "asleep (wakes on join)" for a sleeping server whose container has stopped.
35
2436 ## Secrets
2537
2638 The Velocity forwarding secret (`forwarding.env`) and an RCON password a service (`rcon-<service>.env`) are generated once, sealed like every forge secret and sent only in the sync's `env`, never committed. A box token is shown once and stored hashed. An uploaded jar is kept by the forge at `/games/jar/<id>/<name>`; the compose a box gets carries it signed for 6 hours, and only for the box that uploaded it. A jar must be a `.jar` (a zip), at most 64 MiB, and a box keeps at most 20 jars and 256 MiB.
src/core/migration-pins/20261201190000-game-sleep.pin added +1
@@ -0,0 +1,1 @@
1 4085a9a780cfb4b47761694578307589f6d64442f8263321a2a9b9251ed6c985
src/core/migrations/20261201190000-game-sleep.ts added +5
@@ -0,0 +1,5 @@
1 // Sleep and wake (#16840): whether a game server's container is stopped by its sleep policy right
2 // now (the compose label forge.sleep and the state its box last said). It wakes when a player joins.
3 export default `
4 ALTER TABLE game_service ADD COLUMN asleep INTEGER NOT NULL DEFAULT 0;
5 `;
src/crew/conversation_ask.ts +1
@@ -328,6 +328,7 @@ export const ASKED_AS: Readonly<Record<string, Form>> = {
328328 if (a["action"] === "env") return `Set ${val(a, "key")} on ${on}${clause(" to ", val(a, "value"))}, a commit that redeploys it`;
329329 if (a["action"] === "plugin") return `Add the plugin ${val(a, "modrinth") || val(a, "value")} to ${on}, a commit that redeploys it`;
330330 if (a["action"] === "config_set") return `Set the setting ${val(a, "key")} on ${on}${clause(" to ", val(a, "value"))}, a commit that restarts it`;
331 if (a["action"] === "sleep") return a["value"] === "warm" ? `Keep ${on} warm, a commit that redeploys it` : `Let ${on} sleep when empty and wake on join, a commit that redeploys it`;
331332 return `Change ${on}`;
332333 },
333334 crew_accounts: (a) => `Let the crew's runs for ${val(a, "repo") || val(a, "owner") || "your repositories"} spend the account ${val(a, "allow")}`,
src/games/compose.ts +135 −19
@@ -57,39 +57,49 @@ export function serviceEnv(text: string, service: string): Record<string, string
5757 }
5858
5959 const KEY = /^[A-Za-z_][A-Za-z0-9_]*$/;
60 const LABEL = /^[A-Za-z0-9][A-Za-z0-9_.-]*$/;
6061 const quote = (v: string): string => JSON.stringify(v);
6162
63 /** A service's labels as the compose file says them (map or list form). */
64 export function serviceLabels(text: string, service: string): Record<string, string> {
65 try {
66 const doc = Bun.YAML.parse(text) as { services?: Record<string, { labels?: unknown }> } | null;
67 const labels = doc?.services?.[service]?.labels;
68 if (Array.isArray(labels))
69 return Object.fromEntries(labels.filter((e): e is string => typeof e === "string").map((e) => [e.split("=")[0]!, e.slice(e.indexOf("=") + 1)]));
70 if (labels !== null && typeof labels === "object") return Object.fromEntries(Object.entries(labels).map(([k, v]) => [k, v === null ? "" : String(v)]));
71 } catch {}
72 return {};
73 }
74
6275 /**
6376 * The compose text with `values` set under `service`'s environment (a value of null removes the
6477 * key). The block keeps its own form: `KEY: value` lines, or `- KEY=value` lines.
6578 */
66 export function setServiceEnv(text: string, service: string, values: Record<string, string | null>): string {
67 for (const k of Object.keys(values)) if (!KEY.test(k)) throw new Error(`${k} is not an environment variable name`);
79 export const setServiceEnv = (text: string, service: string, values: Record<string, string | null>): string =>
80 setServiceMap(text, service, "environment", values);
81
82 /** The same for a service's `labels` (`forge.sleep: "true"`). */
83 export const setServiceLabels = (text: string, service: string, values: Record<string, string | null>): string =>
84 setServiceMap(text, service, "labels", values);
85
86 function setServiceMap(text: string, service: string, block: "environment" | "labels", values: Record<string, string | null>): string {
87 for (const k of Object.keys(values))
88 if (!(block === "environment" ? KEY : LABEL).test(k)) throw new Error(`${k} is not ${block === "environment" ? "an environment variable" : "a label"} name`);
6889 const lines = text.split("\n");
69 const indentOf = (l: string): number => l.length - l.trimStart().length;
70 const svc = lines.findIndex(
71 (l, i) => new RegExp(`^\\s+${service.replace(/[.]/g, "\\.")}:\\s*$`).test(l) && lines.slice(0, i).some((p) => /^services:\s*$/.test(p)),
72 );
73 if (svc < 0) throw new Error(`${service} is not a service in this compose file`);
74 const svcIndent = indentOf(lines[svc]!);
75 let end = lines.length;
76 for (let i = svc + 1; i < lines.length; i++)
77 if (lines[i]!.trim() !== "" && !lines[i]!.trimStart().startsWith("#") && indentOf(lines[i]!) <= svcIndent) {
78 end = i;
79 break;
80 }
90 const { at: svc, end, indent: svcIndent } = serviceSpan(lines, service);
8191 let env = -1;
8292 for (let i = svc + 1; i < end; i++)
83 if (/^\s+environment:\s*$/.test(lines[i]!)) {
93 if (new RegExp(`^\\s+${block}:\\s*$`).test(lines[i]!)) {
8494 env = i;
8595 break;
8696 }
8797 if (env < 0) {
8898 const child = svcIndent + 2;
89 const block = Object.entries(values)
99 const fresh = Object.entries(values)
90100 .filter(([, v]) => v !== null)
91101 .map(([k, v]) => `${" ".repeat(child + 2)}${k}: ${quote(v!)}`);
92 lines.splice(svc + 1, 0, `${" ".repeat(child)}environment:`, ...block);
102 lines.splice(svc + 1, 0, `${" ".repeat(child)}${block}:`, ...fresh);
93103 return lines.join("\n");
94104 }
95105 const envIndent = indentOf(lines[env]!);
@@ -105,7 +115,7 @@ export function setServiceEnv(text: string, service: string, values: Record<stri
105115 const keyOf = (l: string): string | undefined => {
106116 const t = l.trimStart();
107117 if (listForm) return t.startsWith("- ") ? t.slice(2).replace(/^["']/, "").split("=")[0] : undefined;
108 return /^[A-Za-z_][A-Za-z0-9_]*:/.test(t) ? t.split(":")[0] : undefined;
118 return /^["']?[A-Za-z0-9_.-]+["']?:/.test(t) ? t.split(":")[0]!.replace(/["']/g, "") : undefined;
109119 };
110120 const render = (k: string, v: string): string =>
111121 listForm ? `${" ".repeat(itemIndent)}- ${quote(`${k}=${v}`)}` : `${" ".repeat(itemIndent)}${k}: ${quote(v)}`;
@@ -123,7 +133,113 @@ export function setServiceEnv(text: string, service: string, values: Record<stri
123133 } else next.push(l);
124134 }
125135 for (const [k, v] of Object.entries(left)) if (v !== null) next.push(render(k, v));
126 lines.splice(env + 1, envEnd - env - 1, ...next);
136 // A block left with nothing in it goes, its key with it: warm again is the file as it was.
137 if (!next.some(meaningful)) lines.splice(env, envEnd - env);
138 else lines.splice(env + 1, envEnd - env - 1, ...next);
139 return lines.join("\n");
140 }
141
142 /** Whether line `at` continues the entry above it: deeper than `indent`, or blank before a deeper line. */
143 function continues(lines: readonly string[], at: number, indent: number): boolean {
144 const deeper = (l: string): boolean => l.length - l.trimStart().length > indent;
145 for (let i = at; i < lines.length; i++) if (lines[i]!.trim() !== "") return deeper(lines[i]!);
146 return false;
147 }
148
149 const indentOf = (l: string): number => l.length - l.trimStart().length;
150 const meaningful = (l: string): boolean => l.trim() !== "" && !l.trimStart().startsWith("#");
151
152 /** Where a service's block is: its own line, the line after its last, and its indent. */
153 function serviceSpan(lines: readonly string[], service: string): { at: number; end: number; indent: number } {
154 const at = lines.findIndex((l, i) => new RegExp(`^\\s+${service.replace(/[.]/g, "\\.")}:\\s*$`).test(l) && lines.slice(0, i).some((p) => /^services:\s*$/.test(p)));
155 if (at < 0) throw new Error(`${service} is not a service in this compose file`);
156 const indent = indentOf(lines[at]!);
157 let end = lines.length;
158 for (let i = at + 1; i < lines.length; i++)
159 if (meaningful(lines[i]!) && indentOf(lines[i]!) <= indent) {
160 end = i;
161 break;
162 }
163 while (end > at + 1 && lines[end - 1]!.trim() === "") end--;
164 return { at, end, indent };
165 }
166
167 /** The compose text with a service's own scalar `key` set (`restart: "no"`), or removed with null. */
168 export function setServiceKey(text: string, service: string, key: string, value: string | null): string {
169 const lines = text.split("\n");
170 const { at, end, indent } = serviceSpan(lines, service);
171 const child = indent + 2;
172 const i = lines.findIndex((l, n) => n > at && n < end && indentOf(l) === child && l.trimStart().startsWith(`${key}:`));
173 const line = `${" ".repeat(child)}${key}: ${value === null ? "" : quote(value)}`;
174 if (i >= 0) {
175 let last = i;
176 while (last + 1 < end && continues(lines, last + 1, child)) last++;
177 lines.splice(i, last - i + 1, ...(value === null ? [] : [line]));
178 } else if (value !== null) lines.splice(at + 1, 0, line);
179 return lines.join("\n");
180 }
181
182 /**
183 * The compose text with one item of a service's list `key` (its `configs:`, say) set: the item
184 * whose lines carry `marker` is replaced by `item` (lines that start "- ", relative), or removed
185 * with null; the list is made when it is missing.
186 */
187 export function setServiceListItem(text: string, service: string, key: string, marker: string, item: readonly string[] | null): string {
188 const lines = text.split("\n");
189 const { at, end, indent } = serviceSpan(lines, service);
190 const child = indent + 2;
191 const k = lines.findIndex((l, n) => n > at && n < end && indentOf(l) === child && new RegExp(`^\\s*${key}:\\s*$`).test(l));
192 const put = (pad: number): string[] => (item ?? []).map((l) => `${" ".repeat(pad)}${l}`);
193 if (k < 0) {
194 if (item !== null) lines.splice(end, 0, `${" ".repeat(child)}${key}:`, ...put(child + 2));
195 return lines.join("\n");
196 }
197 let listEnd = k + 1;
198 while (listEnd < end && (lines[listEnd]!.trim() === "" || indentOf(lines[listEnd]!) > child)) listEnd++;
199 while (listEnd > k + 1 && lines[listEnd - 1]!.trim() === "") listEnd--;
200 const firstItem = lines.slice(k + 1, listEnd).find((l) => l.trimStart().startsWith("- "));
201 const pad = firstItem === undefined ? child + 2 : indentOf(firstItem);
202 // The items, each a run of lines from its "- ".
203 const items: string[][] = [];
204 for (const l of lines.slice(k + 1, listEnd)) {
205 if (indentOf(l) === pad && l.trimStart().startsWith("- ")) items.push([l]);
206 else if (items.length > 0) items[items.length - 1]!.push(l);
207 }
208 const kept = items.filter((it) => !it.some((l) => l.includes(marker)));
209 lines.splice(k + 1, listEnd - k - 1, ...kept.flat(), ...put(pad));
210 return lines.join("\n");
211 }
212
213 /**
214 * The compose text with the top-level `section`'s entry `name` set to `block` (its lines below the
215 * name, relative to it), or removed with null; the section is made at the end when it is missing.
216 */
217 export function setTopEntry(text: string, section: string, name: string, block: readonly string[] | null): string {
218 const lines = text.split("\n");
219 const entry = block === null ? [] : [` ${name}:`, ...block.map((l) => (l === "" ? "" : ` ${l}`))];
220 const sec = lines.findIndex((l) => new RegExp(`^${section}:\\s*$`).test(l));
221 if (sec < 0) {
222 if (block === null) return text;
223 while (lines.length > 0 && lines[lines.length - 1]!.trim() === "") lines.pop();
224 lines.push("", `${section}:`, ...entry, "");
225 return lines.join("\n");
226 }
227 let end = lines.length;
228 for (let i = sec + 1; i < lines.length; i++)
229 if (meaningful(lines[i]!) && indentOf(lines[i]!) === 0) {
230 end = i;
231 break;
232 }
233 const at = lines.findIndex((l, n) => n > sec && n < end && l.startsWith(` ${name}:`) && indentOf(l) === 2);
234 if (at >= 0) {
235 let last = at;
236 while (last + 1 < end && (lines[last + 1]!.trim() === "" ? continues(lines, last + 1, 2) : indentOf(lines[last + 1]!) > 2)) last++;
237 lines.splice(at, last - at + 1);
238 end -= last - at + 1;
239 }
240 let tail = end;
241 while (tail > sec + 1 && lines[tail - 1]!.trim() === "") tail--;
242 lines.splice(tail, 0, ...entry);
127243 return lines.join("\n");
128244 }
129245
src/games/sleep.ts added +258
@@ -0,0 +1,258 @@
1 /**
2 * Sleep and wake for game servers (#16840). A sleeping server's container stops after
3 * `EMPTY_SECONDS` with nobody on it, which frees all its memory, and starts again when a player
4 * joins through the proxy, who waits on the join screen while it boots (measured 13–30 s for Paper
5 * 1.21.6 on a quiet machine).
6 *
7 * The policy is the compose label `forge.sleep: "true"` with `restart: "no"`, so a commit changes it,
8 * the crew can propose it and a merge redeploys it. From the labels the forge writes the rest of the
9 * file, every time a policy changes (`syncSleep`):
10 * - AutoStopper (a Velocity plugin) in the proxy's MODRINTH_PROJECTS, pinned to one version whose jar
11 * the image checks against its sha512 before it loads it, and its config as a compose config the
12 * proxy image copies into its plugin folder: the sleeping servers, their readiness probe, the
13 * empty time. AutoStopper stops a server that has been empty that long and, when a player asks
14 * for it, starts it, waits until it answers, and sends the player on.
15 * - `forge-waker`, a Docker socket proxy pinned by digest, that is the boundary: the proxy may
16 * inspect, start and stop the sleeping servers' containers and nothing else; the proxy never holds
17 * the socket. A container name outside `[A-Za-z0-9_.-]` is refused, so no name can widen its
18 * allowlist, and each name is escaped in it as a regular expression too.
19 * The proxy itself is never a sleeping server: it is the door.
20 */
21
22 import type { App } from "../app.ts";
23 import type { User } from "../core/users.ts";
24 import {
25 commitCompose,
26 serviceEnv,
27 serviceLabels,
28 setServiceEnv,
29 setServiceKey,
30 setServiceLabels,
31 setServiceListItem,
32 setTopEntry,
33 } from "./compose.ts";
34 import type { GameBox } from "./store.ts";
35
36 export const SLEEP_LABEL = "forge.sleep";
37 /** Ten minutes empty before a sleeping server stops. */
38 export const EMPTY_SECONDS = 600;
39 /** The socket proxy the forge adds while any server sleeps. */
40 export const WAKER = "forge-waker";
outdated

Unpinned supply chain: a jar loaded into the proxy, fetched with no hash. Pin a checksum or vendor it, and say so in the docs.

41 /** The compose config that holds AutoStopper's settings. */
42 export const WAKER_CONFIG = "forge_sleep";
43 /**
44 * AutoStopper 3.0.0, as Modrinth project:version ids. The proxy image (mc-image-helper) downloads
45 * that one version and checks the jar against the sha512 Modrinth lists for it, which is
46 * `AUTOSTOPPER_SHA512` (a Modrinth version's files cannot be replaced), refusing a jar that differs.
47 */
48 export const AUTOSTOPPER = "PG4gqnzX:EclCtvWk";
49 export const AUTOSTOPPER_SHA512 =
50 "066bbc8b7ac41d8f360cb28de41a78b260843cd0f10af328f49a51bf37e4c52c63b258bfd73c783d7c649e6fe233a1153f7f062aa8c2cf952bbc5192d265361c";
51 /** The jar's URL an earlier forge wrote into the proxy's PLUGINS, unchecked: taken out wherever it is. */
52 const AUTOSTOPPER_URL = "https://cdn.modrinth.com/data/PG4gqnzX/versions/EclCtvWk/AutoStopper-3.0.0.jar";
53 /**
54 * The image wants a game version beside MODRINTH_PROJECTS; a pinned version id is fetched as it is,
55 * so this only satisfies it: the network's own version when a server says one.
56 */
57 const GAME_VERSION = "1.21.6";
58 /** The socket proxy, wollomatic/socket-proxy 1.14.0, by digest: it holds the Docker socket as root. */
59 export const WAKER_IMAGE = "wollomatic/socket-proxy:1.14.0@sha256:fead157c4de4092461267092be49c993c2e6dd296a54c89ed04b8c870016b045";
60 /** What a container name may be, here: it goes into YAML and into the waker's allowlist. */
61 const CONTAINER = /^[A-Za-z0-9_.-]{1,128}$/;
62 const regexEscape = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
63 const AUTOSTOPPER_AT = "/config/plugins/autostopper/config.yml";
64 /**
65 * Velocity's read-timeout while a server sleeps: it holds a joining player for as long as a cold
66 * start takes (it drops a silent connection at its default 30 s, measured), and its default again
67 * when nothing sleeps.
68 */
69 export const HOLD_MS = 120_000;
70 const VELOCITY_READ_TIMEOUT = 30_000;
71 const READ_TIMEOUT = /^(\s+read-timeout\s*=\s*)\d+(\s*)$/m;
72
73 export type Policy = "warm" | "sleep";
74
75 interface Doc {
76 name?: unknown;
77 services?: Record<string, { image?: unknown; container_name?: unknown; networks?: unknown; labels?: unknown; restart?: unknown }>;
78 }
79 const parse = (text: string): Doc => {
80 try {
81 return (Bun.YAML.parse(text) as Doc | null) ?? {};
82 } catch {
83 return {};
84 }
85 };
86 const imageOf = (doc: Doc, service: string): string => {
87 const image = doc.services?.[service]?.image;
88 return typeof image === "string" ? image : "";
89 };
90
91 /** Whether a service is a game server that can sleep: itzg's minecraft-server image. */
92 export const canSleep = (text: string, service: string): boolean => /(^|\/)itzg\/minecraft-server(:|$)/.test(imageOf(parse(text), service));
93
94 /** The proxy players come in through: the service running itzg's mc-proxy. */
95 export function proxyOf(text: string): string | undefined {
96 const doc = parse(text);
97 return Object.keys(doc.services ?? {}).find((s) => /(^|\/)itzg\/mc-proxy(:|$)/.test(imageOf(doc, s)));
98 }
99
100 /** The policy the compose file says: sleep when it is labelled and not restarted by Docker. */
101 export function policyOf(text: string, service: string): Policy {
102 const restart = parse(text).services?.[service]?.restart;
103 return serviceLabels(text, service)[SLEEP_LABEL] === "true" && (restart === "no" || restart === false) ? "sleep" : "warm";
104 }
105
106 /** Every service whose policy is sleep, sorted. */
107 export const sleeping = (text: string): string[] =>
108 Object.keys(parse(text).services ?? {})
109 .filter((s) => policyOf(text, s) === "sleep")
110 .sort();
111
112 /** The container a service runs as: its `container_name`, else compose's `<project>-<service>-1`. */
outdated

server_name and container_name come from the compose file and go into YAML unquoted. Quote them (JSON.stringify) so a name with a colon or newline cannot change the config.

113 function containerOf(doc: Doc, service: string): string {
114 const named = doc.services?.[service]?.container_name;
115 return typeof named === "string" ? named : `${typeof doc.name === "string" ? doc.name : "game"}-${service}-1`;
116 }
117
118 /** A container name the waker may name, or why not. */
119 function checkedContainer(doc: Doc, service: string): string {
120 const name = containerOf(doc, service);
121 if (!CONTAINER.test(name)) throw new Error(`${service} runs as the container "${name}"; a server that sleeps needs a container name of letters, digits, _ . and - only`);
122 return name;
123 }
124
125 /** AutoStopper's settings for these servers (a server's name in the proxy is its service's), each value quoted. */
126 function autostopperConfig(doc: Doc, servers: readonly string[]): string[] {
outdated

Only . is escaped; |, ), (, * and the rest in a container_name would change the allowlist this boundary rests on. Escape every regex metacharacter.

127 return [
128 `inactivity_timeout_seconds: ${EMPTY_SECONDS}`,
129 "docker:",
130 ` endpoint: tcp://${WAKER}:2375`,
outdated

Floating tag :1 on a root container holding the Docker socket. Pin by digest.

131 "monitored_servers:",
132 ...servers.flatMap((s) => [
133 ` - server_name: ${JSON.stringify(s)}`,
134 ` container_name: ${JSON.stringify(checkedContainer(doc, s))}`,
135 " readiness:",
136 " strategy: minecraft_status",
137 ` target_host: ${JSON.stringify(s)}`,
138 " target_port: 25565",
139 " probe_interval_millis: 1000",
140 " timeout_seconds: 120",
141 ]),
142 ];
143 }
144
145 /** The socket proxy's service: the proxy may inspect, start and stop these containers, nothing else. */
146 function wakerService(doc: Doc, proxy: string, servers: readonly string[]): string[] {
147 const names = servers.map((s) => regexEscape(checkedContainer(doc, s))).join("|");
148 if (!CONTAINER.test(proxy)) throw new Error(`the proxy's service name "${proxy}" must be letters, digits, _ . and - only`);
149 const networks = doc.services?.[proxy]?.networks;
150 return [
151 "# Written by the forge from the forge.sleep labels (src/games/sleep.ts): change a label, not this.",
152 `image: ${WAKER_IMAGE}`,
153 "restart: unless-stopped",
154 // It reads the socket as root, which a socket proxy needs; what it lets through is the allowlist.
155 'user: "0:0"',
156 ...(Array.isArray(networks) ? [`networks: [${networks.filter((n): n is string => typeof n === "string").join(", ")}]`] : []),
157 "command:",
158 " - -loglevel=warn",
159 " - -listenip=0.0.0.0",
160 ` - -allowfrom=${proxy}`,
161 ` - '-allowGET=(/v1\\..{1,2})?/(_ping|version|containers/(${names})/json)'`,
162 " - '-allowHEAD=/_ping'",
163 ` - '-allowPOST=(/v1\\..{1,2})?/containers/(${names})/(start|stop)'`,
164 "volumes:",
165 " - /var/run/docker.sock:/var/run/docker.sock:ro",
166 ];
167 }
168
169 /**
170 * The compose text with everything sleep needs written from its labels: the waker and AutoStopper's
171 * config while a server sleeps, all of it gone when none does. Run after every policy change, and
172 * again harmlessly: the same labels give the same file.
173 */
174 export function syncSleep(text: string): string {
175 const doc = parse(text);
176 const proxy = proxyOf(text);
177 const servers = sleeping(text);
178 if (proxy === undefined) {
179 if (servers.length > 0) throw new Error("sleep needs the proxy players come in through (itzg/mc-proxy) in the same compose file");
180 return text;
181 }
182 const on = servers.length > 0;
183 let out = setTopEntry(
184 text,
185 "configs",
186 WAKER_CONFIG,
187 on
188 ? [
189 "# Written by the forge from the forge.sleep labels (src/games/sleep.ts).",
190 "content: |",
191 ...autostopperConfig(doc, servers).map((l) => ` ${l}`),
192 ]
193 : null,
194 );
195 out = setTopEntry(out, "services", WAKER, on ? wakerService(doc, proxy, servers) : null);
196 out = setServiceListItem(
197 out,
198 proxy,
199 "configs",
200 `source: ${WAKER_CONFIG}`,
201 on ? [`- source: ${WAKER_CONFIG}`, ` target: ${AUTOSTOPPER_AT}`] : null,
202 );
203 // The proxy's own velocity.toml (inline in the file), where it says read-timeout.
204 out = out.replace(READ_TIMEOUT, (_, head: string, tail: string) => `${head}${on ? HOLD_MS : VELOCITY_READ_TIMEOUT}${tail}`);
205 const env = serviceEnv(out, proxy);
206 const items = (key: string): string[] => (env[key] ?? "").split(/[\s,]+/).filter((p) => p !== "" && p !== AUTOSTOPPER && p !== AUTOSTOPPER_URL);
207 const plugins = items("PLUGINS");
208 const projects = on ? [...items("MODRINTH_PROJECTS"), AUTOSTOPPER] : items("MODRINTH_PROJECTS");
209 // The image refuses MODRINTH_PROJECTS without a game version: the forge adds one when there is
210 // none, and takes back only its own when no project is left.
211 const version = gameVersion(text);
212 const ownVersion = env["MINECRAFT_VERSION"] === version;
213 const minecraftVersion = projects.length > 0 ? (env["MINECRAFT_VERSION"] ?? version) : ownVersion ? null : (env["MINECRAFT_VERSION"] ?? null);
214 // The sleepers in the proxy own environment too: compose recreates a container whose environment
215 // changed, not one whose config content did (measured), so AutoStopper reads every change.
216 return setServiceEnv(out, proxy, {
217 PLUGINS: plugins.length === 0 ? null : plugins.join(","),
218 MODRINTH_PROJECTS: projects.length === 0 ? null : projects.join(","),
219 MINECRAFT_VERSION: minecraftVersion,
220 FORGE_SLEEP: on ? servers.join(",") : null,
221 });
222 }
223
224 /** The network's game version: the first game server's VERSION that names one, else `GAME_VERSION`. */
225 function gameVersion(text: string): string {
226 for (const s of Object.keys(parse(text).services ?? {}).sort()) {
227 const v = canSleep(text, s) ? (serviceEnv(text, s)["VERSION"] ?? "") : "";
228 if (/^\d+\.\d+(\.\d+)?$/.test(v)) return v;
229 }
230 return GAME_VERSION;
231 }
232
233 /** The compose text with `service` set to `policy`, and the rest written to match. */
234 export function setPolicy(text: string, service: string, policy: Policy): string {
235 if (policy === "sleep" && !canSleep(text, service))
236 throw new Error(`${service} is not a game server that can sleep; only itzg/minecraft-server servers do`);
237 const labelled = setServiceLabels(text, service, { [SLEEP_LABEL]: policy === "sleep" ? "true" : null });
238 // Docker must not start a server that sleeps; a warm one takes the restart its anchor gives it.
239 return syncSleep(setServiceKey(labelled, service, "restart", policy === "sleep" ? "no" : null));
240 }
241
242 /** Commit a server's policy as the person: "games: <service> sleeps when empty" or "… stays warm". */
243 export function commitPolicy(
244 app: App,
245 user: User,
246 box: GameBox,
247 service: string,
248 policy: Policy,
249 ): Promise<{ ok: true; sha: string } | { ok: false; error: string }> {
250 return commitCompose(app, user, box, {
251 message: `games: ${service} ${policy === "sleep" ? "sleeps when empty" : "stays warm"}`,
252 what: "its sleep",
253 edit: (text) => setPolicy(text, service, policy),
254 });
255 }
256
257 /** A service's state in words: "asleep (wakes on join)" while its sleep has stopped it, else its own state. */
258 export const stateWords = (state: string, asleep: boolean): string => (asleep ? "asleep (wakes on join)" : state || "unknown");
src/games/store.ts +10 −2
@@ -56,6 +56,8 @@ export interface GameService {
5656 readonly cpuPct: number;
5757 readonly memMiB: number;
5858 readonly seenAt: string;
outdated

Stale comment: this is sleep, not auto-pause; and it says 'frozen' where the container is stopped.

59 /** Stopped by its sleep right now (`games/sleep.ts`): the container is stopped, and starts when someone joins. */
60 readonly asleep: boolean;
5961 }
6062
6163 interface BoxRow {
@@ -149,12 +151,17 @@ export function boxByToken(db: Database, token: string): GameBox | undefined {
149151 return r === null ? undefined : toBox(r);
150152 }
151153
154 /** Mark asleep each service of `sleepers` (its policy is sleep) whose container has stopped; every other one awake. */
155 export function markAsleep(db: Database, boxId: string, sleepers: readonly string[]): void {
156 db.query("UPDATE game_service SET asleep = (state = 'exited' AND name IN (SELECT value FROM json_each(?2))) WHERE box_id = ?1").run(boxId, JSON.stringify(sleepers));
157 }
158
152159 export const servicesOf = (db: Database, boxId: string): GameService[] =>
153160 db
154161 .query<
155 { name: string; state: string; health: string; started_at: string; cpu_pct: number; mem_mib: number; seen_at: string },
162 { name: string; state: string; health: string; started_at: string; cpu_pct: number; mem_mib: number; seen_at: string; asleep: number },
156163 [string]
157 >("SELECT name, state, health, started_at, cpu_pct, mem_mib, seen_at FROM game_service WHERE box_id = ?1 ORDER BY name")
164 >("SELECT name, state, health, started_at, cpu_pct, mem_mib, seen_at, asleep FROM game_service WHERE box_id = ?1 ORDER BY name")
158165 .all(boxId)
159166 .map((r) => ({
160167 name: r.name,
@@ -164,6 +171,7 @@ export const servicesOf = (db: Database, boxId: string): GameService[] =>
164171 cpuPct: r.cpu_pct,
165172 memMiB: r.mem_mib,
166173 seenAt: r.seen_at,
174 asleep: r.asleep === 1,
167175 }));
168176
169177 /** A box's word about its boot as every door says it: "Box is up but missing jq: …". */
src/generated/migrations.ts +12 −10
@@ -456,11 +456,12 @@ import m451 from "../core/migrations/20261201150000-dns-record.ts";
456456 import m452 from "../core/migrations/20261201150000-pinned-firewall.ts";
457457 import m453 from "../core/migrations/20261201170000-managed-database.ts";
458458 import m454 from "../core/migrations/20261201180000-game-box-diag.ts";
459 import m455 from "../core/migrations/20261201190000-working-edit.ts";
460 import m456 from "../core/migrations/20261201190200-dep-accept.ts";
461 import m457 from "../core/migrations/20261201190500-runner-machine.ts";
462 import m458 from "../core/migrations/20261201200000-cloud-projects.ts";
463 import m459 from "../core/migrations/20261202000000-mail-relay-scope.ts";
459 import m455 from "../core/migrations/20261201190000-game-sleep.ts";
460 import m456 from "../core/migrations/20261201190000-working-edit.ts";
461 import m457 from "../core/migrations/20261201190200-dep-accept.ts";
462 import m458 from "../core/migrations/20261201190500-runner-machine.ts";
463 import m459 from "../core/migrations/20261201200000-cloud-projects.ts";
464 import m460 from "../core/migrations/20261202000000-mail-relay-scope.ts";
464465
465466 /** Each migration file's name and its default export, in name order. */
466467 export const MIGRATION_MODULES: readonly (readonly [string, unknown])[] = [
@@ -919,9 +920,10 @@ export const MIGRATION_MODULES: readonly (readonly [string, unknown])[] = [
919920 ["20261201150000-pinned-firewall.ts", m452],
920921 ["20261201170000-managed-database.ts", m453],
921922 ["20261201180000-game-box-diag.ts", m454],
922 ["20261201190000-working-edit.ts", m455],
923 ["20261201190200-dep-accept.ts", m456],
924 ["20261201190500-runner-machine.ts", m457],
925 ["20261201200000-cloud-projects.ts", m458],
926 ["20261202000000-mail-relay-scope.ts", m459],
923 ["20261201190000-game-sleep.ts", m455],
924 ["20261201190000-working-edit.ts", m456],
925 ["20261201190200-dep-accept.ts", m457],
926 ["20261201190500-runner-machine.ts", m458],
927 ["20261201200000-cloud-projects.ts", m459],
928 ["20261202000000-mail-relay-scope.ts", m460],
927929 ];
src/http/games_routes.ts +7 −3
@@ -7,10 +7,11 @@ import { composeServices, readCompose } from "../games/compose.ts";
77 import { AGENT_SH, AGENT_SHA } from "../games/boot.ts";
88 import { synced } from "../games/notify.ts";
99 import { auditShellResults } from "../games/shell.ts";
10 import { boxByToken, envFiles, recordSync, signJarUrls, type SyncBody } from "../games/store.ts";
10 import { sleeping } from "../games/sleep.ts";
11 import { boxByToken, envFiles, markAsleep, recordSync, signJarUrls, type SyncBody } from "../games/store.ts";
1112 import { BODY_CAPS } from "../kernel/body_caps.ts";
1213 import {
13 gameBoxPage, gameCommandSubmit, gameEnvSubmit, gameGrantSubmit, gameJarDownload, gameJarSubmit, gamePluginSubmit, gamePowerSubmit, gameServicePage, gameSettingsSubmit, gameServiceStream, gameShellStream, gameShellSubmit, gamesPage,
14 gameBoxPage, gameCommandSubmit, gameEnvSubmit, gameGrantSubmit, gameJarDownload, gameJarSubmit, gamePluginSubmit, gamePowerSubmit, gameSleepSubmit, gameServicePage, gameSettingsSubmit, gameServiceStream, gameShellStream, gameShellSubmit, gamesPage,
1415 } from "../web/pages/games.ts";
1516 import type { Ctx, Handler } from "./context.ts";
1617 import { InvalidJson } from "./json_body.ts";
@@ -37,8 +38,10 @@ export async function gameAgentSync(ctx: Ctx): Promise<Response> {
3738 const commands = recordSync(ctx.app.db, box, body);
3839 // Every shell command the box answered, its output with it, into the audit.
3940 auditShellResults(ctx.app, box, (body.results ?? []).map((r) => r.id));
40 synced(ctx.app, box.id);
4141 const compose = await readCompose(ctx.app, box);
42 // A server its sleep stopped is asleep, not down: the compose file says which sleep.
43 markAsleep(ctx.app.db, box.id, compose === undefined ? [] : sleeping(compose.text));
44 synced(ctx.app, box.id);
4245 const reply: Record<string, unknown> = {
4346 composeSha: compose?.sha ?? "",
4447 env: envFiles(ctx.app, box, compose?.text ?? "", compose === undefined ? [] : composeServices(compose.text)),
@@ -78,6 +81,7 @@ export function gamesRoutes(router: Router<Handler>): void {
7881 router.add("POST", "/games/:box/:service/power", gamePowerSubmit);
7982 router.add("POST", "/games/:box/:service/env", gameEnvSubmit);
8083 router.add("POST", "/games/:box/:service/plugin", gamePluginSubmit);
84 router.add("POST", "/games/:box/:service/sleep", gameSleepSubmit);
8185 router.add("POST", "/games/:box/:service/jar", gameJarSubmit);
8286 router.add("POST", "/games/:box/:service/settings", gameSettingsSubmit);
8387 }
src/http/lazy_lists.ts +1
@@ -611,6 +611,7 @@ export const OPERATIONS_ROUTES = [
611611 ["POST", "/games/:box/:service/power"],
612612 ["POST", "/games/:box/:service/env"],
613613 ["POST", "/games/:box/:service/plugin"],
614 ["POST", "/games/:box/:service/sleep"],
614615 ["POST", "/games/:box/:service/jar"],
615616 ["POST", "/games/:box/:service/settings"],
616617 ["GET", "/resilience"],
src/http/mcp/tools/games.ts +11 −4
@@ -3,18 +3,19 @@ import { boxStatus, boxStatusShared } from "../../../games/diag.ts";
33 import { commitSettings, previewSettings, serviceSettings } from "../../../games/settings.ts";
44 import { boxNamed, listBoxes, mayDo, queueCommand, roleOn, seesBox, SERVICE_NAME, servicesOf, type CommandKind } from "../../../games/store.ts";
55 import { good, bad, type Tool, str } from "../shared.ts";
6 import { commitPolicy } from "../../../games/sleep.ts";
67
78 const POWER = ["start", "stop", "restart", "recreate", "pull"];
89
910 export const tool: Tool = {
1011 name: "games",
1112 listedTo: "admin",
12 doc: "`{ action, box?, service?, text?, kind?, key?, value?, modrinth?, preview?, dryRun? }`: game boxes. `list`; `console` queues `text` as RCON; `power` `kind` (start, stop, restart); `env` commits `key`=`value` (empty removes); `plugin` adds a `modrinth` slug (`preview` true only says what it would add: the newest compatible version and its required dependencies; incompatible is refused with the reason, a lockfile with sha512 is committed); `config` lists a service's settings (server.properties, Paper's); `config_set` sets `key` to `value`, planned first (`dryRun: false` commits the plan on the commit it was planned on). Grants as on /games",
13 description: "Game boxes: list, console, power, env, plugins, settings.",
13 doc: "`{ action, box?, service?, text?, kind?, key?, value?, modrinth?, preview?, dryRun? }`: game boxes. `list`; `sleep` sets a `service` to `value` warm or sleep (stops when empty, starts on join), a commit; `console` queues `text` as RCON; `power` `kind` (start, stop, restart); `env` commits `key`=`value` (empty removes); `plugin` adds a `modrinth` slug (`preview` true only says what it would add: the newest compatible version and its required dependencies; incompatible is refused with the reason, a lockfile with sha512 is committed); `config` lists a service's settings (server.properties, Paper's); `config_set` sets `key` to `value`, planned first (`dryRun: false` commits the plan on the commit it was planned on). Grants as on /games",
14 description: "Game boxes: list, console, power, env, plugins, settings, sleep.",
1415 inputSchema: {
1516 type: "object",
1617 properties: {
17 action: { type: "string", enum: ["list", "console", "power", "env", "plugin", "config", "config_set"] },
18 action: { type: "string", enum: ["list", "console", "power", "env", "plugin", "config", "config_set", "sleep"] },
1819 box: { type: "string", maxLength: 40 },
1920 service: { type: "string", maxLength: 64 },
2021 text: { type: "string", maxLength: 1000 },
@@ -97,6 +98,12 @@ export const tool: Tool = {
9798 const done = await commitSettings(ctx.app, user, box, service, plan.value);
9899 return done.ok ? good({ says: `Committed ${done.value.slice(0, 10)}; the server restarts on the box's next sync.`, lines: plan.value.lines, sha: done.value }) : bad("refused", done.error);
99100 }
100 return bad("bad_action", "action is list, console, power, env, plugin, config or config_set");
101 if (action === "sleep") {
102 const policy = str(args["value"]);
103 if (policy !== "warm" && policy !== "sleep") return bad("invalid", "value is warm or sleep");
104 const done = await commitPolicy(ctx.app, user, box, service, policy);
105 return done.ok ? good({ says: `${service} ${policy === "sleep" ? "sleeps when empty" : "stays warm"} once the box redeploys (${done.sha.slice(0, 10)}).`, sha: done.sha }) : bad("refused", done.error);
106 }
107 return bad("bad_action", "action is list, console, power, env, plugin, config, config_set or sleep");
101108 },
102109 };
src/tui/screens/games.ts +19 −1
@@ -13,6 +13,7 @@
1313
1414 import { movedKey } from "./moved_key.ts";
1515 import { emptyText } from "../../core/empty_words.ts";
16 import { commitPolicy, policyOf, stateWords } from "../../games/sleep.ts";
1617 import { SHELL_SERVICE, queueShell } from "../../games/shell.ts";
1718 import { onSync } from "../../games/notify.ts";
1819 import { boxStatus, boxStatusShared, boxTails } from "../../games/diag.ts";
@@ -64,6 +65,7 @@ export function gamesScreen(f: Session, ctx: Ctx): Screen {
6465 binding(["s"], "start"),
6566 binding(["x"], "stop"),
6667 binding(["r"], "restart"),
68 binding(["z"], "sleep when empty, or keep warm"),
6769 ],
6870 render(area, s) {
6971 const c = ctx.theme.c;
@@ -89,7 +91,7 @@ export function gamesScreen(f: Session, ctx: Ctx): Screen {
8991 const view: ListRow[] = all.map(({ box, service }) => ({
9092 title: `${box.name}/${service.name}`,
9193 ...(service.state === "exited" ? { tone: "danger" as const } : {}),
92 secondary: `${service.state || "unknown"} · ${Math.round(service.memMiB)} MiB · ${service.cpuPct.toFixed(1)}% CPU`,
94 secondary: `${stateWords(service.state, service.asleep)} · ${Math.round(service.memMiB)} MiB · ${service.cpuPct.toFixed(1)}% CPU`,
9395 meta: box.seenAt.slice(11, 19),
9496 }));
9597 drawList(s, list!, c, state, view);
@@ -119,6 +121,22 @@ export function gamesScreen(f: Session, ctx: Ctx): Screen {
119121 ctx.invalidate();
120122 return true;
121123 }
124 if (at !== undefined && !e.ctrl && !e.alt && e.key === "z") {
125 if (!mayDo(roleOn(f.app.db, f.user, at.box.id, at.service.name), "operator")) note = `You are not an operator of ${at.service.name}.`;
126 else {
127 const { box, service } = at;
128 note = `${box.name}/${service.name}: committing…`;
129 void (async () => {
130 const compose = await readCompose(f.app, box);
131 const next = compose !== undefined && policyOf(compose.text, service.name) === "sleep" ? "warm" : "sleep";
132 const done = await commitPolicy(f.app, f.user!, box, service.name, next);
133 note = done.ok ? `${box.name}/${service.name} ${next === "sleep" ? "sleeps when empty" : "stays warm"} once the box redeploys (${done.sha.slice(0, 10)}).` : done.error;
134 ctx.invalidate();
135 })();
136 }
137 ctx.invalidate();
138 return true;
139 }
122140 const kind: CommandKind | undefined = e.key === "s" ? "start" : e.key === "x" ? "stop" : e.key === "r" ? "restart" : undefined;
123141 if (kind === undefined || at === undefined || e.ctrl || e.alt) return false;
124142 if (!mayDo(roleOn(f.app.db, f.user, at.box.id, at.service.name), "operator")) note = `You are not an operator of ${at.service.name}.`;
src/web/pages/games.ts +40 −1
@@ -47,6 +47,7 @@ import { html, type Html } from "../html.ts";
4747 import { flashTo, page } from "../layout.ts";
4848 import { badge, btn, disclosure, field as input, row, rowList, time } from "../ui.ts";
4949 import { onSync } from "../../games/notify.ts";
50 import { canSleep, commitPolicy, EMPTY_SECONDS, policyOf, stateWords } from "../../games/sleep.ts";
5051 import { emptyLine } from "../empty_words.ts";
5152
5253 const dollars = (cents: number): string => `$${(cents / 100).toFixed(2)}`;
@@ -135,7 +136,7 @@ export async function gameBoxPage(ctx: Ctx): Promise<Response> {
135136 return row({
136137 href: `/games/${box.name}/${n}`,
137138 title: n,
138 trail: badge(s?.state || "unknown", { tone: TONE[s?.state ?? ""] ?? "default" }),
139 trail: badge(stateWords(s?.state ?? "", s?.asleep === true), { tone: s?.asleep === true ? "default" : (TONE[s?.state ?? ""] ?? "default") }),
139140 meta: html`${mib(s?.memMiB)} ·
140141 ${s === undefined ? "" : `${s.cpuPct.toFixed(1)}% CPU`}${s?.startedAt ? html` · up since ${time(s.startedAt)}` : ""}`,
141142 ...(act ? { after: power(box, n) } : {}),
@@ -277,6 +278,7 @@ export async function gameServicePage(ctx: Ctx): Promise<Response> {
277278 const env = compose === undefined ? {} : serviceEnv(compose.text, service);
278279 const plugins = compose === undefined ? { plugins: [], modrinth: [] } : pluginsOf(compose.text, service);
279280 const commands = recentCommands(ctx.app.db, box.id, service, 5);
281 const seen = servicesOf(ctx.app.db, box.id).find((s) => s.name === service);
280282 const base = `/games/${box.name}/${service}`;
281283 // Settings: each as the compose file says; a "Preview" (s.<key>=value in the query) planned on it.
282284 const settings = compose === undefined ? [] : settingsOf(compose.text, service, env);
@@ -326,6 +328,7 @@ ${tail.lines.join("\n")}${tail.lines.length > 0 ? "\n" : ""}</pre
326328 ),
327329 )}
328330 </section>
331 ${compose === undefined || !canSleep(compose.text, service) ? null : sleepBlock(box, service, compose.text, seen?.asleep === true, act)}
329332 <section class="settings-block">
330333 <h2>Environment</h2>
331334 ${Object.keys(env).length === 0
@@ -540,6 +543,42 @@ export async function gameEnvSubmit(ctx: Ctx): Promise<Response> {
540543 );
541544 }
542545
546 /** Warm or sleep: what the compose says, and the choice for an operator. */
547 function sleepBlock(box: GameBox, service: string, text: string, asleep: boolean, act: boolean): Html {
548 const policy = policyOf(text, service);
549 const wait = "Someone joining starts it, and they wait on the join screen while it boots, about half a minute.";
550 const now =
551 policy === "sleep"
552 ? asleep
553 ? `Asleep now: it is stopped and holds no memory. ${wait}`
554 : `Stops after ${EMPTY_SECONDS / 60} minutes with nobody on it, which frees its memory. ${wait}`
555 : "Kept warm: it runs whether or not anyone is on it.";
556 return html`<section class="settings-block">
557 <h2>Sleep</h2>
558 <p>${now}</p>
559 ${act
560 ? html`<form method="post" action="/games/${box.name}/${service}/sleep" class="row-fields">
561 <input type="hidden" name="policy" value="${policy === "sleep" ? "warm" : "sleep"}" />
562 ${btn(policy === "sleep" ? "Keep it warm" : "Let it sleep when empty", { variant: "secondary" })}
563 </form>`
564 : null}
565 </section>`;
566 }
567
568 // POST /games/:box/:service/sleep: warm or sleep, a commit to the compose file.
569 export async function gameSleepSubmit(ctx: Ctx): Promise<Response> {
570 const got = await operatorForm(ctx);
571 if (got instanceof Response) return got;
572 const policy = field(got.form, "policy");
573 if (policy !== "warm" && policy !== "sleep") return flashTo(ctx, `/games/${got.box.name}/${got.service}`, { tone: "danger", message: "Choose warm or sleep." });
574 const done = await commitPolicy(ctx.app, ctx.auth.user!, got.box, got.service, policy);
575 return flashTo(
576 ctx,
577 `/games/${got.box.name}/${got.service}`,
578 done.ok ? { message: `${got.service} ${policy === "sleep" ? "sleeps when empty" : "stays warm"} once the box redeploys (${done.sha.slice(0, 10)}).` } : { tone: "danger", message: done.error },
579 );
580 }
581
543582 // POST /games/:box/:service/plugin: a Modrinth slug.
544583 export async function gamePluginSubmit(ctx: Ctx): Promise<Response> {
545584 const got = await operatorForm(ctx);
test/conversation-ask.test.ts +2
@@ -522,6 +522,8 @@ const SAID: readonly (readonly [string, Record<string, unknown>, string])[] = [
522522 ["games", { action: "env", box: "net", service: "hub", key: "MOTD", value: "Hello" }, "Set MOTD on hub on net to Hello, a commit that redeploys it."],
523523 ["games", { action: "plugin", box: "net", service: "survival", modrinth: "waystones" }, "Add the plugin waystones to survival on net, a commit that redeploys it."],
524524 ["games", { action: "config_set", box: "net", service: "hub", key: "view-distance", value: "12", dryRun: false }, "Set the setting view-distance on hub on net to 12, a commit that restarts it."],
525 ["games", { action: "sleep", box: "net", service: "hunting", value: "sleep" }, "Let hunting on net sleep when empty and wake on join, a commit that redeploys it."],
526 ["games", { action: "sleep", box: "net", service: "hub", value: "warm" }, "Keep hub on net warm, a commit that redeploys it."],
525527 ["crew_accounts", { repo: "marin/cakes", allow: "espo-corp" }, "Let the crew's runs for marin/cakes spend the account espo-corp."],
526528 ["subscriptions", { everywhere: "espo-corp" }, "Put the account espo-corp in the pool, so the crew uses it by default on every repository a forge admin owns."],
527529 ["subscriptions", { limit: "espo-corp" }, "Keep the account espo-corp to where it is allowed."],
test/game-sleep.test.ts added +282
@@ -0,0 +1,282 @@
1 /**
2 * Sleep and wake (#16840): a server's policy is the compose label `forge.sleep` with `restart: "no"`,
3 * and from the labels the forge writes the rest: AutoStopper in the proxy's MODRINTH_PROJECTS (a pinned version the image checks by sha512) with its config,
4 * and the socket proxy that lets the proxy start and stop only the sleeping containers. The same
5 * labels give the same file; warm again gives the file back as it was; nothing else moves; the
6 * proxy never sleeps; a stopped sleeper is "asleep (wakes on join)"; and the change is a commit by
7 * an operator who can write the repository, on the page and through the tool.
8 */
9 import { Database } from "bun:sqlite";
10 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
11 import { mkdtemp, rm } from "node:fs/promises";
12 import { tmpdir } from "node:os";
13 import { join } from "node:path";
14 import { createApp, type App } from "../src/app.ts";
15 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
16 import { createToken } from "../src/core/tokens.ts";
17 import { createUser, getUserByName, type User } from "../src/core/users.ts";
18 import { readCompose, setServiceEnv } from "../src/games/compose.ts";
19 import { AUTOSTOPPER, canSleep, policyOf, setPolicy, sleeping, stateWords, syncSleep, WAKER, WAKER_CONFIG, WAKER_IMAGE } from "../src/games/sleep.ts";
20 import { boxNamed, createGameBox, markAsleep } from "../src/games/store.ts";
21 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
22 import { quietLogs } from "./helpers/globals.ts";
23
24 quietLogs();
25
26 // The shape of trevato/mc-network's compose: top-level configs, a network, an anchor for the Paper
27 // servers, a proxy with its own configs, a `|` block value, a list-form environment.
28 const COMPOSE = `name: game
29
30 x-paper: &paper
31 image: itzg/minecraft-server:latest
32 restart: unless-stopped
33 networks: [mc]
34
35 configs:
36 velocity_toml:
37 content: |
38 bind = "0.0.0.0:25565"
39 [servers]
40 hub = "hub:25565"
41 hunting = "hunting:25565"
42 [advanced]
43 read-timeout = 30000
44
45 networks:
46 mc:
47 driver: bridge
48
49 services:
50 velocity:
51 image: itzg/mc-proxy:latest
52 container_name: velocity
53 networks: [mc]
54 environment:
55 TYPE: VELOCITY
56 MEMORY: 512M
57 configs:
58 - source: velocity_toml
59 target: /config/velocity.toml
60
61 hub:
62 <<: *paper
63 container_name: hub
64 environment:
65 TYPE: PAPER
66 PLUGINS: |
67 https://example.test/Akropolis.jar
68
69 survival:
70 <<: *paper
71 container_name: survival
72 environment:
73 - TYPE=FABRIC
74 - MEMORY=3G
75
76 # A Paper server for trying a plugin.
77 hunting:
78 <<: *paper
79 container_name: hunting
80 environment:
81 TYPE: PAPER
82 PLUGINS: ""
83 `;
84
85 const yaml = (t: string): any => Bun.YAML.parse(t);
86
87 describe("the policy in the compose file", () => {
88 test("only an itzg game server can sleep; the proxy is the door", () => {
89 expect(["velocity", "hub", "survival", "hunting"].map((s) => canSleep(COMPOSE, s))).toEqual([false, true, true, true]);
90 expect(() => setPolicy(COMPOSE, "velocity", "sleep")).toThrow("velocity is not a game server that can sleep");
91 });
92
93 test("nothing set is warm", () => {
94 expect(sleeping(COMPOSE)).toEqual([]);
95 });
96
97 test("sleep: the label, restart no, AutoStopper and its config in the proxy, and the waker allowing only that container", () => {
98 const t = setPolicy(COMPOSE, "hunting", "sleep");
99 const doc = yaml(t);
100 expect(policyOf(t, "hunting")).toBe("sleep");
101 expect(doc.services.hunting.labels).toEqual({ "forge.sleep": "true" });
102 expect(doc.services.hunting.restart).toBe("no");
103 expect(doc.services.hunting.image).toBe("itzg/minecraft-server:latest");
104 // AutoStopper's settings, as the plugin reads them.
105 const conf = yaml(doc.configs[WAKER_CONFIG].content);
106 expect(conf.docker.endpoint).toBe(`tcp://${WAKER}:2375`);
107 expect(conf.inactivity_timeout_seconds).toBe(600);
108 expect(conf.monitored_servers).toEqual([
109 { server_name: "hunting", container_name: "hunting", readiness: { strategy: "minecraft_status", target_host: "hunting", target_port: 25565, probe_interval_millis: 1000, timeout_seconds: 120 } },
110 ]);
111 // Velocity holds a joining player for a cold start, not its default 30 s.
112 expect(doc.configs.velocity_toml.content).toContain("read-timeout = 120000");
113 // The proxy loads the plugin by its pinned Modrinth version, which the image checks by sha512,
114 // with the game version the image wants beside it; its own config stays.
115 expect(doc.services.velocity.environment.MODRINTH_PROJECTS).toBe(AUTOSTOPPER);
116 expect(AUTOSTOPPER).toBe("PG4gqnzX:EclCtvWk");
117 expect(doc.services.velocity.environment.MINECRAFT_VERSION).toBe("1.21.6");
118 expect(doc.services.velocity.environment.PLUGINS).toBeUndefined();
119 // A change of sleepers changes the proxy environment, so compose recreates it and AutoStopper reads it.
120 expect(doc.services.velocity.environment.FORGE_SLEEP).toBe("hunting");
121 expect(doc.services.velocity.configs).toEqual([
122 { source: "velocity_toml", target: "/config/velocity.toml" },
123 { source: WAKER_CONFIG, target: "/config/plugins/autostopper/config.yml" },
124 ]);
125 // The boundary: only the proxy, only inspect, start and stop, only hunting.
126 const waker = doc.services[WAKER];
127 expect(waker.image).toBe(WAKER_IMAGE);
128 expect(WAKER_IMAGE).toMatch(/^wollomatic\/socket-proxy:[\d.]+@sha256:[0-9a-f]{64}$/);
129 expect(waker.networks).toEqual(["mc"]);
130 expect(waker.volumes).toEqual(["/var/run/docker.sock:/var/run/docker.sock:ro"]);
131 expect(waker.command).toEqual([
132 "-loglevel=warn",
133 "-listenip=0.0.0.0",
134 "-allowfrom=velocity",
135 "-allowGET=(/v1\\..{1,2})?/(_ping|version|containers/(hunting)/json)",
136 "-allowHEAD=/_ping",
137 "-allowPOST=(/v1\\..{1,2})?/containers/(hunting)/(start|stop)",
138 ]);
139 expect(waker.ports).toBeUndefined();
140 // Nothing else moves.
141 for (const s of ["hub", "survival"]) expect(doc.services[s]).toEqual(yaml(COMPOSE).services[s]);
142 expect(t).toContain(" # A Paper server for trying a plugin.\n");
143 });
144
145 test("a second sleeper joins the same config and allowlist; the same labels give the same file", () => {
146 const one = setPolicy(COMPOSE, "hunting", "sleep");
147 const two = setPolicy(one, "survival", "sleep");
148 const doc = yaml(two);
149 expect(sleeping(two)).toEqual(["hunting", "survival"]);
150 expect(yaml(doc.configs[WAKER_CONFIG].content).monitored_servers.map((m: { server_name: string }) => m.server_name)).toEqual(["hunting", "survival"]);
151 expect(doc.services[WAKER].command).toContain("-allowPOST=(/v1\\..{1,2})?/containers/(hunting|survival)/(start|stop)");
152 expect(doc.services.velocity.environment.FORGE_SLEEP).toBe("hunting,survival");
153 expect(syncSleep(two)).toBe(two);
154 expect(setPolicy(two, "survival", "sleep")).toBe(two);
155 });
156
157 test("a container name that could widen the waker's allowlist or break the config is refused; every name is escaped and quoted", () => {
158 const named = (name: string) => COMPOSE.replace("container_name: hunting", `container_name: ${JSON.stringify(name)}`);
159 for (const bad of ["hub|velocity", "hunting)|(.*", ".*", "a+", "x?", "a b", "x\"\n - server_name: y", "", "a/b"])
160 expect(() => setPolicy(named(bad), "hunting", "sleep")).toThrow("a server that sleeps needs a container name of letters, digits, _ . and - only");
161 // Nothing was committed for a refused name: the file is as it was.
162 expect(policyOf(COMPOSE, "hunting")).toBe("warm");
163 // A dot is a literal dot in the allowlist, not any character.
164 const dotted = yaml(setPolicy(named("game.hunting_1-a"), "hunting", "sleep"));
165 expect(dotted.services[WAKER].command).toContain("-allowPOST=(/v1\\..{1,2})?/containers/(game\\.hunting_1-a)/(start|stop)");
166 // Each value AutoStopper reads is a quoted YAML string.
167 const t = setPolicy(COMPOSE, "hunting", "sleep");
168 const content = yaml(t).configs[WAKER_CONFIG].content as string;
169 expect(content).toContain('- server_name: "hunting"');
170 expect(content).toContain('container_name: "hunting"');
171 expect(content).toContain('target_host: "hunting"');
172 });
173
174 test("warm again gives the file back as it was: the waker, the config, the plugin and the label all go", () => {
175 const back = setPolicy(setPolicy(setPolicy(setPolicy(COMPOSE, "hunting", "sleep"), "survival", "sleep"), "survival", "warm"), "hunting", "warm");
176 expect(back).toBe(COMPOSE);
177 });
178
179 test("a `|` block value is replaced whole, its lines with it", () => {
180 const t = setServiceEnv(COMPOSE, "hub", { PLUGINS: "https://example.test/Other.jar" });
181 expect(yaml(t).services.hub.environment).toEqual({ TYPE: "PAPER", PLUGINS: "https://example.test/Other.jar" });
182 expect(t).not.toContain("Akropolis");
183 });
184 });
185
186 describe("a stopped sleeper, as the box reports it", () => {
187 test("asleep when its policy is sleep and its container has stopped; a warm one that stopped is just exited", async () => {
188 const db = new Database(":memory:");
189 db.exec("CREATE TABLE user (id TEXT PRIMARY KEY, username TEXT)");
190 for (const m of ["20261201000000-games", "20261201190000-game-sleep"]) db.exec((await import(`../src/core/migrations/${m}.ts`)).default);
191 db.query("INSERT INTO game_service (box_id, name, state) VALUES ('b', 'hunting', 'exited'), ('b', 'hub', 'exited'), ('b', 'survival', 'running')").run();
192 markAsleep(db, "b", sleeping(setPolicy(setPolicy(COMPOSE, "hunting", "sleep"), "survival", "sleep")));
193 expect(db.query<{ name: string; asleep: number }, []>("SELECT name, asleep FROM game_service ORDER BY name").all()).toEqual([
194 { name: "hub", asleep: 0 },
195 { name: "hunting", asleep: 1 },
196 { name: "survival", asleep: 0 },
197 ]);
198 expect(stateWords("exited", true)).toBe("asleep (wakes on join)");
199 expect(stateWords("exited", false)).toBe("exited");
200 });
201 });
202
203 describe("changing it", () => {
204 let dataDir = "";
205 let app: App;
206 let http: ForgeHttp;
207 let alice: User;
208 let admin = "";
209 let cookie = "";
210 beforeAll(async () => {
211 dataDir = await mkdtemp(join(tmpdir(), "forge-game-sleep-"));
212 app = createApp({ dataDir, port: 0 });
213 http = forgeHttp(app);
214 const made = await createUser(app.db, {
215 origin: "seed",
216 trusted: true,
217 username: "alice",
218 email: "[email protected]",
219 password: "a-good-passphrase",
220 adminIfFirst: true,
221 });
222 if (!made.ok) throw new Error(made.error);
223 alice = getUserByName(app.db, "alice")!;
224 const repo = await createRepo(app, alice, { name: "mc-network", visibility: "private" });
225 if (!repo.ok) throw new Error(String(repo.error));
226 const seeded = await commitToBranch(app, alice, repo.value, {
227 message: "seed",
228 files: [{ path: "docker-compose.yml", content: COMPOSE }],
229 });
230 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
231 createGameBox(app.db, { name: "net", repo: "alice/mc-network" });
232 admin = createToken(app.db, alice.id, "sleep", "admin").token;
233 const { createSession } = await import("../src/core/sessions.ts");
234 cookie = `forge_session=${createSession(app.db, alice.id).token}`;
235 }, 30_000);
236 afterAll(async () => {
237 app.close();
238 await rm(dataDir, { recursive: true, force: true });
239 });
240
241 test("the service page offers it, and its commit writes the label, the waker and the plugin", async () => {
242 const page = await (await http.handle(new Request("http://forge.test/games/net/hunting", { headers: { cookie } }))).text();
243 expect(page).toContain("<h2>Sleep</h2>");
244 expect(page).toContain("Kept warm: it runs whether or not anyone is on it.</p>");
245 const proxy = await (await http.handle(new Request("http://forge.test/games/net/velocity", { headers: { cookie } }))).text();
246 expect(proxy).not.toContain("<h2>Sleep</h2>");
247 const box = boxNamed(app.db, "net")!;
248 const { commitPolicy } = await import("../src/games/sleep.ts");
249 const done = await commitPolicy(app, alice, box, "hunting", "sleep");
250 expect(done.ok).toBe(true);
251 const now = await readCompose(app, box);
252 expect(policyOf(now!.text, "hunting")).toBe("sleep");
253 expect(yaml(now!.text).services[WAKER].command).toContain("-allowfrom=velocity");
254 const log = Bun.spawnSync(["git", "log", "-1", "--format=%s", "main"], { cwd: join(app.reposRoot, "alice", "mc-network.git") });
255 expect(log.stdout.toString().trim()).toBe("games: hunting sleeps when empty");
256 const after = await (await http.handle(new Request("http://forge.test/games/net/hunting", { headers: { cookie } }))).text();
257 expect(after).toContain("Stops after 10 minutes with nobody on it, which frees its memory. Someone joining starts it, and they wait on the join screen while it boots, about half a minute.");
258 });
259
260 test("the tool sets it back to warm; a word other than warm or sleep is refused", async () => {
261 const call = async (args: Record<string, unknown>): Promise<{ text: string; isError: boolean }> => {
262 const res = await http.handle(
263 new Request("http://forge.test/mcp", {
264 method: "POST",
265 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${admin}` },
266 body: JSON.stringify({
267 jsonrpc: "2.0",
268 id: 1,
269 method: "tools/call",
270 params: { name: "games", arguments: args },
271 }),
272 }),
273 );
274 const body = (await res.json()) as { result: { content: { text: string }[]; isError?: boolean } };
275 return { text: body.result.content[0]!.text, isError: body.result.isError === true };
276 };
277 expect((await call({ action: "sleep", box: "net", service: "hunting", value: "nap" })).text).toContain("value is warm or sleep");
278 const warm = await call({ action: "sleep", box: "net", service: "hunting", value: "warm" });
279 expect(warm.isError, warm.text).toBe(false);
280 expect(policyOf((await readCompose(app, boxNamed(app.db, "net")!))!.text, "hunting")).toBe("warm");
281 });
282 });

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

Keyboard shortcuts

Docs