Public: anyone can read this; the crew can change it.
Game servers: Minecraft Java as a ready-made /infra design (#16696) #17341
Merged 2d 6h ago, live in production
scout/forge:scout/17076-game-servers-minecraft-java-as-a-ready-m → main 0 commits fork
7 files
changed +451
−1
docs/features/infra.md +12
| @@ -65,3 +65,15 @@ Deleting a database, and the data in it, is not here yet: do it at DigitalOcean, | ||
| 65 | 65 | Phase 3's first kind, DigitalOcean Spaces (`src/cloud/bucket.ts`; a new provider is one more row of `BUCKETS`). In Talk or MCP, `infra` `price` with `bucket: {region, name, stored_gib?, out_gib?}` says what a bucket costs a month and where it would answer: the provider's list price ($5 with 250 GiB stored and 1 TiB out in it, 2¢ and 1¢ a GiB over), held as numbers because Spaces has no price endpoint. `bind` with `repo` sets that app's secret `BUCKET_URL` to the bucket's address (`src/actions/bucket.ts`), which restarts the app as any secret change does. Not done yet: making the bucket from a plan (it needs Spaces keys, which the forge does not hold), Hetzner and B2, and the page and terminal doors; make the bucket at the provider and keep its keys as the app's secrets. |
| 66 | 66 | |
| 67 | 67 | Terminal: the **Buckets** palette entry (`src/tui/screens/buckets.ts`): `p` reads a price for anyone signed in, `b` binds a bucket's address to an app as `BUCKET_URL`, a forge admin's only. |
| 68 | ||
| 69 | ## Minecraft Java, ready-made (#17076) | |
| 70 | ||
| 71 | A design: answer a few questions and the forge plans a game box running `itzg/minecraft-server` with its address. Ask for it through the `infra` tool's `plan` with `want: {design: "minecraft", players, where: "digitalocean/main@<place id>", domain: "example.com", dns: "cloudflare/main", repo: "owner/name", eula: true, name?: "mc", version?: "1.21.4"}`, or in the terminal's Infrastructure screen with `M` (name, the Cloudflare account when there is more than one, players, place, domain, repository, then Mojang's EULA, then the plan with Build). The web page does not offer it yet. | |
| 72 | ||
| 73 | - **Sized by players** (`src/games/minecraft.ts`): 1–5 players get a 2 GB heap, to 10 3 GB, to 20 4 GB, to 40 6 GB, to 80 8 GB, to 150 12 GB. The place must have the heap plus 2 GB; a smaller one, or an Arm size (Hetzner CAX), is refused in a sentence before anything is planned. | |
| 74 | - **Pinned**: the image is a fixed tag and `VERSION` a fixed release (`1.21.4` unless `version` names another; `latest` is refused), so a restart of the box never changes the world's server under it. | |
| 75 | - **The address**: `play.<domain>` is the box's host, written as an A record as for any game box, and an SRV record `_minecraft._tcp.play.<domain>` → `play.<domain>` port 25565 through the Cloudflare account named. Both are wants in one plan, so the ceiling and refusals are the plan's own. | |
| 76 | - **The EULA** is accepted by the person (`eula: true`, or the terminal's confirm), never for them. | |
| 77 | - **The compose file** comes back with the plan (`compose`, and a `note`). The forge does not commit it: put it as `docker-compose.yml` on the main branch of the named repository, and the box runs it. It holds one service `mc`, the world on a named volume, RCON through the box's own sealed `RCON_MC`. | |
| 78 | ||
| 79 | Not yet: the page, committing the compose file, sleep and wake, backups, and a Steam catalog. |
src/actions/minecraft.ts added +39
| @@ -0,0 +1,39 @@ | ||
| 1 | /** | |
| 2 | * Minecraft Java as a design (#17076): the plan of a game box and its SRV record, from a few | |
| 3 | * answers. Reads the place's memory from the kept catalog; plans through `planWants`, so the | |
| 4 | * ceiling, the read-only switch and every refusal are the plan's own. | |
| 5 | */ | |
| 6 | ||
| 7 | import type { App } from "../app.ts"; | |
| 8 | import { keptPlaces } from "../cloud/places_read.ts"; | |
| 9 | import { keptRate } from "../cloud/rates.ts"; | |
| 10 | import type { User } from "../core/users.ts"; | |
| 11 | import { minecraftDesign, type MinecraftInput } from "../games/minecraft.ts"; | |
| 12 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 13 | import { planWants, type Planned } from "./infra.ts"; | |
| 14 | ||
| 15 | export interface MinecraftPlanned { | |
| 16 | readonly planned: Planned; | |
| 17 | /** The `docker-compose.yml` to commit in the named repository. */ | |
| 18 | readonly compose: string; | |
| 19 | readonly address: string; | |
| 20 | /** What is left to the person, in a sentence. */ | |
| 21 | readonly note: string; | |
| 22 | } | |
| 23 | ||
| 24 | /** Plan Minecraft for `i`; nothing is made. Admins only, as every infra plan is. */ | |
| 25 | export function planMinecraft(app: App, actor: User | undefined, i: MinecraftInput): Result<MinecraftPlanned, string> { | |
| 26 | const placeId = i.where.split("@")[1] ?? ""; | |
| 27 | const place = keptPlaces(app.db, keptRate(app.db, "EUR")).find((p) => p.id === placeId); | |
| 28 | if (place === undefined) return err("Pick where the server runs."); | |
| 29 | const design = minecraftDesign(i, place); | |
| 30 | if (!design.ok) return design; | |
| 31 | const planned = planWants(app, actor, [design.value.machine, design.value.srv]); | |
| 32 | if (!planned.ok) return planned; | |
| 33 | return ok({ | |
| 34 | planned: planned.value, | |
| 35 | compose: design.value.compose, | |
| 36 | address: design.value.address, | |
| 37 | note: `Commit this as docker-compose.yml on the main branch of ${i.repo}; the box runs what is there. Players join at ${design.value.address}.`, | |
| 38 | }); | |
| 39 | } |
src/games/minecraft.ts added +114
| @@ -0,0 +1,114 @@ | ||
| 1 | /** | |
| 2 | * Minecraft Java as a ready-made design (#17076, #16696 phase G): itzg/minecraft-server on an x86 | |
| 3 | * place, sized by the players it must hold, addressed as play.<domain> by an A record (the game | |
| 4 | * box's host) and an SRV record. Pure: plain strings in, a compose file and the wants out; the | |
| 5 | * plan, the build and the box are the ones every game box already has (`actions/minecraft.ts`). | |
| 6 | */ | |
| 7 | ||
| 8 | import { dnsWantOf, type DnsWant, type MachineWant } from "../cloud/plan.ts"; | |
| 9 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 10 | import { BOX_NAME } from "./store.ts"; | |
| 11 | ||
| 12 | export const MINECRAFT_PORT = 25565; | |
| 13 | export const MAX_PLAYERS = 150; | |
| 14 | ||
| 15 | /** What a person types, whichever door it came through. */ | |
| 16 | export interface MinecraftInput { | |
| 17 | readonly name: string; | |
| 18 | readonly players: string; | |
| 19 | /** `account@placeId`. */ | |
| 20 | readonly where: string; | |
| 21 | /** The zone's name, e.g. `example.com`; the server answers at `play.<domain>`. */ | |
| 22 | readonly domain: string; | |
| 23 | /** The Cloudflare account that writes the SRV record, `cloudflare/<name>`. */ | |
| 24 | readonly dns: string; | |
| 25 | /** The repository (`owner/name`) whose `docker-compose.yml` the box runs. */ | |
| 26 | readonly repo: string; | |
| 27 | /** Mojang's EULA is accepted by the person, never for them. */ | |
| 28 | readonly eula: boolean; | |
| 29 | /** | |
| 30 | * The Minecraft release the world runs, like `1.21.4`; empty is `DEFAULT_VERSION`. Never | |
| 31 | * "latest". | |
| 32 | */ | |
| 33 | readonly version?: string; | |
| 34 | } | |
| 35 | ||
| 36 | /** The itzg image, pinned: a restart of the box never pulls a new one under the world. */ | |
| 37 | const IMAGE = "itzg/minecraft-server:2025.4.0"; | |
| 38 | /** The release a server runs when the person names none. */ | |
| 39 | const DEFAULT_VERSION = "1.21.4"; | |
| 40 | const VERSION = /^\d{1,2}\.\d{1,2}(?:\.\d{1,2})?$/; | |
| 41 | ||
| 42 | /** The JVM heap, in GiB, a server for this many players is given. */ | |
| 43 | export function heapGiB(players: number): number { | |
| 44 | return players <= 5 ? 2 : players <= 10 ? 3 : players <= 20 ? 4 : players <= 40 ? 6 : players <= 80 ? 8 : 12; | |
| 45 | } | |
| 46 | ||
| 47 | /** The machine's memory the heap needs: the heap, the OS, Docker and the agent. */ | |
| 48 | export const needMiB = (players: number): number => (heapGiB(players) + 2) * 1024; | |
| 49 | ||
| 50 | const LABEL = "[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"; | |
| 51 | const DOMAIN = new RegExp(`^(?=.{1,200}$)${LABEL}(?:\\.${LABEL})+$`); | |
| 52 | const REPO = /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/; | |
| 53 | ||
| 54 | /** | |
| 55 | * The compose file: one service, its world on a named volume, RCON through the box's sealed key. | |
| 56 | */ | |
| 57 | export function minecraftCompose(players: number, version: string = DEFAULT_VERSION): string { | |
| 58 | return [ | |
| 59 | "services:", | |
| 60 | " mc:", | |
| 61 | ` image: ${IMAGE}`, | |
| 62 | " restart: unless-stopped", | |
| 63 | " ports:", | |
| 64 | ` - "${MINECRAFT_PORT}:${MINECRAFT_PORT}"`, | |
| 65 | " environment:", | |
| 66 | ' EULA: "TRUE"', | |
| 67 | ' TYPE: "PAPER"', | |
| 68 | ` VERSION: "${version}"`, | |
| 69 | ` MEMORY: "${heapGiB(players)}G"`, | |
| 70 | ` MAX_PLAYERS: "${players}"`, | |
| 71 | ' RCON_PASSWORD: "${RCON_MC}"', | |
| 72 | " volumes:", | |
| 73 | " - mc-data:/data", | |
| 74 | "volumes:", | |
| 75 | " mc-data: {}", | |
| 76 | "", | |
| 77 | ].join("\n"); | |
| 78 | } | |
| 79 | ||
| 80 | export interface MinecraftDesign { | |
| 81 | readonly compose: string; | |
| 82 | readonly address: string; | |
| 83 | readonly players: number; | |
| 84 | readonly machine: MachineWant; | |
| 85 | readonly srv: DnsWant; | |
| 86 | } | |
| 87 | ||
| 88 | /** | |
| 89 | * The design for `i` at a place with `memoryMiB` of memory and a `size` (its provider's shape | |
| 90 | * name), or the one thing still wrong in a sentence. A place too small for the players, or not x86, | |
| 91 | * is refused here, not at the provider. | |
| 92 | */ | |
| 93 | export function minecraftDesign(i: MinecraftInput, place: { readonly memoryMiB: number; readonly size: string }): Result<MinecraftDesign, string> { | |
| 94 | if (!i.eula) return err("Minecraft's EULA (https://aka.ms/MinecraftEULA) must be accepted by you: say eula is true."); | |
| 95 | if (!BOX_NAME.test(i.name)) return err("A name is lowercase letters, digits and dashes, starting with a letter."); | |
| 96 | const players = /^\d{1,3}$/.test(i.players.trim()) ? Number(i.players.trim()) : 0; | |
| 97 | if (players < 1 || players > MAX_PLAYERS) return err(`Say how many players, from 1 to ${MAX_PLAYERS}.`); | |
| 98 | const domain = i.domain.trim().toLowerCase(); | |
| 99 | if (!DOMAIN.test(domain)) return err("Name the domain the server answers under, like example.com."); | |
| 100 | if (!/^cloudflare\/[A-Za-z0-9._-]{1,60}$/.test(i.dns)) return err("Pick a Cloudflare account that allows writes: it writes the server's address."); | |
| 101 | if (!REPO.test(i.repo)) return err("Name the repository that holds the compose file as owner/name."); | |
| 102 | const [account = "", placeId = ""] = i.where.split("@"); | |
| 103 | if (account === "" || placeId === "") return err("Pick where the server runs."); | |
| 104 | // Hetzner's CAX shapes are Arm: the itzg image would run, but the design promises x86. | |
| 105 | if (/^cax/i.test(place.size)) return err("This place is Arm; pick an x86 size."); | |
| 106 | if (place.memoryMiB < needMiB(players)) | |
| 107 | return err(`${players} players need a place with at least ${needMiB(players) / 1024} GB of memory; this one has ${Math.round(place.memoryMiB / 1024)} GB.`); | |
| 108 | const version = (i.version ?? "").trim() || DEFAULT_VERSION; | |
| 109 | if (!VERSION.test(version)) return err("Name the Minecraft version as numbers, like 1.21.4; \"latest\" would change the world on a restart."); | |
| 110 | const address = `play.${domain}`; | |
| 111 | const machine: MachineWant = { kind: "machine", game: true, name: i.name, account, place: placeId, app: i.repo, source: "", host: address }; | |
| 112 | const srv = dnsWantOf({ name: `${i.name}-srv`, account: i.dns, type: "SRV", host: `_minecraft._tcp.${address}`, value: address, port: MINECRAFT_PORT }); | |
| 113 | return ok({ compose: minecraftCompose(players, version), address, players, machine, srv }); | |
| 114 | } |
src/http/mcp/tools/infra.ts +18 −1
| @@ -3,6 +3,7 @@ import { buildOf, firewallWant, gameWant, planDatabase, goneWords, infraOf, infr | ||
| 3 | 3 | import { bindBucket, readBucket } from "../../../actions/bucket.ts"; |
| 4 | 4 | import { endsWords, keepPinned } from "../../../actions/pinned.ts"; |
| 5 | 5 | import { lookAtRecords, lookWords } from "../../../actions/dns_record.ts"; |
| 6 | import { planMinecraft } from "../../../actions/minecraft.ts"; | |
| 6 | 7 | import { dnsWantOf } from "../../../cloud/plan.ts"; |
| 7 | 8 | import { EXPERIMENT_WORDS, attachMachine, beginExperiment, findExperiment, recordResult } from "../../../cloud/experiments.ts"; |
| 8 | 9 | import { good, bad, type Tool, str } from "../shared.ts"; |
| @@ -18,7 +19,7 @@ const s = (v: unknown, max: number): string => str(v).slice(0, max); | ||
| 18 | 19 | export const tool: Tool = { |
| 19 | 20 | name: "infra", |
| 20 | 21 | listedTo: "admin", |
| 21 | doc: "`{ action, id?, want?, question?, names?, result?, bucket? }`: `list` (its `says` names every machine), `show` an `id` (a plan, an experiment or a machine's name), `plan` a `want` `{app, where, question?, experiment?, days?}` or a firewall `{firewall: name}` or a DNS record `{dns: true, name, account, type: A|SRV, host, value, port?}` or a game box `{game: true, where, name?, repo?, host?}` or Postgres `{database: true, app, where: account@region, size?, secret?}` or dead `names`, `apply` its `id`, `check` DNS records, `code` (infra.json against what runs), `keep`, `begin`, `attach`, `record_result`; `price`/`bind` a `bucket` `{region, name, repo?, stored_gib?, out_gib?}`.", | |
| 22 | doc: "`{ action, id?, want?, question?, names?, result?, bucket? }`: `list` (its `says` names every machine), `show` an `id` (a plan, an experiment or a machine's name), `plan` a `want` `{app, where, question?, experiment?, days?}` or a firewall `{firewall: name}` or a DNS record `{dns: true, name, account, type: A|SRV, host, value, port?}` or a game box `{game: true, where, name?, repo?, host?}` or Minecraft Java `{design: minecraft, players, where, domain, dns, repo, eula: true, name?, version?}` (its `compose` comes back with the plan) or Postgres `{database: true, app, where: account@region, size?, secret?}` or dead `names`, `apply` its `id`, `check` DNS records, `code` (infra.json against what runs), `keep`, `begin`, `attach`, `record_result`; `price`/`bind` a `bucket` `{region, name, repo?, stored_gib?, out_gib?}`.", | |
| 22 | 23 | description: "Cloud machines and spend.", |
| 23 | 24 | inputSchema: { |
| 24 | 25 | type: "object", |
| @@ -110,6 +111,22 @@ export const tool: Tool = { | ||
| 110 | 111 | if (p.lacks !== "") return bad("incomplete", p.lacks); |
| 111 | 112 | return good({ id: p.plan.id, says: p.summary, steps: p.plan.steps.map((x) => x.says), refusals: p.fixes, byAccount: p.plan.byAccount, deltaCents: p.plan.deltaCents, etaSeconds: p.plan.etaSeconds }); |
| 112 | 113 | } |
| 114 | // Minecraft Java as a design (#17076): a game box sized by its players, with A + SRV records. | |
| 115 | if (w["design"] === "minecraft") { | |
| 116 | const made = planMinecraft(ctx.app, user, { | |
| 117 | name: s(w["name"], 40) || "mc", | |
| 118 | players: String(w["players"] ?? ""), | |
| 119 | where: s(w["where"], 260), | |
| 120 | domain: s(w["domain"], 200), | |
| 121 | dns: s(w["dns"], 80), | |
| 122 | repo: s(w["repo"], 140), | |
| 123 | eula: w["eula"] === true, | |
| 124 | version: s(w["version"], 20), | |
| 125 | }); | |
| 126 | if (!made.ok) return bad("incomplete", made.error); | |
| 127 | const p = made.value.planned; | |
| 128 | return good({ id: p.plan.id, says: p.summary, steps: p.plan.steps.map((x) => x.says), refusals: p.fixes, byAccount: p.plan.byAccount, deltaCents: p.plan.deltaCents, compose: made.value.compose, note: made.value.note }); | |
| 129 | } | |
| 113 | 130 | // A game box: Docker and the game agent on the owner's cloud, running a compose file. |
| 114 | 131 | if (w["game"] === true) { |
| 115 | 132 | const want = gameWant({ name: s(w["name"], 40) || nameFor(s(w["repo"], 140) || "trevato/game"), where: s(w["where"], 260), repo: s(w["repo"], 140), host: s(w["host"], 253) }); |
src/tui/screens/infra.ts +66
| @@ -16,6 +16,7 @@ import { dropRecord, lookAtRecords, lookWords } from "../../actions/dns_record.t | ||
| 16 | 16 | import { infraCode, type CodeFile } from "../../cloud/infra_read.ts"; |
| 17 | 17 | import { buildOf, composeChoices, databaseChoices, infraOf, nameFor, planCompose, planDatabase, planRecord, recordAccounts, startBuild, type Compose, type Planned, type Running } from "../../actions/infra.ts"; |
| 18 | 18 | import { deleteSnapshot, endWithSnapshot, restoredName, restoreSnapshot } from "../../actions/infra_snapshot.ts"; |
| 19 | import { planMinecraft } from "../../actions/minecraft.ts"; | |
| 19 | 20 | import { LIFETIME_DAYS, clearPinned, endsWords, keepPinned, retirePinned, retireWords } from "../../actions/pinned.ts"; |
| 20 | 21 | import type { SnapshotView } from "../../actions/infra_snapshot.ts"; |
| 21 | 22 | import { dollars } from "../../cloud/prices.ts"; |
| @@ -268,12 +269,72 @@ export function infraScreen(f: Session, ctx: Ctx): Screen { | ||
| 268 | 269 | }); |
| 269 | 270 | }; |
| 270 | 271 | |
| 272 | /** | |
| 273 | * Minecraft Java as a design (#17076): players, place, domain, repository, the EULA; then the | |
| 274 | * plan. | |
| 275 | */ | |
| 276 | const composeMinecraft = (parent: Screen): Screen => { | |
| 277 | const accounts = recordAccounts(f.app); | |
| 278 | const places = composeChoices(f.app).places.filter((p) => p.orderable); | |
| 279 | if (accounts.length === 0) { | |
| 280 | say("No Cloudflare account allows writes: connect one in Cloud accounts."); | |
| 281 | return parent; | |
| 282 | } | |
| 283 | if (places.length === 0) { | |
| 284 | say("No place can be ordered: allow writes on a cloud account first."); | |
| 285 | return parent; | |
| 286 | } | |
| 287 | const d = { name: "", players: "", where: "", domain: "", dns: accounts[0]!, repo: "", eula: false }; | |
| 288 | const ask = (title: string, label: string, set: (v: string) => void, next: () => Screen): Screen => | |
| 289 | promptScreen(ctx, parent, { title, label, onSubmit: (v) => { set(v.trim()); return later(ctx, next); } }); | |
| 290 | const showPlan = (): Screen => { | |
| 291 | const made = planMinecraft(f.app, f.user, d); | |
| 292 | if (!made.ok) return confirmScreen(ctx, parent, { title: "Not yet", body: [made.error], width: 96, actions: [{ label: "Close" }], onChoose: () => {} }); | |
| 293 | return confirmScreen(ctx, parent, { | |
| 294 | title: made.value.planned.plan.refusals.length === 0 ? "The plan" : "Not yet", | |
| 295 | body: [made.value.planned.summary, "", ...made.value.planned.plan.steps.map((s) => ` ${s.says}`), ...made.value.planned.fixes.map((x) => x.why), "", made.value.note, "", ...made.value.compose.split("\n")], | |
| 296 | width: 96, | |
| 297 | actions: made.value.planned.plan.refusals.length === 0 ? [{ label: "Build" }, { label: "Cancel" }] : [{ label: "Close" }], | |
| 298 | onChoose: (i) => { | |
| 299 | if (i !== 0 || made.value.planned.plan.refusals.length > 0) return; | |
| 300 | const started = startBuild(f.app, f.user, made.value.planned.plan); | |
| 301 | if (!started.ok) return say(started.error); | |
| 302 | building = started.value; | |
| 303 | say("Building: each step shows as it happens."); | |
| 304 | }, | |
| 305 | }); | |
| 306 | }; | |
| 307 | const eula = (): Screen => | |
| 308 | confirmScreen(ctx, parent, { | |
| 309 | title: "Minecraft's EULA", | |
| 310 | body: ["You must accept Mojang's EULA (https://aka.ms/MinecraftEULA) to run a server."], | |
| 311 | width: 96, | |
| 312 | actions: [{ label: "I accept" }, { label: "Cancel" }], | |
| 313 | onChoose: (i) => { | |
| 314 | if (i !== 0) return; | |
| 315 | d.eula = true; | |
| 316 | void later(ctx, showPlan); | |
| 317 | }, | |
| 318 | }); | |
| 319 | const repo = (): Screen => ask("Compose repository", "owner/name that holds docker-compose.yml", (v) => (d.repo = v), eula); | |
| 320 | const domain = (): Screen => ask("Domain", "the zone, like example.com: players join at play.<domain>", (v) => (d.domain = v), repo); | |
| 321 | const place = (): Screen => | |
| 322 | pickerScreen(ctx, parent, { title: "Where", items: places.map((p) => ({ id: p.value, label: `${p.where} · ${p.size}`, hint: month(p.costCents) })), onPick: ([w = ""]) => { d.where = w; void later(ctx, domain); } }); | |
| 323 | const players = (): Screen => ask("Players", "how many at once (1 to 150): it sizes the memory", (v) => (d.players = v), place); | |
| 324 | // The name is the box's own, so a second server is not the first; the Cloudflare account is | |
| 325 | // asked only when there is a choice. | |
| 326 | const account = (): Screen => | |
| 327 | accounts.length < 2 ? players() : pickerScreen(ctx, parent, { title: "Cloudflare account", items: accounts.map((a) => ({ id: a, label: a, hint: "" })), onPick: ([a = ""]) => { d.dns = a; void later(ctx, players); } }); | |
| 328 | return ask("Name", "lowercase letters, digits and dashes: the server's name on the forge", (v) => (d.name = v), account); | |
| 329 | }; | |
| 330 | ||
| 271 | 331 | const screen: Screen = { |
| 272 | 332 | title: "Infrastructure", |
| 273 | 333 | keys: [ |
| 274 | 334 | binding(["j", "k"], "move cursor"), |
| 275 | 335 | binding(["n"], "new"), |
| 276 | 336 | binding(["b"], "new database"), |
| 337 | binding(["M"], "new Minecraft server"), | |
| 277 | 338 | binding(["+"], `keep ${LIFETIME_DAYS} more days`), |
| 278 | 339 | binding(["x"], "end now"), |
| 279 | 340 | binding(["c"], "clear a dead row"), |
| @@ -383,6 +444,11 @@ export function infraScreen(f: Session, ctx: Ctx): Screen { | ||
| 383 | 444 | void lookAtRecords(f.app, f.user).then((n) => say(n.ok ? lookWords(n.value) : n.error)); |
| 384 | 445 | return true; |
| 385 | 446 | } |
| 447 | if (e.key === "M") { | |
| 448 | const next = composeMinecraft(screen); | |
| 449 | if (next !== screen) ctx.push(next); | |
| 450 | return true; | |
| 451 | } | |
| 386 | 452 | if (e.key === "m") { |
| 387 | 453 | const next = composeRecord(screen); |
| 388 | 454 | if (next !== screen) ctx.push(next); |
test/egress-literals.test.ts +1
| @@ -35,6 +35,7 @@ const NOT_CALLED: Record<string, string> = { | ||
| 35 | 35 | "git.open-platform.sh": "placeholder in the follow-upstream form", |
| 36 | 36 | "jsonfeed.org": "the JSON Feed version URI, a name and not a request", |
| 37 | 37 | "ui.shadcn.com": "the registry schema URIs in registry/items.ts, names the shadcn CLI reads and the forge never requests", |
| 38 | "aka.ms": "the Minecraft EULA link in the games design text, shown to the user and never requested", | |
| 38 | 39 | "ntfy.sh": "placeholder in the account notification field", |
| 39 | 40 | "schema.org": "the JSON-LD @context, a name and not a request", |
| 40 | 41 | "specification.website": "section links in release and preview reports", |
test/minecraft-design.test.ts added +201
| @@ -0,0 +1,201 @@ | ||
| 1 | /** | |
| 2 | * Minecraft Java as a design (#17076): players size the heap and the place, the compose file is | |
| 3 | * the itzg image with the EULA accepted only by the person, and the address is A + SRV. | |
| 4 | */ | |
| 5 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 6 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 7 | import { tmpdir } from "node:os"; | |
| 8 | import { join } from "node:path"; | |
| 9 | import { createApp, type App } from "../src/app.ts"; | |
| 10 | import { addAccount, allowWrite, net as cloudNet } from "../src/actions/cloud.ts"; | |
| 11 | import { readPlaces } from "../src/cloud/places_read.ts"; | |
| 12 | import { planMinecraft } from "../src/actions/minecraft.ts"; | |
| 13 | import { createForgeApp } from "../src/tui/forge.ts"; | |
| 14 | import { infraScreen } from "../src/tui/screens/infra.ts"; | |
| 15 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; | |
| 16 | import type { Ctx } from "../src/http/context.ts"; | |
| 17 | import { tool } from "../src/http/mcp/tools/infra.ts"; | |
| 18 | import { createUser, getUserByName } from "../src/core/users.ts"; | |
| 19 | import { heapGiB, minecraftCompose, minecraftDesign, needMiB, type MinecraftInput } from "../src/games/minecraft.ts"; | |
| 20 | import { seedPlaces } from "./helpers/places-fixture.ts"; | |
| 21 | import { settleApp } from "./helpers/tui.ts"; | |
| 22 | import { quietLogs } from "./helpers/globals.ts"; | |
| 23 | ||
| 24 | quietLogs(); | |
| 25 | ||
| 26 | const input: MinecraftInput = { name: "mc", players: "10", where: "digitalocean/main@digitalocean:nyc3:s-2vcpu-4gb", domain: "Example.com", dns: "cloudflare/main", repo: "alice/mc", eula: true }; | |
| 27 | ||
| 28 | describe("the design", () => { | |
| 29 | test("players size the heap and the memory a place must have", () => { | |
| 30 | expect([1, 5, 6, 10, 11, 20, 21, 40, 41, 80, 81, 150].map(heapGiB)).toEqual([2, 2, 3, 3, 4, 4, 6, 6, 8, 8, 12, 12]); | |
| 31 | expect(needMiB(10)).toBe(5 * 1024); | |
| 32 | }); | |
| 33 | ||
| 34 | test("the compose file is itzg's image with the heap, the players and the box's own RCON key", () => { | |
| 35 | const c = minecraftCompose(20); | |
| 36 | expect(c).toMatch(/image: itzg\/minecraft-server:\d/); | |
| 37 | expect(c).not.toContain(":latest"); | |
| 38 | expect(c).not.toMatch(/VERSION: "(?:LATEST|latest)"/); | |
| 39 | expect(c).toContain('VERSION: "1.21.4"'); | |
| 40 | expect(c).toContain('MEMORY: "4G"'); | |
| 41 | expect(c).toContain('MAX_PLAYERS: "20"'); | |
| 42 | expect(c).toContain("${RCON_MC}"); | |
| 43 | expect(c).not.toContain("19132"); | |
| 44 | expect((Bun.YAML.parse(c) as { services: Record<string, unknown> }).services).toHaveProperty("mc"); | |
| 45 | }); | |
| 46 | ||
| 47 | test("the version is pinned, a person's own pinned too, and latest is refused", () => { | |
| 48 | const place = { memoryMiB: 8192, size: "s-4vcpu-8gb" }; | |
| 49 | const d = minecraftDesign({ ...input, version: "1.20.6" }, place); | |
| 50 | expect(d.ok && d.value.compose).toContain('VERSION: "1.20.6"'); | |
| 51 | for (const v of ["latest", "LATEST", "1.x", "1.21.4\nEULA: x"]) { | |
| 52 | const bad = minecraftDesign({ ...input, version: v }, place); | |
| 53 | expect(bad.ok ? "" : bad.error).toContain("version"); | |
| 54 | } | |
| 55 | }); | |
| 56 | ||
| 57 | test("builds a game box at play.<domain> and an SRV record to it", () => { | |
| 58 | const d = minecraftDesign(input, { memoryMiB: 8192, size: "s-4vcpu-8gb" }); | |
| 59 | if (!d.ok) throw new Error(d.error); | |
| 60 | expect(d.value.address).toBe("play.example.com"); | |
| 61 | expect(d.value.machine).toMatchObject({ game: true, name: "mc", place: "digitalocean:nyc3:s-2vcpu-4gb", app: "alice/mc", host: "play.example.com" }); | |
| 62 | expect(d.value.srv).toMatchObject({ type: "SRV", host: "_minecraft._tcp.play.example.com", value: "play.example.com", port: 25565, account: "cloudflare/main" }); | |
| 63 | }); | |
| 64 | ||
| 65 | test("refuses, in a sentence, what is not right", () => { | |
| 66 | const why = (o: Partial<MinecraftInput>, p = { memoryMiB: 8192, size: "s-4vcpu-8gb" }): string => { | |
| 67 | const d = minecraftDesign({ ...input, ...o }, p); | |
| 68 | return d.ok ? "" : d.error; | |
| 69 | }; | |
| 70 | expect(why({ eula: false })).toContain("EULA"); | |
| 71 | expect(why({ players: "0" })).toContain("1 to 150"); | |
| 72 | expect(why({ players: "151" })).toContain("1 to 150"); | |
| 73 | expect(why({ players: "ten" })).toContain("1 to 150"); | |
| 74 | expect(why({ domain: "no dots" })).toContain("domain"); | |
| 75 | expect(why({ domain: "a.com\nb" })).toContain("domain"); | |
| 76 | expect(why({ name: "../x" })).toContain("name"); | |
| 77 | expect(why({ repo: "a b" })).toContain("owner/name"); | |
| 78 | expect(why({ dns: "digitalocean/main" })).toContain("Cloudflare"); | |
| 79 | expect(why({ where: "nowhere" })).toContain("where"); | |
| 80 | expect(why({}, { memoryMiB: 2048, size: "s-1vcpu-2gb" })).toContain("at least 5 GB"); | |
| 81 | expect(why({}, { memoryMiB: 8192, size: "cax31" })).toContain("Arm"); | |
| 82 | }); | |
| 83 | }); | |
| 84 | ||
| 85 | describe("the doors", () => { | |
| 86 | let app: App; | |
| 87 | let dir = ""; | |
| 88 | const saved = cloudNet.fetch; | |
| 89 | const where = "digitalocean/main@digitalocean:nyc3:s-4vcpu-8gb"; | |
| 90 | const full = { design: "minecraft", players: 10, where, domain: "example.com", dns: "cloudflare/main", repo: "alice/mc", eula: true }; | |
| 91 | const ctxOf = (user: NonNullable<ReturnType<typeof getUserByName>>): Ctx => { | |
| 92 | const url = new URL("http://forge.test/mcp"); | |
| 93 | return { app, request: new Request(url.href), url, params: {}, auth: { user, scope: "admin", via: "token" }, theme: undefined }; | |
| 94 | }; | |
| 95 | const alice = () => getUserByName(app.db, "alice")!; | |
| 96 | beforeAll(async () => { | |
| 97 | dir = await mkdtemp(join(tmpdir(), "forge-minecraft-")); | |
| 98 | app = createApp({ dataDir: dir, port: 0 }); | |
| 99 | for (const [username, adminIfFirst] of [["alice", true], ["bob", false]] as const) { | |
| 100 | const made = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@f.test`, password: "a-good-passphrase", adminIfFirst }); | |
| 101 | if (!made.ok) throw new Error(String(made.error)); | |
| 102 | } | |
| 103 | await seedPlaces(app.db); | |
| 104 | // A kept place with the memory ten players need, as a real read keeps it. | |
| 105 | const json = (o: unknown): Response => new Response(JSON.stringify(o), { status: 200 }); | |
| 106 | const sizes = [{ slug: "s-4vcpu-8gb", memory: 8192, vcpus: 4, disk: 160, transfer: 5, price_monthly: 30, available: true, regions: ["nyc3"] }]; | |
| 107 | await readPlaces(app.db, "digitalocean", async (url) => json(String(url).includes("/sizes") ? { sizes } : { regions: [{ slug: "nyc3", available: true }] }), "t"); | |
| 108 | cloudNet.fetch = async (url) => | |
| 109 | String(url).includes("cloudflare") ? json({ success: true, result: [{ id: "a".repeat(32), name: "example.com" }] }) : json({ account: { email: "[email protected]", status: "active" } }); | |
| 110 | for (const [provider, key] of [["digitalocean", "dop_v1_9Zq4TxLm7Kp2Vb8nWcR5"], ["cloudflare", "cf-token-0123456789abcdef0123456789abcdef"]] as const) { | |
| 111 | const added = await addAccount(app, alice(), provider, "main", key); | |
| 112 | if (!added.ok) throw new Error(String(added.error)); | |
| 113 | allowWrite(app, alice(), provider, "main", true); | |
| 114 | } | |
| 115 | }, 30_000); | |
| 116 | afterAll(async () => { | |
| 117 | cloudNet.fetch = saved; | |
| 118 | app.close?.(); | |
| 119 | await rm(dir, { recursive: true, force: true }); | |
| 120 | }); | |
| 121 | ||
| 122 | test("a place the forge has not read is not planned", () => { | |
| 123 | expect(planMinecraft(app, alice(), { ...input, where: "digitalocean/main@digitalocean:nyc3:nope" })).toEqual({ ok: false, error: "Pick where the server runs." }); | |
| 124 | }); | |
| 125 | ||
| 126 | test("a kept place plans both wants through the plan, with the compose file and what is left to do", () => { | |
| 127 | const made = planMinecraft(app, alice(), { ...input, where }); | |
| 128 | if (!made.ok) throw new Error(made.error); | |
| 129 | const p = made.value.planned.plan; | |
| 130 | expect(p.refusals).toEqual([]); | |
| 131 | expect(p.wants.map((w) => w.kind)).toEqual(["machine", "dns"]); | |
| 132 | expect(p.steps.map((x) => x.kind)).toContain("record"); | |
| 133 | expect(p.steps.some((x) => x.kind === "machine" && x.says.includes("game box"))).toBe(true); | |
| 134 | expect(made.value.compose).toContain('MAX_PLAYERS: "10"'); | |
| 135 | expect(made.value.address).toBe("play.example.com"); | |
| 136 | expect(made.value.note).toContain("alice/mc"); | |
| 137 | expect(made.value.note).toContain("play.example.com"); | |
| 138 | }); | |
| 139 | ||
| 140 | test("a person who is not an admin gets the plan's own refusal", () => { | |
| 141 | expect(planMinecraft(app, getUserByName(app.db, "bob")!, { ...input, where })).toEqual({ ok: false, error: "not_found" }); | |
| 142 | }); | |
| 143 | ||
| 144 | test("the infra tool plans a full want, with the compose file and steps, and says what is missing", async () => { | |
| 145 | const said = (await tool.run(ctxOf(alice()), alice(), { action: "plan", want: { design: "minecraft", players: 10, eula: true } })) as any; | |
| 146 | expect(said).toMatchObject({ ok: false, error: "incomplete" }); | |
| 147 | const made = (await tool.run(ctxOf(alice()), alice(), { action: "plan", want: full })) as any; | |
| 148 | expect(made.ok).toBe(true); | |
| 149 | expect(made.value.compose).toContain("itzg/minecraft-server:"); | |
| 150 | expect(made.value.steps.length).toBeGreaterThanOrEqual(2); | |
| 151 | expect(made.value.refusals).toEqual([]); | |
| 152 | expect(made.value.note).toContain("play.example.com"); | |
| 153 | }); | |
| 154 | ||
| 155 | test("the terminal's M asks the name, plans, and shows the compose file", async () => { | |
| 156 | const { app: tui, session, terminal } = (() => { | |
| 157 | const terminal = headlessTerminal(140, 40); | |
| 158 | return { terminal, ...createForgeApp(app, { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: alice() }, { terminal, exitHooks: false }) }; | |
| 159 | })(); | |
| 160 | tui.start(); | |
| 161 | tui.ctx.push(infraScreen(session, tui.ctx)); | |
| 162 | await settleApp(tui); | |
| 163 | const feed = async (text: string): Promise<void> => { | |
| 164 | for (const k of text) { | |
| 165 | terminal.feed(k); | |
| 166 | await settleApp(tui); | |
| 167 | } | |
| 168 | }; | |
| 169 | await feed("M"); | |
| 170 | expect(tui.screen.toText()).toContain("Name"); | |
| 171 | await feed("mc2\r"); | |
| 172 | expect(tui.screen.toText()).toContain("Players"); | |
| 173 | await feed("10\r"); | |
| 174 | expect(tui.screen.toText()).toContain("Where"); | |
| 175 | terminal.feed("\r"); | |
| 176 | await settleApp(tui); | |
| 177 | await feed("example.com\r"); | |
| 178 | await feed("alice/mc\r"); | |
| 179 | expect(tui.screen.toText()).toContain("EULA"); | |
| 180 | terminal.feed("\r"); | |
| 181 | await settleApp(tui); | |
| 182 | const text = tui.screen.toText(); | |
| 183 | expect(text).toContain("The plan"); | |
| 184 | expect(text).toContain("itzg/minecraft-server:"); | |
| 185 | expect(text).toContain("play.example.com"); | |
| 186 | tui.stop?.(); | |
| 187 | }); | |
| 188 | ||
| 189 | test("with no Cloudflare account that writes, the terminal says why it cannot start", async () => { | |
| 190 | allowWrite(app, alice(), "cloudflare", "main", false); | |
| 191 | const { app: tui, session } = createForgeApp(app, { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: alice() }, { terminal: headlessTerminal(200, 24), exitHooks: false }); | |
| 192 | tui.start(); | |
| 193 | tui.ctx.push(infraScreen(session, tui.ctx)); | |
| 194 | await settleApp(tui); | |
| 195 | tui.dispatch({ type: "key", key: "M", ctrl: false, alt: false, shift: false }); | |
| 196 | await settleApp(tui); | |
| 197 | expect(tui.screen.toText()).toContain("No Cloudflare account allows writes"); | |
| 198 | tui.stop?.(); | |
| 199 | allowWrite(app, alice(), "cloudflare", "main", true); | |
| 200 | }); | |
| 201 | }); |
new above
offline