Public: anyone can read this; the crew can change it.
Games G6: "give me a new void world with FAWE and bedwars": world presets as one planned commit (#17284) #17309
Merged 24h 48m ago, live in production
sold/game-presets → main 0 commits 4 threads · 4 unresolved
12 files
changed +899
−27
- docs/features/games.md
- src/crew/conversation_ask.ts
- src/games/mods.ts
- src/games/presets.ts
- src/http/games_routes.ts
- src/http/lazy_lists.ts
- src/http/mcp/tools/games.ts
- src/tui/screens/games.ts
- src/web/pages/games.ts
- test/conversation-ask.test.ts
- test/game-presets.test.ts
- test/private-by-default.test.ts
docs/features/games.md +11
| @@ -54,6 +54,17 @@ An import link is treated as a secret (a signed link is one): it reaches the box | ||
| 54 | 54 | |
| 55 | 55 | Uploading a world file is still to come: a link is how a world comes in today. |
| 56 | 56 | |
| 57 | ## New servers | |
| 58 | ||
| 59 | "Give me a new void world with FAWE and bedwars" makes a server (#17284 G6), on `/games/<box>` (New server: words, Plan it, then Create it), with `n` on the terminal Games screen, through the `games` tool `create_server` (`words`, or `name`, `level` and `plugins`; it plans, and commits with `dryRun: false` and the plan's `sha`) or from Talk. Every door commits only on the commit its plan was made on: when the repository moved, it says "The box changed since the preview; plan it again." The plan says, before anything is written: | |
| 60 | ||
| 61 | - the server: Paper at the network's own version, its world (void: one layer of air in the void biome; flat; or normal), its memory, sleeping when empty and waking on join; | |
| 62 | - each plugin resolved for its loader and version and pinned in its lockfile with what it requires, or refused if it does not run there (`fawe` and `worldedit` are FastAsyncWorldEdit, `bedwars` is Screaming BedWars); | |
| 63 | - the memory math, a sleeping server's heap counted free: "velocity 0.8G + hub 1G + survival 3G = 4.8G awake; bedwars 1.5G sleep, counted free; the box has 7.7G, 1G kept for itself: fits", refused when it does not; | |
| 64 | - where players join: `<name>.<the network's domain>` (the wildcard name already points at the box) or `/server <name>`. | |
| 65 | ||
| 66 | Creating it is one commit to the network's compose file: the service from the Paper anchor with its own RCON key, a volume, the proxy's `[servers]` and `[forced-hosts]` lines, sleep's label and waker lists, and its lockfile beside it. Remove on the server's row, `d` on the terminal Games screen, or `remove_server` takes the service and its proxy lines back out by commit, its plan shown first, and keeps its world's volume (`src/games/presets.ts`). The proxy, the waker, and a server the proxy's `try` list or another forced host still names are refused. | |
| 67 | ||
| 57 | 68 | ## Secrets |
| 58 | 69 | |
| 59 | 70 | 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/crew/conversation_ask.ts +3
| @@ -340,6 +340,9 @@ export const ASKED_AS: Readonly<Record<string, Form>> = { | ||
| 340 | 340 | if (a["action"] === "mods_pack") return `Make ${val(a, "project") || "a Modrinth modpack"} the modpack of ${on}, a commit that restarts it`; |
| 341 | 341 | if (a["action"] === "mods_remove") return `Remove ${val(a, "project") || "a Modrinth project"} from ${on}, a commit that restarts it`; |
| 342 | 342 | if (a["action"] === "config_set") return `Set the setting ${val(a, "key")} on ${on}${clause(" to ", val(a, "value"))}, a commit that restarts it`; |
| 343 | if (a["action"] === "create_server") | |
| 344 | return `Add a new server to ${val(a, "box") || "a game box"}${clause(": ", val(a, "words"))}${clause(", called ", val(a, "name"))}, sleeping when empty, a commit that brings it up`; | |
| 345 | if (a["action"] === "remove_server") return `Take ${val(a, "service") || "a server"} out of ${val(a, "box") || "a game box"}, keeping its world, a commit`; | |
| 343 | 346 | 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`; |
| 344 | 347 | if (a["action"] === "people") { |
| 345 | 348 | const p = val(a, "player") || "a player"; |
src/games/mods.ts +1 −1
| @@ -98,7 +98,7 @@ export function parseLock(text: string | undefined): { projects: Locked[]; pack: | ||
| 98 | 98 | } |
| 99 | 99 | } |
| 100 | 100 | |
| 101 | function lockText(t: Target, lock: readonly Locked[], pack: LockedPack | undefined): string { | |
| 101 | export function lockText(t: Target, lock: readonly Locked[], pack: LockedPack | undefined): string { | |
| 102 | 102 | return `${JSON.stringify( |
| 103 | 103 | { |
| 104 | 104 | about: |
src/games/presets.ts added +326
| @@ -0,0 +1,326 @@ | ||
| 1 | /** | |
| 2 | * New servers from a few words (#17284 G6): "give me a new void world with FAWE and bedwars" is a | |
| 3 | * preset (a level, plugins, a name) planned into one commit to the network's compose file: a Paper | |
| 4 | * service from the network's own anchor, its world (void, flat or normal), its plugins resolved for | |
| 5 | * its loader and version and pinned in its lockfile (`mods.ts`), sleep on (`sleep.ts`), and a line | |
| 6 | * in the proxy's [servers] and [forced-hosts] so `<name>.<domain>` reaches it. The plan says all of | |
| 7 | * it first, with the memory it takes: a sleeping server's heap counts as free, since sleep is what | |
| 8 | * makes the room. Undo is `planRemoveServer`, which takes the service and its proxy lines back out | |
| 9 | * (its world's volume stays until someone deletes it on purpose). | |
| 10 | */ | |
| 11 | ||
| 12 | import type { App } from "../app.ts"; | |
| 13 | import type { User } from "../core/users.ts"; | |
| 14 | import { commitCompose, composeServices, readCompose, serviceEnv, setTopEntry } from "./compose.ts"; | |
| 15 | import { lockPath, lockText, planInstall, type Mods } from "./mods.ts"; | |
| 16 | import { targetOf, type Locked, type Result } from "./modrinth.ts"; | |
| 17 | import { policyOf, proxyOf, setPolicy, WAKER } from "./sleep.ts"; | |
| 18 | import { SERVICE_NAME, servicesOf, type GameBox } from "./store.ts"; | |
| 19 | ||
| 20 | export const LEVELS = ["void", "flat", "normal"] as const; | |
| 21 | export type Level = (typeof LEVELS)[number]; | |
| 22 | ||
| 23 | /** Words people say for a plugin, to its Modrinth slug (each checked to run on Paper 1.21.6). */ | |
| 24 | export const ALIASES: Readonly<Record<string, string>> = { | |
| 25 | fawe: "fastasyncworldedit", | |
| 26 | fastasyncworldedit: "fastasyncworldedit", | |
| 27 | worldedit: "fastasyncworldedit", | |
| 28 | bedwars: "screamingbedwars", | |
| 29 | luckperms: "luckperms", | |
| 30 | }; | |
| 31 | ||
| 32 | export interface Wish { | |
| 33 | readonly name: string; | |
| 34 | readonly level: Level; | |
| 35 | readonly plugins: readonly string[]; | |
| 36 | readonly memory: string; | |
| 37 | } | |
| 38 | ||
| 39 | const MEMORY = "1536M"; | |
| 40 | /** What the box keeps for itself and Docker, out of its memory. */ | |
| 41 | const KEPT_MIB = 1024; | |
| 42 | ||
| 43 | /** | |
| 44 | * A wish from a sentence: "a new void world with FAWE and bedwars called arena". Unknown words are | |
| 45 | * left to the caller's plugins. | |
| 46 | */ | |
| 47 | export function parseWish(words: string, existing: readonly string[] = []): Wish { | |
| 48 | const w = words.toLowerCase(); | |
| 49 | const level: Level = /\bvoid\b|\bempty\b|\bskyblock\b/.test(w) | |
| 50 | ? "void" | |
| 51 | : /\bflat\b|\bsuperflat\b|\bcreative\b/.test(w) | |
| 52 | ? "flat" | |
| 53 | : "normal"; | |
| 54 | const plugins = [ | |
| 55 | ...new Set( | |
| 56 | Object.keys(ALIASES) | |
| 57 | .filter((k) => new RegExp(`\\b${k}\\b`).test(w)) | |
| 58 | .map((k) => ALIASES[k]!), | |
| 59 | ), | |
| 60 | ]; | |
| 61 | const called = /\b(?:called|named)\s+([a-z0-9][a-z0-9-]{0,30})/.exec(w)?.[1]; | |
| 62 | const base = | |
| 63 | called ?? (plugins.includes("screamingbedwars") ? "bedwars" : level === "void" ? "void" : level === "flat" ? "creative" : "world"); | |
| 64 | let name = base; | |
| 65 | for (let i = 2; existing.includes(name); i++) name = `${base}-${i}`; | |
| 66 | return { name, level, plugins, memory: MEMORY }; | |
| 67 | } | |
| 68 | ||
| 69 | /** | |
| 70 | * `parseWish` on this box: a name free both on the box and in its compose file, so every door plans | |
| 71 | * the same one. | |
| 72 | */ | |
| 73 | export async function wishOn(app: App, box: GameBox, words: string): Promise<Wish> { | |
| 74 | const compose = await readCompose(app, box); | |
| 75 | return parseWish(words, [...servicesOf(app.db, box.id).map((s) => s.name), ...(compose === undefined ? [] : composeServices(compose.text))]); | |
| 76 | } | |
| 77 | ||
| 78 | /** A heap in MiB from itzg's MEMORY ("1G", "1536M", "512m"); 1 GiB when it says nothing. */ | |
| 79 | export function heapMiB(memory: string | undefined): number { | |
| 80 | const m = /^(\d+(?:\.\d+)?)\s*([gGmM])?$/.exec((memory ?? "").trim()); | |
| 81 | if (m === null) return 1024; | |
| 82 | return Math.round(Number(m[1]) * (m[2]?.toLowerCase() === "m" ? 1 : 1024)); | |
| 83 | } | |
| 84 | const gb = (mib: number): string => (mib % 1024 === 0 ? `${mib / 1024}G` : `${(mib / 1024).toFixed(1)}G`); | |
| 85 | ||
| 86 | /** | |
| 87 | * The memory math: every warm server's heap added up, a sleeping one's counted free, against the | |
| 88 | * box's memory less what it keeps for itself. Its words go in the preview. | |
| 89 | */ | |
| 90 | export function memoryMath( | |
| 91 | text: string, | |
| 92 | add: { name: string; memory: string; sleeps: boolean }, | |
| 93 | boxMiB: number, | |
| 94 | ): { fits: boolean; line: string } { | |
| 95 | // Sleep's waker is a socket proxy with no heap, not a server. | |
| 96 | const parts = composeServices(text).filter((s) => s !== WAKER).map((s) => ({ | |
| 97 | name: s, | |
| 98 | mib: heapMiB(serviceEnv(text, s)["MEMORY"]), | |
| 99 | sleeps: policyOf(text, s) === "sleep", | |
| 100 | })); | |
| 101 | parts.push({ name: add.name, mib: heapMiB(add.memory), sleeps: add.sleeps }); | |
| 102 | const warm = parts.filter((p) => !p.sleeps); | |
| 103 | const asleep = parts.filter((p) => p.sleeps); | |
| 104 | const used = warm.reduce((sum, p) => sum + p.mib, 0); | |
| 105 | const sum = warm.map((p) => `${p.name} ${gb(p.mib)}`).join(" + "); | |
| 106 | const slept = asleep.length === 0 ? "" : `; ${asleep.map((p) => `${p.name} ${gb(p.mib)}`).join(", ")} sleep, counted free`; | |
| 107 | if (boxMiB <= 0) return { fits: true, line: `${sum} = ${gb(used)} awake${slept}; the box has not said its memory yet.` }; | |
| 108 | const room = boxMiB - KEPT_MIB; | |
| 109 | return { | |
| 110 | fits: used <= room, | |
| 111 | line: `${sum} = ${gb(used)} awake${slept}; the box has ${gb(boxMiB)}, ${gb(KEPT_MIB)} kept for itself: ${used <= room ? `fits, ${gb(room - used)} to spare` : `${gb(used - room)} too much`}.`, | |
| 112 | }; | |
| 113 | } | |
| 114 | ||
| 115 | /** | |
| 116 | * The proxy's inline velocity.toml in the compose text, with `[servers]` and `[forced-hosts]` lines | |
| 117 | * for `name` added (or, with `remove`, taken out). | |
| 118 | */ | |
| 119 | export function proxyLines(text: string, name: string, remove = false): { text: string; host: string | undefined } { | |
| 120 | const lines = text.split("\n"); | |
| 121 | const at = (re: RegExp, from = 0) => lines.findIndex((l, i) => i >= from && re.test(l)); | |
| 122 | const servers = at(/^\s+\[servers\]\s*$/); | |
| 123 | if (servers < 0) throw new Error("the proxy's velocity.toml has no [servers] table in this compose file"); | |
| 124 | const pad = lines[servers]!.slice(0, lines[servers]!.length - lines[servers]!.trimStart().length); | |
| 125 | const forced = at(/^\s+\[forced-hosts\]\s*$/); | |
| 126 | // The network's own name: the shortest of its forced hosts ("mc.trevato.dev" beside | |
| 127 | // "hub.mc.trevato.dev"). | |
| 128 | const hosts = forced < 0 ? [] : lines.slice(forced + 1).map((l) => /^\s+"([a-z0-9.-]+)"\s*=/.exec(l)?.[1]).filter((h): h is string => h !== undefined); | |
| 129 | const domain = hosts.sort((a, b) => a.length - b.length)[0]; | |
| 130 | const mine = (l: string) => | |
| 131 | new RegExp(`^\\s+${name.replace(/[.]/g, "\\.")}\\s*=\\s*"`).test(l) || | |
| 132 | new RegExp(`^\\s+"${name.replace(/[.]/g, "\\.")}\\.[a-z0-9.-]+"\\s*=`).test(l); | |
| 133 | if (remove) return { text: lines.filter((l) => !mine(l)).join("\n"), host: undefined }; | |
| 134 | if (lines.some(mine)) throw new Error(`the proxy already knows a server called ${name}`); | |
| 135 | // Before `try = …` (which must stay last in [servers]), else at the end of the table. | |
| 136 | let end = servers + 1; | |
| 137 | while ( | |
| 138 | end < lines.length && | |
| 139 | lines[end]!.startsWith(pad) && | |
| 140 | !/^\s+\[/.test(lines[end]!) && | |
| 141 | !/^\s+try\s*=/.test(lines[end]!) && | |
| 142 | lines[end]!.trim() !== "" | |
| 143 | ) | |
| 144 | end++; | |
| 145 | lines.splice(end, 0, `${pad}${name} = "${name}:25565"`); | |
| 146 | let host: string | undefined; | |
| 147 | const forcedNow = forced < 0 ? -1 : forced + 1; | |
| 148 | if (forcedNow > 0 && domain !== undefined) { | |
| 149 | host = `${name}.${domain}`; | |
| 150 | lines.splice(forcedNow + 1, 0, `${pad}"${host}" = ["${name}"]`); | |
| 151 | } | |
| 152 | return { text: lines.join("\n"), host }; | |
| 153 | } | |
| 154 | ||
| 155 | /** | |
| 156 | * The environment of a new server: Paper at the network's own version, its world, RCON from the | |
| 157 | * sealed key. | |
| 158 | */ | |
| 159 | function serverEnv(text: string, wish: Wish): Record<string, string> { | |
| 160 | const versions = composeServices(text) | |
| 161 | .map((s) => serviceEnv(text, s)) | |
| 162 | .filter((e) => e["TYPE"] === "PAPER" && /^\d/.test(e["VERSION"] ?? "")) | |
| 163 | .map((e) => e["VERSION"]!); | |
| 164 | const env: Record<string, string> = { | |
| 165 | TYPE: "PAPER", | |
| 166 | VERSION: versions[0] ?? "1.21.6", | |
| 167 | EULA: "TRUE", | |
| 168 | MEMORY: wish.memory, | |
| 169 | USE_AIKAR_FLAGS: "true", | |
| 170 | ONLINE_MODE: "false", | |
| 171 | ENABLE_RCON: "true", | |
| 172 | RCON_PASSWORD: `\${RCON_${wish.name.toUpperCase().replace(/[^A-Z0-9]+/g, "_")}:?}`, | |
| 173 | }; | |
| 174 | if (wish.level === "flat") env["LEVEL_TYPE"] = "FLAT"; | |
| 175 | if (wish.level === "void") { | |
| 176 | env["LEVEL_TYPE"] = "FLAT"; | |
| 177 | env["GENERATOR_SETTINGS"] = '{"layers":[{"block":"minecraft:air","height":1}],"biome":"minecraft:the_void"}'; | |
| 178 | env["SPAWN_PROTECTION"] = "0"; | |
| 179 | } | |
| 180 | return env; | |
| 181 | } | |
| 182 | ||
| 183 | const CHANGED = "The box changed since the preview; plan it again."; | |
| 184 | ||
| 185 | export interface ServerPlan { | |
| 186 | readonly lines: readonly string[]; | |
| 187 | readonly text: string; | |
| 188 | readonly lock: { path: string; content: string } | undefined; | |
| 189 | readonly message: string; | |
| 190 | readonly sha: string; | |
| 191 | readonly done: string; | |
| 192 | } | |
| 193 | ||
| 194 | /** | |
| 195 | * Plan a new server on `box` from `wish`: every line it writes, the plugins it pins, the memory it | |
| 196 | * takes. | |
| 197 | */ | |
| 198 | export async function planServer(app: App, box: GameBox, wish: Wish): Promise<Result<ServerPlan>> { | |
| 199 | const compose = await readCompose(app, box); | |
| 200 | if (compose === undefined) return { ok: false, error: `No ${box.path} on ${box.repo}@${box.branch}.` }; | |
| 201 | const services = composeServices(compose.text); | |
| 202 | if (!SERVICE_NAME.test(wish.name) || !/^[a-z0-9][a-z0-9-]{0,30}$/.test(wish.name)) | |
| 203 | return { ok: false, error: "A server's name is lowercase letters, digits and dashes." }; | |
| 204 | if (services.includes(wish.name)) return { ok: false, error: `The network already has a server called ${wish.name}.` }; | |
| 205 | if (proxyOf(compose.text) === undefined) | |
| 206 | return { ok: false, error: "This compose file has no proxy (itzg/mc-proxy) for a new server to sit behind." }; | |
| 207 | const env = serverEnv(compose.text, wish); | |
| 208 | // Plugins resolved one after another on the same lock, each for this server's loader and version. | |
| 209 | const target = targetOf(env, ""); | |
| 210 | if (!target.ok) return target; | |
| 211 | let m: Mods = { target: target.value, lock: [], loose: [], urls: [], held: [], sha: compose.sha, env, pack: undefined }; | |
| 212 | const pluginLines: string[] = []; | |
| 213 | let pinned: readonly Locked[] = []; | |
| 214 | for (const slug of wish.plugins) { | |
| 215 | const planned = await planInstall(app, m, wish.name, slug); | |
| 216 | if (!planned.ok) return { ok: false, error: `${slug}: ${planned.error}` }; | |
| 217 | pinned = planned.value.lock; | |
| 218 | pluginLines.push(...planned.value.lines); | |
| 219 | const nextEnv = { ...m.env }; | |
| 220 | for (const [k, v] of Object.entries(planned.value.env)) | |
| 221 | if (v === null) delete nextEnv[k]; | |
| 222 | else nextEnv[k] = v; | |
| 223 | m = { ...m, lock: pinned, env: nextEnv }; | |
| 224 | } | |
| 225 | const memory = memoryMath(compose.text, { name: wish.name, memory: wish.memory, sleeps: true }, box.host["memMiB"] ?? 0); | |
| 226 | if (!memory.fits) return { ok: false, error: `Not enough memory on the box: ${memory.line}` }; | |
| 227 | let text: string; | |
| 228 | let host: string | undefined; | |
| 229 | try { | |
| 230 | const anchored = /^x-paper:\s*&paper\s*$/m.test(compose.text); | |
| 231 | const paperGlobal = /^\s{2}paper_global:\s*$/m.test(compose.text); | |
| 232 | const block = [ | |
| 233 | ...(anchored ? ["<<: *paper"] : ["image: itzg/minecraft-server:latest", "restart: unless-stopped"]), | |
| 234 | `container_name: ${wish.name}`, | |
| 235 | "environment:", | |
| 236 | ...Object.entries(m.env).map(([k, v]) => ` ${k}: ${JSON.stringify(v)}`), | |
| 237 | ...(paperGlobal ? ["configs:", " - source: paper_global", " target: /config/paper-global.yml"] : []), | |
| 238 | "volumes:", | |
| 239 | ` - ${wish.name}:/data`, | |
| 240 | ]; | |
| 241 | text = setTopEntry(compose.text, "services", wish.name, block); | |
| 242 | text = setTopEntry(text, "volumes", wish.name, []); | |
| 243 | ({ text, host } = proxyLines(text, wish.name)); | |
| 244 | text = setPolicy(text, wish.name, "sleep"); | |
| 245 | if ((Bun.YAML.parse(text) as { services?: Record<string, unknown> }).services?.[wish.name] === undefined) | |
| 246 | throw new Error("the new service did not land in the compose file"); | |
| 247 | } catch (e) { | |
| 248 | return { ok: false, error: e instanceof Error ? e.message : String(e) }; | |
| 249 | } | |
| 250 | const levelWords = wish.level === "void" ? "a void world" : wish.level === "flat" ? "a flat world" : "a normal world"; | |
| 251 | return { | |
| 252 | ok: true, | |
| 253 | value: { | |
| 254 | lines: [ | |
| 255 | `Adds ${wish.name}: Paper ${env["VERSION"]}, ${levelWords}, ${wish.memory}, sleeping when empty and waking on join.`, | |
| 256 | ...pluginLines, | |
| 257 | `Memory: ${memory.line}`, | |
| 258 | host === undefined | |
| 259 | ? `Players reach it with /server ${wish.name}.` | |
| 260 | : `Players join at ${host} (the network's wildcard name already points at the box), or /server ${wish.name}.`, | |
| 261 | ], | |
| 262 | text, | |
| 263 | lock: pinned.length === 0 ? undefined : { path: lockPath(box, wish.name), content: lockText(m.target, pinned, undefined) }, | |
| 264 | message: `games: new server ${wish.name} (${levelWords}${wish.plugins.length === 0 ? "" : ` with ${wish.plugins.join(", ")}`})`, | |
| 265 | sha: compose.sha, | |
| 266 | done: `${wish.name} is in the network${host === undefined ? "" : `, at ${host}`}`, | |
| 267 | }, | |
| 268 | }; | |
| 269 | } | |
| 270 | ||
| 271 | /** | |
| 272 | * Commit a planned server, on the commit it was planned on or not at all. `seen` is the sha of the | |
| 273 | * plan the person was shown: a door that plans again (the page, the tool) sends it back with the | |
| 274 | * yes. | |
| 275 | */ | |
| 276 | export function commitServer( | |
| 277 | app: App, | |
| 278 | user: User, | |
| 279 | box: GameBox, | |
| 280 | plan: ServerPlan, | |
| 281 | seen: string, | |
| 282 | ): Promise<{ ok: true; sha: string } | { ok: false; error: string }> { | |
| 283 | if (seen !== plan.sha) return Promise.resolve({ ok: false, error: CHANGED }); | |
| 284 | return commitCompose(app, user, box, { | |
| 285 | message: plan.message, | |
| 286 | edit: () => plan.text, | |
| 287 | ...(plan.lock === undefined ? {} : { extra: [plan.lock] }), | |
| 288 | expectTip: plan.sha, | |
| 289 | what: "the network", | |
| 290 | }); | |
| 291 | } | |
| 292 | ||
| 293 | /** Plan taking a server back out: its service and its proxy lines go, its world's volume stays. */ | |
| 294 | export async function planRemoveServer(app: App, box: GameBox, name: string): Promise<Result<ServerPlan>> { | |
| 295 | const compose = await readCompose(app, box); | |
| 296 | if (compose === undefined) return { ok: false, error: `No ${box.path} on ${box.repo}@${box.branch}.` }; | |
| 297 | if (!composeServices(compose.text).includes(name)) return { ok: false, error: `The network has no server called ${name}.` }; | |
| 298 | if (proxyOf(compose.text) === name) return { ok: false, error: "The proxy is the way in; it stays." }; | |
| 299 | if (name === WAKER) return { ok: false, error: `${WAKER} wakes the sleeping servers; it stays.` }; | |
| 300 | let text: string; | |
| 301 | try { | |
| 302 | // Warm first, so sleep's lists drop it; then the service and its proxy lines. | |
| 303 | text = policyOf(compose.text, name) === "sleep" ? setPolicy(compose.text, name, "warm") : compose.text; | |
| 304 | text = setTopEntry(text, "services", name, null); | |
| 305 | text = proxyLines(text, name, true).text; | |
| 306 | // Still in the proxy's `try` or another name's forced host: without it players would land | |
| 307 | // nowhere. | |
| 308 | if (text.split("\n").some((l) => /^\s+(try|"[a-z0-9.-]+")\s*=\s*\[/.test(l) && l.includes(`"${name}"`))) | |
| 309 | throw new Error(`The proxy sends players to ${name} (its try list or a forced host); change that first.`); | |
| 310 | } catch (e) { | |
| 311 | return { ok: false, error: e instanceof Error ? e.message : String(e) }; | |
| 312 | } | |
| 313 | return { | |
| 314 | ok: true, | |
| 315 | value: { | |
| 316 | lines: [ | |
| 317 | `Takes ${name} out of the network and the proxy. Its world stays in its volume (${name}) until someone deletes it on purpose.`, | |
| 318 | ], | |
| 319 | text, | |
| 320 | lock: undefined, | |
| 321 | message: `games: remove server ${name}`, | |
| 322 | sha: compose.sha, | |
| 323 | done: `${name} is out of the network; its world is kept`, | |
| 324 | }, | |
| 325 | }; | |
| 326 | } |
src/http/games_routes.ts +2 −1
| @@ -14,7 +14,7 @@ import { sleeping } from "../games/sleep.ts"; | ||
| 14 | 14 | import { boxByToken, envFiles, markAsleep, recordSync, signJarUrls, type SyncBody } from "../games/store.ts"; |
| 15 | 15 | import { BODY_CAPS } from "../kernel/body_caps.ts"; |
| 16 | 16 | import { |
| 17 | gameBoxPage, gameCommandSubmit, gameCrashShare, gameEnvSubmit, gameGrantSubmit, gameJarDownload, gameJarSubmit, gameModInstall, gameModPack, gameModRemove, gameModUpdate, gamePeopleSubmit, gameHead, gameWorldSubmit, gamePowerSubmit, gameSleepSubmit, gameServicePage, gameSettingsSubmit, gameServiceStream, gameShellStream, gameShellSubmit, gamesPage, | |
| 17 | gameBoxPage, gameCommandSubmit, gameCrashShare, gameEnvSubmit, gameGrantSubmit, gameServersSubmit, gameJarDownload, gameJarSubmit, gameModInstall, gameModPack, gameModRemove, gameModUpdate, gamePeopleSubmit, gameHead, gameWorldSubmit, gamePowerSubmit, gameSleepSubmit, gameServicePage, gameSettingsSubmit, gameServiceStream, gameShellStream, gameShellSubmit, gamesPage, | |
| 18 | 18 | } from "../web/pages/games.ts"; |
| 19 | 19 | import type { Ctx, Handler } from "./context.ts"; |
| 20 | 20 | import { InvalidJson } from "./json_body.ts"; |
| @@ -83,6 +83,7 @@ export function gamesRoutes(router: Router<Handler>): void { | ||
| 83 | 83 | // Before the service routes: no compose service can be named "@shell". |
| 84 | 84 | router.add("POST", "/games/:box/@shell", gameShellSubmit); |
| 85 | 85 | router.add("GET", "/games/:box/@shell/stream", gameShellStream); |
| 86 | router.add("POST", "/games/:box/servers", gameServersSubmit); | |
| 86 | 87 | router.add("GET", "/games/:box/:service", gameServicePage); |
| 87 | 88 | router.add("GET", "/games/:box/:service/stream", gameServiceStream); |
| 88 | 89 | router.add("POST", "/games/:box/:service/command", gameCommandSubmit); |
src/http/lazy_lists.ts +1
| @@ -612,6 +612,7 @@ export const OPERATIONS_ROUTES = [ | ||
| 612 | 612 | ["POST", "/games/:box/grant"], |
| 613 | 613 | ["POST", "/games/:box/@shell"], |
| 614 | 614 | ["GET", "/games/:box/@shell/stream"], |
| 615 | ["POST", "/games/:box/servers"], | |
| 615 | 616 | ["GET", "/games/:box/:service"], |
| 616 | 617 | ["GET", "/games/:box/:service/stream"], |
| 617 | 618 | ["POST", "/games/:box/:service/command"], |
src/http/mcp/tools/games.ts +31 −4
| @@ -9,6 +9,7 @@ import { compactMetrics, compactSeries } from "../../../games/metrics_answer.ts" | ||
| 9 | 9 | import { WINDOWS, type Window } from "../../../games/metrics.ts"; |
| 10 | 10 | import { boxNamed, listBoxes, mayDo, queueCommand, roleOn, seesBox, SERVICE_NAME, servicesOf, type CommandKind } from "../../../games/store.ts"; |
| 11 | 11 | import { good, bad, type Tool, str } from "../shared.ts"; |
| 12 | import { ALIASES, commitServer, LEVELS, planRemoveServer, planServer, wishOn, type Level } from "../../../games/presets.ts"; | |
| 12 | 13 | import { commitPolicy } from "../../../games/sleep.ts"; |
| 13 | 14 | import { eventsOf, networkOf, PEOPLE_OPS, peopleOf, peopleWords, queuePeople } from "../../../games/people.ts"; |
| 14 | 15 | import { linkShown } from "../../../games/snapshots.ts"; |
| @@ -19,18 +20,22 @@ const POWER = ["start", "stop", "restart", "recreate", "pull"]; | ||
| 19 | 20 | export const tool: Tool = { |
| 20 | 21 | name: "games", |
| 21 | 22 | listedTo: "admin", |
| 22 | doc: "`{ action, box?, service?, text?, kind?, key?, value?, query?, project?, dryRun?, window?, url?, snapshot? }`: game boxes. `list` (with each service's world snapshots); `metrics` per service (now, 1h, 24h), or one `service` over `window` (1h to 30d); `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); `mods` lists a server's Modrinth projects and updates; `mods_search` searches `query` for its loader (each says whether it runs there); `mods_pack_search` searches modpacks; `mods_install`, `mods_update` (`project` or all; the modpack on a pack server), `mods_remove` and `mods_pack` (a modpack, every file locked) plan first (the lines it would change, dependencies included) and commit with `dryRun: false`; `world` `op` import (a world from `url`, a .zip or .tar.gz with level.dat; the world it had is kept first), restore (`snapshot`) or snapshot, a job whose steps the box reports; `people` with `op` list (online, whitelist, ops, bans, who is where, the latest joins, deaths and chat) or op, deop, whitelist-add, whitelist-remove, whitelist-on, whitelist-off, ban, pardon, kick for `player`, or move `player` to `to`; `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", | |
| 23 | description: "Game boxes: list, metrics, console, power, env, Modrinth mods, people, settings, sleep, worlds.", | |
| 23 | doc: "`{ action, box?, service?, text?, kind?, key?, value?, query?, project?, words?, name?, level?, plugins?, dryRun?, sha?, window?, url?, snapshot? }`: game boxes. `list` (with each service's world snapshots); `create_server` adds a server from `words` ('a void world with FAWE and bedwars') or `name`, `level` (void, flat, normal) and `plugins` (Modrinth slugs): Paper, its plugins locked, sleeping when empty, a proxy entry and forced host; `remove_server` takes `service` out (its world kept); both plan first and commit with `dryRun: false` and the plan's `sha`; `metrics` per service (now, 1h, 24h), or one `service` over `window` (1h to 30d); `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); `mods` lists a server's Modrinth projects and updates; `mods_search` searches `query` for its loader (each says whether it runs there); `mods_pack_search` searches modpacks; `mods_install`, `mods_update` (`project` or all; the modpack on a pack server), `mods_remove` and `mods_pack` (a modpack, every file locked) plan first (the lines it would change, dependencies included) and commit with `dryRun: false`; `world` `op` import (a world from `url`, a .zip or .tar.gz with level.dat; the world it had is kept first), restore (`snapshot`) or snapshot, a job whose steps the box reports; `people` with `op` list (online, whitelist, ops, bans, who is where, the latest joins, deaths and chat) or op, deop, whitelist-add, whitelist-remove, whitelist-on, whitelist-off, ban, pardon, kick for `player`, or move `player` to `to`; `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", | |
| 24 | description: "Game boxes: list, metrics, console, power, env, Modrinth mods, people, settings, sleep, worlds, new servers.", | |
| 24 | 25 | inputSchema: { |
| 25 | 26 | type: "object", |
| 26 | 27 | properties: { |
| 27 | action: { type: "string", enum: ["list", "metrics", "console", "power", "env", "mods", "mods_search", "mods_pack_search", "mods_install", "mods_update", "mods_remove", "mods_pack", "people", "config", "config_set", "sleep", "world"] }, | |
| 28 | action: { type: "string", enum: ["list", "metrics", "console", "power", "env", "mods", "mods_search", "mods_pack_search", "mods_install", "mods_update", "mods_remove", "mods_pack", "people", "config", "config_set", "sleep", "create_server", "remove_server", "world"] }, | |
| 28 | 29 | op: { type: "string", enum: ["list", ...PEOPLE_OPS, "import", "restore", "snapshot"] }, |
| 29 | 30 | player: { type: "string", maxLength: 17 }, |
| 30 | 31 | to: { type: "string", maxLength: 64 }, |
| 31 | 32 | window: { type: "string", enum: Object.keys(WINDOWS) }, |
| 32 | 33 | url: { type: "string", maxLength: 3800 }, |
| 33 | 34 | snapshot: { type: "string", maxLength: 120 }, |
| 35 | words: { type: "string", maxLength: 300 }, | |
| 36 | name: { type: "string", maxLength: 31 }, | |
| 37 | level: { type: "string", enum: [...LEVELS] }, | |
| 38 | plugins: { type: "array", items: { type: "string", maxLength: 100 }, maxItems: 10 }, | |
| 34 | 39 | box: { type: "string", maxLength: 40 }, |
| 35 | 40 | service: { type: "string", maxLength: 64 }, |
| 36 | 41 | text: { type: "string", maxLength: 1000 }, |
| @@ -40,6 +45,7 @@ export const tool: Tool = { | ||
| 40 | 45 | query: { type: "string", maxLength: 200 }, |
| 41 | 46 | project: { type: "string", maxLength: 100 }, |
| 42 | 47 | dryRun: { type: "boolean" }, |
| 48 | sha: { type: "string", maxLength: 64 }, | |
| 43 | 49 | }, |
| 44 | 50 | required: ["action"], |
| 45 | 51 | }, |
| @@ -47,7 +53,7 @@ export const tool: Tool = { | ||
| 47 | 53 | heldNotWhen: (args) => |
| 48 | 54 | ["list", "metrics", "mods", "mods_search", "mods_pack_search", "config"].includes(String(args["action"])) || |
| 49 | 55 | (args["action"] === "people" && args["op"] === "list") || |
| 50 | ((String(args["action"]).startsWith("mods_") || args["action"] === "config_set") && args["dryRun"] !== false), | |
| 56 | ((String(args["action"]).startsWith("mods_") || ["config_set", "create_server", "remove_server"].includes(String(args["action"]))) && args["dryRun"] !== false), | |
| 51 | 57 | async run(ctx, user, args) { |
| 52 | 58 | const action = str(args["action"]); |
| 53 | 59 | const db = ctx.app.db; |
| @@ -78,6 +84,27 @@ export const tool: Tool = { | ||
| 78 | 84 | }); |
| 79 | 85 | } |
| 80 | 86 | const box = boxNamed(db, str(args["box"])); |
| 87 | // A server added or taken out is the box's: its operators', planned first. | |
| 88 | if (action === "create_server" || action === "remove_server") { | |
| 89 | if (box === undefined || !seesBox(db, user, box.id)) return bad("not_found", "no such box here"); | |
| 90 | if (!mayDo(roleOn(db, user, box.id), "operator")) return bad("forbidden", `you are not an operator of ${box.name}`); | |
| 91 | let planned; | |
| 92 | if (action === "create_server") { | |
| 93 | const parsed = await wishOn(ctx.app, box, str(args["words"])); | |
| 94 | const given = Array.isArray(args["plugins"]) ? args["plugins"].filter((p): p is string => typeof p === "string") : []; | |
| 95 | const level = str(args["level"]); | |
| 96 | planned = await planServer(ctx.app, box, { | |
| 97 | ...parsed, | |
| 98 | ...(str(args["name"]) === "" ? {} : { name: str(args["name"]) }), | |
| 99 | ...((LEVELS as readonly string[]).includes(level) ? { level: level as Level } : {}), | |
| 100 | plugins: [...new Set([...parsed.plugins, ...given.map((p) => ALIASES[p.toLowerCase()] ?? p)])], | |
| 101 | }); | |
| 102 | } else planned = await planRemoveServer(ctx.app, box, str(args["service"])); | |
| 103 | if (!planned.ok) return bad("refused", planned.error); | |
| 104 | if (args["dryRun"] !== false) return good({ planned: true, says: "This is the plan; send dryRun: false with this sha to commit it.", sha: planned.value.sha, lines: planned.value.lines }); | |
| 105 | const done = await commitServer(ctx.app, user, box, planned.value, str(args["sha"])); | |
| 106 | return done.ok ? good({ says: `${planned.value.done} (${done.sha.slice(0, 10)}); the box brings it up on its next sync.`, sha: done.sha, lines: planned.value.lines }) : bad("refused", done.error); | |
| 107 | } | |
| 81 | 108 | const service = str(args["service"]); |
| 82 | 109 | if (action === "metrics") { |
| 83 | 110 | if (box === undefined || !seesBox(db, user, box.id)) return bad("not_found", "no such box here"); |
src/tui/screens/games.ts +53 −1
| @@ -51,7 +51,8 @@ import { style } from "../term/style.ts"; | ||
| 51 | 51 | import { truncate } from "../term/width.ts"; |
| 52 | 52 | import type { Session } from "../session.ts"; |
| 53 | 53 | import { fill, len, split } from "../ui/layout.ts"; |
| 54 | import { ListState, drawList, promptScreen, type ListRow } from "./common.ts"; | |
| 54 | import { ListState, confirmScreen, drawList, promptScreen, type ListRow } from "./common.ts"; | |
| 55 | import { commitServer, planRemoveServer, planServer, wishOn, type ServerPlan } from "../../games/presets.ts"; | |
| 55 | 56 | import type { PaletteEntry } from "./entries.ts"; |
| 56 | 57 | import { gameModsScreen } from "./game_mods.ts"; |
| 57 | 58 | |
| @@ -76,6 +77,29 @@ export function gamesScreen(f: Session, ctx: Ctx): Screen { | ||
| 76 | 77 | listBoxes(f.app.db) |
| 77 | 78 | .filter((b) => seesBox(f.app.db, f.user, b.id)) |
| 78 | 79 | .flatMap((b) => servicesOf(f.app.db, b.id).filter((s) => mayDo(roleOn(f.app.db, f.user, b.id, s.name), "viewer")).map((s) => ({ box: b, service: s }))); |
| 80 | /** A server's plan, line by line; yes commits exactly that plan, or says the repository moved. */ | |
| 81 | const showPlan = (box: GameBox, title: string, yes: string, planned: { ok: true; value: ServerPlan } | { ok: false; error: string }): void => { | |
| 82 | if (planned.ok) | |
| 83 | ctx.push( | |
| 84 | confirmScreen(ctx, screen, { | |
| 85 | title, | |
| 86 | body: planned.value.lines, | |
| 87 | actions: [{ label: yes }, { label: "Not now" }], | |
| 88 | yesNo: true, | |
| 89 | onChoose: (i) => { | |
| 90 | if (i !== 0) return; | |
| 91 | void ctx.track( | |
| 92 | commitServer(f.app, f.user!, box, planned.value, planned.value.sha).then((done) => { | |
| 93 | note = done.ok ? `${planned.value.done} (${done.sha.slice(0, 10)}).` : done.error; | |
| 94 | ctx.invalidate(); | |
| 95 | }), | |
| 96 | ); | |
| 97 | }, | |
| 98 | }), | |
| 99 | ); | |
| 100 | else note = planned.error; | |
| 101 | ctx.invalidate(); | |
| 102 | }; | |
| 79 | 103 | const screen: Screen = { |
| 80 | 104 | title: "Games", |
| 81 | 105 | keys: [ |
| @@ -87,6 +111,8 @@ export function gamesScreen(f: Session, ctx: Ctx): Screen { | ||
| 87 | 111 | binding(["s"], "start"), |
| 88 | 112 | binding(["x"], "stop"), |
| 89 | 113 | binding(["r"], "restart"), |
| 114 | binding(["n"], "new server"), | |
| 115 | binding(["d"], "remove a server"), | |
| 90 | 116 | binding(["z"], "sleep when empty, or keep warm"), |
| 91 | 117 | ], |
| 92 | 118 | render(area, s) { |
| @@ -144,6 +170,32 @@ export function gamesScreen(f: Session, ctx: Ctx): Screen { | ||
| 144 | 170 | ctx.invalidate(); |
| 145 | 171 | return true; |
| 146 | 172 | } |
| 173 | // A new server on the selected box (or the first you run): words in, the plan shown, yes | |
| 174 | // commits. | |
| 175 | if (!e.ctrl && !e.alt && e.key === "n") { | |
| 176 | const box = at?.box ?? listBoxes(f.app.db).find((b) => mayDo(roleOn(f.app.db, f.user, b.id), "operator")); | |
| 177 | if (box === undefined || !mayDo(roleOn(f.app.db, f.user, box.id), "operator")) note = "You run no game box to add a server to."; | |
| 178 | else | |
| 179 | ctx.push( | |
| 180 | promptScreen(ctx, screen, { | |
| 181 | title: `New server on ${box.name}`, | |
| 182 | label: "What kind (a void world with FAWE and bedwars)", | |
| 183 | onSubmit: async (words) => { | |
| 184 | showPlan(box, `New server on ${box.name}`, "Create it", await planServer(f.app, box, await wishOn(f.app, box, words))); | |
| 185 | }, | |
| 186 | }), | |
| 187 | ); | |
| 188 | ctx.invalidate(); | |
| 189 | return true; | |
| 190 | } | |
| 191 | // The selected server out of the network: the plan shown, yes commits; its world is kept. | |
| 192 | if (at !== undefined && !e.ctrl && !e.alt && e.key === "d") { | |
| 193 | const { box, service } = at; | |
| 194 | if (!mayDo(roleOn(f.app.db, f.user, box.id), "operator")) note = `You are not an operator of ${box.name}.`; | |
| 195 | else void ctx.track(planRemoveServer(f.app, box, service.name).then((planned) => showPlan(box, `Remove ${service.name} from ${box.name}`, "Remove it", planned))); | |
| 196 | ctx.invalidate(); | |
| 197 | return true; | |
| 198 | } | |
| 147 | 199 | if (at !== undefined && !e.ctrl && !e.alt && e.key === "z") { |
| 148 | 200 | 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}.`; |
| 149 | 201 | else { |
src/web/pages/games.ts +78 −20
| @@ -1,9 +1,10 @@ | ||
| 1 | 1 | /** |
| 2 | 2 | * `/games` (forge games): the game boxes a person may see, each box's network (one row a service, |
| 3 | * with Start, Stop and Restart), and a service's console (a live log over SSE and an RCON input), | |
| 4 | * environment editor and its Modrinth projects (search, a preview, then one commit; `games/mods.ts`). Every route asks `roleOn` first: viewer reads, operator acts, | |
| 5 | * owner (and every forge admin) also grants. Env and plugin changes are commits to the box's | |
| 6 | * compose repository, so a merge redeploys and the crew can propose them too. | |
| 3 | * with Start, Stop, Restart and Remove), a new server from a few words, and a service's console (a | |
| 4 | * live log over SSE and an RCON input), environment editor and its Modrinth projects (search, a | |
| 5 | * preview, then one commit; `games/mods.ts`). Every route asks `roleOn` first: viewer reads, | |
| 6 | * operator acts, owner (and every forge admin) also grants. Env and plugin changes are commits to | |
| 7 | * the box's compose repository, so a merge redeploys and the crew can propose them too. | |
| 7 | 8 | */ |
| 8 | 9 | |
| 9 | 10 | import { addPluginUrl, commitServiceEnv, composeServices, readCompose, SECRET_KEY, serviceEnv } from "../../games/compose.ts"; |
| @@ -53,7 +54,8 @@ import { consoleHtml, consoleText, crashOf, shareOnMclogs } from "../../games/co | ||
| 53 | 54 | import { flashTo, page } from "../layout.ts"; |
| 54 | 55 | import { avatar, badge, btn, disclosure, field as input, row, rowList, time } from "../ui.ts"; |
| 55 | 56 | import { onSync } from "../../games/notify.ts"; |
| 56 | import { canSleep, commitPolicy, EMPTY_SECONDS, policyOf, stateWords } from "../../games/sleep.ts"; | |
| 57 | import { commitServer, planRemoveServer, planServer, wishOn } from "../../games/presets.ts"; | |
| 58 | import { canSleep, commitPolicy, EMPTY_SECONDS, policyOf, proxyOf, stateWords, WAKER } from "../../games/sleep.ts"; | |
| 57 | 59 | import { CLOUD_EVENT, cloudFacts, GAME_CLOUD_EVENT, pinnedOfBox } from "../../actions/cloud_says.ts"; |
| 58 | 60 | import { topologyBlock, TOPOLOGY_CSS } from "./games_topology.ts"; |
| 59 | 61 | import { defaultHeadResponse, headResponse } from "../../games/heads.ts"; |
| @@ -81,6 +83,53 @@ const mib = (n: number | undefined): string => | ||
| 81 | 83 | n === undefined || n === 0 ? "?" : n >= 1024 ? `${(n / 1024).toFixed(1)} GiB` : `${Math.round(n)} MiB`; |
| 82 | 84 | const TONE: Record<string, "success" | "danger" | "default"> = { running: "success", exited: "danger", restarting: "danger" }; |
| 83 | 85 | |
| 86 | /** | |
| 87 | * New server: words in ("a void world with FAWE and bedwars"), the plan out (the service, its | |
| 88 | * plugins pinned, the memory math, where players join), then one button that commits it. | |
| 89 | */ | |
| 90 | function newServerBlock(box: GameBox, words: string, preview: Awaited<ReturnType<typeof planServer>> | undefined): Html { | |
| 91 | return html`<section class="settings-block" data-new-server> | |
| 92 | <h2>New server</h2> | |
| 93 | <form method="get" action="/games/${box.name}" class="row-fields"> | |
| 94 | ${input({ name: "words", label: "What kind", placeholder: "a void world with FAWE and bedwars", required: true, value: words })} | |
| 95 | ${btn("Plan it", { variant: "secondary" })} | |
| 96 | </form> | |
| 97 | ${preview === undefined | |
| 98 | ? html`<p class="muted small">Void, flat or normal; FAWE, BedWars or LuckPerms by name; it sleeps when empty, so its memory counts free.</p>` | |
| 99 | : preview.ok | |
| 100 | ? previewBlock(preview.value, `/games/${box.name}/servers`, { op: "create", words }, "Create it", `/games/${box.name}`) | |
| 101 | : html`<p role="alert">${preview.error}</p>`} | |
| 102 | </section>`; | |
| 103 | } | |
| 104 | ||
| 105 | /** | |
| 106 | * Remove, asked for on a server's row: its plan, then the one button. Its world is kept, so nothing | |
| 107 | * asks twice. | |
| 108 | */ | |
| 109 | const removeServerBlock = (box: GameBox, service: string, preview: Awaited<ReturnType<typeof planRemoveServer>>): Html => | |
| 110 | html`<section class="settings-block" data-remove-server> | |
| 111 | <h2>Remove ${service}</h2> | |
| 112 | ${preview.ok | |
| 113 | ? previewBlock(preview.value, `/games/${box.name}/servers`, { op: "remove", service }, "Remove it", `/games/${box.name}`) | |
| 114 | : html`<p role="alert">${preview.error}</p>`} | |
| 115 | </section>`; | |
| 116 | ||
| 117 | // POST /games/:box/servers: create or remove a server as previewed, by commit: planned again, and | |
| 118 | // refused when the box's repository moved. | |
| 119 | export async function gameServersSubmit(ctx: Ctx): Promise<Response> { | |
| 120 | const got = boxOf(ctx, "operator"); | |
| 121 | if (got instanceof Response) return got; | |
| 122 | const form = await readForm(ctx, "rw"); | |
| 123 | if (form instanceof Response) return form; | |
| 124 | const planned = | |
| 125 | field(form, "op") === "remove" | |
| 126 | ? await planRemoveServer(ctx.app, got.box, field(form, "service")) | |
| 127 | : await planServer(ctx.app, got.box, await wishOn(ctx.app, got.box, field(form, "words"))); | |
| 128 | if (!planned.ok) return flashTo(ctx, `/games/${got.box.name}`, { tone: "danger", message: planned.error }); | |
| 129 | const done = await commitServer(ctx.app, ctx.auth.user!, got.box, planned.value, field(form, "sha")); | |
| 130 | return flashTo(ctx, `/games/${got.box.name}`, done.ok ? { message: `${planned.value.done} (${done.sha.slice(0, 10)}); the box brings it up on its next sync.` } : { tone: "danger", message: done.error }); | |
| 131 | } | |
| 132 | ||
| 84 | 133 | function boxOf(ctx: Ctx, need: Role, service = ""): { box: GameBox; role: Role } | Response { |
| 85 | 134 | if (!ctx.auth.user) return signInFirst(ctx); |
| 86 | 135 | const box = boxNamed(ctx.app.db, ctx.params.box ?? ""); |
| @@ -148,6 +197,15 @@ export async function gameBoxPage(ctx: Ctx): Promise<Response> { | ||
| 148 | 197 | // What the provider says of the box's machine, for its owners only, as kept: the page never waits on it. |
| 149 | 198 | const machine = role === "owner" ? pinnedOfBox(ctx.app, box) : undefined; |
| 150 | 199 | const cloud = machine === undefined ? undefined : cloudFacts(ctx.app, machine); |
| 200 | // A new server asked for in words (?words=…): planned for the preview before anything is written. | |
| 201 | const operator = mayDo(role, "operator"); | |
| 202 | const words = (ctx.url.searchParams.get("words") ?? "").slice(0, 300); | |
| 203 | const preview = operator && words.trim() !== "" ? await planServer(ctx.app, box, await wishOn(ctx.app, box, words)) : undefined; | |
| 204 | // A server asked to be taken out (?remove=…): its plan, the same way. | |
| 205 | const leaving = operator ? (ctx.url.searchParams.get("remove") ?? "").slice(0, 64) : ""; | |
| 206 | const removal = leaving === "" ? undefined : await planRemoveServer(ctx.app, box, leaving); | |
| 207 | const stays = compose === undefined ? undefined : proxyOf(compose.text); | |
| 208 | const removable = (n: string): boolean => operator && compose !== undefined && composeServices(compose.text).includes(n) && n !== stays && n !== WAKER; | |
| 151 | 209 | return timePhase(ctx.request, "render", () => page({ |
| 152 | 210 | ctx, |
| 153 | 211 | title: `Games · ${box.name}`, |
| @@ -176,11 +234,15 @@ export async function gameBoxPage(ctx: Ctx): Promise<Response> { | ||
| 176 | 234 | meta: html`${players === null ? "" : `${players} online · `}${tps === null ? "" : `${tps.toFixed(1)} TPS · `}${mib(s?.memMiB)} · |
| 177 | 235 | ${s === undefined ? "" : `${s.cpuPct.toFixed(1)}% CPU`}${s?.startedAt ? html` · up since ${time(s.startedAt)}` : ""} |
| 178 | 236 | ${day.length === 0 ? "" : html`<span class="bar muted">${sparkOf(day, (p) => p.players, `${n}: players over 24 hours`)}${sparkOf(day, (p) => p.tps, `${n}: TPS over 24 hours`)}${sparkOf(day, (p) => p.memMiB, `${n}: memory over 24 hours`)}</span>`}`, |
| 179 | ...(act ? { after: power(box, n) } : {}), | |
| 237 | ...(act | |
| 238 | ? { after: html`${power(box, n)}${removable(n) ? btn("Remove", { size: "sm", variant: "ghost", href: `/games/${box.name}?remove=${encodeURIComponent(n)}`, label: `Remove ${n}` }) : null}` } | |
| 239 | : {}), | |
| 180 | 240 | }); |
| 181 | 241 | }), |
| 182 | 242 | )} |
| 243 | ${removal === undefined ? null : removeServerBlock(box, leaving, removal)} | |
| 183 | 244 | ${topologyBlock(ctx, box, compose?.text, visible)} |
| 245 | ${operator ? newServerBlock(box, words, preview) : null} | |
| 184 | 246 | ${role === "owner" ? boxBlock(box, packCheckLines(ctx.app, box.id)) : sharedBoxBlock(box, packCheckLines(ctx.app, box.id))} ${role === "owner" ? shellBlock(ctx, box) : null} |
| 185 | 247 | ${role === "owner" ? grantsBlock(ctx, box) : null}`, |
| 186 | 248 | })); |
| @@ -481,17 +543,14 @@ function numbersBlock(ctx: Ctx, box: GameBox, service: string): Html { | ||
| 481 | 543 | } |
| 482 | 544 | |
| 483 | 545 | /** What a change does, line by line, with the one button that commits it on the commit shown. */ |
| 484 | const previewCard = (plan: Plan, action: string, project: string, label: string, cancel: string): Html => | |
| 485 | html`<div class="card" aria-label="What this does"> | |
| 486 | <div class="card-body stack"> | |
| 487 | ${rowList(plan.lines.map((l) => row({ title: l })))} | |
| 488 | <form method="post" action="${action}" class="row-fields"> | |
| 489 | <input type="hidden" name="project" value="${project}" /> | |
| 490 | <input type="hidden" name="sha" value="${plan.sha}" /> | |
| 491 | ${btn(label, { variant: "primary" })} ${btn("Cancel", { variant: "ghost", href: cancel })} | |
| 492 | </form> | |
| 493 | </div> | |
| 494 | </div>`; | |
| 546 | const previewBlock = (plan: { lines: readonly string[]; sha: string }, action: string, sent: Readonly<Record<string, string>>, label: string, cancel: string): Html => | |
| 547 | html`<h3>What this does</h3> | |
| 548 | ${rowList(plan.lines.map((l) => row({ title: l })))} | |
| 549 | <form method="post" action="${action}" class="row-fields"> | |
| 550 | ${Object.entries(sent).map(([k, v]) => html`<input type="hidden" name="${k}" value="${v}" />`)} | |
| 551 | <input type="hidden" name="sha" value="${plan.sha}" /> | |
| 552 | ${btn(label, { variant: "primary" })} ${btn("Cancel", { variant: "ghost", href: cancel })} | |
| 553 | </form>`; | |
| 495 | 554 | |
| 496 | 555 | /** |
| 497 | 556 | * A mod server's modpack: the one it runs (every file locked; its update, one click), and a search |
| @@ -551,7 +610,7 @@ function packBlock(o: { | ||
| 551 | 610 | ${o.preview === undefined |
| 552 | 611 | ? null |
| 553 | 612 | : o.preview.ok |
| 554 | ? previewCard(o.preview.value, `${o.base}/mods/pack`, o.packing, "Install pack and restart", href("")) | |
| 613 | ? previewBlock(o.preview.value, `${o.base}/mods/pack`, { project: o.packing }, "Install pack and restart", href("")) | |
| 555 | 614 | : html`<p class="notice danger" role="alert">${o.preview.error}</p>`} |
| 556 | 615 | ${o.act |
| 557 | 616 | ? html`<form method="get" action="${o.base}#modpack" class="row-fields" role="search"> |
| @@ -668,7 +727,7 @@ function modsBlock(o: { | ||
| 668 | 727 | ${o.preview === undefined |
| 669 | 728 | ? null |
| 670 | 729 | : o.preview.ok |
| 671 | ? previewCard(o.preview.value, `${o.base}/mods/install`, o.adding, "Install and restart", searchHref("")) | |
| 730 | ? previewBlock(o.preview.value, `${o.base}/mods/install`, { project: o.adding }, "Install and restart", searchHref("")) | |
| 672 | 731 | : html`<p class="notice danger" role="alert">${o.preview.error}</p>`} |
| 673 | 732 | ${o.act && !t.pack |
| 674 | 733 | ? html`<form method="get" action="${o.base}#mods" class="row-fields" role="search"> |
| @@ -716,7 +775,6 @@ function modsBlock(o: { | ||
| 716 | 775 | </section>`; |
| 717 | 776 | } |
| 718 | 777 | |
| 719 | ||
| 720 | 778 | // GET /games/:box/:service/stream: new log lines and command results after each sync. |
| 721 | 779 | export function gameServiceStream(ctx: Ctx): Response { |
| 722 | 780 | const service = ctx.params.service ?? ""; |
test/conversation-ask.test.ts +2
| @@ -522,6 +522,8 @@ const SAID: readonly (readonly [string, Record<string, unknown>, string])[] = [ | ||
| 522 | 522 | ["games", { action: "env", box: "net", service: "hub", key: "MOTD", value: "Hello" }, "Set MOTD on hub on net to Hello, a commit that redeploys it."], |
| 523 | 523 | ["games", { action: "mods_install", box: "net", service: "survival", project: "waystones" }, "Install waystones and what it requires on survival on net, a commit that restarts it."], |
| 524 | 524 | ["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: "create_server", box: "mc", words: "a new void world with FAWE and bedwars" }, "Add a new server to mc: a new void world with FAWE and bedwars, sleeping when empty, a commit that brings it up."], | |
| 526 | ["games", { action: "remove_server", box: "mc", service: "bedwars" }, "Take bedwars out of mc, keeping its world, a commit."], | |
| 525 | 527 | ["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 | 528 | ["games", { action: "sleep", box: "net", service: "hub", value: "warm" }, "Keep hub on net warm, a commit that redeploys it."], |
| 527 | 529 | ["games", { action: "people", box: "mc", service: "hub", op: "ban", player: "Griefer" }, "Ban Griefer from hub on mc."], |
test/game-presets.test.ts added +390
| @@ -0,0 +1,390 @@ | ||
| 1 | /** | |
| 2 | * New servers from a few words (#17284 G6): "give me a new void world with FAWE and bedwars" is | |
| 3 | * planned (its plugins resolved for Paper 1.21.6 and pinned, the memory math with sleepers counted | |
| 4 | * free, the proxy's [servers] and forced-host lines, sleep on), committed as one change on the | |
| 5 | * page, the terminal's n and the games tool, and taken back out by remove_server with its world | |
| 6 | * kept. | |
| 7 | */ | |
| 8 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 9 | import { mkdtempSync } from "node:fs"; | |
| 10 | import { rm } from "node:fs/promises"; | |
| 11 | import { tmpdir } from "node:os"; | |
| 12 | import { join } from "node:path"; | |
| 13 | import { createApp, type App } from "../src/app.ts"; | |
| 14 | import { commitToBranch, createRepo } from "../src/actions/repos.ts"; | |
| 15 | import { createSession } from "../src/core/sessions.ts"; | |
| 16 | import { getRepo } from "../src/core/repos.ts"; | |
| 17 | import { createToken } from "../src/core/tokens.ts"; | |
| 18 | import { createUser, type User } from "../src/core/users.ts"; | |
| 19 | import { readCompose, readRepoFile, serviceEnv, serviceLabels } from "../src/games/compose.ts"; | |
| 20 | import { lockPath } from "../src/games/mods.ts"; | |
| 21 | import { commitServer, heapMiB, memoryMath, parseWish, planRemoveServer, planServer, proxyLines } from "../src/games/presets.ts"; | |
| 22 | import { policyOf, WAKER } from "../src/games/sleep.ts"; | |
| 23 | import { boxNamed, createGameBox, recordSync } from "../src/games/store.ts"; | |
| 24 | import { forgeHttp, type ForgeHttp } from "../src/http/server.ts"; | |
| 25 | import { createForgeApp } from "../src/tui/forge.ts"; | |
| 26 | import { gamesScreen } from "../src/tui/screens/games.ts"; | |
| 27 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; | |
| 28 | import { quietLogs } from "./helpers/globals.ts"; | |
| 29 | import { settleApp, settleUntil } from "./helpers/tui.ts"; | |
| 30 | ||
| 31 | quietLogs(); | |
| 32 | ||
| 33 | // The shape of mc-network: an anchor, the proxy's toml inline with its servers and forced hosts. | |
| 34 | const COMPOSE = `name: game | |
| 35 | ||
| 36 | x-paper: &paper | |
| 37 | image: itzg/minecraft-server:latest | |
| 38 | restart: unless-stopped | |
| 39 | networks: [mc] | |
| 40 | ||
| 41 | configs: | |
| 42 | velocity_toml: | |
| 43 | content: | | |
| 44 | bind = "0.0.0.0:25565" | |
| 45 | [servers] | |
| 46 | hub = "hub:25565" | |
| 47 | survival = "survival:25565" | |
| 48 | try = ["hub"] | |
| 49 | ||
| 50 | [forced-hosts] | |
| 51 | "mc.trevato.dev" = ["hub"] | |
| 52 | "survival.mc.trevato.dev" = ["survival"] | |
| 53 | ||
| 54 | [advanced] | |
| 55 | read-timeout = 30000 | |
| 56 | paper_global: | |
| 57 | content: | | |
| 58 | _version: 31 | |
| 59 | ||
| 60 | networks: | |
| 61 | mc: | |
| 62 | driver: bridge | |
| 63 | ||
| 64 | volumes: | |
| 65 | velocity: {} | |
| 66 | hub: {} | |
| 67 | ||
| 68 | services: | |
| 69 | velocity: | |
| 70 | image: itzg/mc-proxy:latest | |
| 71 | container_name: velocity | |
| 72 | networks: [mc] | |
| 73 | environment: | |
| 74 | TYPE: VELOCITY | |
| 75 | MEMORY: 768M | |
| 76 | configs: | |
| 77 | - source: velocity_toml | |
| 78 | target: /config/velocity.toml | |
| 79 | ||
| 80 | hub: | |
| 81 | <<: *paper | |
| 82 | container_name: hub | |
| 83 | environment: | |
| 84 | TYPE: PAPER | |
| 85 | VERSION: "1.21.6" | |
| 86 | MEMORY: 1G | |
| 87 | ||
| 88 | survival: | |
| 89 | <<: *paper | |
| 90 | container_name: survival | |
| 91 | environment: | |
| 92 | TYPE: PAPER | |
| 93 | VERSION: "1.21.6" | |
| 94 | MEMORY: 3G | |
| 95 | `; | |
| 96 | ||
| 97 | const yaml = (t: string): any => Bun.YAML.parse(t); | |
| 98 | ||
| 99 | // A Modrinth with FAWE and Screaming BedWars for Paper 1.21.6, and one plugin that is not. | |
| 100 | const PROJECTS = [ | |
| 101 | { id: "FAid0001", slug: "fastasyncworldedit", title: "FastAsyncWorldEdit", games: ["1.21.6"] }, | |
| 102 | { id: "SBid0001", slug: "screamingbedwars", title: "Screaming BedWars", games: ["1.21.6"] }, | |
| 103 | { id: "OLid0001", slug: "oldthing", title: "Old Thing", games: ["1.20.1"] }, | |
| 104 | ]; | |
| 105 | const wire = (p: (typeof PROJECTS)[number]) => ({ | |
| 106 | id: `${p.id.slice(0, 2)}v00001`, | |
| 107 | project_id: p.id, | |
| 108 | version_number: "1.0.0", | |
| 109 | version_type: "release", | |
| 110 | date_published: "2026-11-01T00:00:00Z", | |
| 111 | game_versions: p.games, | |
| 112 | loaders: ["paper", "spigot"], | |
| 113 | files: [ | |
| 114 | { | |
| 115 | url: `https://cdn.modrinth.com/data/${p.id}/versions/x/${p.slug}.jar`, | |
| 116 | filename: `${p.slug}.jar`, | |
| 117 | primary: true, | |
| 118 | hashes: { sha512: "a".repeat(128), sha1: "x" }, | |
| 119 | }, | |
| 120 | ], | |
| 121 | dependencies: [], | |
| 122 | }); | |
| 123 | async function modrinth(url: string): Promise<Response> { | |
| 124 | const u = new URL(url); | |
| 125 | const p = u.pathname; | |
| 126 | const proj = /^\/v2\/project\/([^/]+)$/.exec(p); | |
| 127 | if (proj) { | |
| 128 | const x = PROJECTS.find((y) => y.id === proj[1] || y.slug === proj[1]); | |
| 129 | return x === undefined ? new Response("{}", { status: 404 }) : Response.json({ id: x.id, slug: x.slug, title: x.title }); | |
| 130 | } | |
| 131 | const list = /^\/v2\/project\/([^/]+)\/version$/.exec(p); | |
| 132 | if (list) { | |
| 133 | const games = JSON.parse(u.searchParams.get("game_versions") ?? "null") as string[] | null; | |
| 134 | return Response.json( | |
| 135 | PROJECTS.filter((x) => (x.id === list[1] || x.slug === list[1]) && (games === null || x.games.some((g) => games.includes(g)))).map( | |
| 136 | wire, | |
| 137 | ), | |
| 138 | ); | |
| 139 | } | |
| 140 | const one = /^\/v2\/version\/([^/]+)$/.exec(p); | |
| 141 | if (one) { | |
| 142 | const x = PROJECTS.find((y) => wire(y).id === one[1]); | |
| 143 | return x === undefined ? new Response("{}", { status: 404 }) : Response.json(wire(x)); | |
| 144 | } | |
| 145 | return new Response("{}", { status: 404 }); | |
| 146 | } | |
| 147 | ||
| 148 | describe("the pieces", () => { | |
| 149 | test("words become a preset: the level, the plugins by their Modrinth names, a free name", () => { | |
| 150 | expect(parseWish("give me a new void world with FAWE and bedwars")).toEqual({ | |
| 151 | name: "bedwars", | |
| 152 | level: "void", | |
| 153 | plugins: ["fastasyncworldedit", "screamingbedwars"], | |
| 154 | memory: "1536M", | |
| 155 | }); | |
| 156 | expect(parseWish("a flat world called build")).toMatchObject({ name: "build", level: "flat", plugins: [] }); | |
| 157 | expect(parseWish("bedwars", ["bedwars"]).name).toBe("bedwars-2"); | |
| 158 | expect([heapMiB("1G"), heapMiB("1536M"), heapMiB("768m"), heapMiB(undefined)]).toEqual([1024, 1536, 768, 1024]); | |
| 159 | }); | |
| 160 | ||
| 161 | test("the memory math counts a sleeping server free, and says so", () => { | |
| 162 | const fits = memoryMath(COMPOSE, { name: "bedwars", memory: "1536M", sleeps: true }, 7_900); | |
| 163 | expect(fits.fits).toBe(true); | |
| 164 | expect(fits.line).toBe( | |
| 165 | "velocity 0.8G + hub 1G + survival 3G = 4.8G awake; bedwars 1.5G sleep, counted free; the box has 7.7G, 1G kept for itself: fits, 2.0G to spare.", | |
| 166 | ); | |
| 167 | expect(memoryMath(COMPOSE, { name: "big", memory: "4G", sleeps: false }, 7_900).fits).toBe(false); | |
| 168 | // Sleep's waker in the compose file is no server: the same sum with it and without. | |
| 169 | const waking = COMPOSE.replace(/^services:\n/m, "services:\n forge-waker:\n image: wollomatic/socket-proxy:1.14.0\n"); | |
| 170 | expect(waking).not.toBe(COMPOSE); | |
| 171 | expect(memoryMath(waking, { name: "bedwars", memory: "1536M", sleeps: true }, 7_900)).toEqual(fits); | |
| 172 | }); | |
| 173 | ||
| 174 | test("the proxy learns the server and its forced host, and forgets them on remove", () => { | |
| 175 | const { text, host } = proxyLines(COMPOSE, "bedwars"); | |
| 176 | expect(host).toBe("bedwars.mc.trevato.dev"); | |
| 177 | const toml = yaml(text).configs.velocity_toml.content as string; | |
| 178 | expect(toml).toContain('survival = "survival:25565"\nbedwars = "bedwars:25565"\ntry = ["hub"]'); | |
| 179 | expect(toml).toContain('"bedwars.mc.trevato.dev" = ["bedwars"]'); | |
| 180 | expect(proxyLines(text, "bedwars", true).text).toBe(COMPOSE); | |
| 181 | }); | |
| 182 | }); | |
| 183 | ||
| 184 | describe("on a forge", () => { | |
| 185 | let dataDir = ""; | |
| 186 | let app: App; | |
| 187 | let http: ForgeHttp; | |
| 188 | let ada: User; | |
| 189 | beforeAll(async () => { | |
| 190 | dataDir = mkdtempSync(join(tmpdir(), "forge-game-presets-")); | |
| 191 | app = createApp({ dataDir, port: 0, modrinthFetch: modrinth as unknown as typeof fetch }); | |
| 192 | http = forgeHttp(app); | |
| 193 | const u = await createUser(app.db, { | |
| 194 | username: "ada", | |
| 195 | email: "[email protected]", | |
| 196 | password: "a-good-passphrase", | |
| 197 | origin: "seed", | |
| 198 | isAdmin: true, | |
| 199 | trusted: true, | |
| 200 | }); | |
| 201 | if (!u.ok) throw new Error(u.error); | |
| 202 | ada = u.value; | |
| 203 | const repo = await createRepo(app, ada, { name: "mc-network", visibility: "private" }); | |
| 204 | if (!repo.ok) throw new Error(String(repo.error)); | |
| 205 | const seeded = await commitToBranch(app, ada, repo.value, { | |
| 206 | message: "seed", | |
| 207 | files: [{ path: "docker-compose.yml", content: COMPOSE }], | |
| 208 | }); | |
| 209 | if (!seeded.ok) throw new Error(JSON.stringify(seeded.error)); | |
| 210 | const { token } = createGameBox(app.db, { name: "mc", repo: "ada/mc-network" }); | |
| 211 | // The box says its memory: 7.9 GB. | |
| 212 | await http.handle( | |
| 213 | new Request("http://forge.test/api/v1/games/agent/sync", { | |
| 214 | method: "POST", | |
| 215 | headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, | |
| 216 | body: JSON.stringify({ agent: 1, host: { memMiB: 7_900 } }), | |
| 217 | }), | |
| 218 | ); | |
| 219 | }, 30_000); | |
| 220 | afterAll(async () => { | |
| 221 | app.close(); | |
| 222 | await rm(dataDir, { recursive: true, force: true }); | |
| 223 | }); | |
| 224 | ||
| 225 | test("a void world with FAWE and bedwars: planned, then one commit with its lock, its proxy lines and sleep on", async () => { | |
| 226 | const box = boxNamed(app.db, "mc")!; | |
| 227 | const planned = await planServer(app, box, parseWish("give me a new void world with FAWE and bedwars")); | |
| 228 | if (!planned.ok) throw new Error(planned.error); | |
| 229 | expect(planned.value.lines[0]).toBe("Adds bedwars: Paper 1.21.6, a void world, 1536M, sleeping when empty and waking on join."); | |
| 230 | expect( | |
| 231 | planned.value.lines.some((l) => | |
| 232 | l.startsWith("Memory: velocity 0.8G + hub 1G + survival 3G = 4.8G awake; bedwars 1.5G sleep, counted free"), | |
| 233 | ), | |
| 234 | ).toBe(true); | |
| 235 | expect(planned.value.lines.at(-1)).toContain("bedwars.mc.trevato.dev"); | |
| 236 | const done = await commitServer(app, ada, box, planned.value, planned.value.sha); | |
| 237 | expect(done.ok).toBe(true); | |
| 238 | const now = (await readCompose(app, box))!; | |
| 239 | const doc = yaml(now.text); | |
| 240 | expect(doc.services.bedwars.image).toBe("itzg/minecraft-server:latest"); | |
| 241 | expect(serviceEnv(now.text, "bedwars")).toMatchObject({ | |
| 242 | TYPE: "PAPER", | |
| 243 | VERSION: "1.21.6", | |
| 244 | LEVEL_TYPE: "FLAT", | |
| 245 | RCON_PASSWORD: "${RCON_BEDWARS:?}", | |
| 246 | }); | |
| 247 | expect(serviceEnv(now.text, "bedwars")["GENERATOR_SETTINGS"]).toContain("minecraft:the_void"); | |
| 248 | expect(serviceEnv(now.text, "bedwars")["MODRINTH_PROJECTS"]).toContain("fastasyncworldedit"); | |
| 249 | expect(serviceLabels(now.text, "bedwars")).toEqual({ "forge.sleep": "true" }); | |
| 250 | expect(policyOf(now.text, "bedwars")).toBe("sleep"); | |
| 251 | expect(doc.services[WAKER].command.join(" ")).toContain("containers/(bedwars)/(start|stop)"); | |
| 252 | expect(doc.configs.velocity_toml.content).toContain('bedwars = "bedwars:25565"'); | |
| 253 | expect(doc.volumes).toHaveProperty("bedwars"); | |
| 254 | const lock = await readRepoFile(app, box, now.sha, lockPath(box, "bedwars")); | |
| 255 | expect(lock).toContain("fastasyncworldedit"); | |
| 256 | expect(lock).toContain("screamingbedwars"); | |
| 257 | }); | |
| 258 | ||
| 259 | test("a plugin that does not run there, a name taken, or too little memory is refused before anything is written", async () => { | |
| 260 | const box = boxNamed(app.db, "mc")!; | |
| 261 | const old = await planServer(app, box, { name: "relic", level: "normal", plugins: ["oldthing"], memory: "1G" }); | |
| 262 | expect(old.ok).toBe(false); | |
| 263 | expect(old.ok ? "" : old.error).toStartWith("oldthing:"); | |
| 264 | expect(await planServer(app, box, { name: "hub", level: "flat", plugins: [], memory: "1G" })).toEqual({ | |
| 265 | ok: false, | |
| 266 | error: "The network already has a server called hub.", | |
| 267 | }); | |
| 268 | const huge = { ...box, host: { memMiB: 4_096 } }; | |
| 269 | const tight = await planServer(app, huge, { name: "arena", level: "flat", plugins: [], memory: "1G" }); | |
| 270 | expect(tight.ok ? "" : tight.error).toStartWith("Not enough memory on the box:"); | |
| 271 | }); | |
| 272 | ||
| 273 | test("the page previews from words and the tool plans then commits; remove_server takes it out, its world kept", async () => { | |
| 274 | const cookie = `forge_session=${createSession(app.db, ada.id).token}`; | |
| 275 | const page = await ( | |
| 276 | await http.handle(new Request("http://forge.test/games/mc?words=a%20flat%20world%20called%20build", { headers: { cookie } })) | |
| 277 | ).text(); | |
| 278 | expect(page).toContain("Adds build: Paper 1.21.6, a flat world"); | |
| 279 | expect(page).toMatch(/>\s*Create it\s*</); | |
| 280 | const call = async (args: Record<string, unknown>) => { | |
| 281 | const res = await http.handle( | |
| 282 | new Request("http://forge.test/mcp", { | |
| 283 | method: "POST", | |
| 284 | headers: { | |
| 285 | "content-type": "application/json", | |
| 286 | accept: "application/json, text/event-stream", | |
| 287 | authorization: `Bearer ${createToken(app.db, ada.id, "g", "admin").token}`, | |
| 288 | }, | |
| 289 | body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "games", arguments: args } }), | |
| 290 | }), | |
| 291 | ); | |
| 292 | const body = (await res.json()) as { result: { content: { text: string }[] } }; | |
| 293 | const text = body.result.content[0]!.text; | |
| 294 | return (text.startsWith("{") ? JSON.parse(text) : { refused: text }) as Record<string, any>; | |
| 295 | }; | |
| 296 | const plan = await call({ action: "create_server", box: "mc", words: "a flat world called build" }); | |
| 297 | expect(plan["planned"]).toBe(true); | |
| 298 | const create = { action: "create_server", box: "mc", words: "a flat world called build", dryRun: false }; | |
| 299 | // No sha, or another commit's, is a yes to a plan nobody was shown. | |
| 300 | for (const sha of [undefined, "0".repeat(40)]) expect((await call({ ...create, sha }))["refused"]).toContain("The box changed since the preview; plan it again."); | |
| 301 | const made = await call({ ...create, sha: plan["sha"] }); | |
| 302 | expect(made["says"]).toContain("build is in the network, at build.mc.trevato.dev"); | |
| 303 | const box = boxNamed(app.db, "mc")!; | |
| 304 | const removing = await planRemoveServer(app, box, "build"); | |
| 305 | if (!removing.ok) throw new Error(removing.error); | |
| 306 | expect((await commitServer(app, ada, box, removing.value, removing.value.sha)).ok).toBe(true); | |
| 307 | const after = (await readCompose(app, box))!.text; | |
| 308 | expect(yaml(after).services.build).toBeUndefined(); | |
| 309 | expect(yaml(after).configs.velocity_toml.content).not.toContain("build"); | |
| 310 | expect(yaml(after).volumes).toHaveProperty("build"); | |
| 311 | expect(await planRemoveServer(app, box, "velocity")).toEqual({ ok: false, error: "The proxy is the way in; it stays." }); | |
| 312 | const hub = await planRemoveServer(app, box, "hub"); | |
| 313 | expect(hub.ok ? "" : hub.error).toStartWith("The proxy sends players to hub"); | |
| 314 | }); | |
| 315 | ||
| 316 | test("the page commits only what it previewed, and Remove on a row shows its plan first", async () => { | |
| 317 | const cookie = `forge_session=${createSession(app.db, ada.id).token}`; | |
| 318 | const box = boxNamed(app.db, "mc")!; | |
| 319 | const read = async (path: string) => (await http.handle(new Request(`http://forge.test${path}`, { headers: { cookie } }))).text(); | |
| 320 | const send = (body: Record<string, string>) => | |
| 321 | http.handle( | |
| 322 | new Request("http://forge.test/games/mc/servers", { | |
| 323 | method: "POST", | |
| 324 | headers: { cookie, origin: "http://forge.test" }, | |
| 325 | body: new URLSearchParams(body), | |
| 326 | }), | |
| 327 | ); | |
| 328 | const services = async () => Object.keys(yaml((await readCompose(app, box))!.text).services); | |
| 329 | const shaOn = (html: string) => /name="sha" value="([0-9a-f]+)"/.exec(html)?.[1] ?? ""; | |
| 330 | const words = "a flat world called lobby"; | |
| 331 | const preview = await read(`/games/mc?words=${encodeURIComponent(words)}`); | |
| 332 | expect(preview).toContain("What this does"); | |
| 333 | expect(preview).not.toContain("card-body"); | |
| 334 | const seen = shaOn(preview); | |
| 335 | expect(seen).not.toBe(""); | |
| 336 | // The repository moves between the preview and the yes. | |
| 337 | const repo = getRepo(app.db, "ada", "mc-network")!; | |
| 338 | const moved = await commitToBranch(app, ada, repo, { message: "a note", files: [{ path: "NOTE.md", content: "x" }] }); | |
| 339 | if (!moved.ok) throw new Error(JSON.stringify(moved.error)); | |
| 340 | await send({ op: "create", words, sha: seen }); | |
| 341 | expect(await services()).not.toContain("lobby"); | |
| 342 | await send({ op: "create", words, sha: shaOn(await read(`/games/mc?words=${encodeURIComponent(words)}`)) }); | |
| 343 | expect(await services()).toContain("lobby"); | |
| 344 | ||
| 345 | const list = await read("/games/mc"); | |
| 346 | expect(list).toContain('href="/games/mc?remove=lobby"'); | |
| 347 | expect(list).not.toContain("?remove=velocity"); | |
| 348 | const leaving = await read("/games/mc?remove=lobby"); | |
| 349 | expect(leaving).toContain("Takes lobby out of the network"); | |
| 350 | expect(await services()).toContain("lobby"); | |
| 351 | await send({ op: "remove", service: "lobby", sha: seen }); | |
| 352 | expect(await services()).toContain("lobby"); | |
| 353 | await send({ op: "remove", service: "lobby", sha: shaOn(leaving) }); | |
| 354 | const after = yaml((await readCompose(app, box))!.text); | |
| 355 | expect(after.services.lobby).toBeUndefined(); | |
| 356 | expect(after.volumes).toHaveProperty("lobby"); | |
| 357 | }); | |
| 358 | ||
| 359 | test("d on the terminal's Games screen shows the plan, and yes takes the server out with its world kept", async () => { | |
| 360 | const box = boxNamed(app.db, "mc")!; | |
| 361 | const planned = await planServer(app, box, { name: "quiet", level: "flat", plugins: [], memory: "1G" }); | |
| 362 | if (!planned.ok) throw new Error(planned.error); | |
| 363 | expect((await commitServer(app, ada, box, planned.value, planned.value.sha)).ok).toBe(true); | |
| 364 | recordSync(app.db, box, { | |
| 365 | composeSha: "", | |
| 366 | services: [{ name: "quiet", state: "running", health: "", startedAt: "", cpuPct: 1, memMiB: 900 }], | |
| 367 | logs: {}, | |
| 368 | results: [], | |
| 369 | host: { memMiB: 7_900 }, | |
| 370 | }); | |
| 371 | const { app: tui, session } = createForgeApp( | |
| 372 | app, | |
| 373 | { sshUsername: "ada", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: ada }, | |
| 374 | { terminal: headlessTerminal(140, 30), exitHooks: false }, | |
| 375 | ); | |
| 376 | tui.start(); | |
| 377 | tui.ctx.push(gamesScreen(session, tui.ctx)); | |
| 378 | await settleApp(tui); | |
| 379 | const press = (key: string) => tui.dispatch({ type: "key", key, ctrl: false, alt: false, shift: false }); | |
| 380 | press("d"); | |
| 381 | await settleUntil(tui, "Takes quiet out of the network"); | |
| 382 | expect((await readCompose(app, box))!.text).toContain("container_name: quiet"); | |
| 383 | press("y"); | |
| 384 | await settleUntil(tui, "quiet is out of the network"); | |
| 385 | const after = yaml((await readCompose(app, box))!.text); | |
| 386 | expect(after.services.quiet).toBeUndefined(); | |
| 387 | expect(after.volumes).toHaveProperty("quiet"); | |
| 388 | tui.stop?.(); | |
| 389 | }); | |
| 390 | }); |
test/private-by-default.test.ts +1
| @@ -128,6 +128,7 @@ const DOORS: Readonly<Record<string, Door>> = { | ||
| 128 | 128 | "mcp fork_flows": { noRepository: "reads the fork flows" }, |
| 129 | 129 | "mcp fork_tree": { noRepository: "reads the fork tree" }, |
| 130 | 130 | "mcp forks": { noRepository: "reads the forks" }, |
| 131 | "mcp games create_server": { noRepository: "a server in the network's compose file: a commit to the box's existing repository" }, | |
| 131 | 132 | "mcp games start": { noRepository: "a game service started (power), not a repository" }, |
| 132 | 133 | "mcp make_it_yours": { proven: "test/make-it-yours.test.ts", says: 'plan.value.visibility).toBe("private")' }, |
| 133 | 134 | "mcp migrate": { proven: "test/migrate-trail.test.ts", says: "a migration that asks for no visibility is private" }, |
new above
offline
Principle 1: the label carries the example and the muted line below repeats it. Keep one.