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

The general layer names no game: people, identity and metrics move behind the kind, and a test greps for it #18482

opened this

Its check is red, 22m ago

check failed: 4 of 2419 tests — "a Worker opens a database once per file and keeps it > every Worker under src/ that opens a database is listed with how it keeps the handle, and every open a Worker imports with wh…

mason/forge:mason/18456-the-general-layer-names-no-game-people-i → main 10 commits fork

Review

Sign in to review this change.
73 files changed +492 −308
docs/features/game-box.md +1 −1
@@ -45,7 +45,7 @@ Code: `src/games/store.ts` (the `game_box` row and its token, the games store's)
4545 - **The box's side of it (#17578):** the sync answers `lend: { token }` once to a box that says `lend: "none"` while the switch is on (a forge restarted before the token was sent, or a reply lost, revokes that runner and enrols a new one: the box is never left without), and `lend: { off: true }` to one that still says `"have"` after the switch went off. The agent keeps the token in `/opt/forge-game/.runner.auth` (mode 600, beside `.auth`), and each tick claims one job (`wait: 0`) when it is safe: no container started in the last 90 s (`FORGE_GAME_LEND_QUIET`), no compose job running, `MemAvailable` at least 768 MiB (`FORGE_GAME_LEND_FLOOR_MIB`), and `bubblewrap` and `git` installed (new boxes install them; an older box runs nothing until they are there). A box that holds a runner token and lacks either says so with each check-in (`lendWhy`: one of three fixed phrases, `src/games/lend_why.ts`), and both doors show it while the switch is on: `cannot lend: bubblewrap is not installed` (or `git`, or both) under the switch on `/games/<box>` and in the terminal's box screen, and on that runner's row in Settings → Runners and the terminal's runners screen. It clears with the next check-in once the tool is installed. A new box's boot installs both (`src/games/boot.ts`).
4646 - **The cell:** the agent itself only claims, fetches the commit over the job's own git door as the unprivileged user `forge-job`, and answers. Each step is its own systemd unit (`forge-job-<id>`: `MemoryMax` the job's declared memory, no swap, `CPUQuota` its cpus, 512 tasks, `timeout` its seconds) as that user, in bubblewrap with `--unshare-all`, `/usr` read-only, the checkout at `/work`, a tmpfs `/tmp` and a cleared environment (`CI` and `FORGE_*` of the job only). It sees no `/run` (the Docker socket), no `/opt/forge-game` (`agent.env`, `.auth`, `.runner.auth`, compose), no data volume. The check step has no network at all. The install step shares the network, but an iptables rule on `forge-job`'s traffic rejects every private, loopback, link-local (the cloud's metadata door) and shared-range address, so the game network is not a route (the box's own addresses too, v4 and v6; a host with IPv6 and no `ip6tables` hands the install step back). A step's output is written inside that same tmpfs and no write takes it past 1 MiB (`FORGE_GAME_LEND_OUT_KIB`): the step is killed by SIGXFSZ, and the last 64 KiB is what is read. The disk cap is the checkout's own tmpfs (the job's `diskMiB`, at most 4 GiB, which is also charged to the job's memory cap). A job that names `egress` hosts, declares no memory, or whose step is missing a tool on the box (exit 126 or 127) is handed back (`abandon`): the forge runs it, and it is never red for the box's lack; after a missing tool the box claims nothing for 10 minutes. `/opt/forge-job-tools` is mounted read-only at `/opt/tools` (on `PATH`) when it exists: the toolchain a repository's check needs (bun, say) is put there by the box's owner.
4747 - **A join:** `docker events` (a container starting) is read by the agent, and in that reader: claiming stops (`.wake`), every `forge-job-*` cgroup is frozen at once (`cgroup.freeze`), and nothing waits on the job. While a step runs, a guard looks twice a second: still frozen and `MemAvailable` under the floor, or frozen for 5 minutes (`FORGE_GAME_LEND_FROZEN_S`), and the job is killed (`cgroup.kill`, then the unit stopped) and answered `interrupted`; a quiet box (90 s, memory above the floor) thaws it. `interrupted` puts the job back in the queue with no result: it is never red, and its claim is not counted, so it is never a try of that check's `MAX_CLAIMS` (the check's log says "stopped the job … not a try, nor a result"). The guard also renews the lease every 10 s, frozen or not.
48 - **Not done, and not proved yet:** nothing here has run on a real box (it waits for the owner's go): tps and mspt of an awake server with and without a job, and the wake time on a join with one running, are still to be measured from `src/games/metrics.ts`'s samples. The cell was checked against stand-ins (`test/game-lend-box.test.ts`), not against a real kernel's bubblewrap.
48 - **Not done, and not proved yet:** nothing here has run on a real box (it waits for the owner's go): tps and mspt of an awake server with and without a job, and the wake time on a join with one running, are still to be measured from `src/kinds/minecraft/metrics.ts`'s samples. The cell was checked against stand-ins (`test/game-lend-box.test.ts`), not against a real kernel's bubblewrap.
4949 - **What an eviction keeps (#17579):** a stopped check loses at most the shard that was running. The agent reads the check's output for the shards that ended green (`── shard N/M done (exit 0`) and sends their test files with `interrupted` (`kept`). The forge puts them on the job's own env as `FORGE_CHECK_DONE` (a bounded set; a second stop adds to it), the job is queued again, and `scripts/test-shards.ts` leaves those files out of the next run ("FORGE_CHECK_DONE keeps N finished file(s)"). A frozen job that is not stopped needs none of this: it thaws when the box is quiet again within `FORGE_GAME_LEND_FROZEN_S` (300 s), else it is stopped and queued as interrupted.
5050
5151 ## Key exchange (#18032)
docs/features/game-spark.md +3 −3
@@ -6,7 +6,7 @@ row: Game spark profiles
66
77 A box stores the profiles its servers' spark plugin posts, so a lag report is read from the forge, not a public paste. The box's owner makes an upload address on `/games/<box>` (Profiles, "Make an upload address"; `p` on the terminal's box screen opens `src/tui/screens/game_spark.ts`, where `u`), shown once: `<forge>/games/@spark/<secret>/`. Set it as spark's `bytebin-url`. spark posts `<address>post` (a gzipped protobuf, `Content-Type: application/x-spark-*`) and is answered `201` with `Location: <key>` and no body; a wrong secret is a `403`, a body past 8 MiB a `413`, anything not gzip or not a spark type a `400`. The secret only allows writes and only its hash is kept; a new address ends the old.
88
9 `GET <address><key>` returns the bytes and type to a forge session with any grant on the box (forge admins too), and `403` to anyone else; no grant table is new. The box's page and the terminal's box screen list what is stored (newest 50, type, time, size); the page's link opens one without the secret. A profile is kept 14 days and a box keeps its newest 50 (`SPARK_KEEP_DAYS`, `SPARK_KEEP_COUNT`, `BODY_CAPS.gameSpark`, each with its reason). `/games/<box>/spark/<key>` (#18058) opens a stored sampler profile on the forge for the same grants, a hidden or missing one a `404`: per thread, in order of time, its time sampled, a flame graph (SVG drawn on the server, no script) and the call tree as text (at most 12 deep and 8 wide, the heaviest calls), names escaped, read by the one decoder `src/games/spark_profile.ts` (`decodeSparkProfile`) and drawn by `src/games/spark_view.ts`. It unpacks at most 8 MiB, builds at most a million fields and reads at most 200 threads, so a hostile profile is refused ("download it"), not inflated. On the terminal, `p` on the box screen opens the profiles; `j`/`k` choose one and `enter` shows the same call tree as indented lines, for any grant. Any other kind, or a profile too large to read here, is kept and offered as a download. Nothing is fetched elsewhere. The gzip is checked by its magic bytes at upload only. Not done: spark's own viewer's other tabs (heap, slowest ticks per window) are not drawn. Code: `src/games/spark.ts`, `src/web/pages/games_spark.ts`.
9 `GET <address><key>` returns the bytes and type to a forge session with any grant on the box (forge admins too), and `403` to anyone else; no grant table is new. The box's page and the terminal's box screen list what is stored (newest 50, type, time, size); the page's link opens one without the secret. A profile is kept 14 days and a box keeps its newest 50 (`SPARK_KEEP_DAYS`, `SPARK_KEEP_COUNT`, `BODY_CAPS.gameSpark`, each with its reason). `/games/<box>/spark/<key>` (#18058) opens a stored sampler profile on the forge for the same grants, a hidden or missing one a `404`: per thread, in order of time, its time sampled, a flame graph (SVG drawn on the server, no script) and the call tree as text (at most 12 deep and 8 wide, the heaviest calls), names escaped, read by the one decoder `src/kinds/minecraft/spark_profile.ts` (`decodeSparkProfile`) and drawn by `src/kinds/minecraft/spark_view.ts`. It unpacks at most 8 MiB, builds at most a million fields and reads at most 200 threads, so a hostile profile is refused ("download it"), not inflated. On the terminal, `p` on the box screen opens the profiles; `j`/`k` choose one and `enter` shows the same call tree as indented lines, for any grant. Any other kind, or a profile too large to read here, is kept and offered as a download. Nothing is fetched elsewhere. The gzip is checked by its magic bytes at upload only. Not done: spark's own viewer's other tabs (heap, slowest ticks per window) are not drawn. Code: `src/kinds/minecraft/spark.ts`, `src/web/pages/games_spark.ts`.
1010
1111 ## Installed with the mod (#18138)
1212
@@ -14,8 +14,8 @@ Installing spark (`mods_install spark`, or as a plugin of a new server) writes s
1414
1515 ## The call tree and flame graph (#18208)
1616
17 A listed profile opens `/games/<box>/spark/<key>` (the bytes stay at `/games/<box>/@spark/<key>`): `decodeSparkProfile` reads it per request, and each thread shows its time sampled (milliseconds), a flame graph (an SVG drawn on the server, no script; a box is as wide as its share of the thread, the call and time in its tooltip) and the call tree as text with shares. The terminal shows the same lines: on a box's Profiles screen (`p`), `j`/`k` pick a profile and Enter opens `src/tui/screens/game_spark_view.ts`. Only the 10 heaviest threads are drawn, on both doors; the rest are named as "N more threads not drawn, download the profile". Only a grant on the box reads it; a body that is not a profile says why and links the download. The tree is the decoder's pruned one: 12 deep, 8 wide, at most 2,000 nodes a thread, from a body of at most 8 MiB (64 MiB unpacked). Under the threads, both doors show (#18140, `summarySections`) the slowest tick windows, time per mod, GC and memory, and the mods listed. Not done: a flame box is not zoomable. Code: `src/games/spark_view.ts` (layout), `src/web/pages/games_spark_view.ts`.
17 A listed profile opens `/games/<box>/spark/<key>` (the bytes stay at `/games/<box>/@spark/<key>`): `decodeSparkProfile` reads it per request, and each thread shows its time sampled (milliseconds), a flame graph (an SVG drawn on the server, no script; a box is as wide as its share of the thread, the call and time in its tooltip) and the call tree as text with shares. The terminal shows the same lines: on a box's Profiles screen (`p`), `j`/`k` pick a profile and Enter opens `src/tui/screens/game_spark_view.ts`. Only the 10 heaviest threads are drawn, on both doors; the rest are named as "N more threads not drawn, download the profile". Only a grant on the box reads it; a body that is not a profile says why and links the download. The tree is the decoder's pruned one: 12 deep, 8 wide, at most 2,000 nodes a thread, from a body of at most 8 MiB (64 MiB unpacked). Under the threads, both doors show (#18140, `summarySections`) the slowest tick windows, time per mod, GC and memory, and the mods listed. Not done: a flame box is not zoomable. Code: `src/kinds/minecraft/spark_view.ts` (layout), `src/web/pages/games_spark_view.ts`.
1818
1919 ## A finding links to its slow tick (#18213)
2020
21 When a box's newest sampler profile has a slowest tick over 50 ms (one tick's budget at 20 TPS), the Profiles block of `/games/<box>` says so in one line ("The server's slowest tick took 62.5 ms (it has 50). See that tick.") and links it to `/games/<box>/spark/<key>#tick-<window>`; the slowest-ticks row of that page has the matching `id="tick-<window>"`. The key is read from the box's own stored profiles, never from a request, so another box's profile is never linked; a box with no slow profile has no line. The terminal's Profiles screen (`p`) shows the same sentence, naming the profile key and the window in its Slowest ticks list. The Slowest ticks rows are titled by the profile's real window number ("Window 3"), no longer by rank ("Window 1"); a window a crafted profile repeats keeps `tick-<window>` on its first row and gets `tick-<window>-2` on the next. Decoded once per profile per forge. Code: `src/games/spark_finding.ts`.
21 When a box's newest sampler profile has a slowest tick over 50 ms (one tick's budget at 20 TPS), the Profiles block of `/games/<box>` says so in one line ("The server's slowest tick took 62.5 ms (it has 50). See that tick.") and links it to `/games/<box>/spark/<key>#tick-<window>`; the slowest-ticks row of that page has the matching `id="tick-<window>"`. The key is read from the box's own stored profiles, never from a request, so another box's profile is never linked; a box with no slow profile has no line. The terminal's Profiles screen (`p`) shows the same sentence, naming the profile key and the window in its Slowest ticks list. The Slowest ticks rows are titled by the profile's real window number ("Window 3"), no longer by rank ("Window 1"); a window a crafted profile repeats keeps `tick-<window>` on its first row and gets `tick-<window>-2` on the next. Decoded once per profile per forge. Code: `src/kinds/minecraft/spark_finding.ts`.
docs/features/games.md +5 −5

Diff not shown — a line 2,916 characters wide (limit 2,000). +5 −5

View file
src/core/accounts.ts +1 −1
@@ -13,7 +13,7 @@
1313
1414 import type { Database } from "bun:sqlite";
1515 import { forgetListings } from "./listings.ts";
16 import { provenEmailAt } from "./proven_identities.ts";
16 import { provenEmailAt } from "./proven_email.ts";
1717
1818 export interface AccountRow {
1919 readonly id: string;
src/core/people_rows.ts +1 −1
@@ -7,7 +7,7 @@
77 */
88
99 import type { Database } from "bun:sqlite";
10 import { provenEmailAt } from "./proven_identities.ts";
10 import { provenEmailAt } from "./proven_email.ts";
1111
1212 export const WORDS = ["owner", "member", "guest", "crew member"] as const;
1313 export type RoleWord = (typeof WORDS)[number];
src/core/proven_email.ts added +12
@@ -0,0 +1,12 @@
1 /**
2 * When an account proved its own email, as SQL: a leaf module, so any reader can import it without
3 * a cycle.
4 */
5 /**
6 * SQL for when the account aliased `u` proved its own email, or NULL: its proven email connection
7 * for that address (`core/identities.ts`, #18222). Every reader of the proof asks this, so there is
8 * no second answer.
9 */
10 export const provenEmailAt = (u: string): string =>
11 `(SELECT k.proven_at FROM connection k WHERE k.user_id = ${u}.id AND k.kind = 'email'
12 AND k.ident = lower(${u}.email) AND k.proven_at IS NOT NULL)`;
src/core/proven_identities.ts +17 −83
@@ -10,16 +10,14 @@
1010 * Plain data in, plain data out; the codes and the network are the callers'.
1111 */
1212 import type { Database } from "bun:sqlite";
13 import { provenEmailAt } from "./proven_email.ts";
1314 import { linksOfKind } from "./account_link.ts";
1415
15 /**
16 * SQL for when the account aliased `u` proved its own email, or NULL: its proven email connection
17 * for that address (`core/identities.ts`, #18222). Every reader of the proof asks this, so there is
18 * no second answer.
19 */
20 export const provenEmailAt = (u: string): string =>
21 `(SELECT k.proven_at FROM connection k WHERE k.user_id = ${u}.id AND k.kind = 'email'
22 AND k.ident = lower(${u}.email) AND k.proven_at IS NOT NULL)`;
16 /** The name list of the kind the forge speaks of, read at call time, never at load. */
17 const prover = () =>
18 // Loaded on first use: the kind reaches the whole games layer, which reaches back into core,
19 // and a static import here makes that cycle run at load (a const read before it is set).
20 (require("../kinds/index.ts") as typeof import("../kinds/index.ts")).defaultKind().names;
2321
2422 export type IdentityKind = "email" | "minecraft";
2523
@@ -56,76 +54,21 @@ export function emailIdentity(db: Database, userId: string): Identity | undefine
5654 }
5755
5856 /**
59 * The account's Minecraft names, in one statement, oldest first. A name bound to no UUID is listed
60 * unproven: it must be linked again.
61 */
62 export const minecraftIdentities = (db: Database, userId: string): Identity[] =>
63 db
64 .query<
65 { boxId: string; box: string | null; player: string; uuid: string; createdAt: string },
66 [string]
67 >(
68 `SELECT l.box_id AS boxId, b.name AS box, l.player, l.uuid, l.created_at AS createdAt
69 FROM game_link l LEFT JOIN game_box b ON b.id = l.box_id
70 WHERE l.user_id = ?1 ORDER BY l.created_at`,
71 )
72 .all(userId)
73 .map(
74 (r): Identity => ({
75 kind: "minecraft",
76 name: r.player,
77 proven: r.uuid !== "",
78 since: r.createdAt,
79 boxId: r.boxId,
80 box: r.box,
81 uuid: r.uuid,
82 }),
83 );
84
85 /**
86 * Every account's Minecraft names (or one's, when `userId` is given), by user id: one read for a
87 * list.
88 */
89 export function minecraftByUser(db: Database, userId = ""): Map<string, Identity[]> {
90 const by = new Map<string, Identity[]>();
91 const rows = db
92 .query<{ userId: string; player: string; uuid: string; createdAt: string }, [string]>(
93 "SELECT user_id AS userId, player, uuid, created_at AS createdAt FROM game_link WHERE (?1 = '' OR user_id = ?1) ORDER BY created_at",
94 )
95 .all(userId);
96 for (const r of rows) by.set(r.userId, [...(by.get(r.userId) ?? []), { kind: "minecraft", name: r.player, proven: r.uuid !== "", since: r.createdAt }]);
97 return by;
98 }
99
100 /**
101 * Every identity of `userId` in one statement, email first then the Minecraft names oldest first,
102 * and whether the forge has a game box to link a name on; no identities for an account that does
103 * not exist. The same rows as `emailIdentity` and `minecraftIdentities`.
57 * Every identity of `userId`, email first then the game names each kind proves, and whether the
58 * forge has a game box to link a name on; no identities for an account that does not exist.
10459 */
10560 export function listOf(db: Database, userId: string): { identities: Identity[]; gameBox: boolean } {
106 const rows = db
107 .query<
108 { kind: IdentityKind; name: string; proven: number; since: string | null; boxId: string | null; box: string | null; uuid: string | null; gameBox: number },
109 [string]
110 >(
111 `SELECT 'email' AS kind, u.email AS name, (u.is_agent = 1 OR u.kind = 'org' OR ${provenEmailAt("u")} IS NOT NULL) AS proven,
112 ${provenEmailAt("u")} AS since, NULL AS boxId, NULL AS box, NULL AS uuid, EXISTS (SELECT 1 FROM game_box) AS gameBox, 0 AS ord
113 FROM user u WHERE u.id = ?1
114 UNION ALL
115 SELECT 'minecraft', l.player, l.uuid != '', l.created_at, l.box_id, b.name, l.uuid, 1, 1
116 FROM game_link l JOIN user u ON u.id = l.user_id LEFT JOIN game_box b ON b.id = l.box_id WHERE l.user_id = ?1
117 ORDER BY ord, since`,
118 )
119 .all(userId);
120 const identities = rows.map(
121 (r): Identity =>
122 r.kind === "email"
123 ? { kind: "email", name: r.name, proven: r.proven === 1, since: r.since }
124 : { kind: "minecraft", name: r.name, proven: r.proven === 1, since: r.since, boxId: r.boxId ?? "", box: r.box, uuid: r.uuid ?? "" },
125 );
126 return { identities, gameBox: rows.some((r) => r.gameBox === 1) };
61 const email = emailIdentity(db, userId);
62 if (email === undefined) return { identities: [], gameBox: false };
63 const p = prover();
64 return { identities: [email, ...p.identities(db, userId)], gameBox: p.hasBox(db) };
12765 }
12866
67 /**
68 * Every account's game names (or one's, when `userId` is given), by user id: one read for a list.
69 */
70 export const gameNamesByUser = (db: Database, userId = ""): Map<string, Identity[]> => prover().byUser(db, userId);
71
12972 /** Every identity of `userId`, email first; none for an account that does not exist. */
13073 export const identitiesOf = (db: Database, userId: string): Identity[] => listOf(db, userId).identities;
13174
@@ -174,12 +117,3 @@ export const identityJson = (i: Identity): Record<string, unknown> => ({
174117 /** One identity as a line, the same words at both doors. */
175118 export const identityLine = (i: Identity): string =>
176119 `${i.kind === "email" ? "Email" : "Minecraft"} ${i.name}: ${i.proven ? "proven" : "unproven"}${i.kind === "minecraft" ? ` on ${i.box ?? "a box"}` : ""}`;
177
178 /**
179 * The account a Minecraft name on a box is linked to, and the UUID it is bound to: the list read
180 * the other way.
181 */
182 export const minecraftOwner = (db: Database, boxId: string, player: string): { userId: string; uuid: string } | undefined =>
183 db
184 .query<{ userId: string; uuid: string }, [string, string]>("SELECT user_id AS userId, uuid FROM game_link WHERE box_id = ?1 AND player = ?2")
185 .get(boxId, player) ?? undefined;
src/core/roles.ts +1 −1
@@ -11,7 +11,7 @@
1111 import { storedText } from "../kernel/blocked.ts";
1212 import type { Database } from "bun:sqlite";
1313 import { isUnclaimed } from "./starts.ts";
14 import { provenEmailAt } from "./proven_identities.ts";
14 import { provenEmailAt } from "./proven_email.ts";
1515
1616 export const ROLES = ["guest", "member", "admin"] as const;
1717 export type Role = (typeof ROLES)[number];
src/core/verify.ts +2 −1
@@ -21,7 +21,8 @@
2121 import type { Database } from "bun:sqlite";
2222 import { sha256 } from "../kernel/hash.ts";
2323 import { id as newId } from "../kernel/id.ts";
24 import { provenAs, provenEmailAt } from "./proven_identities.ts";
24 import { provenEmailAt } from "./proven_email.ts";
25 import { provenAs } from "./proven_identities.ts";
2526
2627 /** How long a link works. */
2728 export const LINK_TTL_MS = 24 * 3_600_000;
src/games/agent.sh +5 −5
@@ -519,7 +519,7 @@ logs() {
519519 running() { capped 5 "${COMPOSE[@]}" ps --status running --format '{{.Service}}' 2>/dev/null | grep -vx 'forge-waker'; }
520520
521521 # Each running service's RCON answers to `list`, `tps` and `mspt` (Paper) and, when `tps` said nothing, `spark tps`, raw: the forge parses
522 # them (games/metrics.ts). A service without rcon-cli (the Velocity proxy) is asked once, then not.
522 # them (kinds/minecraft/metrics.ts). A service without rcon-cli (the Velocity proxy) is asked once, then not.
523523 NORCON=" "
524524 metrics() {
525525 local out='{}' name list tps mspt spark prom
@@ -529,7 +529,7 @@ metrics() {
529529 # The waker (sleep's socket proxy) has no sh and no rcon-cli: asking it fills Docker's journal with errors.
530530 [ "$name" = "$WAKER" ] && continue
531531 case "$NORCON" in *" $name "*) continue ;; esac
532 # `list uuids`: each name with its UUID, so the forge can show who it is (games/people.ts).
532 # `list uuids`: each name with its UUID, so the forge can show who it is (kinds/minecraft/people.ts).
533533 if ! list="$(capped 5 "${COMPOSE[@]}" exec -T "$name" rcon-cli -- list uuids 2>/dev/null)"; then
534534 NORCON="$NORCON$name "
535535 continue
@@ -538,7 +538,7 @@ metrics() {
538538 mspt="$(capped 5 "${COMPOSE[@]}" exec -T "$name" rcon-cli -- mspt 2>/dev/null || true)"
539539 # A Fabric server has neither command: FabricExporter's Prometheus page (127.0.0.1:25585, inside the
540540 # container only), cut to the tick and TPS lines, is read when `tps` said nothing. The grep is looser
541 # than `parsePrometheus` (src/games/metrics.ts), which alone decides what counts; extra lines are dropped there.
541 # than `parsePrometheus` (src/kinds/minecraft/metrics.ts), which alone decides what counts; extra lines are dropped there.
542542 # spark (a plugin or mod many servers run instead) answers `spark tps` with both; asked only when `tps` said nothing.
543543 spark=""
544544 if [[ "$tps" != *TPS* ]]; then
@@ -553,7 +553,7 @@ metrics() {
553553 echo "$out"
554554 }
555555
556 # ---- people (games/people.ts): every 60 s, or right after a people command, each game server's
556 # ---- people (kinds/minecraft/people.ts): every 60 s, or right after a people command, each game server's
557557 # whitelist, ops and bans (its own JSON files, read where the server keeps them) and the proxy's
558558 # glist all (who is on which server), from Velocircon, its RCON console. ----
559559 PEOPLE_EVERY="${FORGE_GAME_PEOPLE_EVERY:-60}"
@@ -761,7 +761,7 @@ run() {
761761 queue_job "$id" "recreate $service" "" up -d --force-recreate "$service"
762762 return
763763 ;;
764 # A player's place on a server (games/people.ts): the server's own commands through its RCON,
764 # A player's place on a server (kinds/minecraft/people.ts): the server's own commands through its RCON,
765765 # or the proxy's `send` to move them. The next sync reads the lists again.
766766 people)
767767 local op player server
src/games/ask.ts +2 −2
@@ -10,8 +10,8 @@
1010 import type { App } from "../app.ts";
1111 import type { User } from "../core/users.ts";
1212 import { composeServices, serviceEnv } from "./compose.ts";
13 import { peopleOf } from "./people.ts";
14 import { needLines, whyLines } from "./player_events.ts";
13 import { peopleOf } from "../kinds/minecraft/people.ts";
14 import { needLines, whyLines } from "../kinds/minecraft/player_events.ts";
1515 import { forcedHosts } from "./presets.ts";
1616 import { proxyOf, proxyPort } from "./sleep.ts";
1717 import { mayDo, roleOn, servicesOf, type GameBox } from "./store.ts";
src/games/chat.ts +3 −3
@@ -30,7 +30,7 @@ import { listTurns } from "../core/conversations.ts";
3030 import { proveMinecraft, unproveMinecraft } from "../core/identities.ts";
3131 import { readReceipt } from "../crew/receipt.ts";
3232 import { publicOrigin } from "../core/public_origin.ts";
33 import { minecraftIdentities, minecraftOwner } from "../core/proven_identities.ts";
33 import { minecraftIdentities, minecraftOwner } from "../kinds/minecraft/identity.ts";
3434 import { getUserById, isActive, type User } from "../core/users.ts";
3535 import { blockedBy, blockedText } from "../kernel/blocked.ts";
3636 import { sha256 } from "../kernel/hash.ts";
@@ -42,8 +42,8 @@ import { doorOf, lockDoor, windowUsed } from "./write_window.ts";
4242 import { defaultKind } from "../kinds/index.ts";
4343 import { readLines, readOf } from "./forge_read.ts";
4444 import { commitServer, planServer, wishOn } from "./presets.ts";
45 import { peopleOf } from "./people.ts";
46 import { checksAccounts, OFFLINE_WORDS } from "./reach.ts";
45 import { peopleOf } from "../kinds/minecraft/people.ts";
46 import { checksAccounts, OFFLINE_WORDS } from "../kinds/minecraft/reach.ts";
4747 import { proxyOf } from "./sleep.ts";
4848 import { LINES_OUT, listBoxes, mayDo, roleOn, SERVICE_NAME, type GameBox, type Role } from "./store.ts";
4949
src/games/client_pack.ts +1 −1
@@ -19,7 +19,7 @@ import type { App } from "../app.ts";
1919 import { id as newId, secret } from "../kernel/id.ts";
2020 import { sha256 } from "../kernel/hash.ts";
2121 import { versionById, type Result } from "./modrinth.ts";
22 import { playerMods } from "./player_events.ts";
22 import { playerMods } from "../kinds/minecraft/player_events.ts";
2323 import { modsOf, type Mods } from "./mods.ts";
2424 import { LOG_KEEP, logsOf, type GameBox } from "./store.ts";
2525
src/games/desk_snapshot.ts +2 −2
@@ -23,8 +23,8 @@ import { answerTo, questionOf, serversSeen } from "./ask.ts";
2323 import { composeServices, readCompose } from "./compose.ts";
2424 import { helpLines } from "./chat.ts";
2525 import { readLines } from "./forge_read.ts";
26 import { peopleOf } from "./people.ts";
27 import { whoMayReach } from "./reach.ts";
26 import { peopleOf } from "../kinds/minecraft/people.ts";
27 import { whoMayReach } from "../kinds/minecraft/reach.ts";
2828 import { proxyOf } from "./sleep.ts";
2929 import { mayDo, roleOn, type GameBox } from "./store.ts";
3030
src/games/door_leave.ts +1 −1
@@ -9,7 +9,7 @@
99
1010 import type { Database } from "bun:sqlite";
1111 import { createLog } from "../kernel/log.ts";
12 import { networkOf, peopleOf } from "./people.ts";
12 import { networkOf, peopleOf } from "../kinds/minecraft/people.ts";
1313 import { SERVICE_NAME } from "./store.ts";
1414 import { doorOf, lockDoor, locksOnLeave } from "./write_window.ts";
1515
src/games/findings.ts +1 −1
@@ -11,7 +11,7 @@
1111 */
1212
1313 import type { Database } from "bun:sqlite";
14 import { peopleOf } from "./people.ts";
14 import { peopleOf } from "../kinds/minecraft/people.ts";
1515
1616 export interface Finding {
1717 /**
src/games/forge_read.ts +1 −1
@@ -9,7 +9,7 @@ import type { User } from "../core/users.ts";
99 import type { Ctx } from "../http/context.ts";
1010 import { loadMcp } from "../http/mcp/load.ts";
1111 import { visible } from "../http/mcp/shared.ts";
12 import { peopleOf } from "./people.ts";
12 import { peopleOf } from "../kinds/minecraft/people.ts";
1313 import { serversSeen } from "./ask.ts";
1414 import { servicesOf, type GameBox } from "./store.ts";
1515
src/games/gist.ts +1 −1
@@ -8,7 +8,7 @@
88 import type { Database } from "bun:sqlite";
99 import { isIP } from "node:net";
1010 import { isPublicAddress } from "../apps/egress.ts";
11 import { peopleOf } from "./people.ts";
11 import { peopleOf } from "../kinds/minecraft/people.ts";
1212 import type { Power } from "./power.ts";
1313 import { commandOf, type GameService } from "./store.ts";
1414
src/games/heal.ts +2 −2
@@ -8,8 +8,8 @@
88 */
99
1010 import type { Database } from "bun:sqlite";
11 import { playerEvents } from "./metrics.ts";
12 import { networkOf } from "./people.ts";
11 import { playerEvents } from "../kinds/minecraft/metrics.ts";
12 import { networkOf } from "../kinds/minecraft/people.ts";
1313 import { proxyOf } from "./sleep.ts";
1414 import { queueCommand, servicesOf, SERVICE_NAME, type GameBox } from "./store.ts";
1515
src/games/lend_fit.ts +1 −1
@@ -6,7 +6,7 @@
66 */
77
88 import type { Database } from "bun:sqlite";
9 import { spareSamples } from "./metrics.ts";
9 import { spareSamples } from "../kinds/minecraft/metrics.ts";
1010 import { spareOf, vcpusOf, WINDOW_DAYS } from "./spare.ts";
1111 import { MEMBER_WRITABLE } from "../core/audience.ts";
1212 import { boxById, isWaker, servicesOf } from "./store.ts";
src/games/mods.ts +1 −1
@@ -23,7 +23,7 @@ import { byVersion, latestRelease, newestPack, packUpdate, readPack, resolve, sl
2323 import { missing as setMissing, setNamed, SETS, SET_PREFIX, type ModSet } from "./mod_sets.ts";
2424 import { memoryRefusal, type BoxRoom } from "./box_memory.ts";
2525 import { withConfig } from "./plugin_config.ts";
26 import { SPARK_CFG, SPARK_VAR, sparkConfig, sparkConfigFile } from "./spark.ts";
26 import { SPARK_CFG, SPARK_VAR, sparkConfig, sparkConfigFile } from "../kinds/minecraft/spark.ts";
2727 import { publicOrigin } from "../core/public_origin.ts";
2828 import { AUTOSTOPPER } from "./sleep.ts";
2929 import { servicesOf, type GameBox } from "./store.ts";
src/games/outcome.ts +1 −1
@@ -9,7 +9,7 @@
99
1010 import type { Database } from "bun:sqlite";
1111 import { editDistance } from "../text/edit_distance.ts";
12 import { PLAYER } from "./metrics.ts";
12 import { PLAYER } from "../kinds/minecraft/metrics.ts";
1313
1414 const VERB = /^\/?(?:minecraft:)?(op|deop|whitelist (?:add|remove)|ban|pardon|kick)\s+(\S+)/i;
1515 /** The answers with which a server (vanilla, Paper, Fabric) did not do what was asked. */
src/games/plugin_config.ts +1 −1
@@ -37,7 +37,7 @@ import type { User } from "../core/users.ts";
3737 import { lineDiff, type DiffLine } from "../web/render/json-doc.ts";
3838 import { commitCompose, composeHistory, readCompose, readRepoFile, setServiceEnv, setServiceLabels, setServiceListItem, setTopEntry } from "./compose.ts";
3939 import type { Result } from "./modrinth.ts";
40 import { peopleOf } from "./people.ts";
40 import { peopleOf } from "../kinds/minecraft/people.ts";
4141 import type { GameBox } from "./store.ts";
4242
4343 /** Where a file lives: the compose file and a pointer into it. */
src/games/spare_row.ts +1 −1
@@ -7,7 +7,7 @@
77 import type { Database } from "bun:sqlite";
88 import { join } from "node:path";
99 import { checkCoreHours } from "../core/ledger_cpu.ts";
10 import { spareSamples } from "./metrics.ts";
10 import { spareSamples } from "../kinds/minecraft/metrics.ts";
1111 import { spareOf, spareParts, vcpusOf, WINDOW_DAYS } from "./spare.ts";
1212 import type { GameBox } from "./store.ts";
1313
src/games/store.ts +2 −2
@@ -23,7 +23,7 @@ import { gameRank, type GameRole } from "../core/may.ts";
2323 import type { User } from "../core/users.ts";
2424 import { sha256 } from "../kernel/hash.ts";
2525 import { id as newId } from "../kernel/id.ts";
26 import { SPARK_VAR, sealedSparkBase } from "./spark.ts";
26 import { SPARK_VAR, sealedSparkBase } from "../kinds/minecraft/spark.ts";
2727 import { lendWhyOf } from "./lend_why.ts";
2828
2929 export const BOX_NAME = /^[a-z][a-z0-9-]{0,39}$/;
@@ -620,7 +620,7 @@ export interface SyncBody {
620620 readonly logs?: Record<string, unknown>;
621621 /**
622622 * Per service, the raw RCON answers the agent read (`list`, `tps`, `mspt`, `spark`):
623 * `games/metrics.ts` parses them.
623 * `kinds/minecraft/metrics.ts` parses them.
624624 */
625625 readonly metrics?: Record<string, unknown>;
626626 /** Each server's whitelist, ops and bans, and the proxy's glist (`people.ts`). */
src/games/when_quiet.ts +1 −1
@@ -7,7 +7,7 @@
77 import type { App } from "../app.ts";
88 import { getUserById } from "../core/users.ts";
99 import { readCompose } from "./compose.ts";
10 import { peopleOf } from "./people.ts";
10 import { peopleOf } from "../kinds/minecraft/people.ts";
1111 import { commitJar, pinOf } from "./proxy_jars.ts";
1212 import { proxyOf } from "./sleep.ts";
1313 import { mayDo, roleOn, servicesOf, type GameBox } from "./store.ts";
src/http/games_routes.ts +7 −10
@@ -12,15 +12,11 @@ import { readDiag } from "../games/diag.ts";
1212 import { heal } from "../games/heal.ts";
1313 import { synced } from "../games/notify.ts";
1414 import { auditShellResults } from "../games/shell.ts";
15 import { recordMetrics } from "../games/metrics.ts";
16 import { recordPeople } from "../games/people.ts";
17 import { followGrants } from "../games/reach.ts";
1815 import { gameAsk, gameChat, runChat } from "../games/chat.ts";
1916 import { snapshotFor } from "../games/desk_snapshot.ts";
2017 import { toldGot, toldTo } from "../games/door.ts";
2118 import { packChecks } from "../games/pack_check.ts";
2219 import { lendAnswer } from "../games/lend.ts";
23 import { recordProxyEvents, tellRefused } from "../games/player_events.ts";
2420 import { proxyOf, sleeping } from "../games/sleep.ts";
2521 import { jarsOf } from "../games/proxy_jars.ts";
2622 import { boxByToken, envFiles, markAsleep, recordSync, signJarUrls, swapGameBoxToken, type GameBox, type SyncBody } from "../games/store.ts";
@@ -40,6 +36,7 @@ import type { Ctx, Handler } from "./context.ts";
4036 import { InvalidJson } from "./json_body.ts";
4137 import { apiError, boundedMachineBody, json } from "./respond.ts";
4238 import type { Router } from "./router.ts";
39 import { defaultKind } from "../kinds/index.ts";
4340
4441 /**
4542 * How long a sync waits for the answers to the requests it just took: a read or a question is done in
@@ -97,24 +94,24 @@ export async function gameAgentSync(ctx: Ctx): Promise<Response> {
9794 }
9895 // Every shell command the box answered, its output with it, into the audit.
9996 auditShellResults(ctx.app, box, (body.results ?? []).map((r) => r.id));
100 recordMetrics(ctx.app.db, box, body);
97 defaultKind().metrics.record(ctx.app.db, box, body);
10198 try {
10299 watchAgent(ctx.app, box, readDiag(JSON.stringify(body.diag ?? {})), AGENT_SHA);
103100 } catch (e) {
104101 ctx.app.log.warn("game agent watch failed", { error: String(e) });
105102 }
106 recordPeople(ctx.app.db, box, body.people);
103 defaultKind().people.recordPeople(ctx.app.db, box, body.people);
107104 // A pack server's files against its lockfile: the answers judged, a check asked where one is due.
108105 if (body.boot === undefined) await packChecks(ctx.app, box, body);
109106 const compose = await readCompose(ctx.app, box);
110 // Each server's whitelist follows the forge's grants (`games/reach.ts`).
111 followGrants(ctx.app.db, box, compose?.text);
107 // Each server's whitelist follows the forge's grants (the kind's people adapter).
108 defaultKind().people.followGrants(ctx.app.db, box, compose?.text);
112109 // A server its sleep stopped is asleep, not down: the compose file says which sleep.
113110 markAsleep(ctx.app.db, box.id, compose === undefined ? [] : sleeping(compose.text));
114111 // Refused joins and wakes, from the proxy's own log.
115 recordProxyEvents(ctx.app.db, box, body.logs, compose === undefined ? undefined : proxyOf(compose.text));
112 defaultKind().people.recordProxyEvents(ctx.app.db, box, body.logs, compose === undefined ? undefined : proxyOf(compose.text));
116113 // A refused player is told why once a server lists them again; Modrinth is never waited for.
117 void tellRefused(ctx.app, box, body.metrics).catch((e: unknown) => ctx.app.log.warn(`game box ${box.name}: telling a refused player failed`, { error: String(e) }));
114 void defaultKind().people.tellRefused(ctx.app, box, body.metrics).catch((e: unknown) => ctx.app.log.warn(`game box ${box.name}: telling a refused player failed`, { error: String(e) }));
118115 // What is safe is mended alone and said (`games/heal.ts`): a stuck wake, a lost start, with a
119116 // limit.
120117 if (body.boot === undefined) heal(ctx.app.db, box, compose?.text);
src/http/mcp/tools/games.ts +11 −13
@@ -10,16 +10,12 @@ import { boxStatus, boxStatusShared } from "../../../games/diag.ts";
1010 import { heldLines, heldOn } from "../../../games/hold.ts";
1111 import { askPower, isPower, POWER } from "../../../games/power.ts";
1212 import { commitSettings, previewSettings, serviceSettings } from "../../../games/settings.ts";
13 import { compactMetrics, compactSeries } from "../../../games/metrics_answer.ts";
14 import { WINDOWS, type Window } from "../../../games/metrics.ts";
1513 import { makePackLink, packRow, revokeLinks } from "../../../games/client_pack.ts";
1614 import { boxNamed, listBoxes, mayDo, queueCommand, roleOn, seesBox, SERVICE_NAME, servicesOf } from "../../../games/store.ts";
1715 import { good, bad, type Tool, str } from "../shared.ts";
1816 import { ALIASES, commitServer, LEVELS, planRemoveServer, planServer, wishOn, type Level } from "../../../games/presets.ts";
1917 import { commitPolicy } from "../../../games/sleep.ts";
2018 import { findingsOf as kickFindingsOf } from "../../../games/findings.ts";
21 import { eventsOf, networkOf, PEOPLE_OPS, peopleOf, peopleWords, queuePeople } from "../../../games/people.ts";
22 import { findingsOf } from "../../../games/player_events.ts";
2319 import { linkShown } from "../../../games/snapshots.ts";
2420 import { verdictsOf } from "../../../games/set_verdict.ts";
2521 import { takeBack } from "../../../games/take_back.ts";
@@ -27,6 +23,8 @@ import { newestProof, proofWords } from "../../../games/lent_proof.ts";
2723 import { queueWorld } from "../../../games/worlds.ts";
2824 import { principalOf } from "../../../core/principal.ts";
2925 import { mayOnGame, seesGameBox } from "../../../games/game_may.ts";
26 import { defaultKind } from "../../../kinds/index.ts";
27 import type { Window } from "../../../kinds/kind.ts";
3028 import { neutralArgs } from "../../../games/neutral_args.ts";
3129
3230 export const tool: Tool = {
@@ -38,10 +36,10 @@ export const tool: Tool = {
3836 type: "object",
3937 properties: {
4038 action: { type: "string", enum: ["list", "machines", "metrics", "console", "take_back", "power", "env", "mods", "mods_search", "mods_pack_search", "mods_install", "mods_update", "mods_remove", "mods_pack", "pack", "pack_link", "pack_end", "people", "config", "config_set", "plugin_config", "plugin_config_set", "plugin_config_revert", "sleep", "create_server", "remove_server", "world"] },
41 op: { type: "string", enum: ["list", ...PEOPLE_OPS, "import", "restore", "snapshot"] },
39 op: { type: "string", enum: ["list", ...defaultKind().people.ops, "import", "restore", "snapshot"] },
4240 player: { type: "string", maxLength: 17 },
4341 to: { type: "string", maxLength: 64 },
44 window: { type: "string", enum: Object.keys(WINDOWS) },
42 window: { type: "string", enum: Object.keys(defaultKind().metrics.windows) },
4543 url: { type: "string", maxLength: 3800 },
4644 snapshot: { type: "string", maxLength: 120 },
4745 words: { type: "string", maxLength: 300 },
@@ -159,11 +157,11 @@ export const tool: Tool = {
159157 const asking = principalOf(ctx.auth);
160158 // The whole box's numbers ask may over the box; one server's, over that server alone.
161159 if (box === undefined || !(service === "" ? seesGameBox(db, asking, "tool metrics", box.id) : seesBox(db, user, box.id))) return bad("not_found", "no such box here");
162 if (service === "") return good(compactMetrics(db, box, (s) => mayOnGame(db, asking, box.id, s, "viewer")));
160 if (service === "") return good(defaultKind().metrics.compactMetrics(db, box, (s) => mayOnGame(db, asking, box.id, s, "viewer")));
163161 if (!SERVICE_NAME.test(service) || !mayOnGame(db, asking, box.id, service, "viewer")) return bad("not_found", "no such service here");
164162 const window = (str(args["window"]) || "1h") as Window;
165 if (!(window in WINDOWS)) return bad("invalid", `window is one of ${Object.keys(WINDOWS).join(", ")}`);
166 return good(compactSeries(db, box, service, window));
163 if (!(window in defaultKind().metrics.windows)) return bad("invalid", `window is one of ${Object.keys(defaultKind().metrics.windows).join(", ")}`);
164 return good(defaultKind().metrics.compactSeries(db, box, service, window));
167165 }
168166 if (box === undefined || !seesBox(db, user, box.id) || !SERVICE_NAME.test(service)) return bad("not_found", "no such box or service here");
169167 if (action === "config") {
@@ -263,11 +261,11 @@ export const tool: Tool = {
263261 if (action === "people") {
264262 const op = str(args["op"]);
265263 if (op === "list") {
266 const { online, lists } = peopleOf(db, box.id, service);
267 return good({ service, online, ...lists, network: networkOf(db, box.id), latest: eventsOf(db, box.id, service, 50), findings: kickFindingsOf(db, box.id, service), refusals: findingsOf(db, box.id, service) });
264 const { online, lists } = defaultKind().people.peopleOf(db, box.id, service);
265 return good({ service, online, ...lists, network: defaultKind().people.networkOf(db, box.id), latest: defaultKind().people.eventsOf(db, box.id, service, 50), findings: kickFindingsOf(db, box.id, service), refusals: defaultKind().people.findingsOf(db, box.id, service) });
268266 }
269 const queued = await queuePeople(ctx.app, box, service, op, str(args["player"]), user, str(args["to"]));
270 return queued.ok ? good({ says: `Queued: ${peopleWords(JSON.stringify({ op, player: str(args["player"]), server: str(args["to"]) }))}; the box does it on its next check-in.`, id: queued.id }) : bad("refused", queued.error);
267 const queued = await defaultKind().people.queuePeople(ctx.app, box, service, op, str(args["player"]), user, str(args["to"]));
268 return queued.ok ? good({ says: `Queued: ${defaultKind().people.peopleWords(JSON.stringify({ op, player: str(args["player"]), server: str(args["to"]) }))}; the box does it on its next check-in.`, id: queued.id }) : bad("refused", queued.error);
271269 }
272270 if (action === "config_set") {
273271 const plan = await previewSettings(ctx.app, box, service, { [str(args["key"])]: str(args["value"]) });
src/kinds/kind.ts +14 −12
@@ -1,12 +1,11 @@
11 /**
2 * A kind of game the forge hosts (P16, #334): one interface with five parts, and a kind is a value
2 * A kind of game the forge hosts (P16, #334): one interface with its parts, and a kind is a value
33 * of it, found by its name. The general layer asks for a kind and calls its parts; it never imports
44 * a kind's directory, so what is specific to one game (Minecraft's compose design, its console,
55 * RCON) stays in `src/kinds/<name>/`.
66 *
7 * The compose design and the console adapter live behind it. The identity prover is the first
8 * of the three declared parts to move; the people adapter and metrics probe are still stubbed by
9 * each kind: the code behind them is in `src/games` until the next move.
7 * All parts live behind it. The people adapter, name list and metrics probe are typed
8 * from what a kind hands over; the identity prover (#18490) is an interface over `account_link`.
109 */
1110
1211 import type { Database } from "bun:sqlite";
@@ -76,14 +75,10 @@ export interface ConsoleAdapter {
7675 };
7776 }
7877
79 /** A part not moved yet: it names where its code still lives. */
80 export interface Stub {
81 readonly stub: true;
82 readonly livesIn: string;
83 }
84
8578 /** Part 3: who is on a server, and who may be (whitelist, ops). */
86 export type PeopleAdapter = Stub;
79 export type PeopleAdapter = typeof import("./minecraft/people_adapter.ts").peopleAdapter;
80 /** The names an account has linked in the game, listed for the general identity list. */
81 export type NameList = typeof import("./minecraft/identity.ts").nameList;
8782 /**
8883 * Part 4: proof that a person owns a name in the game (#18490). The proof is one row of
8984 * `account_link` keyed by this kind; the prover says what the kind's outside id is and writes and
@@ -104,13 +99,20 @@ export interface IdentityProver {
10499 owners(db: Database, outsideId: unknown): string[];
105100 }
106101 /** Part 5: what a running server reports about itself. */
107 export type MetricsProbe = Stub;
102 export type MetricsProbe = typeof import("./minecraft/metrics_probe.ts").metricsProbe;
103
104 export type { GameFinding } from "./minecraft/player_events.ts";
105 export type { PeopleOp } from "./minecraft/people.ts";
106 export type { Point, Window } from "./minecraft/metrics.ts";
107 export type { SparkSummary } from "./minecraft/spark_profile.ts";
108 export type { SparkFinding } from "./minecraft/spark_finding.ts";
108109
109110 export interface Kind {
110111 readonly name: string;
111112 readonly compose: ComposeDesign;
112113 readonly console: ConsoleAdapter;
113114 readonly people: PeopleAdapter;
115 readonly names: NameList;
114116 readonly identity: IdentityProver;
115117 readonly metrics: MetricsProbe;
116118 }
src/kinds/minecraft/identity.ts added +60
@@ -0,0 +1,60 @@
1 /**
2 * The Minecraft name list: the names an account has linked on a game box, each bound to a
3 * UUID or not yet. The general list (`core/proven_identities.ts`) reaches it through the kind.
4 */
5 import type { Database } from "bun:sqlite";
6 import type { Identity } from "../../core/proven_identities.ts";
7
8 /**
9 * The account's Minecraft names, in one statement, oldest first. A name bound to no UUID is listed
10 * unproven: it must be linked again.
11 */
12 export const minecraftIdentities = (db: Database, userId: string): Identity[] =>
13 db
14 .query<
15 { boxId: string; box: string | null; player: string; uuid: string; createdAt: string },
16 [string]
17 >(
18 `SELECT l.box_id AS boxId, b.name AS box, l.player, l.uuid, l.created_at AS createdAt
19 FROM game_link l LEFT JOIN game_box b ON b.id = l.box_id
20 WHERE l.user_id = ?1 ORDER BY l.created_at`,
21 )
22 .all(userId)
23 .map(
24 (r): Identity => ({
25 kind: "minecraft",
26 name: r.player,
27 proven: r.uuid !== "",
28 since: r.createdAt,
29 boxId: r.boxId,
30 box: r.box,
31 uuid: r.uuid,
32 }),
33 );
34
35 /** Every account's Minecraft names (or one's, when `userId` is given), by user id: one read. */
36 export function minecraftByUser(db: Database, userId = ""): Map<string, Identity[]> {
37 const by = new Map<string, Identity[]>();
38 const rows = db
39 .query<{ userId: string; player: string; uuid: string; createdAt: string }, [string]>(
40 "SELECT user_id AS userId, player, uuid, created_at AS createdAt FROM game_link WHERE (?1 = '' OR user_id = ?1) ORDER BY created_at",
41 )
42 .all(userId);
43 for (const r of rows) by.set(r.userId, [...(by.get(r.userId) ?? []), { kind: "minecraft", name: r.player, proven: r.uuid !== "", since: r.createdAt }]);
44 return by;
45 }
46
47 /** Whether the forge has a game box to link a name on. */
48 export const hasGameBox = (db: Database): boolean => db.query("SELECT 1 FROM game_box LIMIT 1").get() !== null;
49
50 /**
51 * The account a Minecraft name on a box is linked to, and the UUID it is bound to: the list read
52 * the other way.
53 */
54 export const minecraftOwner = (db: Database, boxId: string, player: string): { userId: string; uuid: string } | undefined =>
55 db
56 .query<{ userId: string; uuid: string }, [string, string]>("SELECT user_id AS userId, uuid FROM game_link WHERE box_id = ?1 AND player = ?2")
57 .get(boxId, player) ?? undefined;
58
59 /** The name list the Minecraft kind hands the general layer. */
60 export const nameList = { identities: minecraftIdentities, byUser: minecraftByUser, owner: minecraftOwner, hasBox: hasGameBox };
src/kinds/minecraft/index.ts +8 −4
@@ -1,12 +1,15 @@
11 /**
2 * The Minecraft kind: its compose design, console and identity prover here; people and metrics
3 * still in `src/games`.
2 * The Minecraft kind: its compose design, console, people adapter, name list, identity prover and
3 * metrics probe, all in this directory.
44 */
55
66 import type { Kind } from "../kind.ts";
77 import { consoleHtml, consoleText, crashOf, shareOnMclogs } from "./console.ts";
88 import { hear } from "./command.ts";
99 import { minecraftDesign } from "./compose.ts";
10 import { nameList } from "./identity.ts";
11 import { metricsProbe } from "./metrics_probe.ts";
12 import { peopleAdapter } from "./people_adapter.ts";
1013 import { minecraftProver } from "./prover.ts";
1114 import { say } from "./speak.ts";
1215
@@ -14,7 +17,8 @@ export const minecraft: Kind = {
1417 name: "minecraft",
1518 compose: { design: minecraftDesign },
1619 console: { html: consoleHtml, text: consoleText, crash: crashOf, share: shareOnMclogs, forge: { hear, say } },
17 people: { stub: true, livesIn: "src/games/people.ts" },
20 people: peopleAdapter,
21 names: nameList,
1822 identity: minecraftProver,
19 metrics: { stub: true, livesIn: "src/games/metrics.ts" },
23 metrics: metricsProbe,
2024 };
src/games/metrics.ts → src/kinds/minecraft/metrics.ts renamed +4 −4
@@ -12,10 +12,10 @@
1212 */
1313
1414 import type { Database } from "bun:sqlite";
15 import { lockWhenLeft } from "./door_leave.ts";
16 import { noteReading } from "./lent_proof.ts";
17 import { SERVICE_NAME, type GameBox } from "./store.ts";
18 import type { SpareSample, SpareService } from "./spare.ts";
15 import { lockWhenLeft } from "../../games/door_leave.ts";
16 import { noteReading } from "../../games/lent_proof.ts";
17 import { SERVICE_NAME, type GameBox } from "../../games/store.ts";
18 import type { SpareSample, SpareService } from "../../games/spare.ts";
1919
2020 /** The most joins, leaves, deaths and chat lines a server keeps (besides the 30 days). */
2121 export const EVENTS_KEPT = 5_000;
src/games/metrics_answer.ts → src/kinds/minecraft/metrics_answer.ts renamed +1 −1
@@ -6,7 +6,7 @@
66
77 import type { Database } from "bun:sqlite";
88 import { metricsSeries, metricsSummary, type Window } from "./metrics.ts";
9 import type { GameBox } from "./store.ts";
9 import type { GameBox } from "../../games/store.ts";
1010
1111 /** The most bytes a metrics answer carries. */
1212 export const ANSWER_MAX = 4_096;
src/kinds/minecraft/metrics_probe.ts added +21
@@ -0,0 +1,21 @@
1 /**
2 * The Minecraft metrics probe: what a running server reports about itself (its list, tick rate,
3 * log) and the spark profiles it posts. The general layer reaches it as `kind.metrics`.
4 */
5 import { compactMetrics, compactSeries } from "./metrics_answer.ts";
6 import { metricsSeries, playerEvents, recentErrors, recordMetrics, WINDOWS } from "./metrics.ts";
7 import { boxOfSparkSecret, hasSparkSecret, keepProfile, newSparkSecret, profileOf, profilesOf, SPARK_WORDS, sparkBase } from "./spark.ts";
8 import { findingHref, sparkFindingsOf } from "./spark_finding.ts";
9 import { decodeSparkProfile, READ_UNPACKED } from "./spark_profile.ts";
10 import { FLAME_WIDTH, flameRects, heaviest, millis, sectionLines, sparkHeadLines, summarySections, treeLines } from "./spark_view.ts";
11
12 export const metricsProbe = {
13 series: metricsSeries, playerEvents, recentErrors, record: recordMetrics, windows: WINDOWS,
14 compactMetrics, compactSeries,
15 profiles: {
16 boxOfSecret: boxOfSparkSecret, hasSecret: hasSparkSecret, keep: keepProfile, newSecret: newSparkSecret,
17 profileOf, profilesOf, words: SPARK_WORDS, base: sparkBase, findingsOf: sparkFindingsOf, findingHref,
18 decode: decodeSparkProfile, readLimit: READ_UNPACKED,
19 view: { FLAME_WIDTH, flameRects, heaviest, millis, sectionLines, sparkHeadLines, summarySections, treeLines },
20 },
21 };
src/games/people.ts → src/kinds/minecraft/people.ts renamed +5 −5
@@ -11,12 +11,12 @@
1111 */
1212
1313 import type { Database } from "bun:sqlite";
14 import type { App } from "../app.ts";
15 import { readCompose } from "./compose.ts";
14 import type { App } from "../../app.ts";
15 import { readCompose } from "../../games/compose.ts";
1616 import { PLAYER, type PlayerEventKind } from "./metrics.ts";
17 import type { User } from "../core/users.ts";
18 import { isGameServer } from "./sleep.ts";
19 import { mayDo, queueCommand, roleOn, SERVICE_NAME, servicesOf, type GameBox } from "./store.ts";
17 import type { User } from "../../core/users.ts";
18 import { isGameServer } from "../../games/sleep.ts";
19 import { mayDo, queueCommand, roleOn, SERVICE_NAME, servicesOf, type GameBox } from "../../games/store.ts";
2020
2121 export interface Player {
2222 readonly name: string;
src/kinds/minecraft/people_adapter.ts added +14
@@ -0,0 +1,14 @@
1 /**
2 * The Minecraft people adapter: who is on a server and who may be (whitelist, ops, bans), what the
3 * players did, and why a player was refused. The general layer reaches it as `kind.people`.
4 */
5 import { findingsOf, recordProxyEvents, tellRefused } from "./player_events.ts";
6 import { eventsOf, eventWords, isBedrock, knowsPlayer, networkOf, PEOPLE_OPS, peopleOf, peopleWords, queuePeople, recordPeople, UNDO } from "./people.ts";
7 import { followGrants, openDoorWords } from "./reach.ts";
8
9 export const peopleAdapter = {
10 peopleOf, knowsPlayer, networkOf, eventsOf, eventWords, isBedrock, queuePeople, peopleWords, recordPeople,
11 ops: PEOPLE_OPS, undo: UNDO,
12 findingsOf, recordProxyEvents, tellRefused,
13 openDoorWords, followGrants,
14 };
src/games/player_events.ts → src/kinds/minecraft/player_events.ts renamed +6 −6
@@ -14,13 +14,13 @@
1414 */
1515
1616 import type { Database } from "bun:sqlite";
17 import type { App } from "../app.ts";
18 import { readCompose, serviceEnv } from "./compose.ts";
17 import type { App } from "../../app.ts";
18 import { readCompose, serviceEnv } from "../../games/compose.ts";
1919 import { HEAD, NAME, parseList, plain } from "./metrics.ts";
20 import { clientProjects, playerSide, resolve, type Locked, type Project, type Result } from "./modrinth.ts";
21 import { modsOf, type Mods } from "./mods.ts";
22 import { synced } from "./notify.ts";
23 import { LINES_OUT, SERVICE_NAME, servicesOf, tell, type GameBox } from "./store.ts";
20 import { clientProjects, playerSide, resolve, type Locked, type Project, type Result } from "../../games/modrinth.ts";
21 import { modsOf, type Mods } from "../../games/mods.ts";
22 import { synced } from "../../games/notify.ts";
23 import { LINES_OUT, SERVICE_NAME, servicesOf, tell, type GameBox } from "../../games/store.ts";
2424
2525 /** How far back refusals count towards a finding. */
2626 const FINDING_MS = 24 * 3_600_000;
src/games/reach.ts → src/kinds/minecraft/reach.ts renamed +5 −5
@@ -11,12 +11,12 @@
1111 */
1212
1313 import type { Database } from "bun:sqlite";
14 import type { User } from "../core/users.ts";
15 import { getUserById, isActive } from "../core/users.ts";
16 import { composeServices, serviceEnv } from "./compose.ts";
14 import type { User } from "../../core/users.ts";
15 import { getUserById, isActive } from "../../core/users.ts";
16 import { composeServices, serviceEnv } from "../../games/compose.ts";
1717 import { peopleOf } from "./people.ts";
18 import { proxyOf } from "./sleep.ts";
19 import { mayDo, queueCommand, roleOn, type GameBox } from "./store.ts";
18 import { proxyOf } from "../../games/sleep.ts";
19 import { mayDo, queueCommand, roleOn, type GameBox } from "../../games/store.ts";
2020
2121 /** The words a player hears when the network lets any name in. */
2222 export const OFFLINE_WORDS = "This network does not check accounts with Mojang (online-mode is off), so no name here can act for a forge account.";
src/games/spark.ts → src/kinds/minecraft/spark.ts renamed +3 −3
@@ -13,9 +13,9 @@
1313 */
1414
1515 import type { Database } from "bun:sqlite";
16 import { sha256 } from "../kernel/hash.ts";
17 import { secret } from "../kernel/id.ts";
18 import { err, ok, type Result } from "../kernel/result.ts";
16 import { sha256 } from "../../kernel/hash.ts";
17 import { secret } from "../../kernel/id.ts";
18 import { err, ok, type Result } from "../../kernel/result.ts";
1919
2020 export const SPARK_KEEP_DAYS = 14;
2121 export const SPARK_KEEP_COUNT = 50;
src/games/spark_finding.ts → src/kinds/minecraft/spark_finding.ts renamed
No content changes.
src/games/spark_profile.ts → src/kinds/minecraft/spark_profile.ts renamed
No content changes.
src/games/spark_view.ts → src/kinds/minecraft/spark_view.ts renamed
No content changes.
src/tui/screens/game_spark.ts +6 −7
@@ -7,8 +7,6 @@
77 */
88
99 import { publicOrigin } from "../../core/public_origin.ts";
10 import { sparkFindingsOf } from "../../games/spark_finding.ts";
11 import { SPARK_WORDS, newSparkSecret, profilesOf, sparkBase } from "../../games/spark.ts";
1210 import type { GameBox } from "../../games/store.ts";
1311 import type { Ctx, Screen } from "../app/app.ts";
1412 import { binding } from "../app/keys.ts";
@@ -18,16 +16,17 @@ import type { Session } from "../session.ts";
1816 import { gameSparkViewScreen } from "./game_spark_view.ts";
1917 import { principalOfUser } from "../../core/principal.ts";
2018 import { mayOnGame } from "../../games/game_may.ts";
19 import { defaultKind } from "../../kinds/index.ts";
2120
2221 export function gameSparkScreen(f: Session, ctx: Ctx, box: GameBox): Screen {
2322 let address = "";
2423 let at = 0;
2524 const lines = (w: number): string[] => {
26 const stored = profilesOf(f.app.db, box.id);
25 const stored = defaultKind().metrics.profiles.profilesOf(f.app.db, box.id);
2726 return [
28 ...wrap(SPARK_WORDS, w),
27 ...wrap(defaultKind().metrics.profiles.words, w),
2928 "",
30 ...sparkFindingsOf(f.app.db, box.id).flatMap((x) => [...wrap(`${x.says} Profile ${x.key}, Window ${String(x.window)}, in the Slowest ticks list.`, w), ""]),
29 ...defaultKind().metrics.profiles.findingsOf(f.app.db, box.id).flatMap((x) => [...wrap(`${x.says} Profile ${x.key}, Window ${String(x.window)}, in the Slowest ticks list.`, w), ""]),
3130 ...(address === "" ? [] : [`bytebin-url: ${address}`, "This is the only time it is shown.", ""]),
3231 ...(stored.length === 0 ? ["None stored yet."] : stored.map((p, i) => `${i === at ? ">" : " "} ${p.at.slice(0, 16).replace("T", " ")} ${p.type.replace("application/x-spark-", "spark ")} ${String(Math.ceil(p.size / 1024))} KiB ${p.key}`)),
3332 ];
@@ -41,7 +40,7 @@ export function gameSparkScreen(f: Session, ctx: Ctx, box: GameBox): Screen {
4140 },
4241 key(e) {
4342 if (e.ctrl || e.alt) return false;
44 const stored = profilesOf(f.app.db, box.id);
43 const stored = defaultKind().metrics.profiles.profilesOf(f.app.db, box.id);
4544 if (e.key === "j" || e.key === "down") {
4645 at = Math.min(at + 1, Math.max(0, stored.length - 1));
4746 } else if (e.key === "k" || e.key === "up") {
@@ -52,7 +51,7 @@ export function gameSparkScreen(f: Session, ctx: Ctx, box: GameBox): Screen {
5251 return true;
5352 } else if (e.key === "u") {
5453 if (!mayOnGame(f.app.db, principalOfUser(f.user), box.id, "", "owner")) return false;
55 address = sparkBase(publicOrigin(f.app.config.url, `http://localhost:${String(f.app.config.port)}`), newSparkSecret(f.app.db, box.id));
54 address = defaultKind().metrics.profiles.base(publicOrigin(f.app.config.url, `http://localhost:${String(f.app.config.port)}`), defaultKind().metrics.profiles.newSecret(f.app.db, box.id));
5655 } else {
5756 return false;
5857 }
src/tui/screens/game_spark_view.ts +7 −9
@@ -1,18 +1,16 @@
11 /**
22 * One stored spark profile in the terminal (#18208): what /games/<box>/spark/<key> shows, in
3 * the same words (`games/spark_view.ts`): the head, then per thread its time sampled and the call
3 * the same words (the kind's spark view): the head, then per thread its time sampled and the call
44 * tree as indented lines. j/k scroll.
55 */
66
7 import { READ_UNPACKED, decodeSparkProfile } from "../../games/spark_profile.ts";
8 import { profileOf } from "../../games/spark.ts";
9 import { heaviest, millis, sectionLines, sparkHeadLines, summarySections, treeLines } from "../../games/spark_view.ts";
107 import type { GameBox } from "../../games/store.ts";
118 import type { Ctx, Screen } from "../app/app.ts";
129 import { binding } from "../app/keys.ts";
1310 import { style } from "../term/style.ts";
1411 import { truncate } from "../term/width.ts";
1512 import type { Session } from "../session.ts";
13 import { defaultKind } from "../../kinds/index.ts";
1614
1715 export function gameSparkViewScreen(f: Session, ctx: Ctx, box: GameBox, key: string): Screen {
1816 let top = 0;
@@ -23,13 +21,13 @@ export function gameSparkViewScreen(f: Session, ctx: Ctx, box: GameBox, key: str
2321 return cached;
2422 };
2523 const build = (): string[] => {
26 const stored = profileOf(f.app.db, box.id, key);
24 const stored = defaultKind().metrics.profiles.profileOf(f.app.db, box.id, key);
2725 if (stored === undefined) return ["This profile is gone: profiles are kept 14 days."];
28 const read = stored.type === "application/x-spark-sampler" ? decodeSparkProfile(stored.body, READ_UNPACKED) : undefined;
26 const read = stored.type === "application/x-spark-sampler" ? defaultKind().metrics.profiles.decode(stored.body, defaultKind().metrics.profiles.readLimit) : undefined;
2927 if (read === undefined || !read.ok) return ["The forge draws a sampler profile only, and this one is not a readable one: download it from the box's page."];
30 const { drawn, note } = heaviest(read.summary.threads);
31 const [head = ""] = sparkHeadLines(read.summary);
32 return [head, "Times are milliseconds sampled, shares are of the thread; trees keep the heaviest calls.", ...drawn.flatMap((t) => ["", `== ${t.name || "(unnamed thread)"}: ${millis(t.ms)} sampled`, ...(t.tree.length === 0 ? ["Nothing was sampled in this thread."] : treeLines(t.tree, t.ms))]), ...(note === "" ? [] : ["", note]), ...summarySections(read.summary).flatMap((x) => ["", `== ${x.title}`, ...sectionLines(x)])];
28 const { drawn, note } = defaultKind().metrics.profiles.view.heaviest(read.summary.threads);
29 const [head = ""] = defaultKind().metrics.profiles.view.sparkHeadLines(read.summary);
30 return [head, "Times are milliseconds sampled, shares are of the thread; trees keep the defaultKind().metrics.profiles.view.heaviest calls.", ...drawn.flatMap((t) => ["", `== ${t.name || "(unnamed thread)"}: ${defaultKind().metrics.profiles.view.millis(t.ms)} sampled`, ...(t.tree.length === 0 ? ["Nothing was sampled in this thread."] : defaultKind().metrics.profiles.view.treeLines(t.tree, t.ms))]), ...(note === "" ? [] : ["", note]), ...defaultKind().metrics.profiles.view.summarySections(read.summary).flatMap((x) => ["", `== ${x.title}`, ...defaultKind().metrics.profiles.view.sectionLines(x)])];
3331 };
3432 return {
3533 title: `${box.name}: profile ${key}`,
src/tui/screens/games.ts +9 −12
@@ -28,10 +28,7 @@ import { watchBox } from "../../games/notify.ts";
2828 import { containersIn, figuresOf } from "../../cloud/containers.ts";
2929 import { joinAddress, NO_ADDRESS, nowWords, powerNow, PREVIEW_WORDS, privateWords, SAVE_WORDS } from "../../games/gist.ts";
3030 import { findingLine, findingsOf as kickFindingsOf } from "../../games/findings.ts";
31 import { eventsOf, eventWords, isBedrock, peopleOf, peopleWords, queuePeople } from "../../games/people.ts";
3231 import { leaveCannotLock } from "../../games/door_leave.ts";
33 import { openDoorWords } from "../../games/reach.ts";
34 import { findingsOf } from "../../games/player_events.ts";
3532 import { queueWorld, type WorldOp } from "../../games/worlds.ts";
3633 import { lendWords, lentRunnerOf, setLend } from "../../games/lend.ts";
3734 import { lendCannot } from "../../games/lend_why.ts";
@@ -67,7 +64,6 @@ import {
6764 type GameBox,
6865 type Role,
6966 } from "../../games/store.ts";
70 import { metricsSeries } from "../../games/metrics.ts";
7167 import type { Ctx, Screen } from "../app/app.ts";
7268 import { binding } from "../app/keys.ts";
7369 import { style } from "../term/style.ts";
@@ -84,10 +80,11 @@ import { gameModsScreen } from "./game_mods.ts";
8480 import { gameSparkScreen } from "./game_spark.ts";
8581 import { principalOfUser } from "../../core/principal.ts";
8682 import { mayOnGame } from "../../games/game_may.ts";
83 import { defaultKind } from "../../kinds/index.ts";
8784
8885 /** "4 online · 19.8 TPS · 3.1 ms tick" from the last hour's numbers, or nothing before any. */
8986 function playersTps(f: Session, box: { id: string }, service: string): string[] {
90 const last = metricsSeries(f.app.db, box, service, "1h").at(-1);
87 const last = defaultKind().metrics.series(f.app.db, box, service, "1h").at(-1);
9188 return last === undefined ? [] : [`${last.players} online`, ...(last.tps === null ? [] : [`${last.tps} TPS`]), ...(last.mspt === null ? [] : [`${last.mspt} ms tick`])];
9289 }
9390
@@ -367,20 +364,20 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s
367364 // What still waits; an answer stands in the log, under the line it came after.
368365 return blocks().filter((b) => b.at === "").flatMap(blockLines);
369366 if (part === "people") {
370 const { online, lists } = peopleOf(f.app.db, box.id, service);
371 const tag = (n: string) => `${n}${isBedrock(n) ? " (Bedrock)" : ""}${lists.ops.some((o) => o.name === n) ? " · op" : ""}`;
367 const { online, lists } = defaultKind().people.peopleOf(f.app.db, box.id, service);
368 const tag = (n: string) => `${n}${defaultKind().people.isBedrock(n) ? " (Bedrock)" : ""}${lists.ops.some((o) => o.name === n) ? " · op" : ""}`;
372369 return [
373370 ...held(),
374371 nowWords(servicesOf(f.app.db, box.id).find((x) => x.name === service), powerNow(f.app.db, box.id, service)),
375372 figuresOf(f.app.db, f.user, boxNamed(f.app.db, box.name) ?? box, service),
376373 ...verdictsOf(f.app.db, box, service).map((v) => (v.takeBack === null ? v.says : `${v.says} In Mods, d then ${v.takeBack} previews it; nothing is taken back alone.`)),
377 ...findingsOf(f.app.db, box.id, service).flatMap((x) => [x.says, ...x.fix.map((l) => `Fix: ${l}`)]),
374 ...defaultKind().people.findingsOf(f.app.db, box.id, service).flatMap((x) => [x.says, ...x.fix.map((l) => `Fix: ${l}`)]),
378375 online.length === 0 ? `Nobody is on ${service} right now.` : `Online: ${online.map((p) => tag(p.name)).join(", ")}`,
379376 `${lists.whitelistOn ? "Only listed players may join" : "Anyone may join"} · ${lists.whitelist.length} listed · ${lists.ops.length} operators · ${lists.bans.length} banned`,
380 ...[openDoorWords(lists.whitelistOn) ?? []].flat(),
377 ...[defaultKind().people.openDoorWords(lists.whitelistOn) ?? []].flat(),
381378 ...lists.bans.map((b) => `banned: ${b.name}${b.reason === "" ? "" : ` (${b.reason})`}`),
382379 ...kickFindingsOf(f.app.db, box.id, service).map(findingLine),
383 ...eventsOf(f.app.db, box.id, service, 20).map((e) => `${e.at.slice(11, 16)} ${eventWords(e, service)}`),
380 ...defaultKind().people.eventsOf(f.app.db, box.id, service, 20).map((e) => `${e.at.slice(11, 16)} ${defaultKind().people.eventWords(e, service)}`),
384381 "p: op (make operator), deop, whitelist-add (let in), whitelist-remove, ban, pardon (lift a ban), kick <player>, or move <player> <server>",
385382 ];
386383 }
@@ -489,9 +486,9 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s
489486 else if (e.key === "p")
490487 ask("Player", "op | deop | whitelist-add | whitelist-remove | ban | pardon | kick <player>, or move <player> <server>", async (raw) => {
491488 const [op = "", player = "", to = ""] = raw.trim().split(/\s+/);
492 const queued = await queuePeople(f.app, box, service, op, player, f.user, to);
489 const queued = await defaultKind().people.queuePeople(f.app, box, service, op, player, f.user, to);
493490 part = "people";
494 return queued.ok ? `Asked: ${peopleWords(JSON.stringify({ op, player, server: to }))}; it shows on the server until the server answers.` : queued.error;
491 return queued.ok ? `Asked: ${defaultKind().people.peopleWords(JSON.stringify({ op, player, server: to }))}; it shows on the server until the server answers.` : queued.error;
495492 });
496493 else if (e.key === "m") ctx.push(gameModsScreen(f, ctx, box, service));
497494 else if (e.key === "f") ctx.push(gameConfigScreen(f, ctx, box, service));
src/web/pages/games.ts +19 −24
@@ -14,8 +14,6 @@ import { verdictsOf } from "../../games/set_verdict.ts";
1414 import { offered, SETS, SET_PREFIX } from "../../games/mod_sets.ts";
1515 import { commitPlan, modsOf, packUpdateOf, planInstall, planPack, planPackUpdate, planRemove, planUpdate, updatesOf, type Mods, type Plan } from "../../games/mods.ts";
1616 import { search, searchPacks, type Hit, type Result } from "../../games/modrinth.ts";
17 import { findingHref, sparkFindingsOf } from "../../games/spark_finding.ts";
18 import { SPARK_WORDS, hasSparkSecret, profilesOf } from "../../games/spark.ts";
1917 import { packRow } from "../../games/client_pack.ts";
2018 import { packCheckLines } from "../../games/pack_check.ts";
2119 import { playersBlock } from "./games_players.ts";
@@ -90,19 +88,16 @@ import { doorBlock } from "./games_door.ts";
9088 import { passkeyJs } from "../passkey-client.ts";
9189 import { windowNote } from "../../games/write_window.ts";
9290 import { defaultHeadResponse, headResponse } from "../../games/heads.ts";
93 import { eventsOf, eventWords, isBedrock, knowsPlayer, peopleOf, peopleWords, queuePeople, UNDO, type PeopleOp } from "../../games/people.ts";
94 import { openDoorWords } from "../../games/reach.ts";
9591 import { queueWorld, undoOf } from "../../games/worlds.ts";
9692 import { START_BOX } from "../../core/empty_words.ts";
9793 import { emptyLine, emptyNote } from "../empty_words.ts";
98 import { findingsOf, type GameFinding } from "../../games/player_events.ts";
9994 import { findingsOf as kickFindingsOf } from "../../games/findings.ts";
10095 import { containersIn, figuresOf } from "../../cloud/containers.ts";
10196 import { joinAddress, mainPower, NO_ADDRESS, PREVIEW_WORDS, privateWords, SAVE_WORDS, nowWords, PEOPLE_BUTTON, PEOPLE_CHOICES, powerNow, whoIsOn } from "../../games/gist.ts";
102 import { metricsSeries, playerEvents, recentErrors, type Point } from "../../games/metrics.ts";
10397 import { daySpark } from "../studio/kpi_row.ts";
10498 import { principalOf } from "../../core/principal.ts";
10599 import { drawsOperator, mayOnGame, seesGameBox } from "../../games/game_may.ts";
100 import type { PeopleOp, GameFinding, Point } from "../../kinds/kind.ts";
106101
107102 /** A small line of a series (oldest first); nothing when no point is known. */
108103 const sparkOf = (points: readonly Point[], pick: (p: Point) => number | null, label: string): Html | null =>
@@ -325,7 +320,7 @@ export async function gameBoxPage(ctx: Ctx): Promise<Response> {
325320 visible.map((n) => {
326321 const s = seen.find((x) => x.name === n);
327322 const act = drawsOperator(ctx.app.db, principalOf(ctx.auth), box.id, n);
328 const day = metricsSeries(ctx.app.db, box, n, "24h");
323 const day = defaultKind().metrics.series(ctx.app.db, box, n, "24h");
329324 const tps = lastOf(day, (p) => p.tps);
330325 const players = day.length === 0 ? null : day.at(-1)!.players;
331326 const sets = verdictsOf(ctx.app.db, box, n);
@@ -497,17 +492,17 @@ export async function gameLendSubmit(ctx: Ctx): Promise<Response> {
497492 * upload address.
498493 */
499494 function sparkBlock(ctx: Ctx, box: GameBox, owner: boolean): Html {
500 const stored = profilesOf(ctx.app.db, box.id);
495 const stored = defaultKind().metrics.profiles.profilesOf(ctx.app.db, box.id);
501496 return html`<section class="settings-block" id="spark">
502497 <h2>Profiles</h2>
503 <p class="muted small">${SPARK_WORDS}</p>
504 ${sparkFindingsOf(ctx.app.db, box.id).map((f) => html`<p class="muted small">${f.says} <a href="${findingHref(box.name, f)}">See that tick</a>.</p>`)}
498 <p class="muted small">${defaultKind().metrics.profiles.words}</p>
499 ${defaultKind().metrics.profiles.findingsOf(ctx.app.db, box.id).map((f) => html`<p class="muted small">${f.says} <a href="${defaultKind().metrics.profiles.findingHref(box.name, f)}">See that tick</a>.</p>`)}
505500 ${stored.length === 0
506501 ? html`<p class="muted small">None stored yet.</p>`
507502 : rowList(stored.map((p) => row({ href: `/games/${box.name}/spark/${p.key}`, title: p.type.replace("application/x-spark-", "spark "), meta: html`${p.at.slice(0, 16).replace("T", " ")} · ${Math.ceil(p.size / 1024)} KiB` })))}
508503 ${owner
509504 ? html`<form method="post" action="/games/${box.name}/@spark" class="row-fields">
510 ${btn(hasSparkSecret(ctx.app.db, box.id) ? "New upload address" : "Make an upload address", { type: "submit", variant: "secondary" })}
505 ${btn(defaultKind().metrics.profiles.hasSecret(ctx.app.db, box.id) ? "New upload address" : "Make an upload address", { type: "submit", variant: "secondary" })}
511506 </form>`
512507 : null}
513508 </section>`;
@@ -605,7 +600,7 @@ export async function gameServicePage(ctx: Ctx): Promise<Response> {
605600 return after === null ? [] : [{ ...b, after }];
606601 });
607602 const players = mods?.ok && mods.value.target.kind === "mod" ? await packRow(ctx.app, box, service) : undefined;
608 const findings = findingsOf(ctx.app.db, box.id, service);
603 const findings = defaultKind().people.findingsOf(ctx.app.db, box.id, service);
609604 // Settings: each as the compose file says; a "Preview" (s.<key>=value in the query) planned on it.
610605 const settings = compose === undefined ? [] : settingsOf(compose.text, service, env);
611606 const wanted = settingsWanted(ctx.url.searchParams);
@@ -728,9 +723,9 @@ const findingsBlock = (findings: readonly GameFinding[]): Html | null =>
728723
729724 /** A service's numbers: 24 hours of players, TPS, tick time and memory, then the latest joins and errors. */
730725 function numbersBlock(ctx: Ctx, box: GameBox, service: string): Html {
731 const day = metricsSeries(ctx.app.db, box, service, "24h");
732 const joins = playerEvents(ctx.app.db, box.id, service, 8);
733 const errors = recentErrors(ctx.app.db, box.id, service, 5);
726 const day = defaultKind().metrics.series(ctx.app.db, box, service, "24h");
727 const joins = defaultKind().metrics.playerEvents(ctx.app.db, box.id, service, 8);
728 const errors = defaultKind().metrics.recentErrors(ctx.app.db, box.id, service, 5);
734729 if (day.length === 0 && joins.length === 0 && errors.length === 0) return html``;
735730 const line = (label: string, pick: (p: Point) => number | null, unit: string): Html => {
736731 const now = lastOf(day, pick);
@@ -1290,7 +1285,7 @@ export async function gameSleepSubmit(ctx: Ctx): Promise<Response> {
12901285
12911286 /** A player's head and name, with a Bedrock badge for a Floodgate player. */
12921287 const who = (name: string, uuid: string): Html =>
1293 html`<img src="/games/head/${uuid === "" || isBedrock(name) ? "none" : uuid}" alt="" width="20" height="20" loading="lazy" /> ${name}${isBedrock(name) ? html` ${badge("Bedrock", { tone: "default" })}` : null}`;
1288 html`<img src="/games/head/${uuid === "" || defaultKind().people.isBedrock(name) ? "none" : uuid}" alt="" width="20" height="20" loading="lazy" /> ${name}${defaultKind().people.isBedrock(name) ? html` ${badge("Bedrock", { tone: "default" })}` : null}`;
12941289
12951290 /** One button that sends a people change for `player` on the service's form. */
12961291 const peopleButton = (base: string, op: PeopleOp, player: string, label: string): Html =>
@@ -1302,8 +1297,8 @@ const peopleButton = (base: string, op: PeopleOp, player: string, label: string)
13021297 * is seen by nobody without a grant.
13031298 */
13041299 function peopleBlock(ctx: Ctx, box: GameBox, service: string, act: boolean): Html {
1305 const { online, lists } = peopleOf(ctx.app.db, box.id, service);
1306 const events = eventsOf(ctx.app.db, box.id, service, 30);
1300 const { online, lists } = defaultKind().people.peopleOf(ctx.app.db, box.id, service);
1301 const events = defaultKind().people.eventsOf(ctx.app.db, box.id, service, 30);
13071302 const base = `/games/${box.name}/${service}`;
13081303 const isOp = (n: string) => lists.ops.some((o) => o.name === n);
13091304 const listed = (n: string) => lists.whitelist.some((w) => w.name === n);
@@ -1327,13 +1322,13 @@ function peopleBlock(ctx: Ctx, box: GameBox, service: string, act: boolean): Htm
13271322 ${peopleButton(base, lists.whitelistOn ? "whitelist-off" : "whitelist-on", "", lists.whitelistOn ? "Let anyone join" : "Only listed players may join")}`
13281323 : null}
13291324 <p class="muted small">${lists.whitelistOn ? "Only listed players may join" : "Anyone may join"} · ${lists.whitelist.length} listed · ${lists.ops.length} operators · ${lists.bans.length} banned</p>
1330 ${openDoorWords(lists.whitelistOn) === undefined ? null : html`<p class="muted small">${openDoorWords(lists.whitelistOn)}</p>`}
1325 ${defaultKind().people.openDoorWords(lists.whitelistOn) === undefined ? null : html`<p class="muted small">${defaultKind().people.openDoorWords(lists.whitelistOn)}</p>`}
13311326 ${lists.bans.length === 0 ? null : html`<h3>Banned</h3>${rowList(lists.bans.map((b) => row({ title: who(b.name, b.uuid), meta: html`${b.reason}`, ...(act ? { after: peopleButton(base, "pardon", b.name, PEOPLE_BUTTON["pardon"]!) } : {}) })))}`}
13321327 ${lists.ops.length === 0 ? null : html`<h3>Operators</h3>${rowList(lists.ops.map((o) => row({ title: who(o.name, o.uuid), meta: html`level ${o.level}`, ...(act ? { after: peopleButton(base, "deop", o.name, PEOPLE_BUTTON["deop"]!) } : {}) })))}`}
13331328 ${lists.whitelistOn && lists.whitelist.length > 0 ? html`<h3>Allowed to join</h3>${rowList(lists.whitelist.map((w) => row({ title: who(w.name, w.uuid), ...(act ? { after: peopleButton(base, "whitelist-remove", w.name, PEOPLE_BUTTON["whitelist-remove"]!) } : {}) })))}` : null}
13341329 ${events.length === 0
13351330 ? null
1336 : html`<h3>Latest</h3>${rowList(events.map((e) => row({ title: e.kind === "chat" ? html`<span class="mono">&lt;${e.player}&gt;</span> ${e.text}` : eventWords(e, service), meta: time(e.at) })))}`}
1331 : html`<h3>Latest</h3>${rowList(events.map((e) => row({ title: e.kind === "chat" ? html`<span class="mono">&lt;${e.player}&gt;</span> ${e.text}` : defaultKind().people.eventWords(e, service), meta: time(e.at) })))}`}
13371332 </section>`;
13381333 }
13391334
@@ -1343,12 +1338,12 @@ export async function gamePeopleSubmit(ctx: Ctx): Promise<Response> {
13431338 if (got instanceof Response) return got;
13441339 const op = field(got.form, "op");
13451340 const player = field(got.form, "player").trim();
1346 const queued = await queuePeople(ctx.app, got.box, got.service, op, player, ctx.auth.user, field(got.form, "to"));
1347 const undo = UNDO[op as PeopleOp];
1341 const queued = await defaultKind().people.queuePeople(ctx.app, got.box, got.service, op, player, ctx.auth.user, field(got.form, "to"));
1342 const undo = defaultKind().people.undo[op as PeopleOp];
13481343 return flashTo(
13491344 ctx,
13501345 `/games/${got.box.name}/${got.service}`,
1351 queued.ok ? { message: `Asked: ${peopleWords(JSON.stringify({ op, player, server: field(got.form, "to") }))}. It shows on the server until the server answers.${undo === undefined ? "" : " Its opposite undoes it."}` } : { tone: "danger", message: queued.error },
1346 queued.ok ? { message: `Asked: ${defaultKind().people.peopleWords(JSON.stringify({ op, player, server: field(got.form, "to") }))}. It shows on the server until the server answers.${undo === undefined ? "" : " Its opposite undoes it."}` } : { tone: "danger", message: queued.error },
13521347 );
13531348 }
13541349
@@ -1356,7 +1351,7 @@ export async function gamePeopleSubmit(ctx: Ctx): Promise<Response> {
13561351 // only, and only for a player the forge has seen on a server this person sees; anyone else's is the default.
13571352 export function gameHead(ctx: Ctx): Promise<Response> | Response {
13581353 const uuid = (ctx.params.uuid ?? "").toLowerCase();
1359 if (!knowsPlayer(ctx.app.db, ctx.auth.user, uuid)) return defaultHeadResponse();
1354 if (!defaultKind().people.knowsPlayer(ctx.app.db, ctx.auth.user, uuid)) return defaultHeadResponse();
13601355 return headResponse(ctx.app, uuid);
13611356 }
13621357
src/web/pages/games_spark.ts +7 −7
@@ -1,5 +1,5 @@
11 /**
2 * The spark profile routes (`games/spark.ts`): a box's server posts a profile to its secret
2 * The spark profile routes (the kind's metrics probe): a box's server posts a profile to its secret
33 * address, a person with a grant on the box reads it back, an owner makes a new address (shown
44 * once).
55 */
@@ -7,34 +7,34 @@ import { publicOrigin } from "../../core/public_origin.ts";
77 import { BODY_CAPS, readBounded } from "../../http/limits.ts";
88 import type { Ctx } from "../../http/context.ts";
99 import { seesBox } from "../../games/store.ts";
10 import { boxOfSparkSecret, keepProfile, newSparkSecret, profileOf, sparkBase } from "../../games/spark.ts";
1110 import { flashTo } from "../layout.ts";
1211 import { readForm } from "../form.ts";
1312 import { boxOf } from "./games.ts";
13 import { defaultKind } from "../../kinds/index.ts";
1414
1515 const plain = (text: string, status: number): Response => new Response(text, { status, headers: { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" } });
1616
1717 // POST /games/@spark/:secret/post: the box's server posts a profile; 201 and `Location: <key>`, no
1818 // body.
1919 export async function gameSparkPost(ctx: Ctx): Promise<Response> {
20 const boxId = boxOfSparkSecret(ctx.app.db, ctx.params.secret ?? "");
20 const boxId = defaultKind().metrics.profiles.boxOfSecret(ctx.app.db, ctx.params.secret ?? "");
2121 if (boxId === undefined) return plain("this address is not a box's upload address", 403);
2222 const bytes = await readBounded(ctx.request, BODY_CAPS.gameSpark.bytes);
2323 if (bytes === "too_large") return plain("a profile is at most 8 MiB", 413);
2424 const type = (ctx.request.headers.get("content-type") ?? "").trim().toLowerCase();
25 const kept = keepProfile(ctx.app.db, boxId, type, bytes);
25 const kept = defaultKind().metrics.profiles.keep(ctx.app.db, boxId, type, bytes);
2626 if (!kept.ok) return plain(kept.error, 400);
2727 return new Response(null, { status: 201, headers: { location: kept.value, "cache-control": "no-store" } });
2828 }
2929
3030 const profileResponse = (ctx: Ctx, boxId: string): Response => {
31 const got = profileOf(ctx.app.db, boxId, ctx.params.key ?? "");
31 const got = defaultKind().metrics.profiles.profileOf(ctx.app.db, boxId, ctx.params.key ?? "");
3232 return got === undefined ? plain("not found", 404) : new Response(got.body, { headers: { "content-type": got.type, "content-disposition": "attachment", "cache-control": "private, no-store" } });
3333 };
3434
3535 // GET /games/@spark/:secret/:key: the profile, for a session with a grant on the box.
3636 export function gameSparkRead(ctx: Ctx): Response {
37 const boxId = boxOfSparkSecret(ctx.app.db, ctx.params.secret ?? "");
37 const boxId = defaultKind().metrics.profiles.boxOfSecret(ctx.app.db, ctx.params.secret ?? "");
3838 if (boxId === undefined) return plain("refused", 403);
3939 if (!seesBox(ctx.app.db, ctx.auth.user, boxId)) return plain("refused: sign in as someone with a grant on this box", 403);
4040 return profileResponse(ctx, boxId);
@@ -54,6 +54,6 @@ export async function gameSparkLink(ctx: Ctx): Promise<Response> {
5454 if (got instanceof Response) return got;
5555 const form = await readForm(ctx, "rw");
5656 if (form instanceof Response) return form;
57 const base = sparkBase(publicOrigin(ctx.app.config.url, `http://localhost:${String(ctx.app.config.port)}`), newSparkSecret(ctx.app.db, got.box.id));
57 const base = defaultKind().metrics.profiles.base(publicOrigin(ctx.app.config.url, `http://localhost:${String(ctx.app.config.port)}`), defaultKind().metrics.profiles.newSecret(ctx.app.db, got.box.id));
5858 return flashTo(ctx, `/games/${got.box.name}#spark`, { message: "Set this as spark's bytebin-url on the server. It allows uploads only; this is the only time it is shown, and the last address no longer works.", code: base });
5959 }
src/web/pages/games_spark_view.ts +14 −15
@@ -1,17 +1,16 @@
11 /**
22 * One stored spark profile as a page (#18208): per thread, its time sampled, a flame graph (SVG
3 * drawn here from `flameRects`, no script) and the call tree as text. The same tree, in the same
4 * words, is the terminal's (`tui/screens/game_spark_view.ts`).
3 * drawn here from `defaultKind().metrics.profiles.view.flameRects`, no script) and the call tree as
4 * text. The same tree, in the same words, is the terminal's (`tui/screens/game_spark_view.ts`).
55 */
66 import type { Ctx } from "../../http/context.ts";
7 import { READ_UNPACKED, decodeSparkProfile, type SparkSummary } from "../../games/spark_profile.ts";
8 import { profileOf } from "../../games/spark.ts";
9 import { FLAME_WIDTH, flameRects, heaviest, millis, sparkHeadLines, summarySections, treeLines } from "../../games/spark_view.ts";
107 import { notFoundPage, pageHead } from "../chrome.ts";
118 import { html, type Html } from "../html.ts";
129 import { page } from "../layout.ts";
1310 import { row, rowList } from "../ui.ts";
1411 import { boxOf } from "./games.ts";
12 import { defaultKind } from "../../kinds/index.ts";
13 import type { SparkSummary } from "../../kinds/kind.ts";
1514
1615 const SAMPLER = "application/x-spark-sampler";
1716 const ROW = 18;
@@ -22,13 +21,13 @@ const CHAR = 6;
2221 * A thread's flame graph: boxes by time, the name inside when it fits, the whole in the tooltip.
2322 */
2423 function flameSvg(thread: SparkSummary["threads"][number]): Html {
25 const rects = flameRects(thread.tree, thread.ms);
24 const rects = defaultKind().metrics.profiles.view.flameRects(thread.tree, thread.ms);
2625 const depth = rects.reduce((m, r) => Math.max(m, r.depth), 0) + 1;
27 return html`<svg viewBox="0 0 ${String(FLAME_WIDTH)} ${String(depth * ROW)}" width="100%" role="img" aria-label="Flame graph of ${thread.name || "the thread"}" focusable="false">
26 return html`<svg viewBox="0 0 ${String(defaultKind().metrics.profiles.view.FLAME_WIDTH)} ${String(depth * ROW)}" width="100%" role="img" aria-label="Flame graph of ${thread.name || "the thread"}" focusable="false">
2827 ${rects.map((r) => {
2928 const fit = Math.floor((r.w - 4) / CHAR);
3029 const short = r.name.length <= fit ? r.name : fit > 3 ? `${r.name.slice(0, fit - 1)}…` : "";
31 return html`<g><title>${r.name}: ${millis(r.ms)} (${(r.share * 100).toFixed(1)}% of the thread)</title><rect x="${String(r.x)}" y="${String(r.depth * ROW)}" width="${String(r.w)}" height="${String(ROW - 1)}" fill="currentColor" fill-opacity="${String(Math.max(0.12, 0.4 - r.depth * 0.03))}"/>${short === "" ? null : html`<text x="${String(r.x + 3)}" y="${String(r.depth * ROW + 13)}" font-size="11" fill="currentColor">${short}</text>`}</g>`;
30 return html`<g><title>${r.name}: ${defaultKind().metrics.profiles.view.millis(r.ms)} (${(r.share * 100).toFixed(1)}% of the thread)</title><rect x="${String(r.x)}" y="${String(r.depth * ROW)}" width="${String(r.w)}" height="${String(ROW - 1)}" fill="currentColor" fill-opacity="${String(Math.max(0.12, 0.4 - r.depth * 0.03))}"/>${short === "" ? null : html`<text x="${String(r.x + 3)}" y="${String(r.depth * ROW + 13)}" font-size="11" fill="currentColor">${short}</text>`}</g>`;
3231 })}
3332 </svg>`;
3433 }
@@ -40,22 +39,22 @@ export function gameSparkView(ctx: Ctx): Response {
4039 const got = boxOf(ctx, "viewer");
4140 if (got instanceof Response) return got;
4241 const key = ctx.params.key ?? "";
43 const stored = profileOf(ctx.app.db, got.box.id, key);
42 const stored = defaultKind().metrics.profiles.profileOf(ctx.app.db, got.box.id, key);
4443 if (stored === undefined) return notFoundPage(ctx);
45 const read = stored.type === SAMPLER ? decodeSparkProfile(stored.body, READ_UNPACKED) : undefined;
44 const read = stored.type === SAMPLER ? defaultKind().metrics.profiles.decode(stored.body, defaultKind().metrics.profiles.readLimit) : undefined;
4645 const href = `/games/${got.box.name}/@spark/${key}`;
47 const shown = read !== undefined && read.ok ? heaviest(read.summary.threads) : undefined;
46 const shown = read !== undefined && read.ok ? defaultKind().metrics.profiles.view.heaviest(read.summary.threads) : undefined;
4847 const body: Html = read === undefined || !read.ok
4948 ? html`<p role="alert">The forge draws a sampler profile only, and this one is not a readable one: download it.</p><p><a href="${href}">Download it</a> and open it in spark's own viewer.</p>`
50 : html`<p class="muted small">${sparkHeadLines(read.summary)[0]}. Times are milliseconds sampled, shares are of the thread; trees keep the heaviest calls. <a href="${href}">Download the profile</a>.</p>
49 : html`<p class="muted small">${defaultKind().metrics.profiles.view.sparkHeadLines(read.summary)[0]}. Times are milliseconds sampled, shares are of the thread; trees keep the defaultKind().metrics.profiles.view.heaviest calls. <a href="${href}">Download the profile</a>.</p>
5150 ${read.summary.threads.length === 0 ? html`<p class="muted small">This profile holds no threads.</p>` : null}
5251 ${(shown?.drawn ?? []).map((t, i) => html`<section class="settings-block">
53 <h2>${t.name || "(unnamed thread)"} <span class="muted small">${millis(t.ms)} sampled</span></h2>
52 <h2>${t.name || "(unnamed thread)"} <span class="muted small">${defaultKind().metrics.profiles.view.millis(t.ms)} sampled</span></h2>
5453 ${t.tree.length === 0 ? html`<p class="muted small">Nothing was sampled in this thread.</p>` : html`${flameSvg(t)}
55 <details ${i === 0 ? html`open` : null}><summary>Call tree</summary><pre>${treeLines(t.tree, t.ms).join("\n")}</pre></details>`}
54 <details ${i === 0 ? html`open` : null}><summary>Call tree</summary><pre>${defaultKind().metrics.profiles.view.treeLines(t.tree, t.ms).join("\n")}</pre></details>`}
5655 </section>`)}
5756 ${shown?.note ? html`<p class="muted small">${shown.note} <a href="${href}">Download it</a>.</p>` : null}
58 ${summarySections(read.summary).map((x) => html`<section class="settings-block" id="${x.id}"><h2>${x.title}</h2>${x.rows.length === 0 ? html`<p class="muted small">${x.empty}</p>` : rowList(x.rows.map((r) => row({ ...(r.id === undefined ? {} : { id: r.id }), title: r.title, facts: r.facts })))}</section>`)}`;
57 ${defaultKind().metrics.profiles.view.summarySections(read.summary).map((x) => html`<section class="settings-block" id="${x.id}"><h2>${x.title}</h2>${x.rows.length === 0 ? html`<p class="muted small">${x.empty}</p>` : rowList(x.rows.map((r) => row({ ...(r.id === undefined ? {} : { id: r.id }), title: r.title, facts: r.facts })))}</section>`)}`;
5958 return page({
6059 ctx,
6160 title: `Games · ${got.box.name} · profile`,
src/web/pages/games_topology.ts +5 −6
@@ -7,14 +7,13 @@
77 */
88
99 import type { Ctx } from "../../http/context.ts";
10 import { metricsSeries } from "../../games/metrics.ts";
11 import { isBedrock, networkOf, peopleOf } from "../../games/people.ts";
1210 import { isGameServer, proxyOf } from "../../games/sleep.ts";
1311 import { drawsOperator } from "../../games/game_may.ts";
1412 import { principalOf } from "../../core/principal.ts";
1513 import { servicesOf, type GameBox, type GameService } from "../../games/store.ts";
1614 import { html, type Html } from "../html.ts";
1715 import { btn } from "../ui.ts";
16 import { defaultKind } from "../../kinds/index.ts";
1817
1918 export const TOPOLOGY_CSS = `/* ---- the network (#17284 G5): the proxy, a line down, the servers under it ---- */
2019 .net { display: grid; gap: 16px; justify-items: center; }
@@ -70,11 +69,11 @@ export function topologyBlock(ctx: Ctx, box: GameBox, compose: string | undefine
7069 if (compose === undefined || proxy === undefined) return html``;
7170 const seen = servicesOf(ctx.app.db, box.id);
7271 const servers = visible.filter((n) => isGameServer(compose, n));
73 const network = networkOf(ctx.app.db, box.id);
72 const network = defaultKind().people.networkOf(ctx.app.db, box.id);
7473 // Each player's UUID from the server they are on (its `list uuids`), for their head.
7574 const uuidOf = new Map<string, string>();
7675 const onServer = (n: string): string[] => {
77 const { online } = peopleOf(ctx.app.db, box.id, n);
76 const { online } = defaultKind().people.peopleOf(ctx.app.db, box.id, n);
7877 for (const p of online) uuidOf.set(p.name, p.uuid);
7978 return network[n] ?? online.map((p) => p.name);
8079 };
@@ -83,7 +82,7 @@ export function topologyBlock(ctx: Ctx, box: GameBox, compose: string | undefine
8382 const proxyState = netState(seen.find((s) => s.name === proxy));
8483 const head = (server: string, name: string, act: boolean): Html => {
8584 const uuid = uuidOf.get(name) ?? "";
86 const face = html`<img src="/games/head/${uuid === "" || isBedrock(name) ? "none" : uuid}" alt="" width="20" height="20" loading="lazy" />`;
85 const face = html`<img src="/games/head/${uuid === "" || defaultKind().people.isBedrock(name) ? "none" : uuid}" alt="" width="20" height="20" loading="lazy" />`;
8786 // Only to a server this person operates too: the move's own rule (`queuePeople`).
8887 const targets = servers.filter((t) => t !== server && netState(seen.find((s) => s.name === t)) !== "stopped" && drawsOperator(ctx.app.db, principalOf(ctx.auth), box.id, t));
8988 if (!act || targets.length === 0) return html`<span class="net-head">${face} ${name}</span>`;
@@ -106,7 +105,7 @@ export function topologyBlock(ctx: Ctx, box: GameBox, compose: string | undefine
106105 ${servers.map((n) => {
107106 const s = seen.find((x) => x.name === n);
108107 const state = netState(s);
109 const tps = metricsSeries(ctx.app.db, box, n, "1h").findLast((p) => p.tps !== null)?.tps ?? null;
108 const tps = defaultKind().metrics.series(ctx.app.db, box, n, "1h").findLast((p) => p.tps !== null)?.tps ?? null;
110109 const list = players.get(n) ?? [];
111110 const act = drawsOperator(ctx.app.db, principalOf(ctx.auth), box.id, n);
112111 return html`<div class="net-server" data-state="${state}">
src/web/pages/people.ts +5 −5
@@ -21,7 +21,7 @@ import { everyGrant, forgePath, type Grant } from "../../core/grants_view.ts";
2121 import { isRemovable } from "../../core/grant_removal.ts";
2222 import { listAccounts as readAccounts, originOf, type AccountRow } from "../../core/accounts.ts";
2323 import { soleOwnedByPerson } from "../../core/orgs.ts";
24 import { minecraftByUser, type Identity } from "../../core/proven_identities.ts";
24 import { gameNamesByUser, type Identity } from "../../core/proven_identities.ts";
2525 import { peopleByActivity, wordFilter, type PersonRow } from "../../core/people_rows.ts";
2626 import { roleLimits } from "../../core/roles.ts";
2727 import { getUserByName, type User } from "../../core/users.ts";
@@ -62,7 +62,7 @@ const rowAt = (username: string): string => `/settings/people/row/${encodeURICom
6262 interface Facts {
6363 readonly accounts: ReadonlyMap<string, AccountRow>;
6464 readonly made: ReadonlyMap<string, string[]>;
65 readonly minecraft: ReadonlyMap<string, Identity[]>;
65 readonly gameNames: ReadonlyMap<string, Identity[]>;
6666 readonly sole: ReadonlyMap<string, string[]>;
6767 readonly grants: ReadonlyMap<string, Grant[]>;
6868 }
@@ -77,7 +77,7 @@ function readFacts(ctx: Ctx, name = ""): Facts {
7777 return {
7878 accounts: new Map(list.map((a) => [a.username, a])),
7979 made: appsMade(ctx, name),
80 minecraft: minecraftByUser(db, one),
80 gameNames: gameNamesByUser(db, one),
8181 sole: soleOwnedByPerson(db),
8282 grants,
8383 };
@@ -92,7 +92,7 @@ function proofFacts(a: AccountRow, mc: readonly Identity[]): { label: string; va
9292 const out: { label: string; value: Html | string }[] =
9393 proven.length === 0
9494 ? [{ label: "Proof", value: `not proved${a.address === null ? "" : `: ${a.address} was never confirmed`}${a.signsInThrough === null ? "" : ` · signs in through ${a.signsInThrough}`}` }]
95 : proven.map((i) => ({ label: i.kind === "email" ? "Email" : "Minecraft", value: html`${i.name} proved by ${by}${i.since === null ? "" : html` ${time(i.since)}`}` }));
95 : proven.map((i) => ({ label: i.kind[0]!.toUpperCase() + i.kind.slice(1), value: html`${i.name} proved by ${by}${i.since === null ? "" : html` ${time(i.since)}`}` }));
9696 if (proven.length > 0 && a.signsInThrough === null && originOf(a) !== "") out.push({ label: "Came by", value: originOf(a) });
9797 return out;
9898 }
@@ -153,7 +153,7 @@ function personRow(r: PersonRow, f: Facts): Html {
153153 meta: html`${r.lastSeen === null ? "never seen" : html`seen ${time(r.lastSeen)}`} · ${apps.length === 0 ? "No apps yet" : apps.length === 1 ? "1 app" : `${apps.length} apps`}${
154154 apps.length === 0 ? "" : html`: ${apps.slice(0, 3).flatMap((n, i) => (i === 0 ? [html`<a href="/${r.username}/${n}">${n}</a>`] : [", ", html`<a href="/${r.username}/${n}">${n}</a>`]))}${apps.length > 3 ? ` and ${apps.length - 3} more` : ""}`
155155 }${sole.length === 0 ? "" : ` · only owner of ${sole.join(", ")}`}`,
156 ...(a === undefined ? {} : { facts: proofFacts(a, a === undefined ? [] : (f.minecraft.get(a.id) ?? [])) }),
156 ...(a === undefined ? {} : { facts: proofFacts(a, a === undefined ? [] : (f.gameNames.get(a.id) ?? [])) }),
157157 ...(owner || crew ? {} : { after: btn("Manage", { href: `/settings/accounts/${encodeURIComponent(r.username)}`, size: "sm", variant: "ghost", label: `Manage ${r.username}` }) }),
158158 children,
159159 });
test/game-chat.test.ts +1 −1
@@ -286,7 +286,7 @@ describe("on a forge", () => {
286286 };
287287 /**
288288 * The tellraws queued since the last look: to whom, on which server, the text and its colour.
289 * The whitelist changes a link queues (`games/reach.ts`) are not chat's.
289 * The whitelist changes a link queues (`kinds/minecraft/reach.ts`) are not chat's.
290290 */
291291 const told = (): { service: string; to: string; text: string; color: string }[] => {
292292 const rows = app.db
test/game-door-lock-on-leave.test.ts +1 −1
@@ -10,7 +10,7 @@ import { join } from "node:path";
1010 import { createApp, type App } from "../src/app.ts";
1111 import { createSession } from "../src/core/sessions.ts";
1212 import { createUser, type User } from "../src/core/users.ts";
13 import { recordMetrics } from "../src/games/metrics.ts";
13 import { recordMetrics } from "../src/kinds/minecraft/metrics.ts";
1414 import { boxNamed, createGameBox, grant, type GameBox } from "../src/games/store.ts";
1515 import { doorOf, locksOnLeave, openWindow, setLocksOnLeave } from "../src/games/write_window.ts";
1616 import { forgeHttp } from "../src/http/server.ts";
test/game-findings.test.ts +2 −2
@@ -12,8 +12,8 @@ import { join } from "node:path";
1212 import { createApp, type App } from "../src/app.ts";
1313 import { chatCommand } from "../src/games/chat.ts";
1414 import { findingsOf } from "../src/games/findings.ts";
15 import { parseLogLine, recordMetrics } from "../src/games/metrics.ts";
16 import { eventsOf, eventWords, keptPeople } from "../src/games/people.ts";
15 import { parseLogLine, recordMetrics } from "../src/kinds/minecraft/metrics.ts";
16 import { eventsOf, eventWords, keptPeople } from "../src/kinds/minecraft/people.ts";
1717 import { AGENT_SH } from "../src/games/boot.ts";
1818 import { boxNamed, commandOf, createGameBox, logsOf, queueCommand, recordSync, type GameBox } from "../src/games/store.ts";
1919 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
test/game-lend.test.ts +1 −1
@@ -16,7 +16,7 @@ import { createToken } from "../src/core/tokens.ts";
1616 import { createUser, getUserByName, type User } from "../src/core/users.ts";
1717 import { lendAnswer, lentRunnerOf, setLend } from "../src/games/lend.ts";
1818 import { lendAuthors } from "../src/games/lend_fit.ts";
19 import { recordMetrics } from "../src/games/metrics.ts";
19 import { recordMetrics } from "../src/kinds/minecraft/metrics.ts";
2020 import { boxNamed, createGameBox, grant, recordSync, type GameBox } from "../src/games/store.ts";
2121 import { setLoadSource } from "../src/checks/lent_yield.ts";
2222 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
test/game-lent-proof.test.ts +1 −1
@@ -18,7 +18,7 @@ import { createToken } from "../src/core/tokens.ts";
1818 import { createUser, getUserByName } from "../src/core/users.ts";
1919 import { lentRunnerOf, setLend } from "../src/games/lend.ts";
2020 import { startProof, lentLineOf, proofLine, newestProof } from "../src/games/lent_proof.ts";
21 import { recordMetrics } from "../src/games/metrics.ts";
21 import { recordMetrics } from "../src/kinds/minecraft/metrics.ts";
2222 import { boxNamed, createGameBox, type GameBox } from "../src/games/store.ts";
2323 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
2424 import { runFacts } from "../src/runs/run_facts.ts";
test/game-metrics.test.ts +2 −2
@@ -22,8 +22,8 @@ import {
2222 playerEvents,
2323 recordMetrics,
2424 stats,
25 } from "../src/games/metrics.ts";
26 import { ANSWER_MAX, compactMetrics, compactSeries } from "../src/games/metrics_answer.ts";
25 } from "../src/kinds/minecraft/metrics.ts";
26 import { ANSWER_MAX, compactMetrics, compactSeries } from "../src/kinds/minecraft/metrics_answer.ts";
2727 import { boxNamed, createGameBox } from "../src/games/store.ts";
2828 import { createToken } from "../src/core/tokens.ts";
2929 import { tool } from "../src/http/mcp/tools/games.ts";
test/game-mods.test.ts +1 −1
@@ -15,7 +15,7 @@ import { createToken } from "../src/core/tokens.ts";
1515 import { createUser, getUserByName, type User } from "../src/core/users.ts";
1616 import { readCompose, readRepoFile, serviceEnv } from "../src/games/compose.ts";
1717 import { configMounts } from "../src/games/plugin_config.ts";
18 import { boxOfSparkSecret } from "../src/games/spark.ts";
18 import { boxOfSparkSecret } from "../src/kinds/minecraft/spark.ts";
1919 import { search, searchPacks, targetOf } from "../src/games/modrinth.ts";
2020 import { noteSet } from "../src/games/set_verdict.ts";
2121 import { commitPlan, lockPath, modsOf, packUpdateOf, planInstall, planPack, planPackUpdate, planRemove, planUpdate, updatesOf } from "../src/games/mods.ts";
test/game-people.test.ts +2 −2
@@ -15,8 +15,8 @@ import { createSession } from "../src/core/sessions.ts";
1515 import { createToken } from "../src/core/tokens.ts";
1616 import { createUser, type User } from "../src/core/users.ts";
1717 import { DEFAULT_HEAD, FETCHES_MAX, HEAD_KEPT_MS, headResponse, MISS_MS } from "../src/games/heads.ts";
18 import { parseList, parseLogLine } from "../src/games/metrics.ts";
19 import { eventsOf, keptPeople, knowsPlayer, networkOf, parseGlist, peopleOf, peopleWords, queuePeople } from "../src/games/people.ts";
18 import { parseList, parseLogLine } from "../src/kinds/minecraft/metrics.ts";
19 import { eventsOf, keptPeople, knowsPlayer, networkOf, parseGlist, peopleOf, peopleWords, queuePeople } from "../src/kinds/minecraft/people.ts";
2020 import { boxNamed, commandOf, createGameBox, grant, recentCommands } from "../src/games/store.ts";
2121 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
2222 import { quietLogs } from "./helpers/globals.ts";
test/game-player-events.test.ts +2 −2
@@ -12,8 +12,8 @@ import { createApp, type App } from "../src/app.ts";
1212 import { createSession } from "../src/core/sessions.ts";
1313 import { createToken } from "../src/core/tokens.ts";
1414 import { createUser, type User } from "../src/core/users.ts";
15 import { eventsOf } from "../src/games/people.ts";
16 import { findingsOf, proxyFacts, recordProxyEvents, refusedLines, tellRefused } from "../src/games/player_events.ts";
15 import { eventsOf } from "../src/kinds/minecraft/people.ts";
16 import { findingsOf, proxyFacts, recordProxyEvents, refusedLines, tellRefused } from "../src/kinds/minecraft/player_events.ts";
1717 import { waitFor } from "./helpers/poll.ts";
1818 import { boxNamed, createGameBox, grant, type GameBox } from "../src/games/store.ts";
1919 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
test/game-player-set.test.ts +1 −1
@@ -14,7 +14,7 @@ import { getRepo } from "../src/core/repos.ts";
1414 import { createUser, getUserByName, type User } from "../src/core/users.ts";
1515 import { clientProjects, playerSide, type Locked, type Project } from "../src/games/modrinth.ts";
1616 import { modsOf } from "../src/games/mods.ts";
17 import { needLines, playerMods } from "../src/games/player_events.ts";
17 import { needLines, playerMods } from "../src/kinds/minecraft/player_events.ts";
1818 import { boxNamed, createGameBox, type GameBox } from "../src/games/store.ts";
1919 import { quietLogs } from "./helpers/globals.ts";
2020
test/game-reach.test.ts +1 −1
@@ -10,7 +10,7 @@ import { join } from "node:path";
1010 import { createApp, type App } from "../src/app.ts";
1111 import { createUser, type User } from "../src/core/users.ts";
1212 import { gameChat } from "../src/games/chat.ts";
13 import { checksAccounts, followGrants, OFFLINE_WORDS, openDoorWords, whitelistPlan, whoMayReach } from "../src/games/reach.ts";
13 import { checksAccounts, followGrants, OFFLINE_WORDS, openDoorWords, whitelistPlan, whoMayReach } from "../src/kinds/minecraft/reach.ts";
1414 import { boxNamed, createGameBox, grant } from "../src/games/store.ts";
1515 import { quietLogs } from "./helpers/globals.ts";
1616
test/game-spare.test.ts +1 −1
@@ -9,7 +9,7 @@ import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
99 import { tmpdir } from "node:os";
1010 import { join } from "node:path";
1111 import { checkCoreHours } from "../src/core/ledger_cpu.ts";
12 import { recordMetrics, spareSamples } from "../src/games/metrics.ts";
12 import { recordMetrics, spareSamples } from "../src/kinds/minecraft/metrics.ts";
1313 import type { GameBox } from "../src/games/store.ts";
1414 import { spareRow } from "../src/games/spare_row.ts";
1515 import { MIN_MINUTES, spareOf, spareParts, vcpusOf, type SpareSample, type SpareService } from "../src/games/spare.ts";
test/game-spark.test.ts +2 −2
@@ -10,8 +10,8 @@ import { createApp, type App } from "../src/app.ts";
1010 import { createSession } from "../src/core/sessions.ts";
1111 import { createUser, getUserByName } from "../src/core/users.ts";
1212 import { gzipSync } from "node:zlib";
13 import { decodeSparkProfile } from "../src/games/spark_profile.ts";
14 import { SPARK_KEEP_COUNT, SPARK_KEEP_DAYS, keepProfile, newSparkSecret, profilesOf } from "../src/games/spark.ts";
13 import { decodeSparkProfile } from "../src/kinds/minecraft/spark_profile.ts";
14 import { SPARK_KEEP_COUNT, SPARK_KEEP_DAYS, keepProfile, newSparkSecret, profilesOf } from "../src/kinds/minecraft/spark.ts";
1515 import { boxNamed, createGameBox, grant, type GameBox } from "../src/games/store.ts";
1616 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
1717 import { BODY_CAPS } from "../src/kernel/body_caps.ts";
test/game-topology.test.ts +1 −1
@@ -13,7 +13,7 @@ import { commitToBranch, createRepo } from "../src/actions/repos.ts";
1313 import { createSession } from "../src/core/sessions.ts";
1414 import { createToken } from "../src/core/tokens.ts";
1515 import { createUser, type User } from "../src/core/users.ts";
16 import { queuePeople } from "../src/games/people.ts";
16 import { queuePeople } from "../src/kinds/minecraft/people.ts";
1717 import { proxyOf, WAKER } from "../src/games/sleep.ts";
1818 import { createGameBox, grant, boxNamed, recentCommands } from "../src/games/store.ts";
1919 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
test/game-when-quiet.test.ts +1 −1
@@ -11,7 +11,7 @@ import { join } from "node:path";
1111 import { createApp, type App } from "../src/app.ts";
1212 import { createUser, type User } from "../src/core/users.ts";
1313 import { boxNamed, createGameBox, type GameBox } from "../src/games/store.ts";
14 import { recordMetrics } from "../src/games/metrics.ts";
14 import { recordMetrics } from "../src/kinds/minecraft/metrics.ts";
1515 import { applyWhenQuiet, FRESH_MS, heldOf, holdUntilQuiet, isQuiet, QUIET_MINUTES } from "../src/games/when_quiet.ts";
1616
1717 let dir = "";
test/games-spark-finding.test.ts +3 −3
@@ -12,9 +12,9 @@ import { gzipSync } from "node:zlib";
1212 import { createApp, type App } from "../src/app.ts";
1313 import { createSession } from "../src/core/sessions.ts";
1414 import { createUser, getUserByName } from "../src/core/users.ts";
15 import { keepProfile } from "../src/games/spark.ts";
16 import { findingHref, sparkFindingsOf } from "../src/games/spark_finding.ts";
17 import { tickAnchor } from "../src/games/spark_view.ts";
15 import { keepProfile } from "../src/kinds/minecraft/spark.ts";
16 import { findingHref, sparkFindingsOf } from "../src/kinds/minecraft/spark_finding.ts";
17 import { tickAnchor } from "../src/kinds/minecraft/spark_view.ts";
1818 import { createGameBox, boxNamed } from "../src/games/store.ts";
1919 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
2020 import { quietLogs } from "./helpers/globals.ts";
test/games-spark-profile.test.ts +1 −1
@@ -1,7 +1,7 @@
11 import { expect, test } from "bun:test";
22 import { gzipSync } from "node:zlib";
33 import { bytes, entry, key, packedDoubles, sparkFixture, text, varint } from "./helpers/spark_fixture.ts";
4 import { decodeSparkProfile, MAX_PACKED, SLOWEST } from "../src/games/spark_profile.ts";
4 import { decodeSparkProfile, MAX_PACKED, SLOWEST } from "../src/kinds/minecraft/spark_profile.ts";
55
66 test("a data version 1 profile (nested nodes, one time each) decodes to its summary", () => {
77 const r = decodeSparkProfile(sparkFixture());
test/games-spark-view.test.ts +5 −5
@@ -11,9 +11,9 @@ import { gzipSync } from "node:zlib";
1111 import { createApp, type App } from "../src/app.ts";
1212 import { createSession } from "../src/core/sessions.ts";
1313 import { createUser, getUserByName } from "../src/core/users.ts";
14 import { keepProfile } from "../src/games/spark.ts";
15 import { decodeSparkProfile, type TreeNode } from "../src/games/spark_profile.ts";
16 import { FLAME_WIDTH, flameRects, treeLines } from "../src/games/spark_view.ts";
14 import { keepProfile } from "../src/kinds/minecraft/spark.ts";
15 import { decodeSparkProfile, type TreeNode } from "../src/kinds/minecraft/spark_profile.ts";
16 import { FLAME_WIDTH, flameRects, treeLines } from "../src/kinds/minecraft/spark_view.ts";
1717 import { boxNamed, createGameBox, grant } from "../src/games/store.ts";
1818 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
1919 import { bytes, key, text, varint } from "./helpers/spark_fixture.ts";
@@ -109,13 +109,13 @@ test("only the heaviest threads are drawn, and the rest are counted, on both doo
109109 expect(body).toContain("T12");
110110 expect(body.indexOf("3 more threads not drawn")).toBeLessThan(body.indexOf('id="ticks"'));
111111 expect(body).not.toContain("T0<");
112 const { heaviest } = await import("../src/games/spark_view.ts");
112 const { heaviest } = await import("../src/kinds/minecraft/spark_view.ts");
113113 expect(heaviest([{ ms: 1 }, { ms: 5 }]).note).toBe("");
114114 });
115115
116116 test("the slowest ticks, time per mod, GC and memory are shown, on both doors (#18140)", async () => {
117117 const { sparkFixture } = await import("./helpers/spark_fixture.ts");
118 const { summarySections, sectionLines } = await import("../src/games/spark_view.ts");
118 const { summarySections, sectionLines } = await import("../src/kinds/minecraft/spark_view.ts");
119119 const box = boxNamed(app.db, "net")!;
120120 const k = keepProfile(app.db, box.id, "application/x-spark-sampler", sparkFixture());
121121 if (!k.ok) throw new Error(k.error);
test/kind-boundary.test.ts added +151
@@ -0,0 +1,151 @@
1 /**
2 * The general layer names no game (#18456, P16 line 1 of #334): outside `src/kinds/minecraft/`, no
3 * source file says Minecraft, RCON, whitelist, EULA, Paper, Modrinth or spark (case-insensitive,
4 * whole words), except the files and words listed below. The list is a ratchet: it may only shrink.
5 * A hit not listed fails, and so does a listed word that no longer appears, so a cleaned file must
6 * leave the list.
7 */
8 import { expect, test } from "bun:test";
9 import { readdirSync, readFileSync } from "node:fs";
10
11 const WORDS = ["minecraft", "rcon", "whitelist", "eula", "paper", "modrinth", "spark"];
12 const ROOT = new URL("../src", import.meta.url).pathname;
13
14 /** The words each file still says, until the public names P16 line 4 renames go. */
15 const ALLOWED: Record<string, string[]> = {
16 "src/actions/identities.ts": ["minecraft"],
17 "src/actions/minecraft.ts": ["minecraft"],
18 "src/app.ts": ["modrinth"],
19 "src/apps/schedule_probe.ts": ["paper"],
20 "src/boards/chart.ts": ["spark"],
21 "src/contract/openapi/routes/getApiV1Identities.ts": ["minecraft"],
22 "src/core/edition.ts": ["paper"],
23 "src/core/empty_words.ts": ["modrinth"],
24 "src/core/identities.ts": ["minecraft"],
25 "src/core/migrations/20261110170000-talk-captain.ts": ["paper"],
26 "src/core/migrations/20261206183000-account-link.ts": ["minecraft"],
27 "src/core/migrations/20261202000000-game-people.ts": ["whitelist"],
28 "src/core/migrations/20261202200722-game-player-set.ts": ["modrinth"],
29 "src/core/migrations/20261204080000-game-spark.ts": ["spark"],
30 "src/core/migrations/20261204110000-print-job-sheets.ts": ["paper"],
31 "src/core/migrations/20261204120000-connection-minecraft.ts": ["minecraft"],
32 "src/core/proven_identities.ts": ["minecraft"],
33 "src/core/secret_text.ts": ["rcon"],
34 "src/core/talk_routines.ts": ["paper"],
35 "src/crew/conversation_ask.ts": ["whitelist","modrinth"],
36 "src/crew/conversation_brief.ts": ["paper"],
37 "src/crew/routine_report.ts": ["paper"],
38 "src/crew/routines.ts": ["paper"],
39 "src/design/themes.ts": ["paper"],
40 "src/devices/print.ts": ["paper"],
41 "src/engine/crossing.ts": ["modrinth"],
42 "src/games/agent.sh": ["minecraft","rcon","whitelist","paper","modrinth","spark"],
43 "src/games/ask.ts": ["minecraft"],
44 "src/games/chat.ts": ["minecraft","paper"],
45 "src/games/client_pack.ts": ["minecraft","modrinth"],
46 "src/games/desk_snapshot.ts": ["minecraft"],
47 "src/games/door_leave.ts": ["minecraft"],
48 "src/games/findings.ts": ["minecraft","whitelist"],
49 "src/games/forge_read.ts": ["minecraft"],
50 "src/games/gist.ts": ["minecraft","whitelist"],
51 "src/games/heal.ts": ["minecraft"],
52 "src/games/lend_fit.ts": ["minecraft"],
53 "src/games/lent_proof.ts": ["rcon"],
54 "src/games/mod_sets.ts": ["minecraft","modrinth"],
55 "src/games/modrinth.ts": ["minecraft","paper","modrinth"],
56 "src/games/mods.ts": ["minecraft","modrinth","spark"],
57 "src/games/outcome.ts": ["minecraft","rcon","whitelist","paper"],
58 "src/games/pack_check.ts": ["modrinth"],
59 "src/games/plugin_config.ts": ["minecraft","paper","modrinth"],
60 "src/games/presets.ts": ["minecraft","rcon","eula","paper","modrinth"],
61 "src/games/proxy_jars.ts": ["modrinth"],
62 "src/games/settings.ts": ["minecraft","rcon","whitelist","paper"],
63 "src/games/shell.ts": ["rcon"],
64 "src/games/sleep.ts": ["minecraft","paper","modrinth"],
65 "src/games/spare_row.ts": ["minecraft"],
66 "src/games/store.ts": ["minecraft","rcon","whitelist","spark"],
67 "src/games/take_back.ts": ["rcon"],
68 "src/games/when_quiet.ts": ["minecraft"],
69 "src/games/write_window.ts": ["minecraft"],
70 "src/http/api/identities.ts": ["minecraft"],
71 "src/http/edition.ts": ["paper"],
72 "src/http/games_routes.ts": ["whitelist","modrinth","spark"],
73 "src/http/lazy_lists.ts": ["minecraft","spark"],
74 "src/http/marks/settings.json": ["minecraft"],
75 "src/http/mcp/tools/games.ts": ["minecraft","rcon","whitelist","paper","modrinth"],
76 "src/http/mcp/tools/infra.ts": ["minecraft","eula"],
77 "src/http/parseable_request.ts": ["minecraft"],
78 "src/http/routes/discovery.ts": ["paper"],
79 "src/http/settings_routes.ts": ["minecraft"],
80 "src/kernel/body_caps.ts": ["minecraft","spark"],
81 "src/kinds/index.ts": ["minecraft"],
82 "src/kinds/kind.ts": ["minecraft","rcon","whitelist","eula"],
83 "src/release/v1_checks.ts": ["paper"],
84 "src/spawn/client_words.ts": ["paper"],
85 "src/system/format.ts": ["spark"],
86 "src/system/ops_log.ts": ["paper"],
87 "src/terminal/blocks.ts": ["rcon"],
88 "src/tui/forge_parts.ts": ["minecraft"],
89 "src/tui/screens/fleetgraph.ts": ["spark"],
90 "src/tui/screens/game_config.ts": ["modrinth"],
91 "src/tui/screens/game_mods.ts": ["minecraft","modrinth"],
92 "src/tui/screens/game_spark.ts": ["spark"],
93 "src/tui/screens/game_spark_view.ts": ["spark"],
94 "src/tui/screens/games.ts": ["minecraft","rcon","whitelist","paper","modrinth","spark"],
95 "src/tui/screens/identities.ts": ["minecraft"],
96 "src/tui/screens/infra.ts": ["minecraft","eula"],
97 "src/tui/screens/limbs.ts": ["spark"],
98 "src/tui/screens/profile.ts": ["minecraft"],
99 "src/tui/screens/series.ts": ["spark"],
100 "src/tui/screens/system.ts": ["spark"],
101 "src/web/figure.ts": ["spark"],
102 "src/web/go_pages.ts": ["minecraft"],
103 "src/web/pages/boards-stream.ts": ["spark"],
104 "src/web/pages/flow-panel.ts": ["spark"],
105 "src/web/pages/games.ts": ["minecraft","rcon","whitelist","paper","modrinth","spark"],
106 "src/web/pages/games_client_pack.ts": ["modrinth"],
107 "src/web/pages/games_spark.ts": ["spark"],
108 "src/web/pages/games_spark_view.ts": ["spark"],
109 "src/web/pages/home_flow_style.ts": ["spark"],
110 "src/web/pages/identities.ts": ["minecraft"],
111 "src/web/pages/milestones.ts": ["spark"],
112 "src/web/pages/origins.ts": ["paper"],
113 "src/web/pages/proven_identities.ts": ["minecraft"],
114 "src/web/pages/search.ts": ["minecraft"],
115 "src/web/pages/settings.ts": ["spark"],
116 "src/web/pages/system.ts": ["spark"],
117 "src/web/studio/kpi_row.ts": ["spark"],
118 "src/web/style/base.ts": ["paper"],
119 "src/web/style/components.ts": ["spark"],
120 "src/web/ui.ts": ["spark"],
121 };
122
123 const walk = (d: string): string[] =>
124 readdirSync(d, { withFileTypes: true }).flatMap((e) => {
125 const p = `${d}/${e.name}`;
126 return e.isDirectory() ? walk(p) : /\.(ts|sh|css|json|md)$/.test(e.name) ? [p] : [];
127 });
128
129 function hits(): Record<string, string[]> {
130 const out: Record<string, string[]> = {};
131 for (const f of walk(ROOT)) {
132 const rel = f.slice(ROOT.length - 3);
133 if (rel.startsWith("src/kinds/minecraft/") || rel.startsWith("src/generated/")) continue;
134 const text = readFileSync(f, "utf8");
135 const found = WORDS.filter((w) => new RegExp(`\\b${w}\\b`, "i").test(text));
136 if (found.length > 0) out[rel] = found;
137 }
138 return out;
139 }
140
141 test("no file outside src/kinds/minecraft/ names the game beyond the listed exceptions", () => {
142 const now = hits();
143 const fresh = Object.entries(now).flatMap(([f, ws]) => ws.filter((w) => !(ALLOWED[f] ?? []).includes(w)).map((w) => `${f}: ${w}`));
144 expect(fresh).toEqual([]);
145 });
146
147 test("every listed exception still hits: the list only shrinks", () => {
148 const now = hits();
149 const stale = Object.entries(ALLOWED).flatMap(([f, ws]) => ws.filter((w) => !(now[f] ?? []).includes(w)).map((w) => `${f}: ${w}`));
150 expect(stale).toEqual([]);
151 });
test/kinds.test.ts +4 −3
@@ -13,11 +13,11 @@ test("a kind is looked up by its name; an unknown name has none", () => {
1313 expect(defaultKind()).toBe(kindNamed("minecraft")!);
1414 });
1515
16 test("a kind has all five parts, the unmoved two declared as stubs", () => {
16 test("a kind has all five parts, people, identity and metrics behind it too", () => {
1717 const k = kindNamed("minecraft")!;
1818 expect(typeof k.compose.design).toBe("function");
1919 expect(typeof k.console.html).toBe("function");
20 for (const part of [k.people, k.metrics]) expect(part.stub).toBe(true);
20 for (const part of [k.people, k.names, k.identity, k.metrics]) expect(typeof part).toBe("object");
2121 });
2222
2323 test("the compose design goes through the kind", () => {
@@ -35,10 +35,11 @@ test("the console goes through the kind", () => {
3535 expect(c.crash(["---- Minecraft Crash Report ----", "Description: boom"])?.summary).toContain("Crashed:");
3636 });
3737
38 // `src/games/` is the game's own code, every file of it listed in test/kind-boundary.test.ts.
3839 test("the general layer reaches the Minecraft kind only through src/kinds/index.ts", () => {
3940 const walk = (d: string): string[] =>
4041 readdirSync(d, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(`${d}/${e.name}`) : e.name.endsWith(".ts") ? [`${d}/${e.name}`] : []));
4142 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 const reaching = walk(root).filter((f) => !f.startsWith(`${root}/kinds/`) && !f.startsWith(`${root}/games/`) && /kinds\/minecraft\//.test(readFileSync(f, "utf8")));
4344 expect(reaching).toEqual([]);
4445 });
test/proven-identities.test.ts +2 −1
@@ -3,7 +3,8 @@ import { mkdtemp, rm } from "node:fs/promises";
33 import { tmpdir } from "node:os";
44 import { join } from "node:path";
55 import { createApp, type App } from "../src/app.ts";
6 import { identitiesOf, identityLine, minecraftOwner, removeEmail } from "../src/core/proven_identities.ts";
6 import { identitiesOf, identityLine, removeEmail } from "../src/core/proven_identities.ts";
7 import { minecraftOwner } from "../src/kinds/minecraft/identity.ts";
78 import { profileScreen } from "../src/tui/screens/profile.ts";
89 import type { Screen } from "../src/tui/app/app.ts";
910 import { quietCtx, screenText, sessionFor } from "./helpers/tui-text.ts";
test/tui-games.test.ts +3 −3
@@ -15,19 +15,19 @@ import { createApp, type App } from "../src/app.ts";
1515 import { createUser, getUserByName, type User } from "../src/core/users.ts";
1616 import { readCompose, serviceEnv } from "../src/games/compose.ts";
1717 import { WAKE_GRACE_MS } from "../src/games/heal.ts";
18 import { boxOfSparkSecret, keepProfile } from "../src/games/spark.ts";
18 import { boxOfSparkSecret, keepProfile } from "../src/kinds/minecraft/spark.ts";
1919 import { lentRunnerOf } from "../src/games/lend.ts";
2020 import { noteUse } from "../src/machines/agent_use.ts";
2121 import { liveBlock } from "../src/web/games_machine.ts";
2222 import type { Ctx } from "../src/http/context.ts";
2323 import { boxNamed, createGameBox, grant, grantsOf, recentCommands, recordSync } from "../src/games/store.ts";
24 import { recordMetrics } from "../src/games/metrics.ts";
24 import { recordMetrics } from "../src/kinds/minecraft/metrics.ts";
2525 import { queueWorld } from "../src/games/worlds.ts";
2626 import { PINS } from "../src/games/proxy_jars.ts";
2727 import { createForgeApp } from "../src/tui/forge.ts";
2828 import { sha256 } from "../src/kernel/hash.ts";
2929 import { synced } from "../src/games/notify.ts";
30 import { recordProxyEvents } from "../src/games/player_events.ts";
30 import { recordProxyEvents } from "../src/kinds/minecraft/player_events.ts";
3131 import { gameBoxScreen, gameGrantsScreen, gameServiceScreen, gamesScreen } from "../src/tui/screens/games.ts";
3232 import { headlessTerminal } from "../src/tui/term/terminal.ts";
3333 import { quietLogs } from "./helpers/globals.ts";

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

Keyboard shortcuts

Docs