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

test/game-desk.test.ts runs under the 20 s file budget and leaves SLOW #18279

opened this

Merged 6h 44m ago, live in production

scout/forge:scout/18240-test-game-desk-test-ts-runs-under-the-20 → main 0 commits fork

  • Merged. scout/18240-test-game-desk-test-ts-runs-under-the-20 was merged into main as fc50ca7.

Review

Sign in to review this change.
6 files changed +379 −336
scripts/gate.ts −1
@@ -51,7 +51,6 @@ export const EXCLUDED: readonly Exclusion[] = [];
5151 * short: an entry is a debt with an owner, not a home.
5252 */
5353 export const SLOW: readonly Exclusion[] = [
54 { file: "test/game-desk.test.ts", reason: "runs the real agent.sh under bash, curl and jq against a fake docker, polling real files; 26 to 31 s of CPU a file under full-suite load", issue: 18204 },
5554 { file: "test/config-secrets.test.ts", reason: "its hostile-line test feeds 25 pathological shapes of MAX_LINE characters to the scanner; 2.3 s of CPU under full-suite load", issue: 18204 },
5655 { file: "test/forge-state-history.test.ts", reason: "its restart test opens the forge database twice and rotates real log files; 2.01 s of CPU under full-suite load, well under 1 s alone", issue: 18122 },
5756 { file: "test/crew-openai-account.test.ts", reason: "each test boots a stand-in crew and runs real agent attempts; its 401 test hands one task over to a second run, 2.25 s of CPU under full-suite load", issue: 18122 },
test/game-desk-answers.test.ts added +95
@@ -0,0 +1,95 @@
1 /**
2 * `/forge` on the proxy, the answers that come in: each is put whole in the inbox, readable, under
3 * the agent's own names; said back until a sync that said it is answered; the forge's snapshot goes
4 * beside the folders.
5 */
6 import { expect } from "bun:test";
7 import { existsSync, readFileSync, writeFileSync } from "node:fs";
8 import { rm } from "node:fs/promises";
9 import { join } from "node:path";
10 import { answer, deskTest, light, made, ok, texts, uuid } from "./helpers/game-desk.ts";
11
12 deskTest("answers are put whole in the inbox, readable, under the agent's own names; none while 64 wait", async () => {
13 const told = [{ id: "../../x", uuid: uuid(1), text: `Restart "hub"? \\n é $(id)`, confirm: true }, { id: "r2", uuid: uuid(2), text: "y".repeat(17_000), confirm: false }];
14 const b = made(() => ok({ told }));
15 await b.run();
16 expect(b.inbox()).toHaveLength(1);
17 const f = join(b.desk, "inbox", b.inbox()[0]!);
18 expect(b.inbox()[0]).toMatch(/^[0-9-]+\.json$/);
19 expect(JSON.parse(readFileSync(f, "utf8"))).toEqual(told[0]);
20 for (let i = 0; i < 63; i++) writeFileSync(join(b.desk, "inbox", `w${i}.json`), "{}");
21 await b.run();
22 expect(b.inbox()).toHaveLength(64);
23 }, 60_000);
24
25
26 deskTest("the forge's snapshot is put whole beside the folders, and the quick poll says which one the box has; one that cannot be installed replaces nothing but is said to be had", async () => {
27 const db = (text: string): string => Buffer.from(text).toString("base64");
28 // In turn: a good one; one with no safe version (never said to be had); one that is not base64;
29 // one over the limit.
30 const answers: Record<number, { v: string; db: string }> = { 2: { v: "k1abc", db: db("SQLite format 3\0 the snapshot") }, 3: { v: "../x", db: db("x") }, 4: { v: "k2", db: "!!!" }, 5: { v: "k3", db: "A".repeat(1_500_004) } };
31 const b = made((n) => (answers[n] === undefined ? ok() : Response.json({ commands: [], desk: answers[n] })));
32 // The good one is in whole when the next quick poll says so, with nothing left beside it.
33 let tmp: boolean | undefined;
34 await b.run(() => {
35 if (tmp === undefined && light(b).length >= 2) tmp = existsSync(join(b.desk, "snapshot.tmp"));
36 return light(b).length >= 5;
37 });
38 expect(tmp).toBe(false);
39 // Each quick poll says the version the box had before its answer.
40 expect(light(b).map((x) => x["desk"])).toEqual([{ v: "" }, { v: "k1abc" }, { v: "k1abc" }, { v: "k2" }, { v: "k3" }]);
41 expect(readFileSync(join(b.desk, "snapshot.db"), "utf8")).toBe("SQLite format 3\0 the snapshot");
42 expect(b.log()).toContain("over its limit");
43 }, 60_000);
44
45
46 deskTest("an answer in the inbox is said back until a sync that said it is answered, and is never written twice", async () => {
47 // Each run is the agent started anew. The third gets no answer; the forge repeats 7 with other
48 // words.
49 const b = made((n) =>
50 n === 3 ? new Response("", { status: 502 }) : ok(n === 1 ? { told: [answer(7, "first"), answer(8, "second", 7)] } : n === 2 ? { told: [answer(7, "other words")] } : n === 5 ? { told: [answer(7, "new", 9)] } : {}),
51 );
52 const got = (): unknown => b.bodies.at(-1)!["got"];
53 await b.run();
54 expect(got()).toEqual([]);
55 expect(texts(b)).toEqual(["first", "second"]);
56 await b.run();
57 expect(got()).toEqual([7, 8]);
58 expect(texts(b)).toEqual(["first", "second"]);
59 await b.run();
60 expect(got()).toEqual([7]);
61 await b.run();
62 expect(got()).toEqual([7]);
63 await b.run();
64 expect(got()).toEqual([]);
65 // A restored forge counts from an older number again: another request's answer is another answer.
66 expect(texts(b)).toEqual(["first", "new", "second"]);
67 }, 60_000);
68
69
70 deskTest("an answer's `lines` go in as they are, and count in its 16 KiB", async () => {
71 const lines = [{ t: "#12 fix \\n é", c: "good", open: "/a/b/pulls/12" }, { t: "Next", put: "/forge more" }];
72 const b = made(() => ok({ told: [{ ...answer(7, "rich"), lines }, { ...answer(8, "big"), lines: [{ t: "y".repeat(17_000) }] }, { ...answer(9, "plain"), lines: "x", other: 1 }] }));
73 await b.run();
74 const in_ = b.inbox().map((f) => JSON.parse(readFileSync(join(b.desk, "inbox", f), "utf8")) as object);
75 const { n: _a, ...rich } = { ...answer(7, "rich"), lines };
76 const { n: _b, ...plain } = answer(9, "plain");
77 expect(in_).toHaveLength(2);
78 expect(in_).toContainEqual(rich);
79 expect(in_).toContainEqual(plain);
80 await b.run();
81 expect(b.bodies[1]!["got"]).toEqual([7, 8, 9]);
82 }, 60_000);
83
84
85 deskTest("an answer that found no room is not said back, and goes in when it comes again", async () => {
86 const b = made(() => ok({ told: [answer(7, "waits")] }));
87 for (let i = 0; i < 64; i++) writeFileSync(join(b.desk, "inbox", `w${i}.json`), "{}");
88 await b.run();
89 for (let i = 0; i < 64; i++) await rm(join(b.desk, "inbox", `w${i}.json`));
90 await b.run();
91 expect(b.bodies[1]!["got"]).toEqual([]);
92 expect(texts(b)).toEqual(["waits"]);
93 await b.run();
94 expect(b.bodies[2]!["got"]).toEqual([7]);
95 }, 60_000);
test/game-desk-poll.test.ts added +120
@@ -0,0 +1,120 @@
1 /**
2 * `/forge` on the proxy, the quick poll: a request goes with it as soon as the proxy says there is
3 * one, the wait between polls ends for that and for nothing else, and a poll that failed is waited
4 * out.
5 */
6 import { expect } from "bun:test";
7 import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
8 import { rm } from "node:fs/promises";
9 import { join } from "node:path";
10 import { answer, carried, deskTest, later, light, made, ok, texts, took, uuid } from "./helpers/game-desk.ts";
11
12 deskTest("a quick poll ends its wait the moment a request comes, not at the next whole second", async () => {
13 const b = made((_n, ask) => took(ask));
14 let wrote = 0;
15 let saw = 0;
16 await b.run(
17 () => {
18 if (wrote === 0 && b.bodies.filter((x) => x["light"] === true).length >= 1) {
19 b.asks(1, 1);
20 wrote = Date.now();
21 }
22 if (wrote > 0 && saw === 0 && b.bodies.some((x) => x["ask"] !== undefined)) saw = Date.now();
23 return saw > 0;
24 },
25 { FORGE_GAME_LIGHT_SLEEP: "3" },
26 );
27 // Waiting out its three seconds would take at least that; the mark ends the wait.
28 expect(saw - wrote).toBeLessThan(2_000);
29 }, 60_000);
30
31
32 deskTest("a poll that failed is waited out even with a request waiting: the agent does not spin on a restarting forge", async () => {
33 const b = made((_n, ask) => (b.bodies.at(-1)!["light"] === true ? new Response("", { status: 502 }) : took(ask)));
34 b.asks(1, 10);
35 await b.run(() => b.bodies.filter((x) => x["light"] === true).length >= 1);
36 const from = Date.now();
37 await b.run(() => Date.now() - from > 1_500, { FORGE_GAME_LIGHT_SLEEP: "1" });
38 // Spinning would poll every tenth of a second: some fifteen in this time.
39 expect(b.bodies.filter((x) => x["light"] === true).length).toBeLessThan(6);
40 }, 60_000);
41
42
43 deskTest("a mark left behind with the proxy stopped does not end the wait: quick polls stay a second apart", async () => {
44 const b = made(() => ok(), "hub");
45 mkdirSync(join(b.root, "game"), { recursive: true });
46 writeFileSync(join(b.root, "game", ".desk.due"), "");
47 const from = Date.now();
48 await b.run(() => Date.now() - from > 2_200, { FORGE_GAME_LIGHT_SLEEP: "1" });
49 expect(b.bodies.filter((x) => x["light"] === true).length).toBeLessThan(6);
50 expect(existsSync(join(b.root, "game", ".desk.due"))).toBe(false);
51 }, 60_000);
52
53
54 deskTest("a request made between full syncs goes with the quick poll, again when that got no answer, and is deleted once named", async () => {
55 // Only the first full sync is answered in time to matter: the next is ten minutes away.
56 let failed = 0;
57 const b = made((_n, ask) => (ask !== undefined && failed++ === 0 ? new Response("", { status: 502 }) : ask === undefined ? ok() : took(ask)));
58 // Two runs: a failed quick poll waits out the rest of the time between full syncs.
59 const first = later(b, 1);
60 await b.run(() => {
61 first();
62 return failed === 1;
63 }, { FORGE_GAME_EVERY: "600" });
64 expect(carried(light(b))).toEqual([[uuid(1)]]);
65 expect(b.outbox()).toEqual([`${uuid(1)}.json`]);
66 const before = b.bodies.length;
67 const second = later(b, 2, before);
68 await b.run(() => {
69 second();
70 return b.outbox().length === 0 && b.bodies.length > before + 3;
71 }, { FORGE_GAME_EVERY: "600" });
72 const all = carried(b.bodies.slice(before)).flat();
73 expect(all.sort()).toEqual([uuid(1), uuid(2)]);
74 expect(carried(light(b)).flat()).toContain(uuid(2));
75 }, 90_000);
76
77
78 deskTest("an older forge that names none in a quick poll is not asked at each one", async () => {
79 const b = made(() => ok());
80 const one = later(b, 1);
81 await b.run(() => {
82 one();
83 return carried(light(b)).length > 0 && light(b).length >= 4;
84 }, { FORGE_GAME_EVERY: "600" });
85 expect(carried(light(b))).toEqual([[uuid(1)]]);
86 expect(b.outbox()).toEqual([`${uuid(1)}.json`]);
87 }, 90_000);
88
89
90 deskTest("a request made in a long full sync goes with a quick poll between its parts, not again with the sync", async () => {
91 const b = made((_n, ask) => took(ask));
92 let since = 0;
93 await b.run(() => {
94 const full = b.bodies.length - light(b).length;
95 if (full === 1 && since === 0 && light(b).length > 0) writeFileSync(join(b.root, "slow"), "");
96 if (since === 0 && existsSync(join(b.root, "in-logs"))) {
97 b.asks(1, 0);
98 since = Date.now();
99 }
100 // Past the second of the last quick poll, and long enough for the proxy's shell to say so.
101 if (since > 0 && existsSync(join(b.root, "slow")) && existsSync(join(b.root, "game/.desk.due")) && Date.now() - since > 1_200) void rm(join(b.root, "slow"), { force: true });
102 return full >= 2;
103 }, { FORGE_GAME_EVERY: "4" });
104 expect(carried(light(b))).toEqual([[uuid(1)]]);
105 expect(carried(b.bodies.filter((x) => x["light"] !== true))).toEqual([]);
106 expect(b.outbox()).toEqual([]);
107 }, 90_000);
108
109
110 deskTest("an answer that comes with the quick poll is put in the inbox too; the quick poll says back what it put in, and an answer too large for the plugin is not asked for again", async () => {
111 const b = made((n) => (n === 2 ? Response.json({ commands: [], told: [answer(7, "quick"), answer(8, "y".repeat(17_000))] }) : b.bodies.at(-1)!["light"] === true ? Response.json({ commands: [] }) : ok()));
112 await b.run(() => b.bodies.length >= 4);
113 // An answer that comes with the quick poll is put in the inbox, whole, as it was told.
114 expect(b.bodies[1]).toMatchObject({ light: true, told: true, got: [] });
115 expect(b.bodies[2]!["got"]).toEqual([7, 8]);
116 expect(b.bodies[3]!["got"]).toEqual([]);
117 expect(texts(b)).toEqual(["quick"]);
118 const { n: _n, ...whole } = answer(7, "quick");
119 expect(JSON.parse(readFileSync(join(b.desk, "inbox", b.inbox()[0]!), "utf8"))).toEqual(whole);
120 }, 60_000);
test/game-desk-proxy.test.ts added +45
@@ -0,0 +1,45 @@
1 /**
2 * `/forge` on the proxy, what runs inside it: the one shell that watches the outbox ends with the
3 * agent, and the plugin's folder gets the forge's origin, https alone.
4 */
5 import { expect } from "bun:test";
6 import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
7 import { join } from "node:path";
8 import { deskTest, made, ok } from "./helpers/game-desk.ts";
9 import { pollUntil } from "./helpers/poll.ts";
10
11 deskTest("the shell in the proxy ends with the agent, stopped or killed", async () => {
12 const alive = (pid: number): boolean => {
13 try {
14 return process.kill(pid, 0);
15 } catch {
16 return false;
17 }
18 };
19 for (const signal of ["SIGTERM", "SIGKILL"] as const) {
20 const b = made(() => ok());
21 let pid = 0;
22 await b.run(() => {
23 pid = existsSync(join(b.root, "watchers")) ? Number(readFileSync(join(b.root, "watchers"), "utf8")) : 0;
24 return pid > 0 && alive(pid);
25 }, {}, signal);
26 await pollUntil(() => !alive(pid), `the shell to end after ${signal}`, 30_000);
27 }
28 }, 120_000);
29
30
31 deskTest("the plugin's folder gets the forge's origin alone, and none that is not https", async () => {
32 const b = made(() => ok());
33 const file = join(b.desk, "origin");
34 // Nothing answers there: the file does not wait for the forge.
35 const https = (url: string, want: string) => b.run(() => existsSync(file) && readFileSync(file, "utf8") === want, { FORGE_URL: url, FORGE_GAME_EVERY: "2" });
36 await https("https://127.0.0.1:1/", "https://127.0.0.1:1\n");
37 await https("https://localhost", "https://localhost\n");
38 // An http forge, one with a name and password in its address, one under a path: the old file
39 // goes.
40 for (const url of [undefined, "https://user:pass@localhost/", "https://localhost/a/path"]) {
41 writeFileSync(file, "https://stale\n");
42 await b.run(() => !existsSync(file), url === undefined ? {} : { FORGE_URL: url });
43 }
44 expect(readdirSync(b.desk).sort()).toEqual(["inbox", "outbox"]);
45 }, 120_000);
test/game-desk.test.ts +11 −335
@@ -1,96 +1,14 @@
11 /**
2 * `/forge` on the proxy: its plugin leaves requests as files and reads answers as files, and the agent
3 * carries both, inside the proxy's own container, so the host never opens a file of that folder. A
4 * request is deleted only when an answer's `asked` names it; a file that is no request is dropped. The
5 * container here is a shell in a folder.
2 * `/forge` on the proxy, the requests that go out: its plugin leaves requests as files and the
3 * agent carries them to the forge, inside the proxy's own container, so the host never opens a file
4 * of that folder. A request is deleted only when an answer's `asked` names it; a file that is no
5 * request is dropped. The container here is a shell in a folder (`test/helpers/game-desk.ts`).
66 */
7 import { afterEach, expect, test } from "bun:test";
8 import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, symlinkSync, utimesSync, writeFileSync } from "node:fs";
7 import { expect } from "bun:test";
8 import { existsSync, readdirSync, symlinkSync, writeFileSync, mkdirSync } from "node:fs";
99 import { rm } from "node:fs/promises";
10 import { tmpdir } from "node:os";
1110 import { join } from "node:path";
12 import { pollUntil } from "./helpers/poll.ts";
13
14 const AGENT = join(import.meta.dir, "../src/games/agent.sh");
15 const lacks = ["bash", "curl", "jq"].filter((t) => Bun.which(t) === null);
16 const cleanups: (() => Promise<void>)[] = [];
17 afterEach(async () => {
18 for (const c of cleanups.splice(0)) await c();
19 });
20 const uuid = (n: number): string => `00000000-0000-4000-8000-${String(n).padStart(12, "0")}`;
21
22 function made(answer: (n: number, ask: { id: string }[] | undefined) => Response, service = "velocity") {
23 const root = mkdtempSync(join(tmpdir(), "forge-game-desk-"));
24 const proxy = join(root, "proxy");
25 const desk = join(proxy, "plugins/forge");
26 mkdirSync(join(desk, "outbox"), { recursive: true });
27 mkdirSync(join(desk, "inbox"));
28 const fake = join(root, "docker");
29 writeFileSync(
30 fake,
31 `#!/usr/bin/env bash
32 case "$*" in *" ps -a --format json") echo '{"Name":"c1","Service":"${service}","State":"running"}'; exit ;; esac
33 case " $* " in *" logs "*) while [ -f "${root}/slow" ]; do : >"${root}/in-logs"; sleep 0.1; done ;; esac
34 while [ $# -gt 0 ] && [ "$1" != exec ]; do shift; done
35 [ $# = 0 ] || echo x >>"${root}/execs"
36 [ "\${1:-}" = exec ] && [ "$2 $3 $4 $5" = "-T -u bungeecord velocity" ] || exit 0
37 shift 5
38 cd "${proxy}" || exit 1
39 case "$*" in *'while read -r $t'*) echo $$ >>"${root}/watchers" ;; esac
40 if [ -f "${root}/cut" ]; then "$@" | head -c 150; else exec "$@"; fi
41 `,
42 );
43 chmodSync(fake, 0o755);
44 const bodies: Record<string, any>[] = [];
45 const forge = Bun.serve({
46 port: 0,
47 hostname: "127.0.0.1",
48 async fetch(req) {
49 bodies.push((await req.json()) as Record<string, any>);
50 return answer(bodies.length, bodies.at(-1)!["ask"]);
51 },
52 });
53 cleanups.push(async () => {
54 forge.stop(true);
55 await rm(root, { recursive: true, force: true });
56 });
57 const run = async (until?: () => boolean | Promise<boolean>, env: Record<string, string> = {}, signal: NodeJS.Signals = "SIGTERM"): Promise<void> => {
58 const p = Bun.spawn(["bash", AGENT], {
59 env: {
60 PATH: process.env["PATH"] ?? "",
61 FORGE_URL: `http://127.0.0.1:${String(forge.port)}`,
62 FORGE_GAME_TOKEN: "fgb_abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG",
63 FORGE_GAME_DIR: join(root, "game"),
64 FORGE_GAME_DOCKER: fake,
65 FORGE_GAME_DIAG_S: "0",
66 FORGE_GAME_VOLUME_CHECK: "0",
67 FORGE_GAME_ONCE: until === undefined ? "1" : "0",
68 FORGE_GAME_LIGHT_SLEEP: "0.1",
69 ...env,
70 },
71 stdout: "ignore",
72 stderr: Bun.file(join(root, "log")),
73 });
74 try {
75 if (until === undefined) await p.exited;
76 else await pollUntil(until, "the agent to get there", 30_000);
77 } finally {
78 p.kill(signal);
79 await p.exited;
80 }
81 };
82 /** A request, as old as `age` seconds. */
83 const asks = (n: number, age: number, text?: string): void => {
84 const f = join(desk, "outbox", `${uuid(n)}.json`);
85 writeFileSync(f, text ?? JSON.stringify({ id: uuid(n), at: 1764700000000, uuid: uuid(n), name: "Alice", server: "hub", words: `"$(id)" \\ 'x' é ${n}` }, null, 2));
86 utimesSync(f, Date.now() / 1000 - age, Date.now() / 1000 - age);
87 };
88 return { root, desk, bodies, run, asks, log: () => readFileSync(join(root, "log"), "utf8"), outbox: () => readdirSync(join(desk, "outbox")).sort(), inbox: () => readdirSync(join(desk, "inbox")).sort() };
89 }
90 const ok = (more: object = {}): Response => Response.json({ composeSha: "", commands: [], ...more });
91 /** An answer that names every request the body carried. */
92 const took = (ask: { id: string }[] | undefined): Response => ok(ask === undefined ? {} : { asked: ask.map((a) => a.id) });
93 const deskTest = test.skipIf(lacks.length > 0);
11 import { deskTest, made, ok, took, uuid } from "./helpers/game-desk.ts";
9412
9513 deskTest("requests go as data, oldest first, and are deleted only once an answer names them", async () => {
9614 // No answer, then an older forge's (no `asked`), then one that took only the older of the two.
@@ -116,6 +34,7 @@ deskTest("requests go as data, oldest first, and are deleted only once an answer
11634 expect(b.bodies[4]!["ask"]).toBeUndefined();
11735 }, 60_000);
11836
37
11938 deskTest("what the forge could never name is dropped, said without its content, and holds no place", async () => {
12039 const b = made(() => ok());
12140 const bad = ["not json", "[1]", "{}", JSON.stringify({ id: uuid(1) }), JSON.stringify({ id: 5 }), "x".repeat(2_049), ""];
@@ -129,6 +48,7 @@ deskTest("what the forge could never name is dropped, said without its content,
12948 expect(b.log()).not.toContain("not json");
13049 }, 60_000);
13150
51
13252 deskTest("a request whose reading was cut short is neither sent nor dropped", async () => {
13353 const b = made((_n, ask) => took(ask));
13454 b.asks(1, 10);
@@ -138,6 +58,7 @@ deskTest("a request whose reading was cut short is neither sent nor dropped", as
13858 expect(b.outbox()).toEqual([`${uuid(1)}.json`]);
13959 }, 60_000);
14060
61
14162 deskTest("at most 20 go, and a link is never read", async () => {
14263 const b = made((_n, ask) => took(ask));
14364 for (let n = 1; n <= 23; n++) b.asks(n, 100 - n);
@@ -152,6 +73,7 @@ deskTest("at most 20 go, and a link is never read", async () => {
15273 expect(existsSync(join(b.root, "secret"))).toBe(true);
15374 }, 60_000);
15475
76
15577 deskTest("a box with no velocity service is never asked, and its quick poll does not say it reads told", async () => {
15678 const b = made(() => ok({ told: [{ id: uuid(1), uuid: uuid(1), text: "hi", confirm: false }] }), "hub");
15779 b.asks(1, 10);
@@ -161,252 +83,6 @@ deskTest("a box with no velocity service is never asked, and its quick poll does
16183 expect(b.outbox()).toHaveLength(1);
16284 }, 60_000);
16385
164 deskTest("answers are put whole in the inbox, readable, under the agent's own names; none while 64 wait", async () => {
165 const told = [{ id: "../../x", uuid: uuid(1), text: `Restart "hub"? \\n é $(id)`, confirm: true }, { id: "r2", uuid: uuid(2), text: "y".repeat(17_000), confirm: false }];
166 const b = made(() => ok({ told }));
167 await b.run();
168 expect(b.inbox()).toHaveLength(1);
169 const f = join(b.desk, "inbox", b.inbox()[0]!);
170 expect(b.inbox()[0]).toMatch(/^[0-9-]+\.json$/);
171 expect(JSON.parse(readFileSync(f, "utf8"))).toEqual(told[0]);
172 for (let i = 0; i < 63; i++) writeFileSync(join(b.desk, "inbox", `w${i}.json`), "{}");
173 await b.run();
174 expect(b.inbox()).toHaveLength(64);
175 }, 60_000);
176
177 deskTest("the forge's snapshot is put whole beside the folders, and the quick poll says which one the box has", async () => {
178 const db = Buffer.from("SQLite format 3\0 the snapshot").toString("base64");
179 const b = made((n) => (n === 2 ? Response.json({ commands: [], desk: { v: "k1abc", db } }) : ok()));
180 await b.run(() => b.bodies.filter((x) => x["light"] === true).length >= 3);
181 const lights = b.bodies.filter((x) => x["light"] === true);
182 expect(lights[0]!["desk"]).toEqual({ v: "" });
183 expect(lights.at(-1)!["desk"]).toEqual({ v: "k1abc" });
184 expect(readFileSync(join(b.desk, "snapshot.db"), "utf8")).toBe("SQLite format 3\0 the snapshot");
185 expect(existsSync(join(b.desk, "snapshot.tmp"))).toBe(false);
186 }, 60_000);
187
188 deskTest("a snapshot that is not base64 replaces nothing but is said to be had, so it is not sent again every poll; one with no safe version is not", async () => {
189 const b = made((n) => (n === 2 ? Response.json({ commands: [], desk: { v: "../x", db: Buffer.from("x").toString("base64") } }) : n === 3 ? Response.json({ commands: [], desk: { v: "k2", db: "!!!" } }) : ok()));
190 writeFileSync(join(b.desk, "snapshot.db"), "old");
191 await b.run(() => b.bodies.filter((x) => x["light"] === true).length >= 4);
192 expect(readFileSync(join(b.desk, "snapshot.db"), "utf8")).toBe("old");
193 expect(b.bodies.filter((x) => x["light"] === true).at(-1)!["desk"]).toEqual({ v: "k2" });
194 }, 60_000);
195
196 deskTest("a snapshot over the limit is not installed, not cut: the version is still said to be had", async () => {
197 const b = made((n) => (n === 2 ? Response.json({ commands: [], desk: { v: "k3", db: "A".repeat(1_500_004) } }) : ok()));
198 writeFileSync(join(b.desk, "snapshot.db"), "old");
199 await b.run(() => b.bodies.filter((x) => x["light"] === true).length >= 3);
200 expect(readFileSync(join(b.desk, "snapshot.db"), "utf8")).toBe("old");
201 expect(b.bodies.filter((x) => x["light"] === true).at(-1)!["desk"]).toEqual({ v: "k3" });
202 expect(b.log()).toContain("over its limit");
203 }, 60_000);
204
205 deskTest("a quick poll ends its wait the moment a request comes, not at the next whole second", async () => {
206 const b = made((_n, ask) => took(ask));
207 let wrote = 0;
208 let saw = 0;
209 await b.run(
210 () => {
211 if (wrote === 0 && b.bodies.filter((x) => x["light"] === true).length >= 2) {
212 b.asks(1, 1);
213 wrote = Date.now();
214 }
215 if (wrote > 0 && saw === 0 && b.bodies.some((x) => x["ask"] !== undefined)) saw = Date.now();
216 return saw > 0;
217 },
218 { FORGE_GAME_LIGHT_SLEEP: "3" },
219 );
220 // Waiting out its three seconds would take at least that; the mark ends the wait.
221 expect(saw - wrote).toBeLessThan(2_000);
222 }, 60_000);
223
224 deskTest("a poll that failed is waited out even with a request waiting: the agent does not spin on a restarting forge", async () => {
225 const b = made((_n, ask) => (b.bodies.at(-1)!["light"] === true ? new Response("", { status: 502 }) : took(ask)));
226 b.asks(1, 10);
227 await b.run(() => b.bodies.filter((x) => x["light"] === true).length >= 1);
228 const from = Date.now();
229 await b.run(() => Date.now() - from > 3_000, { FORGE_GAME_LIGHT_SLEEP: "1" });
230 expect(b.bodies.filter((x) => x["light"] === true).length).toBeLessThan(12);
231 }, 60_000);
232
233 deskTest("a mark left behind with the proxy stopped does not end the wait: quick polls stay a second apart", async () => {
234 const b = made(() => ok(), "hub");
235 mkdirSync(join(b.root, "game"), { recursive: true });
236 writeFileSync(join(b.root, "game", ".desk.due"), "");
237 const from = Date.now();
238 await b.run(() => Date.now() - from > 3_500, { FORGE_GAME_LIGHT_SLEEP: "1" });
239 expect(b.bodies.filter((x) => x["light"] === true).length).toBeLessThan(8);
240 expect(existsSync(join(b.root, "game", ".desk.due"))).toBe(false);
241 }, 60_000);
242
243 deskTest("an answer that comes with the quick poll is put in the inbox too", async () => {
244 const told = [{ id: "r1", uuid: uuid(1), text: "hi", confirm: false }];
245 const b = made((n) => (n === 2 ? Response.json({ commands: [], told }) : ok()));
246 await b.run(() => b.inbox().some((f) => f.endsWith(".json")));
247 expect(b.bodies[1]).toMatchObject({ light: true, told: true });
248 expect(JSON.parse(readFileSync(join(b.desk, "inbox", b.inbox()[0]!), "utf8"))).toEqual(told[0]);
249 }, 60_000);
250
251 const light = (b: ReturnType<typeof made>) => b.bodies.filter((x) => x["light"] === true);
252 /** Makes request `n`, once, when the agent has sent more than `after` bodies. */
253 const later = (b: ReturnType<typeof made>, n: number, after = 0) => {
254 let made = false;
255 return (): void => {
256 if (made || b.bodies.length <= after) return;
257 made = true;
258 b.asks(n, 0);
259 };
260 };
261 const carried = (xs: Record<string, any>[]): string[][] => xs.flatMap((x) => (x["ask"] === undefined ? [] : [x["ask"].map((a: { id: string }) => a.id)]));
262
263 deskTest("a request made between full syncs goes with the quick poll, again when that got no answer, and is deleted once named", async () => {
264 // Only the first full sync is answered in time to matter: the next is ten minutes away.
265 let failed = 0;
266 const b = made((_n, ask) => (ask !== undefined && failed++ === 0 ? new Response("", { status: 502 }) : ask === undefined ? ok() : took(ask)));
267 // Two runs: a failed quick poll waits out the rest of the time between full syncs.
268 const first = later(b, 1);
269 await b.run(() => {
270 first();
271 return failed === 1;
272 }, { FORGE_GAME_EVERY: "600" });
273 expect(carried(light(b))).toEqual([[uuid(1)]]);
274 expect(b.outbox()).toEqual([`${uuid(1)}.json`]);
275 const before = b.bodies.length;
276 const second = later(b, 2, before);
277 await b.run(() => {
278 second();
279 return b.outbox().length === 0 && b.bodies.length > before + 3;
280 }, { FORGE_GAME_EVERY: "600" });
281 const all = carried(b.bodies.slice(before)).flat();
282 expect(all.sort()).toEqual([uuid(1), uuid(2)]);
283 expect(carried(light(b)).flat()).toContain(uuid(2));
284 }, 90_000);
285
286 deskTest("the shell in the proxy ends with the agent, stopped or killed", async () => {
287 const alive = (pid: number): boolean => {
288 try {
289 return process.kill(pid, 0);
290 } catch {
291 return false;
292 }
293 };
294 for (const signal of ["SIGTERM", "SIGKILL"] as const) {
295 const b = made(() => ok());
296 let pid = 0;
297 await b.run(() => {
298 pid = existsSync(join(b.root, "watchers")) ? Number(readFileSync(join(b.root, "watchers"), "utf8")) : 0;
299 return pid > 0 && alive(pid);
300 }, {}, signal);
301 await pollUntil(() => !alive(pid), `the shell to end after ${signal}`, 30_000);
302 }
303 }, 120_000);
304
305 deskTest("the plugin's folder gets the forge's origin alone, and none that is not https", async () => {
306 const b = made(() => ok());
307 const file = join(b.desk, "origin");
308 // Nothing answers there: the file does not wait for the forge.
309 const https = (url: string, want: string) => b.run(() => existsSync(file) && readFileSync(file, "utf8") === want, { FORGE_URL: url, FORGE_GAME_EVERY: "2" });
310 await https("https://127.0.0.1:1/", "https://127.0.0.1:1\n");
311 await https("https://localhost", "https://localhost\n");
312 // An http forge, one with a name and password in its address, one under a path: the old file goes.
313 await b.run(() => !existsSync(file));
314 await https("https://localhost", "https://localhost\n");
315 await b.run(() => !existsSync(file), { FORGE_URL: "https://user:pass@localhost/" });
316 await https("https://localhost", "https://localhost\n");
317 await b.run(() => !existsSync(file), { FORGE_URL: "https://localhost/a/path" });
318 expect(readdirSync(b.desk).sort()).toEqual(["inbox", "outbox"]);
319 }, 120_000);
320
321 deskTest("an older forge that names none in a quick poll is not asked at each one", async () => {
322 const b = made(() => ok());
323 const one = later(b, 1);
324 await b.run(() => {
325 one();
326 return carried(light(b)).length > 0 && light(b).length >= 6;
327 }, { FORGE_GAME_EVERY: "600" });
328 expect(carried(light(b))).toEqual([[uuid(1)]]);
329 expect(b.outbox()).toEqual([`${uuid(1)}.json`]);
330 }, 90_000);
331
332 deskTest("a request made in a long full sync goes with a quick poll between its parts, not again with the sync", async () => {
333 const b = made((_n, ask) => took(ask));
334 let since = 0;
335 await b.run(() => {
336 const full = b.bodies.length - light(b).length;
337 if (full === 1 && since === 0 && light(b).length > 0) writeFileSync(join(b.root, "slow"), "");
338 if (since === 0 && existsSync(join(b.root, "in-logs"))) {
339 b.asks(1, 0);
340 since = Date.now();
341 }
342 // Past the second of the last quick poll, and long enough for the proxy's shell to say so.
343 if (since > 0 && existsSync(join(b.root, "slow")) && existsSync(join(b.root, "game/.desk.due")) && Date.now() - since > 1_200) void rm(join(b.root, "slow"), { force: true });
344 return full >= 2;
345 }, { FORGE_GAME_EVERY: "20" });
346 expect(carried(light(b))).toEqual([[uuid(1)]]);
347 expect(carried(b.bodies.filter((x) => x["light"] !== true))).toEqual([]);
348 expect(b.outbox()).toEqual([]);
349 }, 90_000);
350
351 const answer = (n: number, text: string, ask = n) => ({ n, id: uuid(ask), uuid: uuid(1), text, confirm: false });
352 const texts = (b: ReturnType<typeof made>): string[] => b.inbox().map((f) => (JSON.parse(readFileSync(join(b.desk, "inbox", f), "utf8")) as { text: string }).text).sort();
353
354 deskTest("an answer in the inbox is said back until a sync that said it is answered, and is never written twice", async () => {
355 // Each run is the agent started anew. The third gets no answer; the forge repeats 7 with other words.
356 const b = made((n) =>
357 n === 3 ? new Response("", { status: 502 }) : ok(n === 1 ? { told: [answer(7, "first"), answer(8, "second", 7)] } : n === 2 ? { told: [answer(7, "other words")] } : n === 5 ? { told: [answer(7, "new", 9)] } : {}),
358 );
359 const got = (): unknown => b.bodies.at(-1)!["got"];
360 await b.run();
361 expect(got()).toEqual([]);
362 expect(texts(b)).toEqual(["first", "second"]);
363 await b.run();
364 expect(got()).toEqual([7, 8]);
365 expect(texts(b)).toEqual(["first", "second"]);
366 await b.run();
367 expect(got()).toEqual([7]);
368 await b.run();
369 expect(got()).toEqual([7]);
370 await b.run();
371 expect(got()).toEqual([]);
372 // A restored forge counts from an older number again: another request's answer is another answer.
373 expect(texts(b)).toEqual(["first", "new", "second"]);
374 }, 60_000);
375
376 deskTest("an answer's `lines` go in as they are, and count in its 16 KiB", async () => {
377 const lines = [{ t: "#12 fix \\n é", c: "good", open: "/a/b/pulls/12" }, { t: "Next", put: "/forge more" }];
378 const b = made(() => ok({ told: [{ ...answer(7, "rich"), lines }, { ...answer(8, "big"), lines: [{ t: "y".repeat(17_000) }] }, { ...answer(9, "plain"), lines: "x", other: 1 }] }));
379 await b.run();
380 const in_ = b.inbox().map((f) => JSON.parse(readFileSync(join(b.desk, "inbox", f), "utf8")) as object);
381 const { n: _a, ...rich } = { ...answer(7, "rich"), lines };
382 const { n: _b, ...plain } = answer(9, "plain");
383 expect(in_).toHaveLength(2);
384 expect(in_).toContainEqual(rich);
385 expect(in_).toContainEqual(plain);
386 await b.run();
387 expect(b.bodies[1]!["got"]).toEqual([7, 8, 9]);
388 }, 60_000);
389
390 deskTest("an answer that found no room is not said back, and goes in when it comes again", async () => {
391 const b = made(() => ok({ told: [answer(7, "waits")] }));
392 for (let i = 0; i < 64; i++) writeFileSync(join(b.desk, "inbox", `w${i}.json`), "{}");
393 await b.run();
394 for (let i = 0; i < 64; i++) await rm(join(b.desk, "inbox", `w${i}.json`));
395 await b.run();
396 expect(b.bodies[1]!["got"]).toEqual([]);
397 expect(texts(b)).toEqual(["waits"]);
398 await b.run();
399 expect(b.bodies[2]!["got"]).toEqual([7]);
400 }, 60_000);
401
402 deskTest("the quick poll says back what it put in, and an answer too large for the plugin is not asked for again", async () => {
403 const b = made((n) => (n === 2 ? Response.json({ commands: [], told: [answer(7, "quick"), answer(8, "y".repeat(17_000))] }) : b.bodies.at(-1)!["light"] === true ? Response.json({ commands: [] }) : ok()));
404 await b.run(() => b.bodies.length >= 4);
405 expect(b.bodies[1]).toMatchObject({ light: true, got: [] });
406 expect(b.bodies[2]!["got"]).toEqual([7, 8]);
407 expect(b.bodies[3]!["got"]).toEqual([]);
408 expect(texts(b)).toEqual(["quick"]);
409 }, 60_000);
41086
41187 deskTest("a folder that is a link is left alone", async () => {
41288 const b = made(() => ok({ told: [{ id: "r1", uuid: uuid(1), text: "hi", confirm: false }] }));
test/helpers/game-desk.ts added +108
@@ -0,0 +1,108 @@
1 /**
2 * The fake proxy and forge the game-desk tests share: the real agent.sh under bash, curl and jq,
3 * against a fake docker whose container is a shell in a folder, and a forge that answers by the
4 * number of the body.
5 */
6 import { afterEach, test } from "bun:test";
7 import { chmodSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, utimesSync, writeFileSync } from "node:fs";
8 import { rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { pollUntil } from "./poll.ts";
12
13 const AGENT = join(import.meta.dir, "../../src/games/agent.sh");
14 const lacks = ["bash", "curl", "jq"].filter((t) => Bun.which(t) === null);
15 const cleanups: (() => Promise<void>)[] = [];
16 afterEach(async () => {
17 for (const c of cleanups.splice(0)) await c();
18 });
19 export const uuid = (n: number): string => `00000000-0000-4000-8000-${String(n).padStart(12, "0")}`;
20
21 export function made(answer: (n: number, ask: { id: string }[] | undefined) => Response, service = "velocity") {
22 const root = mkdtempSync(join(tmpdir(), "forge-game-desk-"));
23 const proxy = join(root, "proxy");
24 const desk = join(proxy, "plugins/forge");
25 mkdirSync(join(desk, "outbox"), { recursive: true });
26 mkdirSync(join(desk, "inbox"));
27 const fake = join(root, "docker");
28 writeFileSync(
29 fake,
30 `#!/usr/bin/env bash
31 case "$*" in *" ps -a --format json") echo '{"Name":"c1","Service":"${service}","State":"running"}'; exit ;; esac
32 case " $* " in *" logs "*) while [ -f "${root}/slow" ]; do : >"${root}/in-logs"; sleep 0.1; done ;; esac
33 while [ $# -gt 0 ] && [ "$1" != exec ]; do shift; done
34 [ $# = 0 ] || echo x >>"${root}/execs"
35 [ "\${1:-}" = exec ] && [ "$2 $3 $4 $5" = "-T -u bungeecord velocity" ] || exit 0
36 shift 5
37 cd "${proxy}" || exit 1
38 case "$*" in *'while read -r $t'*) echo $$ >>"${root}/watchers" ;; esac
39 if [ -f "${root}/cut" ]; then "$@" | head -c 150; else exec "$@"; fi
40 `,
41 );
42 chmodSync(fake, 0o755);
43 const bodies: Record<string, any>[] = [];
44 const forge = Bun.serve({
45 port: 0,
46 hostname: "127.0.0.1",
47 async fetch(req) {
48 bodies.push((await req.json()) as Record<string, any>);
49 return answer(bodies.length, bodies.at(-1)!["ask"]);
50 },
51 });
52 cleanups.push(async () => {
53 forge.stop(true);
54 await rm(root, { recursive: true, force: true });
55 });
56 const run = async (until?: () => boolean | Promise<boolean>, env: Record<string, string> = {}, signal: NodeJS.Signals = "SIGTERM"): Promise<void> => {
57 const p = Bun.spawn(["bash", AGENT], {
58 env: {
59 PATH: process.env["PATH"] ?? "",
60 FORGE_URL: `http://127.0.0.1:${String(forge.port)}`,
61 FORGE_GAME_TOKEN: "fgb_abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG",
62 FORGE_GAME_DIR: join(root, "game"),
63 FORGE_GAME_DOCKER: fake,
64 FORGE_GAME_DIAG_S: "0",
65 FORGE_GAME_VOLUME_CHECK: "0",
66 FORGE_GAME_ONCE: until === undefined ? "1" : "0",
67 FORGE_GAME_LIGHT_SLEEP: "0.1",
68 ...env,
69 },
70 stdout: "ignore",
71 stderr: Bun.file(join(root, "log")),
72 });
73 try {
74 if (until === undefined) await p.exited;
75 else await pollUntil(until, "the agent to get there", 30_000);
76 } finally {
77 p.kill(signal);
78 await p.exited;
79 }
80 };
81 /** A request, as old as `age` seconds. */
82 const asks = (n: number, age: number, text?: string): void => {
83 const f = join(desk, "outbox", `${uuid(n)}.json`);
84 writeFileSync(f, text ?? JSON.stringify({ id: uuid(n), at: 1764700000000, uuid: uuid(n), name: "Alice", server: "hub", words: `"$(id)" \\ 'x' é ${n}` }, null, 2));
85 utimesSync(f, Date.now() / 1000 - age, Date.now() / 1000 - age);
86 };
87 return { root, desk, bodies, run, asks, log: () => readFileSync(join(root, "log"), "utf8"), outbox: () => readdirSync(join(desk, "outbox")).sort(), inbox: () => readdirSync(join(desk, "inbox")).sort() };
88 }
89 export const ok = (more: object = {}): Response => Response.json({ composeSha: "", commands: [], ...more });
90 /** An answer that names every request the body carried. */
91 export const took = (ask: { id: string }[] | undefined): Response => ok(ask === undefined ? {} : { asked: ask.map((a) => a.id) });
92 export const deskTest = test.skipIf(lacks.length > 0);
93 export const light = (b: ReturnType<typeof made>) => b.bodies.filter((x) => x["light"] === true);
94
95
96 /** Makes request `n`, once, when the agent has sent more than `after` bodies. */
97 export const later = (b: ReturnType<typeof made>, n: number, after = 0) => {
98 let made = false;
99 return (): void => {
100 if (made || b.bodies.length <= after) return;
101 made = true;
102 b.asks(n, 0);
103 };
104 };
105 export const carried = (xs: Record<string, any>[]): string[][] => xs.flatMap((x) => (x["ask"] === undefined ? [] : [x["ask"].map((a: { id: string }) => a.id)]));
106
107 export const answer = (n: number, text: string, ask = n) => ({ n, id: uuid(ask), uuid: uuid(1), text, confirm: false });
108 export const texts = (b: ReturnType<typeof made>): string[] => b.inbox().map((f) => (JSON.parse(readFileSync(join(b.desk, "inbox", f), "utf8")) as { text: string }).text).sort();

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

Keyboard shortcuts

Docs