@hadoku/game-server 0.1.14 → 0.1.16
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/dist/http/room-core.d.ts +32 -0
- package/dist/http/room-core.js +100 -0
- package/dist/room/events.d.ts +1 -1
- package/dist/room/lobby.d.ts +80 -0
- package/dist/room/lobby.js +120 -0
- package/dist/room/seat-eviction.d.ts +54 -0
- package/dist/room/seat-eviction.js +68 -0
- package/dist/room/serve.d.ts +126 -0
- package/dist/room/serve.js +177 -0
- package/package.json +5 -5
package/dist/http/room-core.d.ts
CHANGED
|
@@ -86,7 +86,39 @@ export interface LobbyCore<V extends RoomViewCore, C> {
|
|
|
86
86
|
ok: false;
|
|
87
87
|
reason: string;
|
|
88
88
|
};
|
|
89
|
+
/**
|
|
90
|
+
* The leader's three atomic seat ops (wave 119 §S; `room/lobby.ts`'s own docs on each): remove a
|
|
91
|
+
* seated member, lower the seat count under occupants, replace a human with the AI — each
|
|
92
|
+
* evicts its occupant to the spectator row in the same call. `string` reasons rather than a
|
|
93
|
+
* union: this file never names the real ones (`RemoveFromSeatResult` et al.), only maps whatever
|
|
94
|
+
* comes back to a status code below.
|
|
95
|
+
*/
|
|
96
|
+
removeFromSeat(roomId: string, callerId: string, targetId: string): {
|
|
97
|
+
ok: true;
|
|
98
|
+
room: V;
|
|
99
|
+
} | {
|
|
100
|
+
ok: false;
|
|
101
|
+
reason: string;
|
|
102
|
+
};
|
|
103
|
+
lowerSeatCapacity(roomId: string, callerId: string, count: number): {
|
|
104
|
+
ok: true;
|
|
105
|
+
room: V;
|
|
106
|
+
evicted: readonly string[];
|
|
107
|
+
} | {
|
|
108
|
+
ok: false;
|
|
109
|
+
reason: string;
|
|
110
|
+
};
|
|
111
|
+
botReplacesHuman(roomId: string, callerId: string, seat: number): {
|
|
112
|
+
ok: true;
|
|
113
|
+
room: V;
|
|
114
|
+
evicted: string | null;
|
|
115
|
+
} | {
|
|
116
|
+
ok: false;
|
|
117
|
+
reason: string;
|
|
118
|
+
};
|
|
89
119
|
}
|
|
120
|
+
/** Every one of the leader's three seat ops, per caller: a burst of 10, then one every 10 s — the same shape as a join attempt, spent only by a leader who is actually a member of the room (checked before this is asked). */
|
|
121
|
+
export declare const SEAT_OP_RATE_LIMIT: RateLimitConfig;
|
|
90
122
|
/** The request-body schemas and the room-id shape, injected rather than imported: the real values live in a Magic-resolved package. */
|
|
91
123
|
export interface RoomCoreWire<C, P extends object> {
|
|
92
124
|
roomIdRe: RegExp;
|
package/dist/http/room-core.js
CHANGED
|
@@ -27,6 +27,53 @@ import { isAdmin } from '../edge-auth.js';
|
|
|
27
27
|
import { bodyErrors, callerOf, parseBody, perCallerLimit } from './request.js';
|
|
28
28
|
import { watchpartyRoomId } from '../room/watchparty-link.js';
|
|
29
29
|
import { jsonLogger } from '../log.js';
|
|
30
|
+
/** A `BodySchema<T>` with no dependency the way `RoomCoreWire`'s injected ones have — this file imports no zod, no `@hadoku/shared`. */
|
|
31
|
+
function field(check, message) {
|
|
32
|
+
return {
|
|
33
|
+
safeParse(body) {
|
|
34
|
+
if (check(body))
|
|
35
|
+
return { success: true, data: body };
|
|
36
|
+
return { success: false, error: { issues: [{ code: 'invalid_type', path: [], message }] } };
|
|
37
|
+
},
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
const removeFromSeatBody = field((v) => typeof v === 'object' && v !== null && typeof v.memberId === 'string', 'memberId must be a string');
|
|
41
|
+
const lowerCapacityBody = field((v) => typeof v === 'object' && v !== null && Number.isInteger(v.count), 'count must be an integer');
|
|
42
|
+
const botReplacesHumanBody = field((v) => typeof v === 'object' && v !== null && Number.isInteger(v.seat), 'seat must be an integer');
|
|
43
|
+
/** Every one of the leader's three seat ops' own refusal, mapped to a status. `'no-room'`/`no such room` reuses the create/join answer on purpose: never telling a non-member whether a room id exists. */
|
|
44
|
+
function seatOpStatus(res, reason) {
|
|
45
|
+
if (reason === 'no-room')
|
|
46
|
+
return noMatch(res);
|
|
47
|
+
if (reason === 'not-member' || reason === 'target-not-member')
|
|
48
|
+
return noMatch(res);
|
|
49
|
+
if (reason === 'not-leader') {
|
|
50
|
+
res.status(403).json({ error: 'only the room leader can do that' });
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
if (reason === 'not-draft' || reason === 'not-lobby') {
|
|
54
|
+
res.status(409).json({ error: 'this room does not seat through game seats, or its seats are fixed right now' });
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
if (reason === 'historical') {
|
|
58
|
+
res.status(409).json({ error: 'a historical room’s field is the event’s, not the leader’s to change' });
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
if (reason === 'too-few') {
|
|
62
|
+
res.status(400).json({ error: 'a room always keeps at least two seats open' });
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
if (reason === 'bad-seat') {
|
|
66
|
+
res.status(400).json({ error: 'not a seat this room has' });
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
res.status(400).json({ error: reason });
|
|
70
|
+
}
|
|
71
|
+
/** Every one of the leader's three seat ops, per caller: a burst of 10, then one every 10 s — the same shape as a join attempt, spent only by a leader who is actually a member of the room (checked before this is asked). */
|
|
72
|
+
export const SEAT_OP_RATE_LIMIT = {
|
|
73
|
+
capacity: 10,
|
|
74
|
+
refillAmount: 1,
|
|
75
|
+
refillIntervalMs: 10_000,
|
|
76
|
+
};
|
|
30
77
|
/** The single answer for "no such room" and "wrong password". Byte-identical by construction. */
|
|
31
78
|
export const NO_MATCH = { error: 'no room with that id and password' };
|
|
32
79
|
/** Join attempts per caller: a burst of 10, then one more every 30 s. Only NON-member attempts spend a token. */
|
|
@@ -68,6 +115,7 @@ export function attachRoomCore(api, deps, opts = {}) {
|
|
|
68
115
|
const log = deps.log ?? jsonLogger('cardtable-rooms');
|
|
69
116
|
const now = deps.now ?? Date.now;
|
|
70
117
|
const joinLimiter = new MultiRateLimiter(deps.joinRateLimit ?? JOIN_RATE_LIMIT);
|
|
118
|
+
const seatOpLimiter = new MultiRateLimiter(SEAT_OP_RATE_LIMIT);
|
|
71
119
|
const roomBody = (room, callerId) => {
|
|
72
120
|
const mine = room.members.find((m) => m.id === callerId);
|
|
73
121
|
const games = deps.tableGames?.(room);
|
|
@@ -239,6 +287,58 @@ export function attachRoomCore(api, deps, opts = {}) {
|
|
|
239
287
|
deps.reseedTesting?.();
|
|
240
288
|
res.json({ ok: true });
|
|
241
289
|
});
|
|
290
|
+
/** 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. */
|
|
291
|
+
const seatOpLimit = (req, res) => {
|
|
292
|
+
const caller = callerOf(req);
|
|
293
|
+
if (seatOpLimiter.allow(caller.id, 1, now()))
|
|
294
|
+
return true;
|
|
295
|
+
log({ event: 'seat-op-refused', reason: 'rate-limited' });
|
|
296
|
+
res.setHeader('Retry-After', String(Math.ceil(SEAT_OP_RATE_LIMIT.refillIntervalMs / 1000)));
|
|
297
|
+
res.status(429).json({ error: 'too many seat changes; wait a little and try again' });
|
|
298
|
+
return false;
|
|
299
|
+
};
|
|
300
|
+
// The leader removes a seated member to the spectator row (wave 119 §S).
|
|
301
|
+
rooms.post('/:id/seats/remove', (req, res) => {
|
|
302
|
+
const body = parseBody(removeFromSeatBody, req, res);
|
|
303
|
+
if (body === null || !seatOpLimit(req, res))
|
|
304
|
+
return;
|
|
305
|
+
const caller = callerOf(req);
|
|
306
|
+
const id = String(req.params.id);
|
|
307
|
+
if (!wire.roomIdRe.test(id))
|
|
308
|
+
return noMatch(res);
|
|
309
|
+
const result = lobby.removeFromSeat(id, caller.id, body.memberId);
|
|
310
|
+
if (!result.ok)
|
|
311
|
+
return seatOpStatus(res, result.reason);
|
|
312
|
+
res.json(roomBody(result.room, caller.id));
|
|
313
|
+
});
|
|
314
|
+
// The leader lowers the seat count, evicting whoever holds a seat past it (wave 119 §S).
|
|
315
|
+
rooms.post('/:id/seats/capacity', (req, res) => {
|
|
316
|
+
const body = parseBody(lowerCapacityBody, req, res);
|
|
317
|
+
if (body === null || !seatOpLimit(req, res))
|
|
318
|
+
return;
|
|
319
|
+
const caller = callerOf(req);
|
|
320
|
+
const id = String(req.params.id);
|
|
321
|
+
if (!wire.roomIdRe.test(id))
|
|
322
|
+
return noMatch(res);
|
|
323
|
+
const result = lobby.lowerSeatCapacity(id, caller.id, body.count);
|
|
324
|
+
if (!result.ok)
|
|
325
|
+
return seatOpStatus(res, result.reason);
|
|
326
|
+
res.json({ ...roomBody(result.room, caller.id), evicted: result.evicted });
|
|
327
|
+
});
|
|
328
|
+
// The leader puts the AI in a seat, evicting its human occupant first (wave 119 §S).
|
|
329
|
+
rooms.post('/:id/seats/bot', (req, res) => {
|
|
330
|
+
const body = parseBody(botReplacesHumanBody, req, res);
|
|
331
|
+
if (body === null || !seatOpLimit(req, res))
|
|
332
|
+
return;
|
|
333
|
+
const caller = callerOf(req);
|
|
334
|
+
const id = String(req.params.id);
|
|
335
|
+
if (!wire.roomIdRe.test(id))
|
|
336
|
+
return noMatch(res);
|
|
337
|
+
const result = lobby.botReplacesHuman(id, caller.id, body.seat);
|
|
338
|
+
if (!result.ok)
|
|
339
|
+
return seatOpStatus(res, result.reason);
|
|
340
|
+
res.json({ ...roomBody(result.room, caller.id), evicted: result.evicted });
|
|
341
|
+
});
|
|
242
342
|
/**
|
|
243
343
|
* `{ gameType }` is this file's own: the game-type registry is platform.
|
|
244
344
|
* Everything else `P` can be (Magic's `{ format }`/`{ settings }`/`{ mode }`)
|
package/dist/room/events.d.ts
CHANGED
|
@@ -47,7 +47,7 @@ export interface Events {
|
|
|
47
47
|
/** False when the form was already attached. */
|
|
48
48
|
attachForm(form: NewForm, now: number): boolean;
|
|
49
49
|
detachForm(formId: string, callerId: string): FormChange;
|
|
50
|
-
/** Forget forms Rally says are
|
|
50
|
+
/** Forget forms Rally says are gone, or closed and done with: nobody lists them again. */
|
|
51
51
|
forgetForms(formIds: readonly string[]): void;
|
|
52
52
|
/** Account erase: an event they organised and a form they attached keep going under `to`, with no name. Answers how many changed, once saved. */
|
|
53
53
|
anonymise(ids: ReadonlySet<string>, to: string): Promise<{
|
package/dist/room/lobby.d.ts
CHANGED
|
@@ -180,6 +180,13 @@ export interface RoomTypeHooks<G, I extends RoomCreateInput = RoomCreateInput> {
|
|
|
180
180
|
ending?(room: LobbyRoom<G>, why: 'close' | 'sweep' | 'forget'): void;
|
|
181
181
|
/** A relay room's match seat count: set for a type whose room IS its match (`onRelayRoomOpened`). */
|
|
182
182
|
relaySeats?: number;
|
|
183
|
+
/**
|
|
184
|
+
* Whether `rest` names a sub-place inside this room that the type keeps track of beyond its game
|
|
185
|
+
* seats (a table id, a match this room remembers) — `room/serve.ts`'s `placeOfKey`, matching a
|
|
186
|
+
* stale table-keyed room-socket join back to its room. Default: never (a type with no such idea,
|
|
187
|
+
* `plainRoomType`'s).
|
|
188
|
+
*/
|
|
189
|
+
subPlaceOf?(room: LobbyRoom<G>, rest: string): boolean;
|
|
183
190
|
}
|
|
184
191
|
/** The fewest seats a room is left with when its seats are closed: one player and one more. */
|
|
185
192
|
export declare const MIN_OPEN_SEATS = 2;
|
|
@@ -240,6 +247,39 @@ export type StandSeatResult<V> = {
|
|
|
240
247
|
ok: false;
|
|
241
248
|
reason: 'no-room' | 'not-member' | 'not-draft' | 'not-lobby';
|
|
242
249
|
};
|
|
250
|
+
/**
|
|
251
|
+
* The three atomic seat ops every member-is-a-player-or-a-spectator room needs and `sitSeat`/
|
|
252
|
+
* `aiSeat`/`closeSeat` do not give it, because each of those refuses an occupied seat
|
|
253
|
+
* (`docs/planning/wave119-2026-11-16.md` §S; the survey's §7 names the same gap in
|
|
254
|
+
* `@wolffm/rooms-protocol` and bomberman, unbuilt everywhere alike). Each evicts its occupant to
|
|
255
|
+
* the spectator row FIRST, in the same call, so there is never a tick with a stale seat and a
|
|
256
|
+
* fresh one both claiming the member. Leader-only; each is the leader's own kick/shrink/replace,
|
|
257
|
+
* never a member acting on themselves. Built against cardtable's own `GameSeats`, not
|
|
258
|
+
* `@wolffm/rooms-protocol`'s `SeatTable` — see `removeFromSeat`'s own doc for why.
|
|
259
|
+
*/
|
|
260
|
+
export type RemoveFromSeatResult<V> = {
|
|
261
|
+
ok: true;
|
|
262
|
+
room: V;
|
|
263
|
+
} | {
|
|
264
|
+
ok: false;
|
|
265
|
+
reason: 'no-room' | 'not-member' | 'not-leader' | 'target-not-member' | 'not-draft' | 'not-lobby';
|
|
266
|
+
};
|
|
267
|
+
export type LowerSeatCapacityResult<V> = {
|
|
268
|
+
ok: true;
|
|
269
|
+
room: V;
|
|
270
|
+
evicted: readonly string[];
|
|
271
|
+
} | {
|
|
272
|
+
ok: false;
|
|
273
|
+
reason: 'no-room' | 'not-member' | 'not-leader' | 'not-draft' | 'not-lobby' | 'historical' | 'too-few';
|
|
274
|
+
};
|
|
275
|
+
export type BotReplacesHumanResult<V> = {
|
|
276
|
+
ok: true;
|
|
277
|
+
room: V;
|
|
278
|
+
evicted: string | null;
|
|
279
|
+
} | {
|
|
280
|
+
ok: false;
|
|
281
|
+
reason: 'no-room' | 'not-member' | 'not-leader' | 'not-draft' | 'not-lobby' | 'historical' | 'bad-seat';
|
|
282
|
+
};
|
|
243
283
|
export interface AvatarChange {
|
|
244
284
|
roomId: string;
|
|
245
285
|
memberId: string;
|
|
@@ -309,6 +349,13 @@ export declare class RoomLobby<V extends PlatformRoomView, I extends RoomCreateI
|
|
|
309
349
|
get(roomId: string): V | undefined;
|
|
310
350
|
/** Whether `memberId` is a member of `roomId`. False when there is no such room. */
|
|
311
351
|
isMember(roomId: string, memberId: string): boolean;
|
|
352
|
+
/**
|
|
353
|
+
* Everyone in a room is a player or a spectator, never neither (the operator, 2026-11-02):
|
|
354
|
+
* `'player'` iff `memberId` holds a game seat, `'spectator'` iff they are a member who holds
|
|
355
|
+
* none. Derived from the seats every time, never stored, so there is no third value to desync
|
|
356
|
+
* into. Undefined for a non-member or no such room — the question does not apply to them.
|
|
357
|
+
*/
|
|
358
|
+
roleOf(roomId: string, memberId: string): 'player' | 'spectator' | undefined;
|
|
312
359
|
/** Per-member opaque state owned by the game's routes (the deck a seat holds). Not part of the view. undefined when unset / no room / not a member. */
|
|
313
360
|
playerState(roomId: string, memberId: string): unknown;
|
|
314
361
|
/** false when there is no such room or memberId is not a member. Persisted. */
|
|
@@ -328,6 +375,13 @@ export declare class RoomLobby<V extends PlatformRoomView, I extends RoomCreateI
|
|
|
328
375
|
* member, or no such room. What a relay match seats a socket by, so the relay and every screen
|
|
329
376
|
* name the same seat holders.
|
|
330
377
|
*/
|
|
378
|
+
/**
|
|
379
|
+
* Whether `rest` names a sub-place inside `roomId` that its type keeps track of beyond its game
|
|
380
|
+
* seats (a table id, a match this room remembers) — `room/serve.ts`'s `placeOfKey`, matching a
|
|
381
|
+
* stale table-keyed room-socket join back to its room. False for no such room, or for a type
|
|
382
|
+
* with no concept of one (`plainRoomType`'s).
|
|
383
|
+
*/
|
|
384
|
+
subPlaceOf(roomId: string, rest: string): boolean;
|
|
331
385
|
gameSeatOf(roomId: string, memberId: string): number | null;
|
|
332
386
|
/**
|
|
333
387
|
* A member steps out. Removed from `members`; their state and Ready go with their row. If they
|
|
@@ -386,6 +440,32 @@ export declare class RoomLobby<V extends PlatformRoomView, I extends RoomCreateI
|
|
|
386
440
|
aiSeat(roomId: string, memberId: string, seat: number, on: boolean): SitSeatResult<V>;
|
|
387
441
|
/** Close an empty seat, or open a closed one: the leader's; never fewer than `MIN_OPEN_SEATS` open. */
|
|
388
442
|
closeSeat(roomId: string, memberId: string, seat: number, closed: boolean): CloseSeatResult<V>;
|
|
443
|
+
/**
|
|
444
|
+
* The leader removes `targetId` from whatever game seat they hold, to the spectator row.
|
|
445
|
+
* Idempotent: a target who holds none is still answered `ok`. Never touches membership — they
|
|
446
|
+
* stay in the room, watching (this file's own "a player or a spectator, never neither",
|
|
447
|
+
* 2026-11-02). `targetId` need not be `memberId`; this is the leader acting on someone else,
|
|
448
|
+
* which is exactly what `standSeat` (self-service) cannot do. `leaveGameSeat` already IS this
|
|
449
|
+
* operation's contract — `@wolffm/rooms-protocol@0.45.95`'s own `removeFromSeat(table,
|
|
450
|
+
* participantId)` is `unseatParticipant(table, participantId, { hold: false })`, the same shape —
|
|
451
|
+
* so no `seat-eviction.ts` entry exists for this one; see that file's header for the two that do.
|
|
452
|
+
*/
|
|
453
|
+
removeFromSeat(roomId: string, memberId: string, targetId: string): RemoveFromSeatResult<V>;
|
|
454
|
+
/**
|
|
455
|
+
* The leader closes seats from the TOP down until `count` are open, evicting any occupant
|
|
456
|
+
* first — a human to the spectator row, an AI simply removed — instead of `closeSeat`'s refusal
|
|
457
|
+
* on an occupied seat. Never below `MIN_OPEN_SEATS`. A `count` already met is a no-op. Answers
|
|
458
|
+
* the humans evicted, highest seat first. `AI_SEAT`/`CLOSED_SEAT` are not member ids, so the
|
|
459
|
+
* default `memberSeats` view reads them as open same as any other non-member string — a room
|
|
460
|
+
* type that wants its view to tell "AI"/"closed" from "open" gives itself its own `seatsView`
|
|
461
|
+
* (same as Magic's pod view carries AI through `podAi`, a field of its own, not this one's).
|
|
462
|
+
*/
|
|
463
|
+
lowerSeatCapacity(roomId: string, memberId: string, count: number): LowerSeatCapacityResult<V>;
|
|
464
|
+
/**
|
|
465
|
+
* The leader puts the AI in `seat`, evicting whoever holds it first — a human to the spectator
|
|
466
|
+
* row — instead of `aiSeat`'s refusal on an occupied seat. Already the AI's: a no-op.
|
|
467
|
+
*/
|
|
468
|
+
botReplacesHuman(roomId: string, memberId: string, seat: number): BotReplacesHumanResult<V>;
|
|
389
469
|
/**
|
|
390
470
|
* Forget every room untouched for longer than `idleMs` (or its type's own idle window), on disk as
|
|
391
471
|
* well as in memory. Never a room with a live game, never one its type spares. Returns the ids dropped.
|
package/dist/room/lobby.js
CHANGED
|
@@ -45,6 +45,7 @@ import { addRoomMember, isMemberReady, isRoomMember, passwordAdmits, removeRoomM
|
|
|
45
45
|
import { makeSecret, mintRoomId } from "./provisioning.js";
|
|
46
46
|
import { AI_SEAT, CLOSED_SEAT, leaveGameSeat, memberSeats, setGameSeat, takeGameSeat } from "./record.js";
|
|
47
47
|
import { isOfferedRoom, isSweepableRoom, NO_BUSY_HOOK, sortRoomsByCreation } from "./room-list.js";
|
|
48
|
+
import { lowerCapacity, replaceWithBot } from "./seat-eviction.js";
|
|
48
49
|
import { watchpartyRoomId } from "./watchparty-link.js";
|
|
49
50
|
/** The fewest seats a room is left with when its seats are closed: one player and one more. */
|
|
50
51
|
export const MIN_OPEN_SEATS = 2;
|
|
@@ -305,6 +306,17 @@ export class RoomLobby {
|
|
|
305
306
|
const room = this.#rooms.get(roomId);
|
|
306
307
|
return room !== undefined && isRoomMember(room, memberId);
|
|
307
308
|
}
|
|
309
|
+
/**
|
|
310
|
+
* Everyone in a room is a player or a spectator, never neither (the operator, 2026-11-02):
|
|
311
|
+
* `'player'` iff `memberId` holds a game seat, `'spectator'` iff they are a member who holds
|
|
312
|
+
* none. Derived from the seats every time, never stored, so there is no third value to desync
|
|
313
|
+
* into. Undefined for a non-member or no such room — the question does not apply to them.
|
|
314
|
+
*/
|
|
315
|
+
roleOf(roomId, memberId) {
|
|
316
|
+
if (!this.isMember(roomId, memberId))
|
|
317
|
+
return undefined;
|
|
318
|
+
return this.gameSeatOf(roomId, memberId) === null ? 'spectator' : 'player';
|
|
319
|
+
}
|
|
308
320
|
/** Per-member opaque state owned by the game's routes (the deck a seat holds). Not part of the view. undefined when unset / no room / not a member. */
|
|
309
321
|
playerState(roomId, memberId) {
|
|
310
322
|
const member = this.#rooms.get(roomId)?.members.find((m) => m.id === memberId);
|
|
@@ -367,6 +379,16 @@ export class RoomLobby {
|
|
|
367
379
|
* member, or no such room. What a relay match seats a socket by, so the relay and every screen
|
|
368
380
|
* name the same seat holders.
|
|
369
381
|
*/
|
|
382
|
+
/**
|
|
383
|
+
* Whether `rest` names a sub-place inside `roomId` that its type keeps track of beyond its game
|
|
384
|
+
* seats (a table id, a match this room remembers) — `room/serve.ts`'s `placeOfKey`, matching a
|
|
385
|
+
* stale table-keyed room-socket join back to its room. False for no such room, or for a type
|
|
386
|
+
* with no concept of one (`plainRoomType`'s).
|
|
387
|
+
*/
|
|
388
|
+
subPlaceOf(roomId, rest) {
|
|
389
|
+
const room = this.#rooms.get(roomId);
|
|
390
|
+
return room !== undefined && (this.hooksOf(room).subPlaceOf?.(room, rest) ?? false);
|
|
391
|
+
}
|
|
370
392
|
gameSeatOf(roomId, memberId) {
|
|
371
393
|
const room = this.#rooms.get(roomId);
|
|
372
394
|
if (room === undefined)
|
|
@@ -688,6 +710,104 @@ export class RoomLobby {
|
|
|
688
710
|
this.log({ event: closed ? 'pod-seat-closed' : 'pod-seat-opened', roomId, memberId, seat, size: size() });
|
|
689
711
|
return { ok: true, room: this.view(room) };
|
|
690
712
|
}
|
|
713
|
+
/**
|
|
714
|
+
* The leader removes `targetId` from whatever game seat they hold, to the spectator row.
|
|
715
|
+
* Idempotent: a target who holds none is still answered `ok`. Never touches membership — they
|
|
716
|
+
* stay in the room, watching (this file's own "a player or a spectator, never neither",
|
|
717
|
+
* 2026-11-02). `targetId` need not be `memberId`; this is the leader acting on someone else,
|
|
718
|
+
* which is exactly what `standSeat` (self-service) cannot do. `leaveGameSeat` already IS this
|
|
719
|
+
* operation's contract — `@wolffm/rooms-protocol@0.45.95`'s own `removeFromSeat(table,
|
|
720
|
+
* participantId)` is `unseatParticipant(table, participantId, { hold: false })`, the same shape —
|
|
721
|
+
* so no `seat-eviction.ts` entry exists for this one; see that file's header for the two that do.
|
|
722
|
+
*/
|
|
723
|
+
removeFromSeat(roomId, memberId, targetId) {
|
|
724
|
+
const room = this.#rooms.get(roomId);
|
|
725
|
+
if (room === undefined)
|
|
726
|
+
return { ok: false, reason: 'no-room' };
|
|
727
|
+
if (!isRoomMember(room, memberId))
|
|
728
|
+
return { ok: false, reason: 'not-member' };
|
|
729
|
+
if (room.leader !== memberId)
|
|
730
|
+
return { ok: false, reason: 'not-leader' };
|
|
731
|
+
if (!isRoomMember(room, targetId))
|
|
732
|
+
return { ok: false, reason: 'target-not-member' };
|
|
733
|
+
const found = this.#seatRoom(roomId, memberId);
|
|
734
|
+
if ('refused' in found)
|
|
735
|
+
return { ok: false, reason: found.refused };
|
|
736
|
+
const { room: r, hooks } = found;
|
|
737
|
+
if (!leaveGameSeat(r, targetId))
|
|
738
|
+
return { ok: true, room: this.view(r) };
|
|
739
|
+
hooks.trimSeats(r);
|
|
740
|
+
this.persist(r);
|
|
741
|
+
this.log({ event: 'seat-removed-by-leader', roomId, memberId, targetId });
|
|
742
|
+
hooks.seatsChanged?.(r);
|
|
743
|
+
return { ok: true, room: this.view(r) };
|
|
744
|
+
}
|
|
745
|
+
/**
|
|
746
|
+
* The leader closes seats from the TOP down until `count` are open, evicting any occupant
|
|
747
|
+
* first — a human to the spectator row, an AI simply removed — instead of `closeSeat`'s refusal
|
|
748
|
+
* on an occupied seat. Never below `MIN_OPEN_SEATS`. A `count` already met is a no-op. Answers
|
|
749
|
+
* the humans evicted, highest seat first. `AI_SEAT`/`CLOSED_SEAT` are not member ids, so the
|
|
750
|
+
* default `memberSeats` view reads them as open same as any other non-member string — a room
|
|
751
|
+
* type that wants its view to tell "AI"/"closed" from "open" gives itself its own `seatsView`
|
|
752
|
+
* (same as Magic's pod view carries AI through `podAi`, a field of its own, not this one's).
|
|
753
|
+
*/
|
|
754
|
+
lowerSeatCapacity(roomId, memberId, count) {
|
|
755
|
+
const room = this.#rooms.get(roomId);
|
|
756
|
+
if (room === undefined)
|
|
757
|
+
return { ok: false, reason: 'no-room' };
|
|
758
|
+
if (!isRoomMember(room, memberId))
|
|
759
|
+
return { ok: false, reason: 'not-member' };
|
|
760
|
+
if (room.leader !== memberId)
|
|
761
|
+
return { ok: false, reason: 'not-leader' };
|
|
762
|
+
const found = this.#seatRoom(roomId, memberId);
|
|
763
|
+
if ('refused' in found)
|
|
764
|
+
return { ok: false, reason: found.refused };
|
|
765
|
+
const { room: r, hooks } = found;
|
|
766
|
+
if (hooks.fieldFixed?.(r) === true)
|
|
767
|
+
return { ok: false, reason: 'historical' };
|
|
768
|
+
if (!Number.isInteger(count) || count < MIN_OPEN_SEATS)
|
|
769
|
+
return { ok: false, reason: 'too-few' };
|
|
770
|
+
const { seats, evicted } = lowerCapacity(r.seats, count);
|
|
771
|
+
if (evicted.length === 0 && seats.every((s, i) => s === r.seats[i]))
|
|
772
|
+
return { ok: true, room: this.view(r), evicted };
|
|
773
|
+
r.seats = seats;
|
|
774
|
+
hooks.trimSeats(r);
|
|
775
|
+
this.persist(r);
|
|
776
|
+
this.log({ event: 'seat-capacity-lowered', roomId, memberId, count, evicted: evicted.length });
|
|
777
|
+
hooks.seatsChanged?.(r);
|
|
778
|
+
return { ok: true, room: this.view(r), evicted };
|
|
779
|
+
}
|
|
780
|
+
/**
|
|
781
|
+
* The leader puts the AI in `seat`, evicting whoever holds it first — a human to the spectator
|
|
782
|
+
* row — instead of `aiSeat`'s refusal on an occupied seat. Already the AI's: a no-op.
|
|
783
|
+
*/
|
|
784
|
+
botReplacesHuman(roomId, memberId, seat) {
|
|
785
|
+
const room = this.#rooms.get(roomId);
|
|
786
|
+
if (room === undefined)
|
|
787
|
+
return { ok: false, reason: 'no-room' };
|
|
788
|
+
if (!isRoomMember(room, memberId))
|
|
789
|
+
return { ok: false, reason: 'not-member' };
|
|
790
|
+
if (room.leader !== memberId)
|
|
791
|
+
return { ok: false, reason: 'not-leader' };
|
|
792
|
+
const found = this.#seatRoom(roomId, memberId);
|
|
793
|
+
if ('refused' in found)
|
|
794
|
+
return { ok: false, reason: found.refused };
|
|
795
|
+
const { room: r, hooks } = found;
|
|
796
|
+
if (hooks.fieldFixed?.(r) === true)
|
|
797
|
+
return { ok: false, reason: 'historical' };
|
|
798
|
+
if (!this.#inReach(r, hooks, seat) || seat >= r.seats.length)
|
|
799
|
+
return { ok: false, reason: 'bad-seat' };
|
|
800
|
+
const { seats, evicted } = replaceWithBot(r.seats, seat);
|
|
801
|
+
if (evicted === null && seats[seat] === r.seats[seat])
|
|
802
|
+
return { ok: true, room: this.view(r), evicted: null };
|
|
803
|
+
r.seats = seats;
|
|
804
|
+
hooks.aiSeated?.(r, seat, true);
|
|
805
|
+
hooks.trimSeats(r);
|
|
806
|
+
this.persist(r);
|
|
807
|
+
this.log({ event: 'seat-bot-replaced-human', roomId, memberId, seat, evicted: evicted !== null });
|
|
808
|
+
hooks.seatsChanged?.(r);
|
|
809
|
+
return { ok: true, room: this.view(r), evicted };
|
|
810
|
+
}
|
|
691
811
|
/**
|
|
692
812
|
* Forget every room untouched for longer than `idleMs` (or its type's own idle window), on disk as
|
|
693
813
|
* well as in memory. Never a room with a live game, never one its type spares. Returns the ids dropped.
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The leader's three atomic "evict, then act" seat operations (wave 119 §S), isolated here so a
|
|
3
|
+
* future swap is a one-file edit.
|
|
4
|
+
*
|
|
5
|
+
* `@wolffm/rooms-protocol@0.45.95` (watchparty d02dbdfb, published while this lane ran) gives its
|
|
6
|
+
* own `SeatTable` the same three operations: `removeFromSeat(table, participantId)`,
|
|
7
|
+
* `replaceWithBot(table, participantId)`, and the pre-existing `setSeatCapacity(table, capacity)`
|
|
8
|
+
* for "lower capacity under occupants, evicting someone" — its own doc calls that the one and
|
|
9
|
+
* only way to do it on a `SeatTable`.
|
|
10
|
+
*
|
|
11
|
+
* Cardtable's rooms are NOT on `SeatTable`. They are `GameSeats` (`record.ts`): a plain
|
|
12
|
+
* `(string | null)[]` with `AI_SEAT`/`CLOSED_SEAT` markers IN PLACE, because a leader can close
|
|
13
|
+
* one specific seat (`CLOSED_SEAT`, `closeSeat`) while every seat around it, including a HIGHER
|
|
14
|
+
* one, stays open — Magic's draft pods do this (`pods.ts`'s `POD_CLOSED`). `SeatTable.capacity`
|
|
15
|
+
* has no such idea: its own `setSeatCapacity` doc says so explicitly — "this table has no concept
|
|
16
|
+
* of a specific seat that is closed while a higher one stays open… inventing one would be a
|
|
17
|
+
* second notion of capacity." That is not a gap to fix here; it is a different, deliberate design
|
|
18
|
+
* for a different shape of room, and reconciling the two (or deciding cardtable keeps its own) is
|
|
19
|
+
* a separate, larger item than this wave's (the survey's §7 "two parallel seat implementations"
|
|
20
|
+
* open risk).
|
|
21
|
+
*
|
|
22
|
+
* So this file does not call `@wolffm/rooms-protocol` at all. It gives `GameSeats` the SAME
|
|
23
|
+
* contract those three operations have — evict first, in the same call, so there is never a tick
|
|
24
|
+
* with a stale seat and a fresh one both claiming the member — against cardtable's own array.
|
|
25
|
+
* `room/lobby.ts`'s `removeFromSeat` method needs no function of its own here: `record.ts`'s
|
|
26
|
+
* `leaveGameSeat` already IS this contract (vacate one seat, remembered nowhere since `GameSeats`
|
|
27
|
+
* has no sticky memory, which is fine — a stood member re-sits through `sitSeat` like anyone
|
|
28
|
+
* else). `lowerCapacity` and `replaceWithBot` below are the two that are genuinely new.
|
|
29
|
+
*
|
|
30
|
+
* If cardtable's seat storage is ever migrated onto `SeatTable` (resolving the `CLOSED_SEAT` gap
|
|
31
|
+
* first), THIS file is what gets replaced with calls to the published functions — `room/lobby.ts`'s
|
|
32
|
+
* three methods would not need to change at all, since they already call through here.
|
|
33
|
+
*/
|
|
34
|
+
import { type GameSeats } from './record.js';
|
|
35
|
+
/**
|
|
36
|
+
* Close seats from the TOP down until `count` are open, evicting any occupant first (a human —
|
|
37
|
+
* returned, for the caller to tell they are now watching — an AI simply gone). Mirrors
|
|
38
|
+
* `@wolffm/rooms-protocol`'s `setSeatCapacity`: eviction is always highest seat first, never a
|
|
39
|
+
* caller-chosen one — same reasoning as that function's own doc.
|
|
40
|
+
*/
|
|
41
|
+
export declare function lowerCapacity(seats: GameSeats, count: number): {
|
|
42
|
+
seats: GameSeats;
|
|
43
|
+
evicted: readonly string[];
|
|
44
|
+
};
|
|
45
|
+
/**
|
|
46
|
+
* The AI takes `seat`, evicting its human occupant first (returned, for the caller to tell they
|
|
47
|
+
* are now watching). Addressed by SEAT, not by the human's id (`@wolffm/rooms-protocol`'s
|
|
48
|
+
* `replaceWithBot` takes the participant) — cardtable's leader picks a seat, empty or occupied,
|
|
49
|
+
* the same way `aiSeat` always has, and an empty seat has no occupant id to address by.
|
|
50
|
+
*/
|
|
51
|
+
export declare function replaceWithBot(seats: GameSeats, seat: number): {
|
|
52
|
+
seats: GameSeats;
|
|
53
|
+
evicted: string | null;
|
|
54
|
+
};
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The leader's three atomic "evict, then act" seat operations (wave 119 §S), isolated here so a
|
|
3
|
+
* future swap is a one-file edit.
|
|
4
|
+
*
|
|
5
|
+
* `@wolffm/rooms-protocol@0.45.95` (watchparty d02dbdfb, published while this lane ran) gives its
|
|
6
|
+
* own `SeatTable` the same three operations: `removeFromSeat(table, participantId)`,
|
|
7
|
+
* `replaceWithBot(table, participantId)`, and the pre-existing `setSeatCapacity(table, capacity)`
|
|
8
|
+
* for "lower capacity under occupants, evicting someone" — its own doc calls that the one and
|
|
9
|
+
* only way to do it on a `SeatTable`.
|
|
10
|
+
*
|
|
11
|
+
* Cardtable's rooms are NOT on `SeatTable`. They are `GameSeats` (`record.ts`): a plain
|
|
12
|
+
* `(string | null)[]` with `AI_SEAT`/`CLOSED_SEAT` markers IN PLACE, because a leader can close
|
|
13
|
+
* one specific seat (`CLOSED_SEAT`, `closeSeat`) while every seat around it, including a HIGHER
|
|
14
|
+
* one, stays open — Magic's draft pods do this (`pods.ts`'s `POD_CLOSED`). `SeatTable.capacity`
|
|
15
|
+
* has no such idea: its own `setSeatCapacity` doc says so explicitly — "this table has no concept
|
|
16
|
+
* of a specific seat that is closed while a higher one stays open… inventing one would be a
|
|
17
|
+
* second notion of capacity." That is not a gap to fix here; it is a different, deliberate design
|
|
18
|
+
* for a different shape of room, and reconciling the two (or deciding cardtable keeps its own) is
|
|
19
|
+
* a separate, larger item than this wave's (the survey's §7 "two parallel seat implementations"
|
|
20
|
+
* open risk).
|
|
21
|
+
*
|
|
22
|
+
* So this file does not call `@wolffm/rooms-protocol` at all. It gives `GameSeats` the SAME
|
|
23
|
+
* contract those three operations have — evict first, in the same call, so there is never a tick
|
|
24
|
+
* with a stale seat and a fresh one both claiming the member — against cardtable's own array.
|
|
25
|
+
* `room/lobby.ts`'s `removeFromSeat` method needs no function of its own here: `record.ts`'s
|
|
26
|
+
* `leaveGameSeat` already IS this contract (vacate one seat, remembered nowhere since `GameSeats`
|
|
27
|
+
* has no sticky memory, which is fine — a stood member re-sits through `sitSeat` like anyone
|
|
28
|
+
* else). `lowerCapacity` and `replaceWithBot` below are the two that are genuinely new.
|
|
29
|
+
*
|
|
30
|
+
* If cardtable's seat storage is ever migrated onto `SeatTable` (resolving the `CLOSED_SEAT` gap
|
|
31
|
+
* first), THIS file is what gets replaced with calls to the published functions — `room/lobby.ts`'s
|
|
32
|
+
* three methods would not need to change at all, since they already call through here.
|
|
33
|
+
*/
|
|
34
|
+
import { AI_SEAT, CLOSED_SEAT } from "./record.js";
|
|
35
|
+
/**
|
|
36
|
+
* Close seats from the TOP down until `count` are open, evicting any occupant first (a human —
|
|
37
|
+
* returned, for the caller to tell they are now watching — an AI simply gone). Mirrors
|
|
38
|
+
* `@wolffm/rooms-protocol`'s `setSeatCapacity`: eviction is always highest seat first, never a
|
|
39
|
+
* caller-chosen one — same reasoning as that function's own doc.
|
|
40
|
+
*/
|
|
41
|
+
export function lowerCapacity(seats, count) {
|
|
42
|
+
const result = [...seats];
|
|
43
|
+
const evicted = [];
|
|
44
|
+
let open = result.filter((s) => s !== CLOSED_SEAT).length;
|
|
45
|
+
for (let seat = result.length - 1; seat >= 0 && open > count; seat--) {
|
|
46
|
+
const holder = result[seat] ?? null;
|
|
47
|
+
if (holder === CLOSED_SEAT)
|
|
48
|
+
continue;
|
|
49
|
+
if (holder !== null && holder !== AI_SEAT)
|
|
50
|
+
evicted.push(holder);
|
|
51
|
+
result[seat] = CLOSED_SEAT;
|
|
52
|
+
open--;
|
|
53
|
+
}
|
|
54
|
+
return { seats: result, evicted };
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* The AI takes `seat`, evicting its human occupant first (returned, for the caller to tell they
|
|
58
|
+
* are now watching). Addressed by SEAT, not by the human's id (`@wolffm/rooms-protocol`'s
|
|
59
|
+
* `replaceWithBot` takes the participant) — cardtable's leader picks a seat, empty or occupied,
|
|
60
|
+
* the same way `aiSeat` always has, and an empty seat has no occupant id to address by.
|
|
61
|
+
*/
|
|
62
|
+
export function replaceWithBot(seats, seat) {
|
|
63
|
+
const holder = seats[seat] ?? null;
|
|
64
|
+
if (holder === AI_SEAT)
|
|
65
|
+
return { seats, evicted: null };
|
|
66
|
+
const evicted = holder !== null && holder !== CLOSED_SEAT ? holder : null;
|
|
67
|
+
return { seats: seats.map((s, i) => (i === seat ? AI_SEAT : s)), evicted };
|
|
68
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A game's rooms, served by its own server: `@wolffm/rooms-server/room`'s `serveRoom` on this
|
|
3
|
+
* server's own socket.io, at the `/room` namespace `RoomChrome`'s `roomOrigin` connects to
|
|
4
|
+
* (`packages/game-ui/src/room/RoomShell.tsx`). The chrome's whole room socket comes here — join,
|
|
5
|
+
* roster, identity, chat — and none of it goes to watchparty, so an open room neither counts on
|
|
6
|
+
* watchparty's server nor holds its deploys.
|
|
7
|
+
*
|
|
8
|
+
* Moved here from `games/magic/server/src/room/serve.ts` (wave 119 §S): the only two things that
|
|
9
|
+
* were Magic-only were a `Lobby` type import and one `magicView(...).tables` read inside
|
|
10
|
+
* `placeOfKey`. Both are gone — the `Lobby` here is `ServeLobby<V>`, a structural slice any
|
|
11
|
+
* `RoomLobby` satisfies (`room/lobby.ts`'s own `LobbyCore` trick in `http/room-core.ts`), and the
|
|
12
|
+
* table/match lookup is `RoomTypeHooks.subPlaceOf`, which Magic implements and a game with no
|
|
13
|
+
* sub-places (bomberman, `plainRoomType`'s) simply never answers yes to.
|
|
14
|
+
*
|
|
15
|
+
* ## One answer to "who is here"
|
|
16
|
+
*
|
|
17
|
+
* `presence` is the server's ONE `PresenceTracker`: the instance the lobby's seat grace and every
|
|
18
|
+
* draft pod's seat-hold already run on. A room connection is a connection of the PERSON (`key` =
|
|
19
|
+
* their participant id, the tracker's lobby key), beside their tab's feed and draft sockets. So
|
|
20
|
+
* the chrome's roster, the seat grace and a pod's hold read one tracker, and a second tab is one
|
|
21
|
+
* person, not two.
|
|
22
|
+
*
|
|
23
|
+
* ## One answer to "who is this"
|
|
24
|
+
*
|
|
25
|
+
* `account` is the app's own account lookup, keyed by the edge's `X-User-Id`, and always reads
|
|
26
|
+
* fresh: serveRoom calls it on the chrome's `identity_update` after a rename or a new picture, on
|
|
27
|
+
* the account's own join or chat once its copy is stale, and on a person's first join since this
|
|
28
|
+
* server started. serveRoom pushes the answer to every connection of the account and calls
|
|
29
|
+
* `apply`, which writes it into the lobby: the room list, the table and the chrome all read the
|
|
30
|
+
* same name, picture and character, and a rename reaches the other players' room list with
|
|
31
|
+
* nobody rejoining.
|
|
32
|
+
*
|
|
33
|
+
* ## Who may join
|
|
34
|
+
*
|
|
35
|
+
* `admit` is the gate: the tier floor (the same one every socket applies), a key this app minted
|
|
36
|
+
* (`<appId>-<id>`, `RoomShell.tsx`'s `roomKeyFor`), and a place the lobby knows. A room has one
|
|
37
|
+
* chat, its own key, on its lobby and on every game at its tables. It admits the room's members,
|
|
38
|
+
* and anyone at all while the room has no password, since anyone may watch an open room's match;
|
|
39
|
+
* a locked room admits its members only. A match no room holds (a game against the AI, a
|
|
40
|
+
* scenario) admits anyone, keyed by the match's own id. A table's key (`<roomId>-<tableId>`) is
|
|
41
|
+
* what screens built before 2026-11-11 joined during a game, and is gated as its room is. A
|
|
42
|
+
* refusal sends nothing of the room.
|
|
43
|
+
*
|
|
44
|
+
* `appId` must agree with the UI's own app id; it is passed in rather than imported, since a
|
|
45
|
+
* server importing UI source is the wrong direction for any app's layering.
|
|
46
|
+
*/
|
|
47
|
+
import type { Server as SocketIOServer } from 'socket.io';
|
|
48
|
+
import type { PresenceTracker } from '@wolffm/rooms-server';
|
|
49
|
+
import { type RoomChatMessage } from '@wolffm/rooms-server/chat';
|
|
50
|
+
import { type ServedRoom } from '@wolffm/rooms-server/room';
|
|
51
|
+
import type { Look } from '@wolffm/platform-wire/look';
|
|
52
|
+
import { type People } from '../people.js';
|
|
53
|
+
/** The minimal room-view shape this file touches, whatever the game. The real `PlatformRoomView` (and Magic's `RoomView`) satisfy it. */
|
|
54
|
+
export interface ServeRoomView {
|
|
55
|
+
id: string;
|
|
56
|
+
locked: boolean;
|
|
57
|
+
members: readonly {
|
|
58
|
+
id: string;
|
|
59
|
+
name: string;
|
|
60
|
+
avatarId?: string;
|
|
61
|
+
}[];
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* The slice of `room/lobby.ts`'s `RoomLobby` this file calls, typed against `V` alone — never the
|
|
65
|
+
* real game-specific view. Method syntax (not property) is load-bearing, same as
|
|
66
|
+
* `http/room-core.ts`'s `LobbyCore`: it is what lets a real, narrower-typed `Lobby` satisfy this
|
|
67
|
+
* interface with no cast, through TypeScript's bivariant parameter checking.
|
|
68
|
+
*/
|
|
69
|
+
export interface ServeLobby<V extends ServeRoomView> {
|
|
70
|
+
get(roomId: string): V | undefined;
|
|
71
|
+
isMember(roomId: string, participantId: string): boolean;
|
|
72
|
+
onChange(listener: (roomId: string) => void): () => void;
|
|
73
|
+
/** `RoomLobby.subPlaceOf`: whether `rest` names a sub-place (a table, a remembered match) inside this room. */
|
|
74
|
+
subPlaceOf(roomId: string, rest: string): boolean;
|
|
75
|
+
/** `people.ts`'s `applyPerson`, writing an account's name, character and look onto a member. */
|
|
76
|
+
rename(caller: {
|
|
77
|
+
id: string;
|
|
78
|
+
name: string;
|
|
79
|
+
}): void;
|
|
80
|
+
setAvatar(roomId: string, memberId: string, avatarId: string | null): boolean;
|
|
81
|
+
setLook(roomId: string, memberId: string, look: Look | undefined): boolean;
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* What a room key names: the served room (its chat and roster), and the lobby room it belongs to
|
|
85
|
+
* (null for a match no room holds), and whether anyone at the floor may watch it.
|
|
86
|
+
*/
|
|
87
|
+
type RoomPlace = {
|
|
88
|
+
served: string;
|
|
89
|
+
roomId: string;
|
|
90
|
+
kind: 'room' | 'table';
|
|
91
|
+
} | {
|
|
92
|
+
served: string;
|
|
93
|
+
roomId: null;
|
|
94
|
+
kind: 'match';
|
|
95
|
+
};
|
|
96
|
+
/**
|
|
97
|
+
* `<appId>-<id>` → the place it names, or null when it is not one of ours or names nothing live.
|
|
98
|
+
* A table's key is `<roomId>-<tableId>`, or `<roomId>-<matchId>` when the screen's copy of the
|
|
99
|
+
* room no longer names the table its match was played at; either is the room's table chat, the
|
|
100
|
+
* match found through the room's own `subPlaceOf`. Screens since 2026-11-11 join the room's own
|
|
101
|
+
* key on every screen; a page loaded before that still joins a table's.
|
|
102
|
+
*/
|
|
103
|
+
export declare function placeOfKey<V extends ServeRoomView>(lobby: Pick<ServeLobby<V>, 'get' | 'subPlaceOf'>, isMatch: (id: string) => boolean, appId: string, roomKey: string, roomIdRe: RegExp): RoomPlace | null;
|
|
104
|
+
export interface ServeDeps<V extends ServeRoomView> {
|
|
105
|
+
lobby: ServeLobby<V>;
|
|
106
|
+
/** The server's one tracker (`state.seatPresence`). */
|
|
107
|
+
presence: PresenceTracker<string>;
|
|
108
|
+
/** The account lookup (`state.people`). */
|
|
109
|
+
people: People;
|
|
110
|
+
/** Whether a match by this id is live or just ended (`state.play.matches.find`). */
|
|
111
|
+
isMatch: (id: string) => boolean;
|
|
112
|
+
/** `CONFIG.minTier` in production — the same floor `room/socket.ts` applies. */
|
|
113
|
+
minTier: string;
|
|
114
|
+
/** Where chat history is kept; a thunk, read on every call. */
|
|
115
|
+
stateDir: () => string;
|
|
116
|
+
/** What a room key is prefixed with: `<appId>-<id>` (`RoomShell.tsx`'s `roomKeyFor`). Must agree with the UI's own app id. */
|
|
117
|
+
appId: string;
|
|
118
|
+
/** A room id's shape, for `placeOfKey`'s own validation. */
|
|
119
|
+
roomIdRe: RegExp;
|
|
120
|
+
/** Default `/room`. */
|
|
121
|
+
namespace?: string;
|
|
122
|
+
onEvent?: (level: 'info' | 'warn' | 'debug', event: string, fields: Record<string, unknown>) => void;
|
|
123
|
+
}
|
|
124
|
+
/** Mount a game's rooms on `io` (see this file's header). */
|
|
125
|
+
export declare function attachServedRoom<V extends ServeRoomView>(io: SocketIOServer, deps: ServeDeps<V>): Promise<ServedRoom<string, RoomChatMessage>>;
|
|
126
|
+
export {};
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A game's rooms, served by its own server: `@wolffm/rooms-server/room`'s `serveRoom` on this
|
|
3
|
+
* server's own socket.io, at the `/room` namespace `RoomChrome`'s `roomOrigin` connects to
|
|
4
|
+
* (`packages/game-ui/src/room/RoomShell.tsx`). The chrome's whole room socket comes here — join,
|
|
5
|
+
* roster, identity, chat — and none of it goes to watchparty, so an open room neither counts on
|
|
6
|
+
* watchparty's server nor holds its deploys.
|
|
7
|
+
*
|
|
8
|
+
* Moved here from `games/magic/server/src/room/serve.ts` (wave 119 §S): the only two things that
|
|
9
|
+
* were Magic-only were a `Lobby` type import and one `magicView(...).tables` read inside
|
|
10
|
+
* `placeOfKey`. Both are gone — the `Lobby` here is `ServeLobby<V>`, a structural slice any
|
|
11
|
+
* `RoomLobby` satisfies (`room/lobby.ts`'s own `LobbyCore` trick in `http/room-core.ts`), and the
|
|
12
|
+
* table/match lookup is `RoomTypeHooks.subPlaceOf`, which Magic implements and a game with no
|
|
13
|
+
* sub-places (bomberman, `plainRoomType`'s) simply never answers yes to.
|
|
14
|
+
*
|
|
15
|
+
* ## One answer to "who is here"
|
|
16
|
+
*
|
|
17
|
+
* `presence` is the server's ONE `PresenceTracker`: the instance the lobby's seat grace and every
|
|
18
|
+
* draft pod's seat-hold already run on. A room connection is a connection of the PERSON (`key` =
|
|
19
|
+
* their participant id, the tracker's lobby key), beside their tab's feed and draft sockets. So
|
|
20
|
+
* the chrome's roster, the seat grace and a pod's hold read one tracker, and a second tab is one
|
|
21
|
+
* person, not two.
|
|
22
|
+
*
|
|
23
|
+
* ## One answer to "who is this"
|
|
24
|
+
*
|
|
25
|
+
* `account` is the app's own account lookup, keyed by the edge's `X-User-Id`, and always reads
|
|
26
|
+
* fresh: serveRoom calls it on the chrome's `identity_update` after a rename or a new picture, on
|
|
27
|
+
* the account's own join or chat once its copy is stale, and on a person's first join since this
|
|
28
|
+
* server started. serveRoom pushes the answer to every connection of the account and calls
|
|
29
|
+
* `apply`, which writes it into the lobby: the room list, the table and the chrome all read the
|
|
30
|
+
* same name, picture and character, and a rename reaches the other players' room list with
|
|
31
|
+
* nobody rejoining.
|
|
32
|
+
*
|
|
33
|
+
* ## Who may join
|
|
34
|
+
*
|
|
35
|
+
* `admit` is the gate: the tier floor (the same one every socket applies), a key this app minted
|
|
36
|
+
* (`<appId>-<id>`, `RoomShell.tsx`'s `roomKeyFor`), and a place the lobby knows. A room has one
|
|
37
|
+
* chat, its own key, on its lobby and on every game at its tables. It admits the room's members,
|
|
38
|
+
* and anyone at all while the room has no password, since anyone may watch an open room's match;
|
|
39
|
+
* a locked room admits its members only. A match no room holds (a game against the AI, a
|
|
40
|
+
* scenario) admits anyone, keyed by the match's own id. A table's key (`<roomId>-<tableId>`) is
|
|
41
|
+
* what screens built before 2026-11-11 joined during a game, and is gated as its room is. A
|
|
42
|
+
* refusal sends nothing of the room.
|
|
43
|
+
*
|
|
44
|
+
* `appId` must agree with the UI's own app id; it is passed in rather than imported, since a
|
|
45
|
+
* server importing UI source is the wrong direction for any app's layering.
|
|
46
|
+
*/
|
|
47
|
+
import { participantHandle } from '@wolffm/rooms-protocol';
|
|
48
|
+
import { createChatHistoryStore } from '@wolffm/rooms-server/chat';
|
|
49
|
+
import { serveRoom } from '@wolffm/rooms-server/room';
|
|
50
|
+
import { rankOf } from '../edge-auth.js';
|
|
51
|
+
import { applyPerson } from '../people.js';
|
|
52
|
+
import { handshakeTier } from './socket-auth.js';
|
|
53
|
+
import { identityFromHeaders } from './identity.js';
|
|
54
|
+
/** In memory per room, and the default/max page a `GET …/chat` page asks for. */
|
|
55
|
+
const MAX_MESSAGES_PER_ROOM = 500;
|
|
56
|
+
const PAGE_LIMIT = 50;
|
|
57
|
+
const PAGE_LIMIT_MAX = 100;
|
|
58
|
+
/** A room's chat file is read back for this long after boot; older, it is deleted on sight. */
|
|
59
|
+
const CHAT_RETENTION_MS = 90 * 24 * 60 * 60 * 1000;
|
|
60
|
+
/**
|
|
61
|
+
* `<appId>-<id>` → the place it names, or null when it is not one of ours or names nothing live.
|
|
62
|
+
* A table's key is `<roomId>-<tableId>`, or `<roomId>-<matchId>` when the screen's copy of the
|
|
63
|
+
* room no longer names the table its match was played at; either is the room's table chat, the
|
|
64
|
+
* match found through the room's own `subPlaceOf`. Screens since 2026-11-11 join the room's own
|
|
65
|
+
* key on every screen; a page loaded before that still joins a table's.
|
|
66
|
+
*/
|
|
67
|
+
export function placeOfKey(lobby, isMatch, appId, roomKey, roomIdRe) {
|
|
68
|
+
const prefix = `${appId}-`;
|
|
69
|
+
if (!roomKey.startsWith(prefix))
|
|
70
|
+
return null;
|
|
71
|
+
const id = roomKey.slice(prefix.length);
|
|
72
|
+
if (!roomIdRe.test(id))
|
|
73
|
+
return null;
|
|
74
|
+
if (lobby.get(id) !== undefined)
|
|
75
|
+
return { served: id, roomId: id, kind: 'room' };
|
|
76
|
+
for (let at = id.indexOf('-'); at !== -1; at = id.indexOf('-', at + 1)) {
|
|
77
|
+
const room = lobby.get(id.slice(0, at));
|
|
78
|
+
if (room === undefined)
|
|
79
|
+
continue;
|
|
80
|
+
const rest = id.slice(at + 1);
|
|
81
|
+
// A room of a game with no idea of a sub-place answers `subPlaceOf` false for every `rest`.
|
|
82
|
+
if (lobby.subPlaceOf(room.id, rest))
|
|
83
|
+
return { served: id, roomId: room.id, kind: 'table' };
|
|
84
|
+
}
|
|
85
|
+
return isMatch(id) ? { served: id, roomId: null, kind: 'match' } : null;
|
|
86
|
+
}
|
|
87
|
+
/** Whether `participantId` may be in `place`: a room's (or its table's) members, or anyone while the room has no password; anyone at a match. */
|
|
88
|
+
function mayJoin(lobby, place, participantId) {
|
|
89
|
+
if (place.roomId === null)
|
|
90
|
+
return true;
|
|
91
|
+
if (lobby.isMember(place.roomId, participantId))
|
|
92
|
+
return true;
|
|
93
|
+
return lobby.get(place.roomId)?.locked === false;
|
|
94
|
+
}
|
|
95
|
+
function accountOfHeaders(headers) {
|
|
96
|
+
const id = headers['x-user-id'];
|
|
97
|
+
return typeof id === 'string' && id !== '' ? id : undefined;
|
|
98
|
+
}
|
|
99
|
+
/** Mount a game's rooms on `io` (see this file's header). */
|
|
100
|
+
export async function attachServedRoom(io, deps) {
|
|
101
|
+
const { lobby, people } = deps;
|
|
102
|
+
const store = createChatHistoryStore({
|
|
103
|
+
stateDir: deps.stateDir,
|
|
104
|
+
maxMessages: MAX_MESSAGES_PER_ROOM,
|
|
105
|
+
pageLimit: PAGE_LIMIT,
|
|
106
|
+
pageLimitMax: PAGE_LIMIT_MAX,
|
|
107
|
+
roomLifeMs: () => CHAT_RETENTION_MS,
|
|
108
|
+
safeRoomId: deps.roomIdRe,
|
|
109
|
+
onEvent: deps.onEvent === undefined ? undefined : (level, event, roomId, fields) => deps.onEvent?.(level, event, { roomId, ...fields }),
|
|
110
|
+
});
|
|
111
|
+
// A room's chat is readable from the moment this server listens, not some time after.
|
|
112
|
+
await store.loadFromDisk(CHAT_RETENTION_MS);
|
|
113
|
+
const served = serveRoom(io, {
|
|
114
|
+
store,
|
|
115
|
+
presence: deps.presence,
|
|
116
|
+
...(deps.namespace === undefined ? {} : { namespace: deps.namespace }),
|
|
117
|
+
...(deps.onEvent === undefined ? {} : { onEvent: deps.onEvent }),
|
|
118
|
+
admit(socket, join) {
|
|
119
|
+
// Provenance is sanitized engine-wide (`gate.ts`'s `gateSocketIo`, installed by the draft
|
|
120
|
+
// socket on this same `io`) before any namespace's `connection` fires.
|
|
121
|
+
const headers = socket.request.headers;
|
|
122
|
+
// Which gate refused, and the key it refused: a refusal the log cannot explain is one nobody can fix.
|
|
123
|
+
const refuse = (gate) => {
|
|
124
|
+
deps.onEvent?.('warn', 'room.refused', { sid: socket.id, room_key: join.room_key, gate });
|
|
125
|
+
return null;
|
|
126
|
+
};
|
|
127
|
+
if (rankOf(handshakeTier(headers)) < rankOf(deps.minTier))
|
|
128
|
+
return refuse('tier');
|
|
129
|
+
const place = placeOfKey(lobby, deps.isMatch, deps.appId, join.room_key, deps.roomIdRe);
|
|
130
|
+
if (place === null)
|
|
131
|
+
return refuse('no-place');
|
|
132
|
+
const participantId = identityFromHeaders(headers, socket.id);
|
|
133
|
+
if (!mayJoin(lobby, place, participantId))
|
|
134
|
+
return refuse('not-member');
|
|
135
|
+
const roomId = place.roomId;
|
|
136
|
+
const accountId = accountOfHeaders(headers);
|
|
137
|
+
return {
|
|
138
|
+
roomId: place.served,
|
|
139
|
+
key: participantId,
|
|
140
|
+
...(accountId === undefined ? {} : { accountId }),
|
|
141
|
+
member: () => {
|
|
142
|
+
const row = roomId === null ? undefined : lobby.get(roomId)?.members.find((m) => m.id === participantId);
|
|
143
|
+
// A stable handle, never the friend key and never the edge's `X-User-Id`.
|
|
144
|
+
return { author: participantHandle(participantId), name: row?.name ?? participantHandle(participantId), sprite: row?.avatarId ?? null };
|
|
145
|
+
},
|
|
146
|
+
apply: () => {
|
|
147
|
+
const person = accountId === undefined ? undefined : people.peek(accountId);
|
|
148
|
+
if (person !== undefined && roomId !== null)
|
|
149
|
+
applyPerson(lobby, roomId, participantId, person);
|
|
150
|
+
},
|
|
151
|
+
};
|
|
152
|
+
},
|
|
153
|
+
// Always read fresh. serveRoom asks without `fresh` only for a person it holds no copy of (their
|
|
154
|
+
// first join or line since this server started), and people's cache may predate a change they
|
|
155
|
+
// made while their socket was down: a restart's resumed match fills it, and the chrome's
|
|
156
|
+
// `identity_update` for a pick made before the socket rejoined is dropped ("join the room
|
|
157
|
+
// first"), so this read is the only one that sees the pick.
|
|
158
|
+
async account(accountId) {
|
|
159
|
+
const person = (await people.resolve([accountId], { fresh: true })).get(accountId);
|
|
160
|
+
if (person === undefined)
|
|
161
|
+
return null;
|
|
162
|
+
// `sprite` rides along so a change of character alone is a change of identity too.
|
|
163
|
+
const identity = {
|
|
164
|
+
...(person.name === null ? {} : { name: person.name }),
|
|
165
|
+
...(person.look?.picture === undefined ? {} : { avatarUrl: person.look.picture }),
|
|
166
|
+
...(person.look?.cosmetics === undefined ? {} : { cosmetics: person.look.cosmetics }),
|
|
167
|
+
...(person.sprite === null ? {} : { sprite: person.sprite }),
|
|
168
|
+
};
|
|
169
|
+
return identity;
|
|
170
|
+
},
|
|
171
|
+
});
|
|
172
|
+
lobby.onChange((roomId) => {
|
|
173
|
+
if (lobby.get(roomId) === undefined)
|
|
174
|
+
void store.clearRoomChat(roomId);
|
|
175
|
+
});
|
|
176
|
+
return served;
|
|
177
|
+
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hadoku/game-server",
|
|
3
|
-
"version": "0.1.
|
|
4
|
-
"gitHead": "
|
|
3
|
+
"version": "0.1.16",
|
|
4
|
+
"gitHead": "dff9c045bde02e9f716a10ad688f091e53273322",
|
|
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.",
|
|
@@ -16,9 +16,9 @@
|
|
|
16
16
|
"play/remote/"
|
|
17
17
|
],
|
|
18
18
|
"dependencies": {
|
|
19
|
-
"@wolffm/host-wire": "npm:@hadoku/host-wire@0.1.
|
|
20
|
-
"@wolffm/platform-wire": "npm:@hadoku/platform-wire@0.1.
|
|
21
|
-
"@wolffm/service-kernel": "npm:@hadoku/service-kernel@0.1.
|
|
19
|
+
"@wolffm/host-wire": "npm:@hadoku/host-wire@0.1.16",
|
|
20
|
+
"@wolffm/platform-wire": "npm:@hadoku/platform-wire@0.1.16",
|
|
21
|
+
"@wolffm/service-kernel": "npm:@hadoku/service-kernel@0.1.49",
|
|
22
22
|
"@wolffm/prefs-client": "npm:@hadoku/prefs-client@^1.1.27",
|
|
23
23
|
"@wolffm/rooms-protocol": "npm:@hadoku/rooms-protocol@^0.45.98",
|
|
24
24
|
"@wolffm/rooms-server": "npm:@hadoku/rooms-server@^0.45.98",
|