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

Minecraft is a kind: one kind interface, with the compose design and the console adapter behind it in one directory #18468

opened this

Merged 4h 1m ago, live in production

mason/forge:mason/18455-minecraft-is-a-kind-one-kind-interface-w → main 0 commits fork

  • Merged. mason/18455-minecraft-is-a-kind-one-kind-interface-w was merged into main as 9745f39.

Review

Sign in to review this change.
13 files changed +190 −58
docs/features/infra.md +1 −1
@@ -86,7 +86,7 @@ Terminal: the **Buckets** palette entry (`src/tui/screens/buckets.ts`): `p` read
8686
8787 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.
8888
89 - **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.
89 - **Sized by players** (`src/kinds/minecraft/compose.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.
9090 - **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.
9191 - **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.
9292 - **The EULA** is accepted by the person (`eula: true`, or the terminal's confirm), never for them.
src/actions/minecraft.ts +4 −3
@@ -8,7 +8,8 @@ import type { App } from "../app.ts";
88 import { keptPlaces } from "../cloud/places_read.ts";
99 import { keptRate } from "../cloud/rates.ts";
1010 import type { User } from "../core/users.ts";
11 import { minecraftDesign, type MinecraftInput } from "../games/minecraft.ts";
11 import { defaultKind } from "../kinds/index.ts";
12 import type { DesignInput } from "../kinds/kind.ts";
1213 import { err, ok, type Result } from "../kernel/result.ts";
1314 import { planWants, type Planned } from "./infra.ts";
1415
@@ -22,11 +23,11 @@ export interface MinecraftPlanned {
2223 }
2324
2425 /** Plan Minecraft for `i`; nothing is made. Admins only, as every infra plan is. */
25 export async function planMinecraft(app: App, actor: User | undefined, i: MinecraftInput): Promise<Result<MinecraftPlanned, string>> {
26 export async function planMinecraft(app: App, actor: User | undefined, i: DesignInput): Promise<Result<MinecraftPlanned, string>> {
2627 const placeId = i.where.split("@")[1] ?? "";
2728 const place = keptPlaces(app.db, keptRate(app.db, "EUR")).find((p) => p.id === placeId);
2829 if (place === undefined) return err("Pick where the server runs.");
29 const design = minecraftDesign(i, place);
30 const design = defaultKind().compose.design(i, place);
3031 if (!design.ok) return design;
3132 const planned = await planWants(app, actor, [design.value.machine, design.value.srv]);
3233 if (!planned.ok) return planned;
src/kinds/index.ts added +18
@@ -0,0 +1,18 @@
1 /** The kinds the forge knows, found by name. The only door the general layer uses to reach one. */
2
3 import type { Kind } from "./kind.ts";
4 import { minecraft } from "./minecraft/index.ts";
5
6 const KINDS: readonly Kind[] = [minecraft];
7
8 /** The kind called `name`, or undefined. */
9 export function kindNamed(name: string): Kind | undefined {
10 return KINDS.find((k) => k.name === name);
11 }
12
13 /**
14 * The kind a games page speaks of today: every game box is Minecraft until a second kind exists.
15 */
16 export function defaultKind(): Kind {
17 return kindNamed("minecraft") ?? minecraft;
18 }
src/kinds/kind.ts added +85
@@ -0,0 +1,85 @@
1 /**
2 * A kind of game the forge hosts (P16, #334): one interface with five parts, and a kind is a value
3 * of it, found by its name. The general layer asks for a kind and calls its parts; it never imports
4 * a kind's directory, so what is specific to one game (Minecraft's compose design, its console,
5 * RCON) stays in `src/kinds/<name>/`.
6 *
7 * The compose design and the console adapter live behind it. The people adapter, identity prover
8 * and metrics probe are declared here and still stubbed by each kind: the code behind them is in
9 * `src/games` until the next move.
10 */
11
12 import type { App } from "../app.ts";
13 import type { DnsWant, MachineWant } from "../cloud/plan.ts";
14 import type { Result } from "../kernel/result.ts";
15
16 /** What a person types to design a box of this kind, whichever door it came through. */
17 export interface DesignInput {
18 readonly name: string;
19 readonly players: string;
20 /** `account@placeId`. */
21 readonly where: string;
22 readonly domain: string;
23 /** The DNS account that writes the server's records, `cloudflare/<name>`. */
24 readonly dns: string;
25 /** The repository (`owner/name`) whose compose file the box runs. */
26 readonly repo: string;
27 /** The game's licence, accepted by the person, never for them. */
28 readonly eula: boolean;
29 readonly version?: string;
30 }
31
32 /** A design: the compose file to commit and the wants that make the box and its address. */
33 export interface Design {
34 readonly compose: string;
35 readonly address: string;
36 readonly players: number;
37 readonly machine: MachineWant;
38 readonly srv: DnsWant;
39 }
40
41 /** Part 1: how a box of this kind is composed and sized. Pure. */
42 export interface ComposeDesign {
43 /** The design for `input` at a place with `memoryMiB` and a provider `size`, or what is wrong. */
44 design(input: DesignInput, place: { readonly memoryMiB: number; readonly size: string }): Result<Design, string>;
45 }
46
47 /** A crash in a server's log: one line that says what happened, and the lines it came from. */
48 export interface Crash {
49 readonly summary: string;
50 readonly lines: readonly string[];
51 }
52
53 /** Part 2: the console as the game writes it. */
54 export interface ConsoleAdapter {
55 /** Console lines as escaped markup, each in its own colours. */
56 html(lines: readonly string[]): string[];
57 /** Console lines as plain text. */
58 text(lines: readonly string[]): string[];
59 /** The last crash in the lines, unless the server started fine after it. */
60 crash(lines: readonly string[]): Crash | undefined;
61 /** Publish a crash's text where anyone with the link can read it, at the person's own click. */
62 share(app: App, text: string): Promise<{ ok: true; id: string } | { ok: false; error: string }>;
63 }
64
65 /** A part not moved yet: it names where its code still lives. */
66 export interface Stub {
67 readonly stub: true;
68 readonly livesIn: string;
69 }
70
71 /** Part 3: who is on a server, and who may be (whitelist, ops). */
72 export type PeopleAdapter = Stub;
73 /** Part 4: proof that a person owns a name in the game. */
74 export type IdentityProver = Stub;
75 /** Part 5: what a running server reports about itself. */
76 export type MetricsProbe = Stub;
77
78 export interface Kind {
79 readonly name: string;
80 readonly compose: ComposeDesign;
81 readonly console: ConsoleAdapter;
82 readonly people: PeopleAdapter;
83 readonly identity: IdentityProver;
84 readonly metrics: MetricsProbe;
85 }
src/games/minecraft.ts → src/kinds/minecraft/compose.ts renamed +5 −33
@@ -5,34 +5,14 @@
55 * plan, the build and the box are the ones every game box already has (`actions/minecraft.ts`).
66 */
77
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";
8 import { dnsWantOf, type MachineWant } from "../../cloud/plan.ts";
9 import { err, ok, type Result } from "../../kernel/result.ts";
10 import { BOX_NAME } from "../../games/store.ts";
11 import type { Design, DesignInput } from "../kind.ts";
1112
1213 export const MINECRAFT_PORT = 25565;
1314 export const MAX_PLAYERS = 150;
1415
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
3616 /** The itzg image, pinned: a restart of the box never pulls a new one under the world. */
3717 const IMAGE = "itzg/minecraft-server:2025.4.0";
3818 /** The release a server runs when the person names none. */
@@ -77,20 +57,12 @@ export function minecraftCompose(players: number, version: string = DEFAULT_VERS
7757 ].join("\n");
7858 }
7959
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
8860 /**
8961 * The design for `i` at a place with `memoryMiB` of memory and a `size` (its provider's shape
9062 * name), or the one thing still wrong in a sentence. A place too small for the players, or not x86,
9163 * is refused here, not at the provider.
9264 */
93 export function minecraftDesign(i: MinecraftInput, place: { readonly memoryMiB: number; readonly size: string }): Result<MinecraftDesign, string> {
65 export function minecraftDesign(i: DesignInput, place: { readonly memoryMiB: number; readonly size: string }): Result<Design, string> {
9466 if (!i.eula) return err("Minecraft's EULA (https://aka.ms/MinecraftEULA) must be accepted by you: say eula is true.");
9567 if (!BOX_NAME.test(i.name)) return err("A name is lowercase letters, digits and dashes, starting with a letter.");
9668 const players = /^\d{1,3}$/.test(i.players.trim()) ? Number(i.players.trim()) : 0;
src/games/console.ts → src/kinds/minecraft/console.ts renamed +5 −11
@@ -11,10 +11,11 @@
1111 * runs into the next line.
1212 */
1313
14 import type { App } from "../app.ts";
15 import { announcedOr } from "../kernel/version.ts";
16 import { readCapped } from "../spawn/bounded_read.ts";
17 import { ansiLines } from "../web/render/ansi.ts";
14 import type { App } from "../../app.ts";
15 import { announcedOr } from "../../kernel/version.ts";
16 import { readCapped } from "../../spawn/bounded_read.ts";
17 import type { Crash } from "../kind.ts";
18 import { ansiLines } from "../../web/render/ansi.ts";
1819
1920 /** § code → SGR: Minecraft's sixteen colours onto the renderer's eight, bold, underline, reset. */
2021 const SECTION: Readonly<Record<string, string>> = {
@@ -60,13 +61,6 @@ export function consoleText(lines: readonly string[]): string[] {
6061
6162 // ---- crashes ----
6263
63 /** A crash in a server's log: one line that says what happened, and the lines it came from. */
64 export interface Crash {
65 readonly summary: string;
66 /** The crash's lines, from where it starts, at most 120. */
67 readonly lines: readonly string[];
68 }
69
7064 const START = [
7165 /---- Minecraft Crash Report ----/,
7266 /Encountered an unexpected exception/,
src/kinds/minecraft/index.ts added +17
@@ -0,0 +1,17 @@
1 /**
2 * The Minecraft kind: its compose design and console here; people, identity and metrics still in
3 * `src/games`.
4 */
5
6 import type { Kind } from "../kind.ts";
7 import { consoleHtml, consoleText, crashOf, shareOnMclogs } from "./console.ts";
8 import { minecraftDesign } from "./compose.ts";
9
10 export const minecraft: Kind = {
11 name: "minecraft",
12 compose: { design: minecraftDesign },
13 console: { html: consoleHtml, text: consoleText, crash: crashOf, share: shareOnMclogs },
14 people: { stub: true, livesIn: "src/games/people.ts" },
15 identity: { stub: true, livesIn: "src/core/proven_identities.ts" },
16 metrics: { stub: true, livesIn: "src/games/metrics.ts" },
17 };
src/logs/game.ts +3 −3
@@ -1,7 +1,7 @@
11 /** A game service's kept log, masked here and nowhere else (`redactHeld`), for every reader. */
22
33 import type { Database } from "bun:sqlite";
4 import { consoleText, crashOf } from "../games/console.ts";
4 import { defaultKind } from "../kinds/index.ts";
55 import { LOG_KEEP, servicesOf } from "../games/store.ts";
66 import { redactHeld } from "../kernel/log.ts";
77 import type { LogAge, LogLine, LogPage } from "./page.ts";
@@ -22,7 +22,7 @@ export function gameLogAfter(db: Database, boxId: string, service: string, after
2222 export function gameLogPage(db: Database, boxId: string, service: string): LogPage {
2323 const { lines } = gameLogAfter(db, boxId, service, 0);
2424 const texts = lines.map((l) => l.text);
25 const crash = crashOf(texts);
25 const crash = defaultKind().console.crash(texts);
2626 const at = crash === undefined ? -1 : texts.lastIndexOf(crash.lines[0]!);
2727 return {
2828 lines,
@@ -65,4 +65,4 @@ export function withAnswerLines(page: LogPage, answers: readonly { readonly afte
6565 }
6666
6767 /** A line as a person reads it, its colour codes gone: what is searched and copied. */
68 export const plainLine = (text: string): string => consoleText([text])[0]!;
68 export const plainLine = (text: string): string => defaultKind().console.text([text])[0]!;
src/web/log_reader.ts +3 −3
@@ -3,7 +3,7 @@
33 * and masks every line; the script only adds the ones that come, so with no script a reload does it.
44 */
55
6 import { consoleHtml } from "../games/console.ts";
6 import { defaultKind } from "../kinds/index.ts";
77 import { plainLine } from "../logs/game.ts";
88 import { ageWords, markLog, matchesLog, type LogAge, type LogLine, type LogPage } from "../logs/page.ts";
99 import { html, raw, type Html } from "./html.ts";
@@ -51,7 +51,7 @@ export function logRows(v: LogView, lines: readonly LogLine[]): { id: number; ht
5151 ? html`${l.text}`
5252 : finding
5353 ? html`${markLog(plainLine(l.text), v.q).map((p) => (p.hit ? html`<mark>${p.text}</mark>` : html`${p.text}`))}`
54 : raw(consoleHtml([l.text])[0]!);
54 : raw(defaultKind().console.html([l.text])[0]!);
5555 const id = String(l.id);
5656 return { id: l.id, html: html`<span class="log-row" id="l${id}"><a class="log-at" href="${hrefOf(v, { at: l.id })}" aria-label="This line in its place"${finding ? null : raw(' tabindex="-1"')}></a>${text}
5757 </span>`.toString() };
@@ -89,7 +89,7 @@ export function logReader(asked: LogView, page: LogPage, age: LogAge, o: { strea
8989 ? null
9090 : html`<div class="notice danger" role="alert">
9191 <p><strong>${f.says}</strong>${f.line === null ? null : html` <a href="${hrefOf(v, { at: f.line })}">Show it in the log</a>`}</p>
92 ${disclosure("The crash", html`<pre class="run-log mono" tabindex="0" aria-label="The crash of ${v.name}">${raw(consoleHtml(f.detail).join("\n"))}</pre>`, { small: true })}
92 ${disclosure("The crash", html`<pre class="run-log mono" tabindex="0" aria-label="The crash of ${v.name}">${raw(defaultKind().console.html(f.detail).join("\n"))}</pre>`, { small: true })}
9393 ${o.findingExtra ?? null}
9494 </div>`}
9595 <form method="get" action="${v.base}#console" class="row-fields" role="search">
src/web/pages/games.ts +2 −2
@@ -72,7 +72,7 @@ import { mapPathOf, mapWords } from "../../games/map_words.ts";
7272 import { notFoundPage, pageHead, signInFirst } from "../chrome.ts";
7373 import { field, readForm, type Form } from "../form.ts";
7474 import { html, type Html } from "../html.ts";
75 import { consoleText, shareOnMclogs } from "../../games/console.ts";
75 import { defaultKind } from "../../kinds/index.ts";
7676 import { answerAfter, gameLogAfter, gameLogAge, gameLogPage } from "../../logs/game.ts";
7777 import { ageWords } from "../../logs/page.ts";
7878 import { LOG_GONE, logReader, LOG_READER_CSS, logReaderJs, logRows, logViewOf, placesAnswers } from "../log_reader.ts";
@@ -1110,7 +1110,7 @@ export async function gameCrashShare(ctx: Ctx): Promise<Response> {
11101110 const back = `/games/${got.box.name}/${got.service}`;
11111111 const crash = gameLogPage(ctx.app.db, got.box.id, got.service).finding;
11121112 if (crash === undefined) return flashTo(ctx, back, { tone: "danger", message: "There is no crash in the log to share." });
1113 const shared = await shareOnMclogs(ctx.app, consoleText(crash.detail).join("\n"));
1113 const shared = await defaultKind().console.share(ctx.app, defaultKind().console.text(crash.detail).join("\n"));
11141114 if (!shared.ok) return flashTo(ctx, back, { tone: "danger", message: shared.error });
11151115 return flashTo(ctx, `${back}?shared=${shared.id}`, { message: `Shared publicly on mclo.gs: https://mclo.gs/${shared.id}` });
11161116 }
test/game-console-colour.test.ts +1 −1
@@ -14,7 +14,7 @@ import { createUser, getUserByName } from "../src/core/users.ts";
1414 import { boxNamed, createGameBox, queueCommand, recordSync } from "../src/games/store.ts";
1515 import { sgrToSection } from "../src/http/parseable_request.ts";
1616 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
17 import { consoleHtml, consoleText, crashOf, sectionToSgr } from "../src/games/console.ts";
17 import { consoleHtml, consoleText, crashOf, sectionToSgr } from "../src/kinds/minecraft/console.ts";
1818
1919 test("a colour escape becomes its § code before the escapes are stripped; resets at either end go", () => {
2020 expect(sgrToSection("\u001b[0;39m[12:00] \u001b[1;91mFAIL\u001b[0m \u001b[38;5;10mok\u001b[0m \u001b[48;5;1mbg\u001b[0m")).toBe("[12:00] \u00a7l\u00a7cFAIL\u00a7r \u00a7aok\u00a7r bg");
test/kinds.test.ts added +44
@@ -0,0 +1,44 @@
1 /**
2 * The kind interface (#18455): a kind is found by name, and the compose design and console go
3 * through it.
4 */
5
6 import { expect, test } from "bun:test";
7 import { readdirSync, readFileSync } from "node:fs";
8 import { defaultKind, kindNamed } from "../src/kinds/index.ts";
9
10 test("a kind is looked up by its name; an unknown name has none", () => {
11 expect(kindNamed("minecraft")?.name).toBe("minecraft");
12 expect(kindNamed("nope")).toBeUndefined();
13 expect(defaultKind()).toBe(kindNamed("minecraft")!);
14 });
15
16 test("a kind has all five parts, the unmoved three declared as stubs", () => {
17 const k = kindNamed("minecraft")!;
18 expect(typeof k.compose.design).toBe("function");
19 expect(typeof k.console.html).toBe("function");
20 for (const part of [k.people, k.identity, k.metrics]) expect(part.stub).toBe(true);
21 });
22
23 test("the compose design goes through the kind", () => {
24 const k = kindNamed("minecraft")!;
25 const input = { name: "hub", players: "10", where: "main@fsn1", domain: "example.com", dns: "cloudflare/main", repo: "alice/mc", eula: true };
26 const done = k.compose.design(input, { memoryMiB: 8192, size: "cx32" });
27 expect(done.ok && done.value.address).toBe("play.example.com");
28 expect(k.compose.design({ ...input, eula: false }, { memoryMiB: 8192, size: "cx32" }).ok).toBe(false);
29 });
30
31 test("the console goes through the kind", () => {
32 const c = kindNamed("minecraft")!.console;
33 expect(c.text(["§aHello §lworld"])).toEqual(["Hello world"]);
34 expect(c.html(["§cred"])[0]).toContain("red");
35 expect(c.crash(["---- Minecraft Crash Report ----", "Description: boom"])?.summary).toContain("Crashed:");
36 });
37
38 test("the general layer reaches the Minecraft kind only through src/kinds/index.ts", () => {
39 const walk = (d: string): string[] =>
40 readdirSync(d, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(`${d}/${e.name}`) : e.name.endsWith(".ts") ? [`${d}/${e.name}`] : []));
41 const root = new URL("../src", import.meta.url).pathname;
42 const reaching = walk(root).filter((f) => !f.startsWith(`${root}/kinds/`) && /kinds\/minecraft\//.test(readFileSync(f, "utf8")));
43 expect(reaching).toEqual([]);
44 });
test/minecraft-design.test.ts +2 −1
@@ -16,7 +16,8 @@ import { headlessTerminal } from "../src/tui/term/terminal.ts";
1616 import type { Ctx } from "../src/http/context.ts";
1717 import { tool } from "../src/http/mcp/tools/infra.ts";
1818 import { createUser, getUserByName } from "../src/core/users.ts";
19 import { heapGiB, minecraftCompose, minecraftDesign, needMiB, type MinecraftInput } from "../src/games/minecraft.ts";
19 import { heapGiB, minecraftCompose, minecraftDesign, needMiB } from "../src/kinds/minecraft/compose.ts";
20 import type { DesignInput as MinecraftInput } from "../src/kinds/kind.ts";
2021 import { seedPlaces } from "./helpers/places-fixture.ts";
2122 import { settleApp } from "./helpers/tui.ts";
2223 import { quietLogs } from "./helpers/globals.ts";

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

Keyboard shortcuts

Docs