@zaisma/game-server 1.40.0 → 1.41.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/bench/glass.js +400 -596
- package/bin/like-zaisma.d.ts +15 -0
- package/bin/like-zaisma.js +252 -0
- package/bin/local-play-runner.js +35 -7
- package/bin/local-play.js +19 -1
- package/bin/node-parts.js +32 -3
- package/bin/node.js +76 -0
- package/package.json +1 -1
- package/sdk/zaisma.js +18 -2
- package/src/internal.d.ts +1 -0
- package/src/internal.js +1 -0
- package/src/sandbox-limits.d.ts +32 -0
- package/src/sandbox-limits.js +41 -0
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/** The exit code with which the runner asks the bench to start it again at once: its copy went over its memory, as on Zaisma. */
|
|
2
|
+
export const COPY_STARTED_AGAIN_EXIT_CODE: number;
|
|
3
|
+
/** Lets the game server's modules import only its own files, as on Zaisma's rooms. Called once, before it's imported. */
|
|
4
|
+
export function refuseOutsideModules(entryFile: string): void;
|
|
5
|
+
/** Counts every WebAssembly memory the game server makes or gets from its modules in memorySizeBytes. Called once, before it's imported. */
|
|
6
|
+
export function countWebAssemblyMemories(): void;
|
|
7
|
+
/** What the runner holds before the game server loads, for memorySizeBytes. */
|
|
8
|
+
export function memoryBaselineBytes(): number;
|
|
9
|
+
/** The game server's memory now, without baselineBytes: its heap and every ArrayBuffer. */
|
|
10
|
+
export function memorySizeBytes(baselineBytes: number): number;
|
|
11
|
+
/** The game server with each handler timed against Zaisma's CPU, per room, ending a room that goes past its limits. */
|
|
12
|
+
export function heldToZaismaLimits<T extends object>(
|
|
13
|
+
gameServer: T,
|
|
14
|
+
options: { print: (level: "warn" | "error", text: string) => void; onStart?: () => void; nowMs?: () => number; elapsedMs?: () => number; cpuMs?: () => number },
|
|
15
|
+
): T;
|
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
// play-locally's game server held to Zaisma's rooms: the limits a copy of the game server has there, measured here, with
|
|
2
|
+
// the same lines in its logs and the same ending when it goes past one, so a game server that fails on Zaisma fails on
|
|
3
|
+
// the developer's computer first. The Node runner on a developer's own server has none of this: it's theirs to size.
|
|
4
|
+
//
|
|
5
|
+
// - Memory: a copy has 128 MB, its data files included (read whole as it starts). Over it, the copy starts again empty.
|
|
6
|
+
// - CPU: 50 ms a call, a real-time room's ticks 30 to a call sharing 1.5 s, and 5 s for a start; 20 calls over theirs in
|
|
7
|
+
// a minute stop the game server, and Cloudflare stops a call at about 2 s. (The top level's 1 s as the code loads isn't
|
|
8
|
+
// held here: Shieldbreak's took 1.3 s on a Mac and started on Zaisma.)
|
|
9
|
+
// - Modules: only the game server's own files, by relative path: no Node modules and no packages left unbundled.
|
|
10
|
+
//
|
|
11
|
+
// CPU here is the time a handler runs before its first await, on this computer: close to what Cloudflare measures, not exact.
|
|
12
|
+
import { registerHooks, isBuiltin } from "node:module";
|
|
13
|
+
import { realpathSync } from "node:fs";
|
|
14
|
+
import { dirname, sep } from "node:path";
|
|
15
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
16
|
+
import { CALL_STOP_CPU_DURATION_MS, CALL_STOPPED_TEXT, FAILURE_COUNT, GAME_SERVER_LIMITS, GAME_SERVER_STOPPED_TEXT, GROUPED_TICK_COUNT, OVER_BUDGET_CALL_COUNT, OVER_BUDGET_WINDOW_MS, overBudgetText } from "../src/internal.js";
|
|
17
|
+
|
|
18
|
+
/** The exit code with which the runner asks the bench to start it again at once: its copy went over its memory, as on Zaisma. */
|
|
19
|
+
export const COPY_STARTED_AGAIN_EXIT_CODE = 75;
|
|
20
|
+
/** Handlers whose call starts a room's game server: setup and onRestored, and a real-time room's first tick after either. */
|
|
21
|
+
const START_HANDLER_NAMES = new Set(["setup", "onRestored"]);
|
|
22
|
+
/** What runs in the call that carries a real-time room's next tick, sharing its CPU: its players' input and their views. */
|
|
23
|
+
const TICK_CALL_HANDLER_NAMES = new Set(["onMessage", "onBytes", "stateView"]);
|
|
24
|
+
/** Handlers given a room that may only read: it can't end the room. */
|
|
25
|
+
const READ_ONLY_HANDLER_NAMES = new Set(["canJoin", "stateView", "onChat"]);
|
|
26
|
+
|
|
27
|
+
/** This thread's CPU so far, in ms: the garbage collector's threads don't count where Node can tell them apart (24 and later). */
|
|
28
|
+
function threadCpuMs() {
|
|
29
|
+
const used = typeof process.threadCpuUsage === "function" ? process.threadCpuUsage() : process.cpuUsage();
|
|
30
|
+
return (used.user + used.system) / 1000;
|
|
31
|
+
}
|
|
32
|
+
/** Who calls outside rooms (onRequest, onSchedule, onWebhook) count as: one place, as the game's own object on Zaisma. */
|
|
33
|
+
const OUTSIDE_ROOMS = "outside_rooms";
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* The game server's modules, as Zaisma's rooms have them: zaisma-server/ (or the one zaisma-server.js) and nothing else.
|
|
37
|
+
* An import of anything else from one of them fails as it does there. Called once, before the game server is imported.
|
|
38
|
+
*/
|
|
39
|
+
export function refuseOutsideModules(entryFile) {
|
|
40
|
+
const realEntry = realpathSync(entryFile);
|
|
41
|
+
const isFolder = realEntry.endsWith(`${sep}index.js`) && dirname(realEntry).endsWith(`${sep}zaisma-server`);
|
|
42
|
+
const folderUrl = pathToFileURL(dirname(realEntry) + sep).href;
|
|
43
|
+
const entryUrl = pathToFileURL(realEntry).href;
|
|
44
|
+
const isGameServerModule = (url) => (isFolder ? url.startsWith(folderUrl) : url === entryUrl);
|
|
45
|
+
registerHooks({
|
|
46
|
+
resolve(specifier, resolveContext, nextResolve) {
|
|
47
|
+
const parentUrl = resolveContext.parentURL;
|
|
48
|
+
// A .wasm file's module is the runner's own stand-in (loadWasmAsModules), which reads the file with Node's.
|
|
49
|
+
if (!parentUrl || !isGameServerModule(parentUrl.split("?")[0]) || new URL(parentUrl).pathname.endsWith(".wasm")) return nextResolve(specifier, resolveContext);
|
|
50
|
+
const parentPath = fileURLToPath(parentUrl.split("?")[0]).slice(dirname(realEntry).length + 1);
|
|
51
|
+
const isRelative = specifier.startsWith("./") || specifier.startsWith("../");
|
|
52
|
+
if (isRelative) {
|
|
53
|
+
const resolved = nextResolve(specifier, resolveContext);
|
|
54
|
+
if (isGameServerModule(resolved.url.split("?")[0])) return resolved;
|
|
55
|
+
}
|
|
56
|
+
const why = isBuiltin(specifier)
|
|
57
|
+
? "Zaisma's rooms run your game server without Node's modules: use what every browser has (fetch, crypto, TextEncoder, setTimeout) and room.readDataFile for files"
|
|
58
|
+
: isRelative
|
|
59
|
+
? `only the game server's own files load on Zaisma's rooms (${isFolder ? "zaisma-server/" : "the one zaisma-server.js"})`
|
|
60
|
+
: "packages from npm aren't installed on Zaisma's rooms: bundle them into the game server (npx esbuild server.ts --format=esm --bundle --outfile=zaisma-server.js)";
|
|
61
|
+
throw new Error(`No such module "${specifier}", imported from ${parentPath}: ${why}.`);
|
|
62
|
+
},
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** The WebAssembly memories the game server made or got from its modules, which Node counts in no figure of its own. */
|
|
67
|
+
const webAssemblyMemories = new Set();
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Notes every WebAssembly memory the game server makes, its modules' exported ones included, so memorySizeBytes counts
|
|
71
|
+
* them as Cloudflare counts a copy's. Called once, before the game server is imported.
|
|
72
|
+
*/
|
|
73
|
+
export function countWebAssemblyMemories() {
|
|
74
|
+
const keep = (memory) => webAssemblyMemories.add(new WeakRef(memory));
|
|
75
|
+
const keepExported = (instance) => {
|
|
76
|
+
for (const exported of Object.values(instance?.exports ?? {})) if (exported instanceof WebAssembly.Memory) keep(exported);
|
|
77
|
+
return instance;
|
|
78
|
+
};
|
|
79
|
+
const NodeMemory = WebAssembly.Memory;
|
|
80
|
+
WebAssembly.Memory = class extends NodeMemory {
|
|
81
|
+
constructor(...memoryArguments) {
|
|
82
|
+
super(...memoryArguments);
|
|
83
|
+
keep(this);
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
const NodeInstance = WebAssembly.Instance;
|
|
87
|
+
WebAssembly.Instance = class extends NodeInstance {
|
|
88
|
+
constructor(...instanceArguments) {
|
|
89
|
+
super(...instanceArguments);
|
|
90
|
+
keepExported(this);
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
for (const name of ["instantiate", "instantiateStreaming"]) {
|
|
94
|
+
const nodeInstantiate = WebAssembly[name];
|
|
95
|
+
if (typeof nodeInstantiate !== "function") continue;
|
|
96
|
+
WebAssembly[name] = (...instantiateArguments) => nodeInstantiate(...instantiateArguments).then((made) => (keepExported(made instanceof NodeInstance ? made : made.instance), made));
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function webAssemblyMemorySizeBytes() {
|
|
101
|
+
let sizeBytes = 0;
|
|
102
|
+
for (const reference of webAssemblyMemories) {
|
|
103
|
+
const memory = reference.deref();
|
|
104
|
+
if (memory) sizeBytes += memory.buffer.byteLength;
|
|
105
|
+
else webAssemblyMemories.delete(reference);
|
|
106
|
+
}
|
|
107
|
+
return sizeBytes;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* The game server's memory now, without what the runner itself held before loading it (baselineBytes): the JavaScript
|
|
112
|
+
* heap, every ArrayBuffer and its WebAssembly memories, as Cloudflare counts a copy's. Garbage is collected first only when it looks over, so a
|
|
113
|
+
* game under its memory never pauses for it.
|
|
114
|
+
*/
|
|
115
|
+
export function memorySizeBytes(baselineBytes) {
|
|
116
|
+
const measure = () => {
|
|
117
|
+
const usage = process.memoryUsage();
|
|
118
|
+
return Math.max(0, usage.heapUsed + usage.arrayBuffers + webAssemblyMemorySizeBytes() - baselineBytes);
|
|
119
|
+
};
|
|
120
|
+
const sizeBytes = measure();
|
|
121
|
+
if (sizeBytes <= GAME_SERVER_LIMITS.maximumMemorySizeBytes || typeof globalThis.gc !== "function") return sizeBytes;
|
|
122
|
+
globalThis.gc();
|
|
123
|
+
return measure();
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** What the runner holds before the game server loads, for memorySizeBytes. */
|
|
127
|
+
export function memoryBaselineBytes() {
|
|
128
|
+
if (typeof globalThis.gc === "function") globalThis.gc();
|
|
129
|
+
const usage = process.memoryUsage();
|
|
130
|
+
return usage.heapUsed + usage.arrayBuffers;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* The game server with each handler timed against Zaisma's CPU, per room: print gets each line its logs would have
|
|
135
|
+
* (level and text), and onStart is told after each start, when its memory is worth a look. A room whose game server
|
|
136
|
+
* goes past its limits ends as on Zaisma, with what its players are told there.
|
|
137
|
+
*/
|
|
138
|
+
export function heldToZaismaLimits(gameServer, { print, onStart = () => {}, nowMs = () => Date.now(), elapsedMs = () => performance.now(), cpuMs = threadCpuMs }) {
|
|
139
|
+
const isRealTime = gameServer.ticksPerSec !== undefined;
|
|
140
|
+
/** How long a call's worth of ticks lasts: a group also closes by time, for a real-time room with no onTick. */
|
|
141
|
+
const tickGroupDurationMs = isRealTime ? (GROUPED_TICK_COUNT * 1000) / gameServer.ticksPerSec : 0;
|
|
142
|
+
/** By room code (or OUTSIDE_ROOMS): its tick group, its calls over budget, its stops, and whether it ended. */
|
|
143
|
+
const places = new Map();
|
|
144
|
+
/** States whose next tick is a start's (setup or onRestored gave or had them). */
|
|
145
|
+
const startingStates = new WeakSet();
|
|
146
|
+
const placeOf = (key) => {
|
|
147
|
+
if (!places.has(key)) places.set(key, { tickCount: 0, tickDurationMs: 0, tickGroupStartedAtMs: nowMs(), overBudgetAtMs: [], failureCount: 0, hasEnded: false, room: null });
|
|
148
|
+
return places.get(key);
|
|
149
|
+
};
|
|
150
|
+
const roomOf = (handlerArguments) => handlerArguments.find((given) => given !== null && typeof given === "object" && typeof given.roomCode === "string" && typeof given.end === "function") ?? null;
|
|
151
|
+
// A read-only handler's room (canJoin, stateView, onChat) can't end: the room ends through the one its other handlers had.
|
|
152
|
+
const end = (place, room) => {
|
|
153
|
+
place.hasEnded = true;
|
|
154
|
+
try {
|
|
155
|
+
(place.room ?? room)?.end(GAME_SERVER_STOPPED_TEXT);
|
|
156
|
+
} catch {
|
|
157
|
+
// Already ending.
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
const overBudget = (place, room) => {
|
|
161
|
+
const atMs = nowMs();
|
|
162
|
+
place.overBudgetAtMs = place.overBudgetAtMs.filter((earlierAtMs) => atMs - earlierAtMs < OVER_BUDGET_WINDOW_MS);
|
|
163
|
+
place.overBudgetAtMs.push(atMs);
|
|
164
|
+
if (place.overBudgetAtMs.length < OVER_BUDGET_CALL_COUNT || !room || place.hasEnded) return;
|
|
165
|
+
print("error", overBudgetText(place.overBudgetAtMs.length));
|
|
166
|
+
place.overBudgetAtMs = [];
|
|
167
|
+
end(place, room);
|
|
168
|
+
};
|
|
169
|
+
const stopped = (place, room) => {
|
|
170
|
+
print("error", `Zaisma: ${CALL_STOPPED_TEXT}`);
|
|
171
|
+
if (++place.failureCount >= FAILURE_COUNT && room && !place.hasEnded) end(place, room);
|
|
172
|
+
};
|
|
173
|
+
/** One call's CPU against what Zaisma gives it. */
|
|
174
|
+
const measured = (handlerName, handlerArguments, isStartCall, durationMs) => {
|
|
175
|
+
const room = roomOf(handlerArguments);
|
|
176
|
+
const place = placeOf(room ? room.roomCode : OUTSIDE_ROOMS);
|
|
177
|
+
if (room && !READ_ONLY_HANDLER_NAMES.has(handlerName)) place.room = room;
|
|
178
|
+
if (place.hasEnded) return;
|
|
179
|
+
if (isStartCall) {
|
|
180
|
+
if (durationMs > GAME_SERVER_LIMITS.maximumStartCpuDurationMs) stopped(place, room);
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
if (handlerName === "onTick" || (isRealTime && TICK_CALL_HANDLER_NAMES.has(handlerName))) {
|
|
184
|
+
// A call's worth of ticks gone by (a room with no onTick counts none): the next group starts from nothing, as live.
|
|
185
|
+
if (place.tickCount === 0 && place.tickDurationMs > 0 && nowMs() - place.tickGroupStartedAtMs >= tickGroupDurationMs) {
|
|
186
|
+
const isOver = place.tickDurationMs > GROUPED_TICK_COUNT * GAME_SERVER_LIMITS.maximumCallCpuDurationMs;
|
|
187
|
+
place.tickDurationMs = 0;
|
|
188
|
+
if (isOver) overBudget(place, room);
|
|
189
|
+
if (place.hasEnded) return;
|
|
190
|
+
}
|
|
191
|
+
if (place.tickCount === 0 && place.tickDurationMs === 0) place.tickGroupStartedAtMs = nowMs();
|
|
192
|
+
place.tickDurationMs += durationMs;
|
|
193
|
+
if (handlerName === "onTick") place.tickCount++;
|
|
194
|
+
if (place.tickDurationMs > CALL_STOP_CPU_DURATION_MS) {
|
|
195
|
+
place.tickCount = 0;
|
|
196
|
+
place.tickDurationMs = 0;
|
|
197
|
+
return stopped(place, room);
|
|
198
|
+
}
|
|
199
|
+
if (place.tickCount < GROUPED_TICK_COUNT) return;
|
|
200
|
+
const isOver = place.tickDurationMs > GROUPED_TICK_COUNT * GAME_SERVER_LIMITS.maximumCallCpuDurationMs;
|
|
201
|
+
place.tickCount = 0;
|
|
202
|
+
place.tickDurationMs = 0;
|
|
203
|
+
if (isOver) overBudget(place, room);
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
if (durationMs > CALL_STOP_CPU_DURATION_MS) stopped(place, room);
|
|
207
|
+
else if (durationMs > GAME_SERVER_LIMITS.maximumCallCpuDurationMs) overBudget(place, room);
|
|
208
|
+
};
|
|
209
|
+
const held = {};
|
|
210
|
+
for (const name of Object.keys(gameServer)) {
|
|
211
|
+
const given = gameServer[name];
|
|
212
|
+
if (typeof given !== "function") {
|
|
213
|
+
held[name] = given;
|
|
214
|
+
continue;
|
|
215
|
+
}
|
|
216
|
+
held[name] = function (...handlerArguments) {
|
|
217
|
+
const state = handlerArguments[0];
|
|
218
|
+
const isStartTick = name === "onTick" && state !== null && typeof state === "object" && startingStates.has(state);
|
|
219
|
+
if (isStartTick) startingStates.delete(state);
|
|
220
|
+
const isStart = START_HANDLER_NAMES.has(name);
|
|
221
|
+
const startedAtMs = elapsedMs();
|
|
222
|
+
const cpuStartedAtMs = cpuMs();
|
|
223
|
+
let answer;
|
|
224
|
+
try {
|
|
225
|
+
answer = given.apply(gameServer, handlerArguments);
|
|
226
|
+
} catch (error) {
|
|
227
|
+
measured(name, handlerArguments, isStart || isStartTick, elapsedMs() - startedAtMs);
|
|
228
|
+
throw error;
|
|
229
|
+
}
|
|
230
|
+
// A start often awaits its data files before it builds from them: its CPU counts until it settles (other rooms' calls
|
|
231
|
+
// meanwhile count too, which only errs high on a budget of seconds). Any other call counts until its first await.
|
|
232
|
+
if ((isStart || isStartTick) && answer && typeof answer.then === "function") answer.then(() => measured(name, handlerArguments, true, cpuMs() - cpuStartedAtMs), () => {});
|
|
233
|
+
else measured(name, handlerArguments, isStart || isStartTick, elapsedMs() - startedAtMs);
|
|
234
|
+
if (isStart) {
|
|
235
|
+
const noteStarting = (state) => {
|
|
236
|
+
if (state !== null && typeof state === "object") startingStates.add(state);
|
|
237
|
+
};
|
|
238
|
+
if (name === "onRestored") noteStarting(handlerArguments[0]);
|
|
239
|
+
if (name === "setup") {
|
|
240
|
+
if (answer && typeof answer.then === "function") answer = answer.then((state) => (noteStarting(state), state));
|
|
241
|
+
else noteStarting(answer);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
if (isStart || isStartTick) {
|
|
245
|
+
if (answer && typeof answer.then === "function") answer.then(onStart, () => {});
|
|
246
|
+
else onStart();
|
|
247
|
+
}
|
|
248
|
+
return answer;
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
return held;
|
|
252
|
+
}
|
package/bin/local-play-runner.js
CHANGED
|
@@ -3,10 +3,11 @@
|
|
|
3
3
|
// Not a command: local-play.js starts it with one JSON argument and hears ZAISMA_LOCAL_RUNNER_READY when it listens.
|
|
4
4
|
import { createServer } from "node:net";
|
|
5
5
|
import { pathToFileURL } from "node:url";
|
|
6
|
-
import { ROOM_MESSAGE_LIMITS, checkRoomData, isRoomCode, relay } from "../src/internal.js";
|
|
6
|
+
import { GAME_SERVER_LIMITS, ROOM_MESSAGE_LIMITS, STATE_COPY_INTERVAL_MS, checkRoomData, copyStartedAgainText, isRoomCode, relay } from "../src/internal.js";
|
|
7
7
|
import { dirname } from "node:path";
|
|
8
|
-
import { loadWasmAsModules, localDatabase } from "./node-parts.js";
|
|
8
|
+
import { loadWasmAsModules, localDatabase, preloadDataFiles } from "./node-parts.js";
|
|
9
9
|
import { startServer } from "./node.js";
|
|
10
|
+
import { COPY_STARTED_AGAIN_EXIT_CODE, countWebAssemblyMemories, heldToZaismaLimits, memoryBaselineBytes, memorySizeBytes, refuseOutsideModules } from "./like-zaisma.js";
|
|
10
11
|
|
|
11
12
|
// How startServer hands this runner its way to send room messages as the developer (node.js).
|
|
12
13
|
const LOCAL_BENCH_ROOM_MESSAGE = Symbol.for("zaisma.localBenchRoomMessage");
|
|
@@ -19,8 +20,34 @@ try {
|
|
|
19
20
|
probe.once("error", (error) => reject(error?.code === "EADDRINUSE" ? new Error(`Port ${config.port} is already in use, so your game server can't start. Stop what's using it, or start the bench with another --port.`) : error));
|
|
20
21
|
probe.listen(config.port, () => probe.close(resolve));
|
|
21
22
|
});
|
|
22
|
-
|
|
23
|
-
|
|
23
|
+
let gameServer = relay;
|
|
24
|
+
// The game server as a copy of it runs on Zaisma's rooms: its own modules only, its data files read whole as it starts,
|
|
25
|
+
// its handlers' CPU and its memory measured (like-zaisma.js). Everything the runner holds before it doesn't count.
|
|
26
|
+
let checkMemory = () => {};
|
|
27
|
+
if (config.entry) {
|
|
28
|
+
loadWasmAsModules(dirname(config.entry));
|
|
29
|
+
refuseOutsideModules(config.entry);
|
|
30
|
+
countWebAssemblyMemories();
|
|
31
|
+
const baselineBytes = memoryBaselineBytes();
|
|
32
|
+
preloadDataFiles(config.dataFolder);
|
|
33
|
+
// Said as Zaisma's rooms say a game server that fails to load.
|
|
34
|
+
const loaded = await import(pathToFileURL(config.entry).href).then(
|
|
35
|
+
(module) => module.default,
|
|
36
|
+
(error) => {
|
|
37
|
+
throw new Error(`Zaisma: the game server didn't start: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
38
|
+
},
|
|
39
|
+
);
|
|
40
|
+
let isCopyStartingAgain = false;
|
|
41
|
+
checkMemory = () => {
|
|
42
|
+
if (isCopyStartingAgain) return;
|
|
43
|
+
const sizeBytes = memorySizeBytes(baselineBytes);
|
|
44
|
+
if (sizeBytes <= GAME_SERVER_LIMITS.maximumMemorySizeBytes) return;
|
|
45
|
+
isCopyStartingAgain = true;
|
|
46
|
+
console.error(copyStartedAgainText(sizeBytes));
|
|
47
|
+
void stop(COPY_STARTED_AGAIN_EXIT_CODE);
|
|
48
|
+
};
|
|
49
|
+
gameServer = loaded && typeof loaded === "object" ? heldToZaismaLimits(loaded, { print: (level, text) => (level === "error" ? console.error(text) : console.warn(text)), onStart: () => setImmediate(checkMemory) }) : loaded;
|
|
50
|
+
}
|
|
24
51
|
const running = startServer({
|
|
25
52
|
gameServer,
|
|
26
53
|
gameSlug: config.gameSlug,
|
|
@@ -36,10 +63,11 @@ try {
|
|
|
36
63
|
developerApiUrl: config.developerApiUrl,
|
|
37
64
|
});
|
|
38
65
|
let stopping = null;
|
|
39
|
-
const stop = () => (stopping ??= running.close().then(() => process.exit(
|
|
40
|
-
|
|
66
|
+
const stop = (exitCode = 0) => (stopping ??= running.close().then(() => process.exit(exitCode)));
|
|
67
|
+
setInterval(() => checkMemory(), STATE_COPY_INTERVAL_MS).unref();
|
|
68
|
+
for (const signal of ["SIGTERM", "SIGINT"]) process.once(signal, () => stop());
|
|
41
69
|
// The bench holds this pipe open while it runs: when it ends, however it ended, this game server stops too (rooms save first).
|
|
42
|
-
process.stdin.once("close", stop);
|
|
70
|
+
process.stdin.once("close", () => stop());
|
|
43
71
|
// The bench's sends to rooms come as JSON lines on the same pipe, { askNumber, message, roomCode }, each answered on a line of its own.
|
|
44
72
|
let rest = "";
|
|
45
73
|
process.stdin.setEncoding("utf8");
|
package/bin/local-play.js
CHANGED
|
@@ -28,6 +28,7 @@ import { BUSY_CLOSE_CODE, GameServerError, PASS_VERSION_NUMBER, RECEIPT_TOKEN_TY
|
|
|
28
28
|
import { qrCodeModules, qrCodeSvg } from "../src/qr-code.js";
|
|
29
29
|
import { ARRIVE_SCRIPT_SOURCE, FRAME_ALLOW, KEPT_SCRIPT_SOURCE, devScriptSource } from "./local-play-bench.js";
|
|
30
30
|
import { isCertificateGood, makeCertificate } from "./local-play-certificate.js";
|
|
31
|
+
import { COPY_STARTED_AGAIN_EXIT_CODE } from "./like-zaisma.js";
|
|
31
32
|
|
|
32
33
|
/** The first of the four ports. */
|
|
33
34
|
export const DEFAULT_PORT_NUMBER = 4800;
|
|
@@ -44,6 +45,9 @@ const PASS_DURATION_SEC = 24 * 3600;
|
|
|
44
45
|
const SCRIPTS_VERSION_NUMBER = 7;
|
|
45
46
|
const SLOW_RESTART_MS = 150;
|
|
46
47
|
const RUNNER_START_TIMEOUT_MS = 15_000;
|
|
48
|
+
/** Memory restarts in MEMORY_RESTART_WINDOW_MS the bench makes before it waits for a fix, so one that goes over as soon as it starts doesn't restart for good. */
|
|
49
|
+
const MEMORY_RESTART_COUNT = 3;
|
|
50
|
+
const MEMORY_RESTART_WINDOW_MS = 60_000;
|
|
47
51
|
const LOCAL_RUNNER_KEY = "zaisma-local-key";
|
|
48
52
|
const TYPES = {
|
|
49
53
|
".html": "text/html; charset=utf-8", ".htm": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".mjs": "text/javascript; charset=utf-8",
|
|
@@ -1522,7 +1526,8 @@ export async function startLocalPlay(givenOptions) {
|
|
|
1522
1526
|
tell("reload");
|
|
1523
1527
|
}
|
|
1524
1528
|
const config = { entry: entry(), gameSlug, port: ports.runner, origin: localhostOrigin(ports.game), issuerUrl: roomsAddress(), databaseFile: join(localFolder, "database.sqlite"), roomStateFile: join(localFolder, "room-states.sqlite"), dataFolder: join(gameFolder, "zaisma-server"), developerApiUrl: `${roomsAddress()}/api/dev`, zaismaKey: LOCAL_RUNNER_KEY };
|
|
1525
|
-
|
|
1529
|
+
// --expose-gc: the runner collects garbage before it decides a game server is over its memory (like-zaisma.js).
|
|
1530
|
+
const child = spawn(process.execPath, ["--disable-warning=ExperimentalWarning", "--expose-gc", runnerFile, JSON.stringify(config)], { stdio: ["pipe", "pipe", "pipe"], env: { ...process.env } });
|
|
1526
1531
|
let isReady = false;
|
|
1527
1532
|
const timeout = setTimeout(() => {
|
|
1528
1533
|
if (!isReady) {
|
|
@@ -1558,6 +1563,17 @@ export async function startLocalPlay(givenOptions) {
|
|
|
1558
1563
|
if (!isReady) {
|
|
1559
1564
|
if (!isClosing) log("Your game server didn't start. Fix what it says above and save the file: it starts again by itself.");
|
|
1560
1565
|
done(null);
|
|
1566
|
+
} else if (!isClosing && !child.zaismaIsRestarting && code === COPY_STARTED_AGAIN_EXIT_CODE) {
|
|
1567
|
+
// Over its memory: Zaisma's rooms start its copy again by themselves, and so does the bench, unless it keeps going over.
|
|
1568
|
+
const nowMs = Date.now();
|
|
1569
|
+
memoryRestartsAtMs = [...memoryRestartsAtMs.filter((atMs) => nowMs - atMs < MEMORY_RESTART_WINDOW_MS), nowMs];
|
|
1570
|
+
if (memoryRestartsAtMs.length > MEMORY_RESTART_COUNT) {
|
|
1571
|
+
log(`Your game server went over its memory ${memoryRestartsAtMs.length} times in a minute, so the bench stopped starting it again. Fix it and save a game server file to start it again.`);
|
|
1572
|
+
memoryRestartsAtMs = [];
|
|
1573
|
+
} else {
|
|
1574
|
+
log("Your game server is starting again, as Zaisma's rooms start a copy that went over its memory. Here every room is saved and comes back through onRestored, and players reconnect; on Zaisma, players stay and the room carries on from its last state copy, with no onRestored.");
|
|
1575
|
+
void restartRunner();
|
|
1576
|
+
}
|
|
1561
1577
|
} else if (!isClosing && !child.zaismaIsRestarting) log(`Your game server stopped (exit code ${code}). Save a game server file to start it again.`);
|
|
1562
1578
|
});
|
|
1563
1579
|
runnerStartCount++;
|
|
@@ -1576,6 +1592,8 @@ export async function startLocalPlay(givenOptions) {
|
|
|
1576
1592
|
setTimeout(() => child.kill("SIGKILL"), 10_000).unref();
|
|
1577
1593
|
});
|
|
1578
1594
|
}
|
|
1595
|
+
// When the game server went over its memory lately: past MEMORY_RESTART_COUNT in a minute, the bench waits for a fix.
|
|
1596
|
+
let memoryRestartsAtMs = [];
|
|
1579
1597
|
let restartChain = Promise.resolve();
|
|
1580
1598
|
const restartRunner = () => {
|
|
1581
1599
|
restartChain = restartChain.then(async () => {
|
package/bin/node-parts.js
CHANGED
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
// profiles, its local SQLite files, and the checks on its options. Nothing here is part of the
|
|
3
3
|
// public package: tests reach it by path.
|
|
4
4
|
import { randomUUID } from "node:crypto";
|
|
5
|
-
import { existsSync, readFileSync, realpathSync, statSync } from "node:fs";
|
|
5
|
+
import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from "node:fs";
|
|
6
6
|
import { registerHooks } from "node:module";
|
|
7
|
-
import { resolve, sep } from "node:path";
|
|
7
|
+
import { join, resolve, sep } from "node:path";
|
|
8
8
|
import { pathToFileURL } from "node:url";
|
|
9
9
|
import { DATABASE_LIMITS, GameServerError, answerDatabase, checkBatch, checkPlayerId, checkStatement, checkedRow, eraseRefused, eraseStatements, readDatabaseAnswer, tablesFromColumns, tooManyRows, TABLE_COLUMNS_SQL } from "../src/internal.js";
|
|
10
10
|
|
|
@@ -429,9 +429,12 @@ const CODE_FILE = /\.(js|json|wasm)$/;
|
|
|
429
429
|
* room.readDataFile and server.readDataFile on your own server: a data file from the folder by its path there (each
|
|
430
430
|
* read once, then the same ArrayBuffer), or null for no such file, a code file, or a path outside the folder.
|
|
431
431
|
*/
|
|
432
|
+
// The files play-locally read first (preloadDataFiles), by folder: the reader of that folder starts from them.
|
|
433
|
+
const preloadedByFolder = new Map();
|
|
434
|
+
|
|
432
435
|
export function dataFilesFrom(dataFolder) {
|
|
433
436
|
const folder = resolve(dataFolder);
|
|
434
|
-
const read = new Map();
|
|
437
|
+
const read = preloadedByFolder.get(folder) ?? new Map();
|
|
435
438
|
return (dataFilePath) => {
|
|
436
439
|
if (read.has(dataFilePath)) return read.get(dataFilePath);
|
|
437
440
|
const path = resolve(folder, dataFilePath);
|
|
@@ -453,6 +456,32 @@ export function dataFilesFrom(dataFolder) {
|
|
|
453
456
|
};
|
|
454
457
|
}
|
|
455
458
|
|
|
459
|
+
/**
|
|
460
|
+
* Reads every data file in the folder now, as a copy of the game server on Zaisma's rooms does as it starts, so they
|
|
461
|
+
* count in its memory from the start (play-locally). Answers their size in all.
|
|
462
|
+
*/
|
|
463
|
+
export function preloadDataFiles(dataFolder) {
|
|
464
|
+
const folder = resolve(dataFolder);
|
|
465
|
+
if (!preloadedByFolder.has(folder)) preloadedByFolder.set(folder, new Map());
|
|
466
|
+
const find = dataFilesFrom(folder);
|
|
467
|
+
let sizeBytes = 0;
|
|
468
|
+
const walk = (subfolder) => {
|
|
469
|
+
let entries = [];
|
|
470
|
+
try {
|
|
471
|
+
entries = readdirSync(join(folder, subfolder), { withFileTypes: true });
|
|
472
|
+
} catch {
|
|
473
|
+
return;
|
|
474
|
+
}
|
|
475
|
+
for (const entry of entries) {
|
|
476
|
+
const path = subfolder ? `${subfolder}/${entry.name}` : entry.name;
|
|
477
|
+
if (entry.isDirectory()) walk(path);
|
|
478
|
+
else if (entry.isFile()) sizeBytes += find(path)?.byteLength ?? 0;
|
|
479
|
+
}
|
|
480
|
+
};
|
|
481
|
+
walk("");
|
|
482
|
+
return sizeBytes;
|
|
483
|
+
}
|
|
484
|
+
|
|
456
485
|
/**
|
|
457
486
|
* Makes `import mod from "./x.wasm"` inside the game server's folder give a WebAssembly.Module, as on Zaisma's rooms,
|
|
458
487
|
* instead of Node's own instance exports (which also fail on a module with imports, like wasm-bindgen's).
|
package/bin/node.js
CHANGED
|
@@ -956,10 +956,84 @@ function playLocallyArguments(argumentList) {
|
|
|
956
956
|
return { folder: folder ?? ".", portNumber, gameSlug: flags.game ?? null, isOnNetwork: flags["on-network"] === true, isOpening: flags["no-open"] !== true, isJson: flags.json === true };
|
|
957
957
|
}
|
|
958
958
|
|
|
959
|
+
/** How this copy of a package was installed, from where its file sits: through npx, in a project, globally, or a source checkout. */
|
|
960
|
+
function installKindOf(filePath) {
|
|
961
|
+
const path = filePath.replaceAll("\\", "/");
|
|
962
|
+
if (path.includes("/_npx/")) return "npx";
|
|
963
|
+
return installKindAt(path);
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
/**
|
|
967
|
+
* A project's or a global install, from the folder that holds the outermost node_modules: a project has its package.json there,
|
|
968
|
+
* npm's global folder (lib/ under its prefix, wherever that is) has none. A path outside any node_modules is a source checkout.
|
|
969
|
+
*/
|
|
970
|
+
function installKindAt(path) {
|
|
971
|
+
const index = path.indexOf("/node_modules/");
|
|
972
|
+
if (index === -1) return "checkout";
|
|
973
|
+
try {
|
|
974
|
+
readFileSync(`${path.slice(0, index)}/package.json`);
|
|
975
|
+
return "project";
|
|
976
|
+
} catch {
|
|
977
|
+
return "global";
|
|
978
|
+
}
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
/** Whether a version is above another, both x.y.z. */
|
|
982
|
+
function isVersionAbove(version, otherVersion) {
|
|
983
|
+
const [first, second] = [version, otherVersion].map((version) => /^(\d+)\.(\d+)\.(\d+)$/.exec(version ?? "")?.slice(1).map(Number));
|
|
984
|
+
if (!first || !second) return false;
|
|
985
|
+
for (let index = 0; index < 3; index++) if (first[index] !== second[index]) return first[index] > second[index];
|
|
986
|
+
return false;
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
/**
|
|
990
|
+
* The one line saying a newer version of a package is out, or null when this one is the latest (or npm wasn't reached). What to do
|
|
991
|
+
* follows from how it was installed: npx gets the latest when it starts again; a project's or a global install moves up with npm.
|
|
992
|
+
*/
|
|
993
|
+
function newerVersionLine({ packageName, version, latestVersion, installKind, command }) {
|
|
994
|
+
if (!latestVersion || !isVersionAbove(latestVersion, version)) return null;
|
|
995
|
+
if (installKind === "project") return `${packageName} ${latestVersion} is out, and this project has ${version}: run npm install ${packageName}@latest, then ${command} again.`;
|
|
996
|
+
if (installKind === "global") return `${packageName} ${latestVersion} is out, and this computer has ${version}: run npm install -g ${packageName}@latest, then ${command} again.`;
|
|
997
|
+
return `${packageName} ${latestVersion} is out (this is ${version}): stop it and run ${command} again to use it.`;
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
/**
|
|
1001
|
+
* npm's newest version of a package in the given major, or null when npm doesn't answer within UPDATE_CHECK_TIMEOUT_MS: a start never
|
|
1002
|
+
* waits on it. Within the major, since the CLI runs @zaisma/game-server@1 and a restart never reaches a later one.
|
|
1003
|
+
*/
|
|
1004
|
+
async function npmLatestVersion(packageName, major) {
|
|
1005
|
+
const registryUrl = (process.env.npm_config_registry || "https://registry.npmjs.org").replace(/\/+$/, "");
|
|
1006
|
+
try {
|
|
1007
|
+
const response = await fetch(`${registryUrl}/${packageName.replace("/", "%2f")}`, { headers: { accept: "application/vnd.npm.install-v1+json" }, signal: AbortSignal.timeout(UPDATE_CHECK_TIMEOUT_MS) });
|
|
1008
|
+
if (!response.ok) return null;
|
|
1009
|
+
const { versions } = await response.json();
|
|
1010
|
+
return Object.keys(versions ?? {}).filter((version) => /^\d+\.\d+\.\d+$/.test(version) && version.split(".")[0] === major).reduce((highest, version) => (highest === null || isVersionAbove(version, highest) ? version : highest), null);
|
|
1011
|
+
} catch {
|
|
1012
|
+
return null;
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
/** How long play-locally waits for npm to say whether a newer version is out, after it has started. */
|
|
1017
|
+
const UPDATE_CHECK_TIMEOUT_MS = 3000;
|
|
1018
|
+
|
|
1019
|
+
/**
|
|
1020
|
+
* The lines play-locally prints when a newer bench is out: this package's, and the CLI's when the CLI started it
|
|
1021
|
+
* (ZAISMA_CLI_VERSION and ZAISMA_CLI_INSTALL_KIND). A source checkout checks nothing: it moves up with git.
|
|
1022
|
+
*/
|
|
1023
|
+
async function newerVersionLines() {
|
|
1024
|
+
const packageFile = new URL("../package.json", import.meta.url);
|
|
1025
|
+
const own = { packageName: "@zaisma/game-server", version: JSON.parse(readFileSync(packageFile, "utf8")).version, installKind: installKindOf(realpathSync(fileURLToPath(import.meta.url))) };
|
|
1026
|
+
const cli = process.env.ZAISMA_CLI_VERSION ? { packageName: "@zaisma/cli", version: process.env.ZAISMA_CLI_VERSION, installKind: process.env.ZAISMA_CLI_INSTALL_KIND ?? "npx" } : null;
|
|
1027
|
+
const checked = [cli, own].filter((each) => each && each.installKind !== "checkout");
|
|
1028
|
+
const lines = await Promise.all(checked.map(async (each) => newerVersionLine({ ...each, latestVersion: await npmLatestVersion(each.packageName, each.version.split(".")[0]), command: "play-locally" })));
|
|
1029
|
+
return lines.filter(Boolean);
|
|
1030
|
+
}
|
|
1031
|
+
|
|
959
1032
|
/** zaisma-game-server play-locally: your game and its game server on this computer, with a test bench (bin/local-play.js). */
|
|
960
1033
|
async function playLocally(argumentList) {
|
|
961
1034
|
const given = playLocallyArguments(argumentList);
|
|
962
1035
|
if (!given) process.exit(1);
|
|
1036
|
+
const newerLines = newerVersionLines();
|
|
963
1037
|
const { startLocalPlay, terminalQr } = await import("./local-play.js");
|
|
964
1038
|
const say = given.isJson ? (line) => console.error(line) : (line) => console.log(line);
|
|
965
1039
|
let running;
|
|
@@ -979,6 +1053,8 @@ async function playLocally(argumentList) {
|
|
|
979
1053
|
say(terminalQr(running.networkUrl));
|
|
980
1054
|
say("Your phone will say the connection isn't private, because the bench signs its own certificate. Continue to the site.");
|
|
981
1055
|
}
|
|
1056
|
+
// A newer bench on npm: one line once npm answers, nothing when it doesn't or this is the latest.
|
|
1057
|
+
newerLines.then((lines) => lines.forEach((line) => say(line)));
|
|
982
1058
|
if (given.isOpening) {
|
|
983
1059
|
const { spawn } = await import("node:child_process");
|
|
984
1060
|
const opener = process.platform === "darwin" ? ["open", [running.benchUrl]] : process.platform === "win32" ? ["cmd", ["/c", "start", "", running.benchUrl]] : ["xdg-open", [running.benchUrl]];
|
package/package.json
CHANGED
package/sdk/zaisma.js
CHANGED
|
@@ -205,6 +205,8 @@
|
|
|
205
205
|
var passKey = "zaisma:pass:" + config.game;
|
|
206
206
|
var passPromise = null;
|
|
207
207
|
var keyPromise = null;
|
|
208
|
+
// The page's last key gave no pass (refused, spent or run out): the next ask says so, and the page gets a fresh one.
|
|
209
|
+
var isKeySpent = false;
|
|
208
210
|
var UNCHECKED = "Zaisma couldn't check this browser, so it can't play online. Reload the game to try again.";
|
|
209
211
|
var NO_ONLINE_PLAY_IN_PREVIEW = "Online play is off in a preview of a version players don't have yet. Test online play with npx @zaisma/cli play-locally, or publish the version and play it through a tester link.";
|
|
210
212
|
|
|
@@ -215,6 +217,7 @@
|
|
|
215
217
|
*/
|
|
216
218
|
function roomKey() {
|
|
217
219
|
if (!keyPromise) {
|
|
220
|
+
var isAgain = isKeySpent;
|
|
218
221
|
keyPromise = new Promise(function (resolve, reject) {
|
|
219
222
|
function fail(message) { reject(codedError("unchecked", message)); }
|
|
220
223
|
function failInPreview(message) { reject(codedError("no_online_play_in_preview", message)); }
|
|
@@ -231,12 +234,24 @@
|
|
|
231
234
|
else fail(UNCHECKED);
|
|
232
235
|
}
|
|
233
236
|
addEventListener("message", onMessage);
|
|
234
|
-
window.parent.postMessage({ type: "zaisma:room-key" }, config.site);
|
|
237
|
+
window.parent.postMessage(isAgain ? { type: "zaisma:room-key", is_again: true } : { type: "zaisma:room-key" }, config.site);
|
|
235
238
|
});
|
|
239
|
+
// A key that didn't come isn't kept: the next join asks the page again, so one failed check doesn't hold the tab until a reload.
|
|
240
|
+
keyPromise.catch(function () { keyPromise = null; isKeySpent = true; });
|
|
236
241
|
}
|
|
237
242
|
return keyPromise;
|
|
238
243
|
}
|
|
239
244
|
|
|
245
|
+
/** A pass from the page's key; a key Zaisma no longer takes (its passes spent, or run out) is swapped for a fresh one, once. */
|
|
246
|
+
function passFromKey(given, isRetry) {
|
|
247
|
+
return post("/v1/pass", { gameSlug: config.game, roomKey: given.key }).catch(function (error) {
|
|
248
|
+
if (isRetry || !error || error.code !== "unchecked") throw error;
|
|
249
|
+
keyPromise = null;
|
|
250
|
+
isKeySpent = true;
|
|
251
|
+
return roomKey().then(function (fresh) { return passFromKey(fresh, true); });
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
|
|
240
255
|
/**
|
|
241
256
|
* What a Zaisma room or request hears about where this player plays from on the meter: the word /v1/pass gave beside the pass, which
|
|
242
257
|
* this SDK can't read, and two things an honest browser can say. Nothing that tells this person from anyone else. Only rooms read them.
|
|
@@ -302,7 +317,8 @@
|
|
|
302
317
|
// and blocks as they are now; the account's player ID is the same either way.
|
|
303
318
|
var kept = keptPass();
|
|
304
319
|
if (kept && kept.kind === "guest" && given.playerKind === "guest") return kept;
|
|
305
|
-
return
|
|
320
|
+
return passFromKey(given, false).then(function (answer) {
|
|
321
|
+
isKeySpent = false;
|
|
306
322
|
var mine = { id: answer.player.id, name: answer.player.name, kind: answer.player.kind, pass: answer.pass, expiresAt: answer.expiresAt };
|
|
307
323
|
keptPlayShare = answer.playShare || null;
|
|
308
324
|
try {
|
package/src/internal.d.ts
CHANGED
package/src/internal.js
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// Never published or locked: games and developers' servers use the package's index.
|
|
3
3
|
export * from "./room.js";
|
|
4
4
|
export * from "./room-calls.js";
|
|
5
|
+
export * from "./sandbox-limits.js";
|
|
5
6
|
export * from "./state-sync.js";
|
|
6
7
|
export * from "./database.js";
|
|
7
8
|
export * from "./dump.js";
|