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

Games: a refused join is an event and a finding, and the player is told in game which mods they miss #17613

opened this

Merged 13h 55m ago, live in production

sold/refused-joins → main 0 commits 2 threads · 2 unresolved

  • Merged. sold/refused-joins was merged into main as b5d7344.

Review

Sign in to review this change.
16 files changed +647 −14
docs/features/games.md +4
@@ -39,6 +39,10 @@ A service page has a People block (#17284), with no plugin on the game servers:
3939
4040 `/games/<box>` draws **the network**: the proxy on top and each game server under it, awake, waking (running while its health check starts), asleep (stopped by its sleep) or stopped, with its TPS and the heads of who is on it, every player by server as the proxy says (Velocircon, an RCON console on Velocity that only the compose network reaches; the agent sends its password through stdin, never a command line), with **Move**: an operator opens a player's head and picks a server that is up. A move goes only to a server of the same box that the person also operates, on the page, in the terminal and in the `games` tool alike. A server's card opens its page (`src/web/pages/games_topology.ts`). In the terminal, the Games screen (`src/tui/screens/games.ts`) lists the same servers with their state, players and TPS.
4141
42 **Refused joins and wakes (#17610).** The proxy's own log lines, and only those, also say a join a server refused, a wake and how long it took, and a server that did not wake (`src/games/player_events.ts`). They are events of the server they are about, on its page, the terminal's people tab and the tool's `people` list; no address is kept. AutoStopper drops the reason a server gives for a refusal, so most refusals at a sleeping server have none. The same refusal twice in a day is a finding, with its fix under it: for a mod server it names the mods Modrinth says a player needs too, as likely when the server's reason is not known. After a refusal the forge looks the mods up in the background and keeps them on the service's row (`player_set_json`), again when the compose file changes; the page, the terminal and the tool read only that, and say "Mods: being looked up." until it is there. A finding changes nothing itself.
43
44 A refused player is told why in game, once (`tellRefused`): the server, the reason when the proxy logged one, and the mods to install with where to get them. The list is the lockfile's and `MODRINTH_PROJECTS`' projects and their dependencies, less those Modrinth does not mark as required on a client; a version is said only when the lockfile pins it. The limit: Velocity closes the player's old server before the new one answers, and AutoStopper does not send them back, so the words wait until a server lists the player again (within 30 minutes). They do not stop the drop itself.
45
4246 The agent reads `list uuids` each sync, and each server's whitelist.json, ops.json and banned-players.json and the proxy's `glist all` every 60 s or right after a change. Heads come from the player's UUID through the forge (`/games/head/<uuid>`), fetched once from mc-heads.net and kept on the forge's disk a week, so a page never calls out. Only a player the forge has seen on a server the person sees (on it now, or in its whitelist, ops or bans) has a head fetched; any other UUID gets the default head. A failed fetch is not tried again for 15 minutes, and at most four fetches are out at once. The terminal's service screen has a people tab (`p` takes "op Alice", "move Alice survival"), and the `games` tool has `people` with `op` list or a change.
4347 ## Modrinth
4448
src/core/migration-pins/20261202194215-game-event-clock.pin added +1
@@ -0,0 +1,1 @@
1 4f3892f4a75bb2ac4e3c6458c23e1b866dc5ab5f1a9fb04f97a4b25148f2c049
src/core/migration-pins/20261202200722-game-player-set.pin added +1
@@ -0,0 +1,1 @@
1 8f3bc90e1f6459f72a70e9c6ea295065d7f7f5e7a43128f942e69ee8687307a8
src/core/migrations/20261202194215-game-event-clock.ts added +7
@@ -0,0 +1,7 @@
1 // The time a log line itself carries, beside an event read from it (#17610): a line that a box
2 // sends again after a sync that was not answered is the same event. And when a
3 // refused player was told why in game. Additive: two columns.
4 export default `
5 ALTER TABLE game_player_event ADD COLUMN clock TEXT NOT NULL DEFAULT '';
6 ALTER TABLE game_player_event ADD COLUMN told_at TEXT NOT NULL DEFAULT '';
7 `;
src/core/migrations/20261202200722-game-player-set.ts added +5
@@ -0,0 +1,5 @@
1 // What a player's own game needs to join a mod server (#17610), as Modrinth last said: looked up in
2 // the background after a refused join, so no page waits for it. Additive: one column.
3 export default `
4 ALTER TABLE game_service ADD COLUMN player_set_json TEXT NOT NULL DEFAULT '';
5 `;
src/games/chat.ts +1 −1
@@ -169,7 +169,7 @@ export const chatLog = (
169169 .all(boxId, limit);
170170
171171 /** Words to a player in game: tellraw on the server they typed on, a line each, bounded. */
172 function tell(app: App, box: GameBox, service: string, player: string, lines: readonly string[], by: string, color = "gray"): void {
172 export function tell(app: App, box: GameBox, service: string, player: string, lines: readonly string[], by: string, color = "gray"): void {
173173 for (const line of lines.slice(0, LINES_OUT))
174174 queueCommand(app.db, box.id, service, "tell", `tellraw ${player} ${JSON.stringify({ text: line.slice(0, 200), color })}`, by);
175175 }
src/games/metrics.ts +4 −4
@@ -34,7 +34,7 @@ export const plain = (s: string): string => s.replace(/\u001b\[[0-9;]*[A-Za-z]/g
3434 */
3535 /** A player's name: Java's 1–16 characters, or Floodgate's Bedrock name with its "." before it. */
3636 export const PLAYER = /^[.]?[A-Za-z0-9_]{1,16}$/;
37 const NAME = "[.]?[A-Za-z0-9_]{1,16}";
37 export const NAME = "[.]?[A-Za-z0-9_]{1,16}";
3838
3939 export function parseList(raw: string): { online: number; max: number; names: string[]; players: { name: string; uuid: string }[] } | undefined {
4040 const text = plain(raw);
@@ -89,7 +89,7 @@ export type LogFact =
8989 * "[12:00:01 INFO] [velocircon]: ". Every fact is matched right after it, so a player's chat that
9090 * reads "[x] Alice joined the game" is chat, never a join (#17295 review).
9191 */
92 const HEAD = "^\\[([^\\]]*)\\](?: \\[([^\\]]*)\\])?: ";
92 export const HEAD = "^\\[([^\\]]*)\\](?: \\[([^\\]]*)\\])?: ";
9393
9494 /** How a death reads after the player's name, from Minecraft's death messages ("was slain by", "drowned"). */
9595 const DEATH = new RegExp(
@@ -410,13 +410,13 @@ export const playerEvents = (
410410 .query<
411411 { service: string; player: string; kind: string; at: string },
412412 [string, number]
413 >("SELECT service, player, kind, at FROM game_player_event WHERE box_id = ?1 ORDER BY id DESC LIMIT ?2")
413 >("SELECT service, player, kind, at FROM game_player_event WHERE box_id = ?1 AND kind IN ('join', 'leave') ORDER BY id DESC LIMIT ?2")
414414 .all(boxId, limit)
415415 : db
416416 .query<
417417 { service: string; player: string; kind: string; at: string },
418418 [string, string, number]
419 >("SELECT service, player, kind, at FROM game_player_event WHERE box_id = ?1 AND service = ?2 ORDER BY id DESC LIMIT ?3")
419 >("SELECT service, player, kind, at FROM game_player_event WHERE box_id = ?1 AND service = ?2 AND kind IN ('join', 'leave') ORDER BY id DESC LIMIT ?3")
420420 .all(boxId, service, limit);
421421
422422 /** The latest error lines a service logged (from the log tail), newest first. */
src/games/modrinth.ts +8
@@ -309,6 +309,14 @@ export interface Project {
309309 slug: string;
310310 title: string;
311311 server_side?: string;
312 client_side?: string;
313 }
314
315 /** Those of `refs` (ids or slugs) that a player needs too, by Modrinth's client_side. */
316 export async function clientNeeds(app: App, refs: readonly string[]): Promise<Result<Project[]>> {
317 if (refs.length === 0) return { ok: true, value: [] };
318 const got = await api<Project[]>(app, `/v2/projects?ids=${q(refs.slice(0, 100))}`, 30 * MINUTE);
319 return got.ok ? { ok: true, value: got.value.filter((p) => p.client_side === "required") } : got;
312320 }
313321
314322 /** One pinned project: what the lockfile holds for it. */
src/games/people.ts +15 −2
@@ -34,7 +34,7 @@ export interface People {
3434 }
3535 export interface PeopleEvent {
3636 readonly player: string;
37 readonly kind: "join" | "leave" | "chat" | "death";
37 readonly kind: "join" | "leave" | "chat" | "death" | "refused" | "wake" | "stuck";
3838 readonly text: string;
3939 readonly at: string;
4040 }
@@ -157,7 +157,20 @@ export const networkOf = (db: Database, boxId: string): Record<string, string[]>
157157 {},
158158 );
159159
160 /** A server's latest joins, leaves, deaths and chat, newest first: for those who may see the server. */
160 /** An event in words, as the page and the terminal say it. */
161 export function eventWords(e: PeopleEvent, service: string): string {
162 if (e.kind === "chat") return `<${e.player}> ${e.text}`;
163 if (e.kind === "death") return e.text;
164 if (e.kind === "refused") return `${e.player === "" ? "A player" : e.player} could not join ${service}${e.text === "" ? "" : `: ${e.text}`}`;
165 if (e.kind === "wake") return `${service} woke in ${e.text}`;
166 if (e.kind === "stuck") return `${service} did not wake: ${e.text}`;
167 return `${e.player} ${e.kind === "join" ? "joined" : "left"}`;
168 }
169
170 /**
171 * A server's latest joins, leaves, deaths, chat, refused joins and wakes, newest first: for those
172 * who may see the server.
173 */
161174 export const eventsOf = (db: Database, boxId: string, service: string, limit = 30): PeopleEvent[] =>
162175 db
163176 .query<
src/games/player_events.ts added +306
@@ -0,0 +1,306 @@
1 /**
2 * What the proxy says happened to a player, and the finding made of it (#17610).
3 *
4 * Two of the proxy's lines tell a join that a server refused. Velocity's own, "disconnected while
5 * connecting to survival: <reason>", is written when Velocity handles the refusal. AutoStopper
6 * (`sleep.ts`) instead takes every join to a sleeping server over: it calls Velocity's `connect()`,
7 * keeps only the status and drops the reason, so its line says SERVER_DISCONNECTED and no why, and
8 * the player sees "refused the connection". Its STARTUP line says a wake and how long it took.
9 *
10 * Only the proxy's log is read, and only right after the head the proxy itself writes, so neither
11 * chat nor another server's log says any of it. An address is never kept. A finding is read from
12 * the events each time (nothing to dismiss, gone a day after the last refusal); it changes nothing:
13 * the owner installs, removes or leaves it.
14 */
15
16 import type { Database } from "bun:sqlite";
17 import type { App } from "../app.ts";
18 import { tell } from "./chat.ts";
19 import { readCompose, serviceEnv } from "./compose.ts";
20 import { HEAD, NAME, parseList, plain } from "./metrics.ts";
21 import { clientNeeds, resolve, type Result } from "./modrinth.ts";
22 import { modsOf } from "./mods.ts";
23 import { synced } from "./notify.ts";
24 import { SERVICE_NAME, servicesOf, type GameBox } from "./store.ts";
25
26 /** How far back refusals count towards a finding. */
27 const FINDING_MS = 24 * 3_600_000;
28 /** The same line within this long is the same line, sent again by a sync that was not answered. */
29 const AGAIN_MS = 10 * 60_000;
30 const REASON_MAX = 300;
31 /** Lines of a reason kept below its first. */
32 const REASON_LINES = 5;
33
34 export interface ProxyFact {
35 /** A join refused, a server woken, a server that did not come up. */
36 readonly kind: "refused" | "wake" | "stuck";
37 readonly server: string;
38 readonly player: string;
39 readonly text: string;
40 /** The line's own time, as the proxy wrote it. */
41 readonly clock: string;
42 }
43
44 const SERVER = "[A-Za-z0-9_.-]{1,64}";
45 const CLOSED = new RegExp(`${HEAD}\\[server connection\\] (${NAME}) -> (${SERVER}) has disconnected$`);
46 const REFUSED = new RegExp(`${HEAD}\\[connected player\\] (${NAME}) \\([^)]*\\): disconnected while connecting to (${SERVER}): (.*)$`);
47 const LIFECYCLE = new RegExp(`${HEAD}AutoStopper lifecycle completed: op=(STARTUP|CONNECTION_WAIT) server=(${SERVER}) origin=[A-Z_]+ outcome=([A-Z_]+) elapsed_ms=(\\d{1,9}) waiters=\\d+$`);
48 const ANY_HEAD = new RegExp(HEAD);
49 const ADDRESS = /\[?(?:\d{1,3}(?:\.\d{1,3}){3}|(?:[0-9a-f]{0,4}:){3,7}[0-9a-f]{0,4})\]?(?::\d{1,5})?/gi;
50 const clockOf = (head: string): string => /\d{2}:\d{2}:\d{2}/.exec(head)?.[0] ?? "";
51
52 /** What the proxy's `lines` say, oldest first; `before` are the lines it wrote just before them. */
53 export function proxyFacts(lines: readonly string[], before: readonly string[] = []): ProxyFact[] {
54 const out: ProxyFact[] = [];
55 // Who was last dropped by each server: AutoStopper's line names no player.
56 const closed = new Map<string, string>();
57 const close = (text: string): void => {
58 const m = CLOSED.exec(text);
59 if (m !== null) closed.set(m[4]!, m[3]!);
60 };
61 for (const line of before) close(plain(line).trimEnd());
62 const texts = lines.map((l) => plain(l).trimEnd());
63 for (const [i, text] of texts.entries()) {
64 close(text);
65 let m = REFUSED.exec(text);
66 if (m !== null) {
67 const under: string[] = [];
68 for (const next of texts.slice(i + 1, i + 1 + REASON_LINES)) {
69 if (ANY_HEAD.test(next)) break;
70 under.push(next.trim());
71 }
72 const reason = [m[5]!, ...under].filter((l) => l !== "").join(" ");
73 out.push({ kind: "refused", server: m[4]!, player: m[3]!, text: reason.replace(ADDRESS, "(address)").slice(0, REASON_MAX), clock: clockOf(m[1]!) });
74 continue;
75 }
76 m = LIFECYCLE.exec(text);
77 if (m === null) continue;
78 const [op, server, outcome, took] = [m[3]!, m[4]!, m[5]!, `${String(Math.round(Number(m[6]!) / 1000))} s`];
79 const clock = clockOf(m[1]!);
80 if (op === "CONNECTION_WAIT") {
81 if (outcome === "SERVER_DISCONNECTED" || outcome === "CONNECTION_FAILED") out.push({ kind: "refused", server, player: closed.get(server) ?? "", text: "", clock });
82 closed.delete(server);
83 } else if (outcome === "READY") out.push({ kind: "wake", server, player: "", text: took, clock });
84 else if (outcome !== "PROXY_SHUTDOWN" && outcome !== "CANCELLED") out.push({ kind: "stuck", server, player: "", text: `${outcome} after ${took}`, clock });
85 }
86 return out;
87 }
88
89 /**
90 * One sync's proxy lines, kept as events of the server they are about (`game_player_event`); how
91 * many were new. Called after the sync's log lines are stored.
92 */
93 export function recordProxyEvents(db: Database, box: Pick<GameBox, "id">, logs: Readonly<Record<string, unknown>> | undefined, proxy: string | undefined, now = new Date()): number {
94 const sent = proxy === undefined ? undefined : logs?.[proxy];
95 if (proxy === undefined || !Array.isArray(sent)) return 0;
96 const lines = sent.slice(-200).filter((l): l is string => typeof l === "string").map((l) => l.slice(0, 2_000));
97 if (lines.length === 0) return 0;
98 const before = db
99 .query<{ line: string }, [string, string, number, number]>("SELECT line FROM game_log WHERE box_id = ?1 AND service = ?2 ORDER BY id DESC LIMIT ?3 OFFSET ?4")
100 .all(box.id, proxy, 20, lines.length)
101 .map((r) => r.line)
102 .reverse();
103 const facts = proxyFacts(lines, before);
104 if (facts.length === 0) return 0;
105 const known = new Set(servicesOf(db, box.id).map((s) => s.name));
106 const since = new Date(now.getTime() - AGAIN_MS).toISOString();
107 return db.transaction(() => {
108 let added = 0;
109 for (const f of facts) {
110 // A server the proxy calls by a name no service has stays on the proxy's own page.
111 const service = SERVICE_NAME.test(f.server) && known.has(f.server) ? f.server : proxy;
112 const again = db
113 .query("SELECT 1 FROM game_player_event WHERE box_id = ?1 AND service = ?2 AND kind = ?3 AND clock = ?4 AND at > ?5 AND (player = ?6 OR ?6 = '' OR player = '') LIMIT 1")
114 .get(box.id, service, f.kind, f.clock, since, f.player);
115 if (again !== null) continue;
116 db.query("INSERT INTO game_player_event (box_id, service, player, kind, at, text, clock) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)").run(box.id, service, f.player, f.kind, now.toISOString(), f.text, f.clock);
117 added++;
118 }
119 return added;
120 })();
121 }
122
123 /** The same trouble, twice or more: what it is and what would end it. */
124 export interface GameFinding {
125 readonly says: string;
126 /** Each a line of its own, in plain words. */
127 readonly fix: readonly string[];
128 readonly at: string;
129 }
130
131 /** What a player's own game needs to join a mod server. */
132 export interface PlayerSet {
133 /** "Fabric 1.21.4". */
134 readonly label: string;
135 readonly loader: string;
136 readonly gameVersion: string;
137 readonly mods: readonly { title: string; slug: string; version: string }[];
138 readonly pack: { title: string; slug: string; version: string } | undefined;
139 }
140
141 /**
142 * What a player needs for `service`: its modpack, else each of its mods (dependencies too) that
143 * Modrinth says a client requires, so one only the server needs is never in it. A version is said
144 * only when the lockfile pins it. Null for a server that takes no mods; not ok when Modrinth did
145 * not answer.
146 */
147 async function playerSet(app: App, box: GameBox, compose: string, service: string): Promise<Result<PlayerSet | null>> {
148 if (!/^(?:FABRIC|QUILT|FORGE|NEOFORGE|MODRINTH)$/i.test((serviceEnv(compose, service)["TYPE"] ?? "").trim())) return { ok: true, value: null };
149 const m = await modsOf(app, box, service);
150 if (!m.ok) return m;
151 const { target, lock, pack } = m.value;
152 // "fabric:waystones:1.2?" names the project in the middle.
153 const loose = m.value.loose.map((e) => e.replace(/^(?:fabric|forge|neoforge|quilt):/, "").replace(/[:?].*$/, "")).filter((e) => /^[\w.-]+$/.test(e));
154 // What the image fetches beside an unpinned mod; when Modrinth cannot say, the mod alone.
155 const deps = await Promise.all(loose.slice(0, 20).map((project) => resolve(app, target, [], [{ project, top: true }])));
156 const needs = await clientNeeds(app, [...new Set([...lock.map((l) => l.project), ...loose, ...deps.flatMap((d) => (d.ok ? d.value.map((l) => l.project) : []))])]);
157 if (!needs.ok) return needs;
158 const pinned = new Map(lock.map((l) => [l.project, l.version]));
159 const seen = new Map(needs.value.map((p) => [p.id, { title: p.title, slug: p.slug, version: pinned.get(p.id) ?? "" }]));
160 return {
161 ok: true,
162 value: { label: target.label, loader: target.loaders[0]!, gameVersion: target.gameVersion, mods: [...seen.values()], pack: pack === undefined ? undefined : { title: pack.title, slug: pack.slug, version: pack.version } },
163 };
164 }
165
166 /**
167 * A server's set as last looked up, kept on its row: at which commit, and whether Modrinth
168 * answered.
169 */
170 interface KeptSet {
171 readonly sha: string;
172 readonly at: string;
173 readonly ok: boolean;
174 readonly set: PlayerSet | null;
175 }
176 function keptSet(db: Database, boxId: string, service: string): KeptSet | undefined {
177 const json = db.query<{ j: string }, [string, string]>("SELECT player_set_json AS j FROM game_service WHERE box_id = ?1 AND name = ?2").get(boxId, service)?.j ?? "";
178 return json === "" ? undefined : (JSON.parse(json) as KeptSet);
179 }
180
181 /** A lookup that failed is tried again after this long. */
182 const AGAIN_LOOK_MS = 5 * 60_000;
183 /** The servers being looked up now, per forge: "<box> <service>". */
184 const looking = new WeakMap<App, Set<string>>();
185
186 /** Looks up, in the background, the set of each server that refused a player in the last day. */
187 async function lookUpSets(app: App, box: GameBox, now: Date): Promise<void> {
188 const refusing = app.db
189 .query<{ service: string }, [string, string]>("SELECT DISTINCT service FROM game_player_event WHERE box_id = ?1 AND kind = 'refused' AND at > ?2 LIMIT 16")
190 .all(box.id, new Date(now.getTime() - FINDING_MS).toISOString());
191 if (refusing.length === 0) return;
192 const compose = await readCompose(app, box);
193 if (compose === undefined) return;
194 const busy = looking.get(app) ?? new Set<string>();
195 looking.set(app, busy);
196 await Promise.all(
197 refusing.map(async ({ service }) => {
198 const had = keptSet(app.db, box.id, service);
199 if (had?.sha === compose.sha && (had.ok || now.getTime() - Date.parse(had.at) < AGAIN_LOOK_MS)) return;
200 const key = `${box.id} ${service}`;
201 if (busy.has(key)) return;
202 busy.add(key);
203 try {
204 const got = await playerSet(app, box, compose.text, service);
205 const kept: KeptSet = { sha: compose.sha, at: now.toISOString(), ok: got.ok, set: got.ok ? got.value : null };
206 app.db.query("UPDATE game_service SET player_set_json = ?3 WHERE box_id = ?1 AND name = ?2").run(box.id, service, JSON.stringify(kept));
207 synced(app, box.id);
208 } finally {
209 busy.delete(key);
210 }
211 }),
212 );
213 }
214
215 const LOADER_SITE: Readonly<Record<string, string>> = { fabric: "fabricmc.net/use", quilt: "quiltmc.org/install", forge: "files.minecraftforge.net", neoforge: "neoforged.net" };
216 /** The most lines a refused player is told: `tell` sends six. */
217 const LINES_TOLD = 6;
218
219 /** What a refused player is told in game: which server, why, what to install and where from. */
220 export function refusedLines(service: string, reason: string, set: PlayerSet | undefined): string[] {
221 const why = reason === "" ? [] : [`${service} said: ${reason}`];
222 if (set === undefined || (set.mods.length === 0 && set.pack === undefined) || !aboutMods(reason))
223 return [`You could not join ${service}.`, ...(why.length > 0 ? why : ["It gave no reason the forge can see. Ask an operator of this network."])];
224 const items = set.pack === undefined ? set.mods.map((m) => `${m.title}${m.version === "" ? "" : ` ${m.version}`}: modrinth.com/mod/${m.slug}`) : [`the modpack ${set.pack.title} ${set.pack.version}: modrinth.com/modpack/${set.pack.slug}`];
225 const head = [
226 `You could not join ${service}. ${reason === "" ? "Most likely your" : "Your"} game needs its mods (Minecraft ${set.gameVersion}).`,
227 ...why,
228 `1. Install ${set.label}: ${LOADER_SITE[set.loader] ?? "modrinth.com"}`,
229 ];
230 const room = LINES_TOLD - head.length;
231 // What does not fit is counted.
232 const shown = items.length <= room ? items : items.slice(0, room - 1);
233 return [...head, ...shown.map((t, i) => `${i === 0 ? "2. Install " : " and "}${t}`), ...(shown.length < items.length ? [` and ${String(items.length - shown.length)} more: ask an operator for the list`] : [])];
234 }
235
236 /** How long a refused player's words wait for Modrinth; then they go without the mods. */
237 const WAIT_MS = 2 * 60_000;
238 /** How long after a refusal a player who comes back is still told why. */
239 const TELL_MS = 30 * 60_000;
240
241 /**
242 * Tells each refused player why, once, on the server they are on. A player loses the server they
243 * were on before the next one refuses them (Velocity's doSwitch), so this waits for a sync after
244 * the refusal in which a server itself lists them.
245 */
246 export async function tellRefused(app: App, box: GameBox, metrics: Readonly<Record<string, unknown>> | undefined, now = new Date()): Promise<void> {
247 tellReady(app, box, metrics, now);
248 await lookUpSets(app, box, now);
249 }
250
251 function tellReady(app: App, box: GameBox, metrics: Readonly<Record<string, unknown>> | undefined, now: Date): void {
252 const waiting = app.db
253 .query<
254 { id: number; service: string; player: string; text: string; at: string },
255 [string, string, string]
256 >("SELECT id, service, player, text, at FROM game_player_event WHERE box_id = ?1 AND kind = 'refused' AND told_at = '' AND player != '' AND at > ?2 AND at < ?3 ORDER BY id DESC LIMIT 20")
257 .all(box.id, new Date(now.getTime() - TELL_MS).toISOString(), now.toISOString());
258 if (waiting.length === 0) return;
259 const on = new Map<string, string>();
260 for (const [service, raw] of Object.entries(metrics ?? {}).slice(0, 64)) {
261 const list = (raw as { list?: unknown } | null)?.list;
262 if (SERVICE_NAME.test(service) && typeof list === "string") for (const name of parseList(list.slice(0, 8_000))?.names ?? []) on.set(name, service);
263 }
264 const said = new Set<string>();
265 for (const w of waiting) {
266 const at = on.get(w.player);
267 if (at === undefined) continue;
268 const kept = keptSet(app.db, box.id, w.service);
269 if (kept?.ok !== true && aboutMods(w.text) && now.getTime() - Date.parse(w.at) < WAIT_MS) continue;
270 app.db.query("UPDATE game_player_event SET told_at = ?2 WHERE id = ?1").run(w.id, now.toISOString());
271 // Tried three times: told once. On the server already: they got in since.
272 if (said.has(`${w.player} ${w.service}`) || at === w.service) continue;
273 said.add(`${w.player} ${w.service}`);
274 tell(app, box, at, w.player, refusedLines(w.service, w.text, kept?.set ?? undefined), "", "yellow");
275 }
276 }
277
278 /** A refusal with no reason, or one that speaks of a loader or mods. */
279 const aboutMods = (reason: string): boolean => reason === "" || /fabric|forge|quilt|\bmods?\b/i.test(reason);
280
281 /** What keeps going wrong for the players of `service`: read from what is kept, nothing asked. */
282 export function findingsOf(db: Database, boxId: string, service: string, now = new Date()): GameFinding[] {
283 const groups = db
284 .query<
285 { text: string; n: number; at: string },
286 [string, string, string]
287 >("SELECT text, COUNT(*) AS n, MAX(at) AS at FROM game_player_event WHERE box_id = ?1 AND service = ?2 AND kind = 'refused' AND at > ?3 GROUP BY text HAVING n > 1 ORDER BY at DESC LIMIT 5")
288 .all(boxId, service, new Date(now.getTime() - FINDING_MS).toISOString());
289 if (groups.length === 0) return [];
290 const kept = keptSet(db, boxId, service);
291 const set = kept?.set ?? undefined;
292 const named = set === undefined ? "" : set.pack !== undefined ? `the modpack ${set.pack.title}` : set.mods.slice(0, 5).map((m) => m.title).join(", ");
293 return groups.map((g) => {
294 const fix: string[] = [];
295 if (aboutMods(g.text)) {
296 if (kept?.ok !== true) fix.push("Mods: being looked up.");
297 else if (named !== "") fix.push(`${g.text === "" ? "Likely: players" : "Players"} need ${set!.label} with ${named}. They install it, or you remove it from ${service}.`);
298 }
299 // Tried with Velocity 3.5.1, a Fabric server and an unmodded client (2026-12-02): without
300 // AutoStopper in between, Velocity says the reason and sends the player to its next server.
301 if (g.text === "")
302 fix.push(`Turn Sleep off for ${service}: the player then sees the reason and lands on another server. Tested with Velocity 3.5.1. The proxy's try list must hold another server.`);
303 if (fix.length === 0) fix.push(`Read the reason, then ${service}'s console at that time.`);
304 return { says: `${String(g.n)} joins to ${service} were refused in the last day.${g.text === "" ? " The proxy did not log why." : ` ${service} said: ${g.text}`}`, fix, at: g.at };
305 });
306 }
src/http/games_routes.ts +6 −1
@@ -12,7 +12,8 @@ import { recordPeople } from "../games/people.ts";
1212 import { gameChat, runChat } from "../games/chat.ts";
1313 import { packChecks } from "../games/pack_check.ts";
1414 import { lendAnswer } from "../games/lend.ts";
15 import { sleeping } from "../games/sleep.ts";
15 import { recordProxyEvents, tellRefused } from "../games/player_events.ts";
16 import { proxyOf, sleeping } from "../games/sleep.ts";
1617 import { boxByToken, envFiles, markAsleep, recordSync, signJarUrls, type SyncBody } from "../games/store.ts";
1718 import { BODY_CAPS } from "../kernel/body_caps.ts";
1819 import {
@@ -50,6 +51,10 @@ export async function gameAgentSync(ctx: Ctx): Promise<Response> {
5051 const compose = await readCompose(ctx.app, box);
5152 // A server its sleep stopped is asleep, not down: the compose file says which sleep.
5253 markAsleep(ctx.app.db, box.id, compose === undefined ? [] : sleeping(compose.text));
54 // Refused joins and wakes, from the proxy's own log.
55 recordProxyEvents(ctx.app.db, box, body.logs, compose === undefined ? undefined : proxyOf(compose.text));
56 // A refused player is told why once a server lists them again; Modrinth is never waited for.
57 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) }));
5358 // `!forge` said in game chat: checked and kept here; a plan, a commit or the crew is never waited
5459 // for (`games/chat.ts`).
5560 gameChat(ctx.app, box, body.chat, compose?.text, ctx.url.origin, Date.now(), body.chatId);
src/http/mcp/tools/games.ts +2 −1
@@ -12,6 +12,7 @@ import { good, bad, type Tool, str } from "../shared.ts";
1212 import { ALIASES, commitServer, LEVELS, planRemoveServer, planServer, wishOn, type Level } from "../../../games/presets.ts";
1313 import { commitPolicy } from "../../../games/sleep.ts";
1414 import { eventsOf, networkOf, PEOPLE_OPS, peopleOf, peopleWords, queuePeople } from "../../../games/people.ts";
15 import { findingsOf } from "../../../games/player_events.ts";
1516 import { linkShown } from "../../../games/snapshots.ts";
1617 import { queueWorld } from "../../../games/worlds.ts";
1718
@@ -212,7 +213,7 @@ export const tool: Tool = {
212213 const op = str(args["op"]);
213214 if (op === "list") {
214215 const { online, lists } = peopleOf(db, box.id, service);
215 return good({ service, online, ...lists, network: networkOf(db, box.id), latest: eventsOf(db, box.id, service, 50) });
216 return good({ service, online, ...lists, network: networkOf(db, box.id), latest: eventsOf(db, box.id, service, 50), findings: findingsOf(db, box.id, service) });
216217 }
217218 const queued = await queuePeople(ctx.app, box, service, op, str(args["player"]), user, str(args["to"]));
218219 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 sync.`, id: queued.id }) : bad("refused", queued.error);
src/tui/screens/games.ts +9 −2
@@ -17,7 +17,8 @@ import { consoleText, crashOf } from "../../games/console.ts";
1717 import { commitPolicy, policyOf, STILL_BILLED, stateWords } from "../../games/sleep.ts";
1818 import { SHELL_SERVICE, queueShell } from "../../games/shell.ts";
1919 import { onSync } from "../../games/notify.ts";
20 import { eventsOf, isBedrock, peopleOf, peopleWords, queuePeople } from "../../games/people.ts";
20 import { eventsOf, eventWords, isBedrock, peopleOf, peopleWords, queuePeople } from "../../games/people.ts";
21 import { findingsOf } from "../../games/player_events.ts";
2122 import { queueWorld, worldWords, type WorldOp } from "../../games/worlds.ts";
2223 import { lendWords, lentRunnerOf, setLend } from "../../games/lend.ts";
2324 import { spareRow } from "../../games/spare_row.ts";
@@ -274,10 +275,11 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s
274275 const { online, lists } = peopleOf(f.app.db, box.id, service);
275276 const tag = (n: string) => `${n}${isBedrock(n) ? " (Bedrock)" : ""}${lists.ops.some((o) => o.name === n) ? " · op" : ""}`;
276277 return [
278 ...findingsOf(f.app.db, box.id, service).flatMap((x) => [x.says, ...x.fix.map((l) => `Fix: ${l}`)]),
277279 online.length === 0 ? `Nobody is on ${service} right now.` : `Online: ${online.map((p) => tag(p.name)).join(", ")}`,
278280 `Whitelist ${lists.whitelistOn ? "on" : "off"} · ${lists.whitelist.length} listed · ${lists.ops.length} ops · ${lists.bans.length} banned`,
279281 ...lists.bans.map((b) => `banned: ${b.name}${b.reason === "" ? "" : ` (${b.reason})`}`),
280 ...eventsOf(f.app.db, box.id, service, 20).map((e) => `${e.at.slice(11, 16)} ${e.kind === "chat" ? `<${e.player}> ${e.text}` : e.kind === "death" ? e.text : `${e.player} ${e.kind === "join" ? "joined" : "left"}`}`),
282 ...eventsOf(f.app.db, box.id, service, 20).map((e) => `${e.at.slice(11, 16)} ${eventWords(e, service)}`),
281283 "p: op, deop, whitelist-add, whitelist-remove, ban, pardon, kick <player>, or move <player> <server>",
282284 ];
283285 }
@@ -327,6 +329,11 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s
327329 binding(["u"], "restore a snapshot"),
328330 binding(["n"], "take a snapshot"),
329331 ],
332 async load(signal) {
333 // Each sync may bring an event or a finding: redraw then.
334 const off = onSync(f.app, box.id, () => ctx.invalidate());
335 signal.addEventListener("abort", off, { once: true });
336 },
330337 render(area, s) {
331338 const c = ctx.theme.c;
332339 const [head, body] = split(area, "v", [len(1), fill(1)]);
src/web/pages/games.ts +9 −3
@@ -63,9 +63,10 @@ import { canSleep, commitPolicy, EMPTY_SECONDS, isGameServer, policyOf, STILL_BI
6363 import { CLOUD_EVENT, cloudFacts, GAME_CLOUD_EVENT, pinnedOfBox } from "../../actions/cloud_says.ts";
6464 import { topologyBlock, TOPOLOGY_CSS } from "./games_topology.ts";
6565 import { defaultHeadResponse, headResponse } from "../../games/heads.ts";
66 import { eventsOf, isBedrock, knowsPlayer, peopleOf, peopleWords, queuePeople, UNDO, type PeopleOp } from "../../games/people.ts";
66 import { eventsOf, eventWords, isBedrock, knowsPlayer, peopleOf, peopleWords, queuePeople, UNDO, type PeopleOp } from "../../games/people.ts";
6767 import { queueWorld, undoOf, worldWords } from "../../games/worlds.ts";
6868 import { emptyLine, emptyNote } from "../empty_words.ts";
69 import { findingsOf, type GameFinding } from "../../games/player_events.ts";
6970 import { metricsSeries, playerEvents, recentErrors, type Point } from "../../games/metrics.ts";
7071 import { daySpark } from "../studio/kpi_row.ts";
7172
@@ -523,6 +524,7 @@ export async function gameServicePage(ctx: Ctx): Promise<Response> {
523524 const commands = recentCommands(ctx.app.db, box.id, service, 5);
524525 const seen = servicesOf(ctx.app.db, box.id).find((s) => s.name === service);
525526 const base = `/games/${box.name}/${service}`;
527 const findings = findingsOf(ctx.app.db, box.id, service);
outdated

Principle 1 and the 50 ms rule: this awaits Modrinth during render. Read a prepared result here, never the network. Compute findings when the refusal is recorded or in the background.

526528 // Settings: each as the compose file says; a "Preview" (s.<key>=value in the query) planned on it.
527529 const settings = compose === undefined ? [] : settingsOf(compose.text, service, env);
528530 const wanted = settingsWanted(ctx.url.searchParams);
@@ -532,6 +534,7 @@ export async function gameServicePage(ctx: Ctx): Promise<Response> {
532534 title: `${service} · ${box.name}`,
533535 scriptJs: gamesConsoleJs,
534536 body: html`${pageHead(service, { sub: `on ${box.name}`, actions: act ? power(box, service) : undefined })}
537 ${findingsBlock(findings)}
535538 ${numbersBlock(ctx, box, service)}
536539 ${peopleBlock(ctx, box, service, act)}
537540 <section class="settings-block">
@@ -630,6 +633,10 @@ ${rawView ? tail.lines.join("\n") : raw(consoleHtml(tail.lines).join("\n"))}${ta
630633 }));
631634 }
632635
636 /** What keeps going wrong for players here, each with its fix. */
637 const findingsBlock = (findings: readonly GameFinding[]): Html | null =>
638 findings.length === 0 ? null : html`<section class="settings-block" id="findings"><h2>Findings</h2>${findings.map((f) => html`<p><strong>${f.says}</strong></p>${f.fix.map((l) => html`<p>${l}</p>`)}<p class="muted small">${time(f.at)}</p>`)}</section>`;
639
633640 /** A service's numbers: 24 hours of players, TPS, tick time and memory, then the latest joins and errors. */
634641 function numbersBlock(ctx: Ctx, box: GameBox, service: string): Html {
635642 const day = metricsSeries(ctx.app.db, box, service, "24h");
@@ -1178,7 +1185,6 @@ function peopleBlock(ctx: Ctx, box: GameBox, service: string, act: boolean): Htm
11781185 act
11791186 ? html`<span class="row-fields">${peopleButton(base, isOp(n) ? "deop" : "op", n, isOp(n) ? "Deop" : "Op")}${lists.whitelistOn ? peopleButton(base, listed(n) ? "whitelist-remove" : "whitelist-add", n, listed(n) ? "Unlist" : "Whitelist") : null}${peopleButton(base, "kick", n, "Kick")}${peopleButton(base, "ban", n, "Ban")}</span>`
11801187 : null;
1181 const words: Record<string, string> = { join: "joined", leave: "left", death: "", chat: "" };
11821188 return html`<section class="settings-block">
11831189 <h2>People</h2>
11841190 ${online.length === 0
@@ -1200,7 +1206,7 @@ function peopleBlock(ctx: Ctx, box: GameBox, service: string, act: boolean): Htm
12001206 ${lists.whitelistOn && lists.whitelist.length > 0 ? html`<h3>Whitelist</h3>${rowList(lists.whitelist.map((w) => row({ title: who(w.name, w.uuid), ...(act ? { after: peopleButton(base, "whitelist-remove", w.name, "Unlist") } : {}) })))}` : null}
12011207 ${events.length === 0
12021208 ? null
1203 : html`<h3>Latest</h3>${rowList(events.map((e) => row({ title: e.kind === "chat" ? html`<span class="mono">&lt;${e.player}&gt;</span> ${e.text}` : e.kind === "death" ? e.text : `${e.player} ${words[e.kind]}`, meta: time(e.at) })))}`}
1209 : 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) })))}`}
12041210 </section>`;
12051211 }
12061212
test/game-player-events.test.ts added +249
@@ -0,0 +1,249 @@
1 /**
2 * What the proxy says happened to a player (#17610): a join a server refused, with the reason when
3 * the proxy logged one, and a wake with its duration, each read only from the proxy's own lines;
4 * then the finding made of the same refusal twice, with the mods Modrinth says a player needs too.
5 */
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
11 import { createApp, type App } from "../src/app.ts";
12 import { createSession } from "../src/core/sessions.ts";
13 import { createToken } from "../src/core/tokens.ts";
14 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";
17 import { boxNamed, createGameBox, grant, type GameBox } from "../src/games/store.ts";
18 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
19 import { quietLogs } from "./helpers/globals.ts";
20
21 quietLogs();
22
23 const up = (clock: string, who = "Alice") => `[${clock} INFO]: [server connection] ${who} -> survival has connected`;
24 const down = (clock: string, who = "Alice") => `[${clock} INFO]: [server connection] ${who} -> survival has disconnected`;
25 const waited = (clock: string, outcome = "SERVER_DISCONNECTED") =>
26 `[${clock} INFO] [autostopper]: AutoStopper lifecycle completed: op=CONNECTION_WAIT server=survival origin=PLAYER_CONNECTION outcome=${outcome} elapsed_ms=52300 waiters=0`;
27 const started = (clock: string, outcome = "READY") =>
28 `[${clock} INFO] [autostopper]: AutoStopper lifecycle completed: op=STARTUP server=survival origin=PLAYER_CONNECTION outcome=${outcome} elapsed_ms=52000 waiters=1`;
29 const REASON = "This server requires Fabric Loader and Fabric API installed on your client!";
30 const refused = (clock: string, reason = REASON) =>
31 `[${clock} ERROR]: [connected player] Alice (/192.0.2.7:51000): disconnected while connecting to survival: ${reason}`;
32
33 describe("the proxy's lines", () => {
34 test("a refused join: the plugin's outcome, the player from the connection just closed", () => {
35 expect(proxyFacts([up("12:00:01"), down("12:00:01"), waited("12:00:01")])).toEqual([
36 { kind: "refused", server: "survival", player: "Alice", text: "", clock: "12:00:01" },
37 ]);
38 expect(proxyFacts([waited("12:00:01", "CONNECTED")])).toEqual([]);
39 });
40
41 test("the player is found when the close came in the sync before", () => {
42 expect(proxyFacts([waited("12:00:01")], [up("12:00:01"), down("12:00:01")])[0]).toMatchObject({ player: "Alice" });
43 expect(proxyFacts([waited("12:00:01")])[0]).toMatchObject({ player: "" });
44 });
45
46 test("Velocity's own refusal: its reason and the lines under it, and never an address", () => {
47 const [f, ...rest] = proxyFacts([refused("12:00:02"), "mods: waystones (from 192.0.2.9:25565)", "[12:00:03 INFO]: next"]);
48 expect(rest).toEqual([]);
49 expect(f).toMatchObject({ kind: "refused", player: "Alice", server: "survival" });
50 expect(f!.text).toContain(REASON);
51 expect(f!.text).toContain("waystones");
52 expect(JSON.stringify(f)).not.toContain("192.0.2.");
53 });
54
55 test("a refusal as Velocity 3.5.1 wrote it for an unmodded client and a Fabric server with Waystones (address replaced)", () => {
56 const recorded = `[20:00:14 INFO]: [server connection] Dora -> survival has connected
57 [20:00:15 INFO]: [server connection] Dora -> hub has disconnected
58 [20:00:15 INFO]: [server connection] Dora -> survival has disconnected
59 [20:00:15 ERROR]: [connected player] Dora (/192.0.2.7:51000): disconnected while connecting to survival: This server requires Fabric Loader and Fabric API installed on your client!
60 The following registry entry namespaces may be related:
61
62 waystones
63
64
65 Contact the server's administrator for more information!
66 [20:00:15 INFO]: [server connection] Dora -> hub has connected`.split("\n");
67 expect(proxyFacts(recorded)).toEqual([
68 {
69 kind: "refused",
70 server: "survival",
71 player: "Dora",
72 text: "This server requires Fabric Loader and Fabric API installed on your client! The following registry entry namespaces may be related: waystones",
73 clock: "20:00:15",
74 },
75 ]);
76 });
77
78 test("a wake and how long it took; one that did not come up", () => {
79 expect(proxyFacts([started("12:00:00")])).toEqual([{ kind: "wake", server: "survival", player: "", text: "52 s", clock: "12:00:00" }]);
80 expect(proxyFacts([started("12:00:00", "SERVER_NOT_READY")])[0]).toMatchObject({ kind: "stuck", text: "SERVER_NOT_READY after 52 s" });
81 });
82
83 test("a player's words are none of it", () => {
84 for (const line of [refused("12:00:02"), waited("12:00:02"), started("12:00:02")])
85 expect(proxyFacts([`[12:00:09 INFO]: <Mallory> ${line}`, `[12:00:09 INFO]: [Mallory] ${line}`, `x ${line}`])).toEqual([]);
86 });
87 });
88
89 const COMPOSE = `services:
90 survival:
91 image: itzg/minecraft-server
92 environment:
93 TYPE: FABRIC
94 VERSION: "1.21.4"
95 MODRINTH_PROJECTS: "waystones,lithium"
96 sky:
97 image: itzg/minecraft-server
98 environment:
99 TYPE: FABRIC
100 VERSION: "1.21.4"
101 MODRINTH_PROJECTS: "balm"
102 hub:
103 image: itzg/minecraft-server
104 environment:
105 TYPE: PAPER
106 VERSION: "1.21.4"
107 velocity:
108 image: itzg/mc-proxy
109 environment:
110 TYPE: VELOCITY
111 `;
112
113 describe("on a forge", () => {
114 let dir = "";
115 let app: App;
116 let http: ForgeHttp;
117 let ada: User;
118 let eve: User;
119 let box: GameBox;
120 let token = "";
121 /** Modrinth takes the question and never answers, whatever the caller's patience. */
122 let deaf = false;
123 const person = async (username: string, isAdmin: boolean): Promise<User> => {
124 const u = await createUser(app.db, { username, email: `${username}@f.test`, password: "a-good-passphrase", origin: "seed", isAdmin, trusted: true });
125 if (!u.ok) throw new Error(u.error);
126 return u.value;
127 };
128 beforeAll(async () => {
129 dir = await mkdtemp(join(tmpdir(), "forge-player-events-"));
130 const modrinth = (async (url: string) =>
131 deaf
132 ? await new Promise<Response>(() => {})
133 : String(url).includes("/v2/projects?")
134 ? Response.json([
135 { id: "LOPbEzlU", slug: "waystones", title: "Waystones", client_side: "required", server_side: "required" },
136 { id: "gvQqBUqZ", slug: "lithium", title: "Lithium", client_side: "optional", server_side: "optional" },
137 ])
138 : Response.json([])) as unknown as typeof fetch;
139 app = createApp({ dataDir: dir, port: 0, modrinthFetch: modrinth });
140 http = forgeHttp(app);
141 ada = await person("ada", true);
142 eve = await person("eve", false);
143 const repo = await createRepo(app, ada, { name: "net", visibility: "private" });
144 if (!repo.ok) throw new Error(JSON.stringify(repo));
145 const put = await commitToBranch(app, ada, repo.value, { message: "net", files: [{ path: "compose.yaml", content: COMPOSE }] });
146 if (!put.ok) throw new Error(JSON.stringify(put.error));
147 token = createGameBox(app.db, { name: "mc", repo: "ada/net", branch: "main", path: "compose.yaml" }).token;
148 box = boxNamed(app.db, "mc")!;
149 grant(app.db, box.id, eve.id, "viewer", "hub");
150 }, 30_000);
151 afterAll(async () => {
152 app.close();
153 await rm(dir, { recursive: true, force: true });
154 });
155 const sync = (logs: Record<string, string[]>) =>
156 http.handle(
157 new Request("http://forge.test/api/v1/games/agent/sync", {
158 method: "POST",
159 headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
160 body: JSON.stringify({ agent: 1, services: ["survival", "sky", "hub", "velocity"].map((name) => ({ name, state: "running" })), logs }),
161 }),
162 );
163 const get = async (path: string, who: User): Promise<string> =>
164 await (await http.handle(new Request(`http://forge.test${path}`, { headers: { cookie: `forge_session=${createSession(app.db, who.id).token}` } }))).text();
165 const findings = (service = "survival") => findingsOf(app.db, box.id, service);
166 const refusals = () => eventsOf(app.db, box.id, "survival").filter((e) => e.kind === "refused");
167
168 test("once is an event; a sync sent again adds none; twice is a finding with its fix", async () => {
169 const once = [up("12:00:01"), down("12:00:01"), waited("12:00:01")];
170 expect((await sync({ velocity: once })).status).toBe(200);
171 await sync({ velocity: once });
172 expect(refusals().map((e) => e.player)).toEqual(["Alice"]);
173 expect(findings()).toEqual([]);
174
175 await sync({ velocity: [up("12:02:01"), down("12:02:01"), waited("12:02:01")] });
176 await tellRefused(app, box, {});
177 const [f, ...rest] = findings();
178 expect(rest).toEqual([]);
179 expect(f!.says).toContain("2 joins to survival were refused");
180 // No reason was logged: the cause is what Modrinth says, and is called likely.
181 expect(f!.fix[0]).toStartWith("Likely: players need Fabric 1.21.4 with Waystones.");
182 expect(f!.fix.join(" ")).not.toContain("Lithium");
183 expect(f!.fix[1]).toContain("Sleep off");
184 });
185
186 test("another server's log cannot say it", async () => {
187 const before = refusals().length;
188 await sync({ hub: [up("13:00:01"), down("13:00:01"), waited("13:00:01"), refused("13:00:02")] });
189 expect(refusals()).toHaveLength(before);
190 expect(recordProxyEvents(app.db, box, { hub: [refused("13:00:03")] }, undefined)).toBe(0);
191 });
192
193 test("a refused player is told once, when a server lists them again: the mods Modrinth says a player needs", async () => {
194 const told = () => app.db.query<{ service: string; text: string }, [string]>("SELECT service, text FROM game_command WHERE box_id = ?1 AND kind = 'tell' ORDER BY rowid").all(box.id);
195 const list = (names: string) => ({ hub: { list: `There are 1 of a max of 20 players online: ${names}` } });
196 app.db.query("DELETE FROM game_player_event").run();
197 recordProxyEvents(app.db, box, { velocity: [down("14:00:01"), waited("14:00:01"), down("14:01:01"), waited("14:01:01")] }, "velocity", new Date(Date.now() - 20_000));
198 await tellRefused(app, box, list("Bob"));
199 expect(told()).toEqual([]);
200 await tellRefused(app, box, list("Alice"));
201 await tellRefused(app, box, list("Alice"));
202 const lines = told();
203 expect(new Set(lines.map((l) => l.service))).toEqual(new Set(["hub"]));
204 const all = lines.map((l) => l.text).join("\n");
205 expect(all.match(/You could not join survival/g)).toHaveLength(1);
206 expect(all).toContain("tellraw Alice");
207 expect(all).toContain("modrinth.com/mod/waystones");
208 expect(all).toContain("Fabric 1.21.4");
209 expect(all).not.toContain("ithium");
210 });
211
212 test("the words: pinned versions, the rest counted, six lines at most, and no mods named for another reason", () => {
213 const mods = Array.from({ length: 9 }, (_, i) => ({ title: `Mod${String(i)}`, slug: `mod${String(i)}`, version: "1.2" }));
214 const set = { label: "Fabric 1.21.4", loader: "fabric", gameVersion: "1.21.4", mods, pack: undefined };
215 const lines = refusedLines("survival", REASON, set);
216 expect(lines).toHaveLength(6);
217 expect(lines.join("\n")).toContain("Mod0 1.2: modrinth.com/mod/mod0");
218 expect(lines.at(-1)).toContain("7 more");
219 expect(refusedLines("survival", "You are banned", set).join("\n")).not.toContain("Mod0");
220 });
221
222 test("a Modrinth that never answers holds no sync and no page: the finding says the mods are being looked up", async () => {
223 deaf = true;
224 const to = (l: string) => l.replaceAll("survival", "sky");
225 const began = performance.now();
226 expect((await sync({ velocity: [down("15:00:01"), waited("15:00:01"), down("15:01:01"), waited("15:01:01")].map(to) })).status).toBe(200);
227 const page = await get("/games/mc/sky", ada);
228 expect(performance.now() - began).toBeLessThan(5_000);
229 expect(page).toContain("2 joins to sky were refused");
230 expect(page).toContain("Mods: being looked up.");
231 expect(findings("sky")[0]!.fix[0]).toBe("Mods: being looked up.");
232 deaf = false;
233 });
234
235 test("the page and the games tool say it, to those who see the server", async () => {
236 const page = await get("/games/mc/survival", ada);
237 expect(page).toContain("2 joins to survival were refused");
238 expect(page).toContain("Alice could not join");
239 expect(await get("/games/mc/hub", eve)).not.toContain("could not join");
240 const said = await http.handle(
241 new Request("http://forge.test/mcp", {
242 method: "POST",
243 headers: { authorization: `Bearer ${createToken(app.db, ada.id, "t", "admin").token}`, "content-type": "application/json", accept: "application/json, text/event-stream" },
244 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "games", arguments: { action: "people", box: "mc", service: "survival", op: "list" } } }),
245 }),
246 );
247 expect(await said.text()).toContain("2 joins to survival were refused");
248 });
249 });
test/tui-games.test.ts +20
@@ -19,6 +19,8 @@ import { boxNamed, createGameBox, grant, grantsOf, recentCommands, recordSync }
1919 import { queueWorld } from "../src/games/worlds.ts";
2020 import { createForgeApp } from "../src/tui/forge.ts";
2121 import { sha256 } from "../src/kernel/hash.ts";
22 import { synced } from "../src/games/notify.ts";
23 import { recordProxyEvents } from "../src/games/player_events.ts";
2224 import { gameBoxScreen, gameGrantsScreen, gameServiceScreen, gamesScreen } from "../src/tui/screens/games.ts";
2325 import { headlessTerminal } from "../src/tui/term/terminal.ts";
2426 import { quietLogs } from "./helpers/globals.ts";
@@ -174,6 +176,24 @@ test("the console tab shows an import's link as host and path, never its query s
174176 tui.stop?.();
175177 });
176178
179 test("the people tab says the findings and the refused joins, and a sync brings new ones while it is open", async () => {
180 const box = boxNamed(app.db, "net")!;
181 const refused = (clock: string) => `[${clock} ERROR]: [connected player] Dora (/192.0.2.7:51000): disconnected while connecting to hub: You need the Fabric mods`;
182 recordProxyEvents(app.db, box, { velocity: [refused("12:00:01")] }, "velocity");
183 const { tui, session, type } = drive(alice);
184 tui.ctx.push(gameServiceScreen(session, tui.ctx, box, "hub"));
185 await settleApp(tui);
186 for (let i = 0; i < 2; i++) await type("\t");
187 expect(tui.screen.toText()).toContain("Dora could not join hub: You need the Fabric mods");
188 expect(tui.screen.toText()).not.toContain("were refused in the last day");
189 recordProxyEvents(app.db, box, { velocity: [refused("12:05:01")] }, "velocity");
190 synced(app, box.id);
191 await settleUntil(tui, "2 joins to hub were refused in the last day");
192 expect(tui.screen.toText()).toContain("Fix: Mods: being looked up.");
193 expect(tui.screen.toText()).not.toContain("192.0.2.7");
194 tui.stop?.();
195 });
196
177197 test("grants: listed to the box's owner, set by them; a member who is not an owner is refused", async () => {
178198 const box = boxNamed(app.db, "net")!;
179199 const asBob = drive(bob);

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

Keyboard shortcuts

Docs