@hadoku/game-server 0.1.196 → 0.1.198

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.
@@ -8,8 +8,9 @@
8
8
  * that cannot be fetched or read never unregisters a game that was read once: the copy on disk
9
9
  * stands in, and the reason is logged. Only a game never read anywhere has no manifest.
10
10
  */
11
- import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
11
+ import { readFile } from 'node:fs/promises';
12
12
  import { join } from 'node:path';
13
+ import { atomicWriteJson } from '@wolffm/service-kernel/state';
13
14
  import { externalGameManifest, manifestPathOf, } from '@wolffm/platform-wire/external-game-manifest';
14
15
  const DEFAULT_TIMEOUT_MS = 5_000;
15
16
  function describe(err) {
@@ -49,12 +50,7 @@ export function manifestReader(opts) {
49
50
  }
50
51
  return parsed(JSON.parse(text));
51
52
  };
52
- const writeCache = async (id, manifest) => {
53
- await mkdir(opts.cacheDir, { recursive: true });
54
- const tmp = `${cacheFile(id)}.tmp`;
55
- await writeFile(tmp, `${JSON.stringify(manifest, null, 2)}\n`, 'utf8');
56
- await rename(tmp, cacheFile(id));
57
- };
53
+ const writeCache = (id, manifest) => atomicWriteJson(cacheFile(id), manifest);
58
54
  return async (game) => {
59
55
  if (game.manifest !== undefined)
60
56
  return { manifest: parsed(game.manifest), source: 'inline' };
@@ -56,3 +56,10 @@ export declare function perCallerLimit(cfg: RateLimitConfig | null, refusal: str
56
56
  now?: () => number;
57
57
  onRefused?: () => void;
58
58
  }): (req: Request, res: Response) => boolean;
59
+ /** A refusal whose HTTP status is already decided: a store throws it, its route answers it with {@link sendRefusal}. */
60
+ export declare class HttpRefusal extends Error {
61
+ readonly status: number;
62
+ constructor(status: number, message: string);
63
+ }
64
+ /** Answers `err` with its status and `{ error }` when it is an {@link HttpRefusal}; false, nothing sent, for anything else. */
65
+ export declare function sendRefusal(res: Response, err: unknown): boolean;
@@ -35,3 +35,19 @@ export function costlyActLimit(cfg, opts) {
35
35
  export function perCallerLimit(cfg, refusal, opts) {
36
36
  return kernelPerCallerLimit(cfg, refusal, { ...opts, callerId: httpCaller });
37
37
  }
38
+ /** A refusal whose HTTP status is already decided: a store throws it, its route answers it with {@link sendRefusal}. */
39
+ export class HttpRefusal extends Error {
40
+ status;
41
+ constructor(status, message) {
42
+ super(message);
43
+ this.name = 'HttpRefusal';
44
+ this.status = status;
45
+ }
46
+ }
47
+ /** Answers `err` with its status and `{ error }` when it is an {@link HttpRefusal}; false, nothing sent, for anything else. */
48
+ export function sendRefusal(res, err) {
49
+ if (!(err instanceof HttpRefusal))
50
+ return false;
51
+ res.status(err.status).json({ error: err.message });
52
+ return true;
53
+ }
@@ -20,7 +20,7 @@
20
20
  * and answers `{ gameType }` (and, opted in, `{ settings }`) itself; anything else goes to `opts.onPatch`, a
21
21
  * hook `rooms.ts` passes in — never a second route, never `res.locals`.
22
22
  */
23
- import { Router, type NextFunction, type Request, type Response } from 'express';
23
+ import { Router, type Request, type Response } from 'express';
24
24
  import { type RateLimitConfig } from '@wolffm/rooms-server';
25
25
  import { bodyErrors, callerOf, type BodySchema } from './request.js';
26
26
  /** Who is asking — exactly what `callerOf` returns, never a redeclared shape. */
@@ -290,8 +290,6 @@ export declare function notDurable(res: Response, verb?: string): void;
290
290
  * with a tier floor (`room/tier-floor.ts`) is for that tier and above, by the edge's own name for it.
291
291
  */
292
292
  export declare function roomVisibleTo(req: Request, room: RoomViewCore): boolean;
293
- /** A room the caller may not see ({@link roomVisibleTo}) is as if it did not exist — shared by this file's router and `rooms.ts`'s. */
294
- export declare function hideRoomsParam<V extends RoomViewCore>(lobby: Pick<LobbyCore<V, never>, 'get'>): (req: Request, res: Response, next: NextFunction, id: string) => void;
295
293
  export interface RoomCoreHandle<V extends RoomViewCore, G = never> {
296
294
  router: Router;
297
295
  roomBody(room: V, callerId: string): RoomBody<V, G>;
@@ -168,9 +168,15 @@ export function roomVisibleTo(req, room) {
168
168
  return false;
169
169
  return tierAdmits(room.minTier, edgeTierOf(req));
170
170
  }
171
- /** A room the caller may not see ({@link roomVisibleTo}) is as if it did not exist — shared by this file's router and `rooms.ts`'s. */
172
- export function hideRoomsParam(lobby) {
171
+ /**
172
+ * Every `:id` route's guard, on the one router this file and `rooms.ts` both add to: an id that is
173
+ * no room id's shape, or a room the caller may not see ({@link roomVisibleTo}), is as if it did not
174
+ * exist — answered before the route reads its body or asks the lobby.
175
+ */
176
+ function roomParam(lobby, roomIdRe) {
173
177
  return (req, res, next, id) => {
178
+ if (!roomIdRe.test(id))
179
+ return noMatch(res);
174
180
  const room = lobby.get(id);
175
181
  if (room !== undefined && !roomVisibleTo(req, room))
176
182
  return noMatch(res);
@@ -181,8 +187,21 @@ export function attachRoomCore(api, deps, opts = {}) {
181
187
  const { lobby, wire } = deps;
182
188
  const log = deps.log ?? jsonLogger('cardtable-rooms');
183
189
  const now = deps.now ?? Date.now;
184
- const joinLimiter = new MultiRateLimiter(deps.joinRateLimit ?? JOIN_RATE_LIMIT);
185
- const seatOpLimiter = new MultiRateLimiter(SEAT_OP_RATE_LIMIT);
190
+ /** A per-caller budget: false once its 429 (with `Retry-After`) is sent. */
191
+ const limitOf = (cfg, event, error) => {
192
+ const limiter = new MultiRateLimiter(cfg);
193
+ return (callerId, res) => {
194
+ if (limiter.allow(callerId, 1, now()))
195
+ return true;
196
+ log({ event, reason: 'rate-limited' });
197
+ res.setHeader('Retry-After', String(Math.ceil(cfg.refillIntervalMs / 1000)));
198
+ res.status(429).json({ error });
199
+ return false;
200
+ };
201
+ };
202
+ const joinLimit = limitOf(deps.joinRateLimit ?? JOIN_RATE_LIMIT, 'room-join-refused', 'too many join attempts; wait a little and try again');
203
+ /** The leader's own limit, spent whether the op succeeds or is refused for any reason but a bad body — a flood of refusals is still a flood. */
204
+ const seatOpLimit = limitOf(SEAT_OP_RATE_LIMIT, 'seat-op-refused', 'too many seat changes; wait a little and try again');
186
205
  const roomBody = (room, callerId) => {
187
206
  const mine = room.members.find((m) => m.id === callerId);
188
207
  const games = deps.tableGames?.(room);
@@ -198,7 +217,7 @@ export function attachRoomCore(api, deps, opts = {}) {
198
217
  };
199
218
  };
200
219
  const rooms = Router();
201
- rooms.param('id', hideRoomsParam(lobby));
220
+ rooms.param('id', roomParam(lobby, wire.roomIdRe));
202
221
  rooms.get('/', (req, res) => {
203
222
  const me = callerOf(req).id;
204
223
  // A testing room is never offered to a non-admin, nor a friends-only room below friend.
@@ -235,11 +254,8 @@ export function attachRoomCore(api, deps, opts = {}) {
235
254
  if (body === null)
236
255
  return;
237
256
  const caller = callerOf(req);
238
- if (!lobby.isMember(watchpartyRoomId(body.room), caller.id) && !joinLimiter.allow(caller.id, 1, now())) {
239
- log({ event: 'room-join-refused', reason: 'rate-limited' });
240
- res.setHeader('Retry-After', String(Math.ceil((deps.joinRateLimit ?? JOIN_RATE_LIMIT).refillIntervalMs / 1000)));
241
- return res.status(429).json({ error: 'too many join attempts; wait a little and try again' });
242
- }
257
+ if (!lobby.isMember(watchpartyRoomId(body.room), caller.id) && !joinLimit(caller.id, res))
258
+ return;
243
259
  const result = lobby.bindWatchparty(caller, body.room);
244
260
  if (!result.ok)
245
261
  return notDurable(res);
@@ -261,7 +277,7 @@ export function attachRoomCore(api, deps, opts = {}) {
261
277
  opts.beforeWildcard?.(rooms);
262
278
  rooms.get('/:id', (req, res) => {
263
279
  const id = String(req.params.id);
264
- const room = wire.roomIdRe.test(id) ? lobby.get(id) : undefined;
280
+ const room = lobby.get(id);
265
281
  if (room === undefined)
266
282
  return noMatch(res);
267
283
  const me = callerOf(req).id;
@@ -275,20 +291,15 @@ export function attachRoomCore(api, deps, opts = {}) {
275
291
  const caller = callerOf(req);
276
292
  const id = String(req.params.id);
277
293
  // A member re-entering needs no password and spends no token.
278
- if (wire.roomIdRe.test(id) && lobby.isMember(id, caller.id)) {
294
+ if (lobby.isMember(id, caller.id)) {
279
295
  const again = lobby.join(id, caller);
280
296
  if (again.ok) {
281
297
  deps.arrived?.(id, caller);
282
298
  return res.json(roomBody(again.room, caller.id));
283
299
  }
284
300
  }
285
- if (!joinLimiter.allow(caller.id, 1, now())) {
286
- log({ event: 'room-join-refused', reason: 'rate-limited' });
287
- res.setHeader('Retry-After', String(Math.ceil((deps.joinRateLimit ?? JOIN_RATE_LIMIT).refillIntervalMs / 1000)));
288
- return res.status(429).json({ error: 'too many join attempts; wait a little and try again' });
289
- }
290
- if (!wire.roomIdRe.test(id))
291
- return noMatch(res);
301
+ if (!joinLimit(caller.id, res))
302
+ return;
292
303
  const result = lobby.join(id, caller, body.password);
293
304
  if (!result.ok) {
294
305
  if (result.reason === 'not-durable')
@@ -307,7 +318,7 @@ export function attachRoomCore(api, deps, opts = {}) {
307
318
  if (!isDurableParticipantId(caller.id))
308
319
  return notDurable(res, 'take part in');
309
320
  const id = String(req.params.id);
310
- if (!wire.roomIdRe.test(id) || !lobby.setReady(id, caller.id, body.ready))
321
+ if (!lobby.setReady(id, caller.id, body.ready))
311
322
  return noMatch(res);
312
323
  const room = lobby.get(id);
313
324
  if (room === undefined)
@@ -324,8 +335,6 @@ export function attachRoomCore(api, deps, opts = {}) {
324
335
  if (!isDurableParticipantId(caller.id))
325
336
  return notDurable(res, 'leave');
326
337
  const id = String(req.params.id);
327
- if (!wire.roomIdRe.test(id))
328
- return noMatch(res);
329
338
  if (req.query.drop !== '1' && lobby.leaveDrops(id, caller.id))
330
339
  return res.status(409).json({ error: 'leaving now drops you from the tournament', reason: 'drops' });
331
340
  const result = lobby.leave(id, caller.id);
@@ -343,7 +352,7 @@ export function attachRoomCore(api, deps, opts = {}) {
343
352
  if (!isDurableParticipantId(caller.id))
344
353
  return notDurable(res, 'close');
345
354
  const id = String(req.params.id);
346
- if (!wire.roomIdRe.test(id) || !lobby.isMember(id, caller.id))
355
+ if (!lobby.isMember(id, caller.id))
347
356
  return noMatch(res);
348
357
  const wasTesting = lobby.get(id)?.testing === true;
349
358
  const result = lobby.close(id, caller.id);
@@ -363,7 +372,7 @@ export function attachRoomCore(api, deps, opts = {}) {
363
372
  return;
364
373
  const caller = callerOf(req);
365
374
  const id = String(req.params.id);
366
- if (!wire.roomIdRe.test(id) || !isAdmin(req) || lobby.get(id)?.testing !== true)
375
+ if (!isAdmin(req) || lobby.get(id)?.testing !== true)
367
376
  return noMatch(res);
368
377
  const result = lobby.close(id, caller.id);
369
378
  if (!result.ok)
@@ -372,104 +381,45 @@ export function attachRoomCore(api, deps, opts = {}) {
372
381
  deps.reseedTesting?.();
373
382
  res.json({ ok: true });
374
383
  });
375
- /** The leader's own rate limit, spent whether the op succeeds or is refused for any reason but a bad body — a flood of refusals is still a flood. */
376
- const seatOpLimit = (req, res) => {
377
- const caller = callerOf(req);
378
- if (seatOpLimiter.allow(caller.id, 1, now()))
379
- return true;
380
- log({ event: 'seat-op-refused', reason: 'rate-limited' });
381
- res.setHeader('Retry-After', String(Math.ceil(SEAT_OP_RATE_LIMIT.refillIntervalMs / 1000)));
382
- res.status(429).json({ error: 'too many seat changes; wait a little and try again' });
383
- return false;
384
+ /**
385
+ * One seat route. `leader`: the leader's op, so an operator (`deps.operator`) may act in the
386
+ * leader's place; a member's own sit and stand are not. `limited`: it spends `SEAT_OP_RATE_LIMIT`
387
+ * (an op on another person or on the room's size); one that touches only the caller's own seat or
388
+ * an open one never does, as a leader filling a pod with the AI makes a dozen of them in a row.
389
+ */
390
+ const seatRoute = (path, schema, how, run) => {
391
+ rooms.post(`/:id/${path}`, (req, res) => {
392
+ // No body at all is `{}`, as it is for every other room route.
393
+ const body = readBody(schema, req.body ?? {});
394
+ if (!body.ok)
395
+ return void res.status(400).json({ error: body.error });
396
+ const caller = callerOf(req);
397
+ if (how.limited && !seatOpLimit(caller.id, res))
398
+ return;
399
+ const result = run(String(req.params.id), caller.id, body.value, how.leader && deps.operator?.(req) === true);
400
+ if (!result.ok)
401
+ return seatOpStatus(res, result.reason);
402
+ res.json({ ...roomBody(result.room, caller.id), ...('evicted' in result ? { evicted: result.evicted } : {}) });
403
+ });
384
404
  };
385
- // The leader removes a seated member to the spectator row (wave 119 §S).
386
- rooms.post('/:id/seats/remove', (req, res) => {
387
- const body = parseBody(removeFromSeatBody, req, res);
388
- if (body === null || !seatOpLimit(req, res))
389
- return;
390
- const caller = callerOf(req);
391
- const id = String(req.params.id);
392
- if (!wire.roomIdRe.test(id))
393
- return noMatch(res);
394
- const result = lobby.removeFromSeat(id, caller.id, body.memberId, deps.operator?.(req) === true);
395
- if (!result.ok)
396
- return seatOpStatus(res, result.reason);
397
- res.json(roomBody(result.room, caller.id));
398
- });
399
- // The leader lowers the seat count, evicting whoever holds a seat past it (wave 119 §S).
400
- rooms.post('/:id/seats/capacity', (req, res) => {
401
- const body = parseBody(lowerCapacityBody, req, res);
402
- if (body === null || !seatOpLimit(req, res))
403
- return;
404
- const caller = callerOf(req);
405
- const id = String(req.params.id);
406
- if (!wire.roomIdRe.test(id))
407
- return noMatch(res);
408
- const result = lobby.lowerSeatCapacity(id, caller.id, body.count, deps.operator?.(req) === true);
409
- if (!result.ok)
410
- return seatOpStatus(res, result.reason);
411
- res.json({ ...roomBody(result.room, caller.id), evicted: result.evicted });
412
- });
413
- // The leader puts the AI in a seat, evicting its human occupant first (wave 119 §S).
414
- rooms.post('/:id/seats/bot', (req, res) => {
415
- const body = parseBody(botReplacesHumanBody, req, res);
416
- if (body === null || !seatOpLimit(req, res))
417
- return;
418
- const caller = callerOf(req);
419
- const id = String(req.params.id);
420
- if (!wire.roomIdRe.test(id))
421
- return noMatch(res);
422
- const result = lobby.botReplacesHuman(id, caller.id, body.seat, deps.operator?.(req) === true);
423
- if (!result.ok)
424
- return seatOpStatus(res, result.reason);
425
- res.json({ ...roomBody(result.room, caller.id), evicted: result.evicted });
426
- });
405
+ const leaderOp = { leader: true, limited: true };
406
+ // The leader removes a seated member to the spectator row, lowers the seat count evicting whoever
407
+ // sits past it, or puts the AI in a human's seat (wave 119 §S); or hands the room to another member.
408
+ seatRoute('seats/remove', removeFromSeatBody, leaderOp, (id, callerId, body, override) => lobby.removeFromSeat(id, callerId, body.memberId, override));
409
+ seatRoute('seats/capacity', lowerCapacityBody, leaderOp, (id, callerId, body, override) => lobby.lowerSeatCapacity(id, callerId, body.count, override));
410
+ seatRoute('seats/bot', botReplacesHumanBody, leaderOp, (id, callerId, body, override) => lobby.botReplacesHuman(id, callerId, body.seat, override));
411
+ seatRoute('leader', removeFromSeatBody, leaderOp, (id, callerId, body, override) => lobby.passLeader(id, callerId, body.memberId, override));
427
412
  const seats = deps.seatRoutes;
428
413
  if (seats !== undefined) {
429
414
  // Opted in (`RoomCoreDeps.seatRoutes`): a member sits and stands; the leader closes, opens, and puts the AI in an open seat or takes it back out.
430
- /**
431
- * One opt-in seat route. `leader`: the leader's op, so an operator (`deps.operator`) may act in
432
- * the leader's place; a member's own sit and stand are not. None of these spends
433
- * `SEAT_OP_RATE_LIMIT`: they touch only the caller's own seat or an open one, and a leader
434
- * filling a pod with the AI makes a dozen of them in a row.
435
- */
436
- const seatRoute = (path, schema, leader, run) => {
437
- rooms.post(`/:id/seats/${path}`, (req, res) => {
438
- // No body at all is `{}`, as it is for every other room route.
439
- const read = readBody(schema, req.body ?? {});
440
- if (!read.ok)
441
- return void res.status(400).json({ error: read.error });
442
- const body = read.value;
443
- const caller = callerOf(req);
444
- const id = String(req.params.id);
445
- if (!wire.roomIdRe.test(id))
446
- return noMatch(res);
447
- const result = run(id, caller.id, body, leader && deps.operator?.(req) === true);
448
- if (!result.ok)
449
- return seatOpStatus(res, result.reason);
450
- res.json(roomBody(result.room, caller.id));
451
- });
452
- };
453
- seatRoute('sit', sitSeatBody, false, (id, callerId, body) => seats.sitSeat(id, callerId, body.seat));
454
- seatRoute('stand', emptyBody, false, (id, callerId) => seats.standSeat(id, callerId));
455
- seatRoute('close', closeSeatBody, true, (id, callerId, body, override) => seats.closeSeat(id, callerId, body.seat, body.closed, override));
456
- seatRoute('bot-on', botReplacesHumanBody, true, (id, callerId, body, override) => seats.aiSeat(id, callerId, body.seat, true, override));
457
- seatRoute('bot-off', botReplacesHumanBody, true, (id, callerId, body, override) => seats.aiSeat(id, callerId, body.seat, false, override));
415
+ const own = { leader: false, limited: false };
416
+ const openSeat = { leader: true, limited: false };
417
+ seatRoute('seats/sit', sitSeatBody, own, (id, callerId, body) => seats.sitSeat(id, callerId, body.seat));
418
+ seatRoute('seats/stand', emptyBody, own, (id, callerId) => seats.standSeat(id, callerId));
419
+ seatRoute('seats/close', closeSeatBody, openSeat, (id, callerId, body, override) => seats.closeSeat(id, callerId, body.seat, body.closed, override));
420
+ seatRoute('seats/bot-on', botReplacesHumanBody, openSeat, (id, callerId, body, override) => seats.aiSeat(id, callerId, body.seat, true, override));
421
+ seatRoute('seats/bot-off', botReplacesHumanBody, openSeat, (id, callerId, body, override) => seats.aiSeat(id, callerId, body.seat, false, override));
458
422
  }
459
- // The leader hands the room to another member, seated or watching. Spends the seat-op limit.
460
- rooms.post('/:id/leader', (req, res) => {
461
- const body = parseBody(removeFromSeatBody, req, res);
462
- if (body === null || !seatOpLimit(req, res))
463
- return;
464
- const caller = callerOf(req);
465
- const id = String(req.params.id);
466
- if (!wire.roomIdRe.test(id))
467
- return noMatch(res);
468
- const result = lobby.passLeader(id, caller.id, body.memberId, deps.operator?.(req) === true);
469
- if (!result.ok)
470
- return seatOpStatus(res, result.reason);
471
- res.json(roomBody(result.room, caller.id));
472
- });
473
423
  /**
474
424
  * `{ gameType }` is this file's own: the game-type registry is platform. So is
475
425
  * `{ settings }` when `deps.settings` is set: the fields are the game's
@@ -482,8 +432,6 @@ export function attachRoomCore(api, deps, opts = {}) {
482
432
  if (v === null)
483
433
  return;
484
434
  const id = String(req.params.id);
485
- if (!wire.roomIdRe.test(id))
486
- return noMatch(res);
487
435
  const settings = deps.settings;
488
436
  if (settings !== undefined && lobby.setSettings !== undefined && hasSettings(v)) {
489
437
  const me = callerOf(req).id;
@@ -7,10 +7,10 @@
7
7
  * how are the lobby's (`Lobby.create` with `scheduledFor`), read from it each time. A form keeps
8
8
  * only its Rally id and who attached it; its title and status are Rally's.
9
9
  */
10
- import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
11
- import { dirname } from 'node:path';
10
+ import { readFile } from 'node:fs/promises';
12
11
  import { randomBytes } from 'node:crypto';
13
12
  import { z } from 'zod';
13
+ import { atomicWriteFile } from '@wolffm/service-kernel/state';
14
14
  import { moveIds, replaceIds } from '../erase/anonymise.js';
15
15
  const EventRecordSchema = z.object({
16
16
  id: z.string(),
@@ -69,9 +69,7 @@ export async function openEvents(file, log, now = Date.now) {
69
69
  const body = JSON.stringify({ events, forms });
70
70
  writing = writing.then(async () => {
71
71
  try {
72
- await mkdir(dirname(file), { recursive: true });
73
- await writeFile(`${file}.tmp`, body);
74
- await rename(`${file}.tmp`, file);
72
+ await atomicWriteFile(file, body);
75
73
  return true;
76
74
  }
77
75
  catch (err) {
@@ -7,7 +7,7 @@
7
7
  * document, a parse of what is on disk, and a merge for an account merge. So Magic's favourites,
8
8
  * last-played stamps, built decks and art picks live in Magic's own file, and this one stays MIT.
9
9
  *
10
- * Every write is a temp file renamed over the target, as `draftRooms.ts` writes a pod, so a
10
+ * Every write is atomic (the kernel's `atomicWriteJson`: a temp file renamed over the target), so a
11
11
  * reader never sees half a document and the nightly state backup (which carries the state dir
12
12
  * whole) never copies one. Updates to one person are serialised in this process, so two requests
13
13
  * that land together both keep their change.
@@ -7,7 +7,7 @@
7
7
  * document, a parse of what is on disk, and a merge for an account merge. So Magic's favourites,
8
8
  * last-played stamps, built decks and art picks live in Magic's own file, and this one stays MIT.
9
9
  *
10
- * Every write is a temp file renamed over the target, as `draftRooms.ts` writes a pod, so a
10
+ * Every write is atomic (the kernel's `atomicWriteJson`: a temp file renamed over the target), so a
11
11
  * reader never sees half a document and the nightly state backup (which carries the state dir
12
12
  * whole) never copies one. Updates to one person are serialised in this process, so two requests
13
13
  * that land together both keep their change.
@@ -20,8 +20,9 @@
20
20
  * `<userId>.json.unreadable-<ms>`, logged, and the person starts from an empty document: their
21
21
  * bytes are kept for the operator, and nothing they do afterwards is refused for it.
22
22
  */
23
- import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
23
+ import { readFile, rename, rm } from 'node:fs/promises';
24
24
  import { join } from 'node:path';
25
+ import { atomicWriteJson } from '@wolffm/service-kernel/state';
25
26
  /** A registry userId: what the edge sends as `X-User-Id`. Anything else never becomes a file name. */
26
27
  const USER_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
27
28
  export function isStorableUserId(userId) {
@@ -73,12 +74,8 @@ export function createUserStore(opts) {
73
74
  return null;
74
75
  }
75
76
  }
76
- async function write(userId, doc) {
77
- const path = pathOf(userId);
78
- await mkdir(dir, { recursive: true });
79
- const tmp = `${path}.${process.pid}.${now()}.tmp`;
80
- await writeFile(tmp, JSON.stringify(doc));
81
- await rename(tmp, path);
77
+ function write(userId, doc) {
78
+ return atomicWriteJson(pathOf(userId), doc, { compact: true });
82
79
  }
83
80
  async function drop(userId) {
84
81
  try {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@hadoku/game-server",
3
- "version": "0.1.196",
4
- "gitHead": "b5239194b4ee158dc5648320e27c0e59565ee057",
3
+ "version": "0.1.198",
4
+ "gitHead": "0962b3184641c70fa0ebdf6ace69eff2016b985b",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "description": "The server parts any hosted game shares, above the kernel: the app config and edge auth, the room core (identity, seats, sessions, membership, the room list, the generic room routes), match hosting (the host contract, local and remote JVMs, placement, the start queue, recordings, the in-process and relay runtimes), streams, erase, telemetry and usage. Knows no game; Magic plugs in from apps/server. MIT; imports only node built-ins, express, socket.io, @wolffm/* and the platform packages.",
@@ -17,9 +17,9 @@
17
17
  "play/remote/"
18
18
  ],
19
19
  "dependencies": {
20
- "@wolffm/host-wire": "npm:@hadoku/host-wire@0.1.196",
21
- "@wolffm/platform-wire": "npm:@hadoku/platform-wire@0.1.196",
22
- "@wolffm/service-kernel": "npm:@hadoku/service-kernel@0.1.229",
20
+ "@wolffm/host-wire": "npm:@hadoku/host-wire@0.1.198",
21
+ "@wolffm/platform-wire": "npm:@hadoku/platform-wire@0.1.198",
22
+ "@wolffm/service-kernel": "npm:@hadoku/service-kernel@0.1.231",
23
23
  "@wolffm/prefs-client": "npm:@hadoku/prefs-client@^1.2.3",
24
24
  "@wolffm/rooms-protocol": "npm:@hadoku/rooms-protocol@^0.45.150",
25
25
  "@wolffm/rooms-server": "npm:@hadoku/rooms-server@^0.45.150",