solid-objects 0.17.4 → 0.17.6

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.
@@ -0,0 +1,392 @@
1
+ # Keep turn-based room state through restarts in Node.js
2
+
3
+ A room in process memory loses its state and its turn timer when the process restarts. Store the room in SQL. Arm the turn timer from durable data. One actor per room gives you ordered moves, a durable turn timer, and the current state after a restart. This guide uses `solid-objects` for turn-based games, lobbies, and shared boards in Node.js.
4
+
5
+ ## The failure: state and timers in process memory
6
+
7
+ ```typescript
8
+ type MemoryRoom = { players: string[]; turnNumber: number; started: boolean }
9
+
10
+ export function createMemoryRooms({ turnMilliseconds }: { turnMilliseconds: number }) {
11
+ const rooms = new Map<string, MemoryRoom>()
12
+ const timers = new Map<string, ReturnType<typeof setTimeout>>()
13
+
14
+ function armTurnTimer(roomId: string): void {
15
+ clearTimeout(timers.get(roomId))
16
+ timers.set(
17
+ roomId,
18
+ setTimeout(() => skipTurn(roomId), turnMilliseconds),
19
+ )
20
+ }
21
+
22
+ function skipTurn(roomId: string): void {
23
+ const room = rooms.get(roomId)
24
+ if (!room) return
25
+ rooms.set(roomId, { ...room, turnNumber: room.turnNumber + 1 })
26
+ armTurnTimer(roomId)
27
+ }
28
+
29
+ return {
30
+ join({ roomId, playerId }: { roomId: string; playerId: string }): void {
31
+ const room = rooms.get(roomId) ?? { players: [], turnNumber: 0, started: false }
32
+ rooms.set(roomId, { ...room, players: [...room.players, playerId] })
33
+ },
34
+ start({ roomId }: { roomId: string }): void {
35
+ const room = rooms.get(roomId)
36
+ if (!room) return
37
+ rooms.set(roomId, { ...room, started: true })
38
+ armTurnTimer(roomId)
39
+ },
40
+ room({ roomId }: { roomId: string }): MemoryRoom | undefined {
41
+ return rooms.get(roomId)
42
+ },
43
+ pendingTimers(): number {
44
+ return timers.size
45
+ },
46
+ close(): void {
47
+ for (const timer of timers.values()) clearTimeout(timer)
48
+ timers.clear()
49
+ },
50
+ }
51
+ }
52
+ ```
53
+
54
+ The `Map` holds the room state in one process. The `setTimeout` holds the turn timer in that process. Neither survives a process restart. A deploy or a crash loses both. A second process has its own memory and cannot read the first process's room or timer.
55
+
56
+ The test models a restart with two instances of `createMemoryRooms`. It starts a game with two players and checks that one timer exists. It then calls `close` and creates a new instance. The new instance has no room and no timer. The test uses new instances in the same process.
57
+
58
+ ## The native fix: a row with a version and a deadline
59
+
60
+ ```typescript
61
+ import { DatabaseSync } from "node:sqlite"
62
+
63
+ export type RoomState = { players: string[]; turnNumber: number }
64
+
65
+ export function openRoomStore({ path }: { path: string }): DatabaseSync {
66
+ const database = new DatabaseSync(path)
67
+ database.exec(`
68
+ CREATE TABLE IF NOT EXISTS rooms (
69
+ room_id TEXT PRIMARY KEY,
70
+ state TEXT NOT NULL,
71
+ version INTEGER NOT NULL,
72
+ turn_deadline INTEGER
73
+ )
74
+ `)
75
+ return database
76
+ }
77
+
78
+ export function saveRoom({
79
+ database,
80
+ roomId,
81
+ state,
82
+ expectedVersion,
83
+ turnDeadline,
84
+ }: {
85
+ database: DatabaseSync
86
+ roomId: string
87
+ state: RoomState
88
+ expectedVersion: number
89
+ turnDeadline: number | null
90
+ }): { saved: boolean } {
91
+ if (expectedVersion === 0) {
92
+ const inserted = database
93
+ .prepare(
94
+ "INSERT OR IGNORE INTO rooms (room_id, state, version, turn_deadline) VALUES (?, ?, 1, ?)",
95
+ )
96
+ .run(roomId, JSON.stringify(state), turnDeadline)
97
+ return { saved: inserted.changes === 1 }
98
+ }
99
+ const updated = database
100
+ .prepare(
101
+ "UPDATE rooms SET state = ?, version = version + 1, turn_deadline = ? WHERE room_id = ? AND version = ?",
102
+ )
103
+ .run(JSON.stringify(state), turnDeadline, roomId, expectedVersion)
104
+ return { saved: updated.changes === 1 }
105
+ }
106
+
107
+ export function loadRoom({
108
+ database,
109
+ roomId,
110
+ }: {
111
+ database: DatabaseSync
112
+ roomId: string
113
+ }): { state: RoomState; version: number } | undefined {
114
+ const row = database.prepare("SELECT state, version FROM rooms WHERE room_id = ?").get(roomId) as
115
+ { state: string; version: number } | undefined
116
+ if (!row) return undefined
117
+ const state: unknown = JSON.parse(row.state)
118
+ if (!isRoomState(state)) throw new Error(`stored room ${roomId} has an unexpected shape`)
119
+ return { state, version: row.version }
120
+ }
121
+
122
+ export function dueTurnDeadlines({
123
+ database,
124
+ now,
125
+ }: {
126
+ database: DatabaseSync
127
+ now: number
128
+ }): string[] {
129
+ const rows = database
130
+ .prepare("SELECT room_id FROM rooms WHERE turn_deadline <= ? ORDER BY turn_deadline")
131
+ .all(now) as { room_id: string }[]
132
+ return rows.map((row) => row.room_id)
133
+ }
134
+
135
+ function isRoomState(value: unknown): value is RoomState {
136
+ if (typeof value !== "object" || value === null) return false
137
+ if (!("players" in value) || !Array.isArray(value.players)) return false
138
+ if (!value.players.every((player) => typeof player === "string")) return false
139
+ return "turnNumber" in value && Number.isSafeInteger(value.turnNumber)
140
+ }
141
+ ```
142
+
143
+ The SQL design stores each room as JSON in a row with a `version` column and a turn deadline. `loadRoom` returns the state and its version. It checks the stored JSON against `RoomState` and throws when the shape is unexpected, so the caller never uses unchecked data. The caller passes that version to `saveRoom` as `expectedVersion`.
144
+
145
+ `saveRoom` updates a row only when its version still matches. A successful update also increases the version. A write from an old version returns `{ saved: false }`. The caller then reloads the room and tries again. An old copy of the state cannot replace a newer copy.
146
+
147
+ The row also stores `turn_deadline`. Call `dueTurnDeadlines` at startup and on an interval. It finds rooms whose deadline equals or precedes `now`. The deadline survives because SQL stores it with the state. The query finds due rooms; it does not apply their timeouts.
148
+
149
+ The application still owns these parts:
150
+
151
+ - A retry loop for version conflicts.
152
+ - A sweep process that checks deadlines.
153
+ - A rule that permits only one process to apply each timeout.
154
+
155
+ The test closes the database and opens the same database again. The room survives. A write with the current version succeeds, and a write with the old version fails. The sweep then finds the due room.
156
+
157
+ ## One actor per room
158
+
159
+ ```typescript
160
+ import { Actor } from "solid-objects"
161
+
162
+ export const TURN_MILLISECONDS = 60_000
163
+
164
+ const MAXIMUM_PLAYERS = 4
165
+
166
+ type Move = { playerId: string; move: string; turnNumber: number }
167
+
168
+ export class TurnRoom extends Actor {
169
+ static override readonly actorType = "TurnRoom"
170
+
171
+ players: string[] = []
172
+ started = false
173
+ turnNumber = 0
174
+ moves: Move[] = []
175
+ skippedTurns: number[] = []
176
+ revision = 0
177
+
178
+ get currentPlayer(): string | null {
179
+ if (!this.started) return null
180
+ return this.players[this.turnNumber % this.players.length] ?? null
181
+ }
182
+
183
+ join({ playerId }: { playerId: string }): { players: string[] } {
184
+ if (this.players.includes(playerId)) return { players: this.players }
185
+ if (this.started) this.reject("game_started", { message: "The game already started" })
186
+ if (this.players.length === MAXIMUM_PLAYERS) {
187
+ this.reject("room_full", { message: "The room is full" })
188
+ }
189
+ this.players = [...this.players, playerId]
190
+ this.revision += 1
191
+ return { players: this.players }
192
+ }
193
+
194
+ start({ playerId }: { playerId: string }): { turnNumber: number } {
195
+ if (this.started) return { turnNumber: this.turnNumber }
196
+ if (!this.players.includes(playerId)) {
197
+ this.reject("not_in_room", { message: "Only a player in the room can start the game" })
198
+ }
199
+ if (this.players.length < 2) {
200
+ this.reject("not_enough_players", { message: "The game needs two players" })
201
+ }
202
+ this.started = true
203
+ this.revision += 1
204
+ this.#armTurnTimer()
205
+ return { turnNumber: this.turnNumber }
206
+ }
207
+
208
+ play({ playerId, move, turnNumber }: { playerId: string; move: string; turnNumber: number }): {
209
+ turnNumber: number
210
+ } {
211
+ if (!this.started) this.reject("game_not_started", { message: "The game has not started" })
212
+ if (turnNumber !== this.turnNumber) {
213
+ this.reject("stale_turn", {
214
+ message: "That turn already ended",
215
+ details: { turnNumber: this.turnNumber },
216
+ })
217
+ }
218
+ if (playerId !== this.currentPlayer) {
219
+ this.reject("not_your_turn", { message: "It is not your turn" })
220
+ }
221
+ this.moves = [...this.moves, { playerId, move, turnNumber }]
222
+ this.#advanceTurn()
223
+ return { turnNumber: this.turnNumber }
224
+ }
225
+
226
+ turnTimeout({ turnNumber }: { turnNumber: number }): { skipped: boolean } {
227
+ if (turnNumber !== this.turnNumber) return { skipped: false }
228
+ this.skippedTurns = [...this.skippedTurns, turnNumber]
229
+ this.#advanceTurn()
230
+ return { skipped: true }
231
+ }
232
+
233
+ #advanceTurn(): void {
234
+ this.turnNumber += 1
235
+ this.revision += 1
236
+ this.#armTurnTimer()
237
+ }
238
+
239
+ #armTurnTimer(): void {
240
+ this.schedule({ at: new Date(Date.now() + TURN_MILLISECONDS) }).turnTimeout({
241
+ turnNumber: this.turnNumber,
242
+ })
243
+ }
244
+ }
245
+ ```
246
+
247
+ Each room has one `TurnRoom` actor identity. Moves for that room run one at a time, in order, across processes. The actor stores the players, moves, turn number, skipped turns, and revision. Other rooms have separate identities.
248
+
249
+ `play` takes the `turnNumber` that the client saw. The actor compares that value with its current turn number before it accepts the move. Two tabs can submit different moves for the same turn. The first accepted move advances the turn. The second submission then rejects with `stale_turn`.
250
+
251
+ The actor also checks the player. A move from the wrong player rejects with `not_your_turn`. The getter `currentPlayer` identifies the player for the current turn. Before the game starts, it returns `null`. A getter is a read-only query.
252
+
253
+ Each turn arms `schedule({ at }).turnTimeout({ turnNumber })`. The reminder stores the turn number that it applies to. A reminder with the same operation and no key moves the same alarm. It does not add a second alarm. Thus, a move sets a new deadline for the next turn.
254
+
255
+ `turnTimeout` compares its argument with the current turn number. It does nothing when that turn already ended. A late or repeated timer cannot skip a later turn. A valid timeout records the skipped turn and advances to the next turn.
256
+
257
+ `revision` increases on every change to the room. A client compares revisions to detect missed changes. A repeated `join` for the same player returns the players without a change. It does not increase `revision`.
258
+
259
+ ## Authorize players
260
+
261
+ ```typescript
262
+ import { createRuntime, type SolidObjectsRuntime } from "solid-objects"
263
+ import { sqlite } from "solid-objects/database/sqlite"
264
+ import { TurnRoom } from "./turn-room.js"
265
+
266
+ export type RoomCaller = { playerId: string }
267
+
268
+ const PLAYER_OPERATIONS = new Set(["join", "start", "play"])
269
+
270
+ export function authorizeRoomMessage({
271
+ actorType,
272
+ operation,
273
+ arguments: argumentsValue,
274
+ authorizationContext,
275
+ }: {
276
+ actorType: string
277
+ operation: string
278
+ arguments: Record<string, unknown>
279
+ authorizationContext: unknown
280
+ }): boolean {
281
+ if (actorType !== TurnRoom.actorType) return false
282
+ if (!PLAYER_OPERATIONS.has(operation)) return false
283
+ if (!isRoomCaller(authorizationContext)) return false
284
+ return argumentsValue.playerId === authorizationContext.playerId
285
+ }
286
+
287
+ export function authorizeRoomQuery({
288
+ actorType,
289
+ authorizationContext,
290
+ }: {
291
+ actorType: string
292
+ authorizationContext: unknown
293
+ }): boolean {
294
+ return actorType === TurnRoom.actorType && isRoomCaller(authorizationContext)
295
+ }
296
+
297
+ export function roomRuntime({ path }: { path: string }): SolidObjectsRuntime {
298
+ const runtime = createRuntime({
299
+ database: sqlite({ path }),
300
+ authorizeMessage: authorizeRoomMessage,
301
+ authorizeQuery: authorizeRoomQuery,
302
+ })
303
+ runtime.register(TurnRoom)
304
+ return runtime
305
+ }
306
+
307
+ function isRoomCaller(value: unknown): value is RoomCaller {
308
+ if (typeof value !== "object" || value === null) return false
309
+ return "playerId" in value && typeof value.playerId === "string"
310
+ }
311
+ ```
312
+
313
+ All authorization callbacks deny by default. The application supplies a policy for messages and queries. The message policy permits only `join`, `start`, and `play` for `TurnRoom`.
314
+
315
+ The policy binds the `playerId` argument to the authenticated player in `authorizationContext`. One player cannot submit a move for another player. The application authenticates the WebSocket or HTTP request and passes the player as `authorizationContext`. A player identifier from an untrusted request does not establish that identity.
316
+
317
+ No caller can run `turnTimeout` directly through this policy. Only the runtime runs it from the reminder. The query policy checks the actor type and the player context. The reconnect function below also checks room membership before it returns the room.
318
+
319
+ ## Reconnect: send the current room
320
+
321
+ ```typescript
322
+ import type { ActorSnapshot, SolidObjectsRuntime } from "solid-objects"
323
+ import { TurnRoom } from "./turn-room.js"
324
+
325
+ export async function resumeRoom({
326
+ runtime,
327
+ roomId,
328
+ playerId,
329
+ lastSeenRevision,
330
+ }: {
331
+ runtime: SolidObjectsRuntime
332
+ roomId: string
333
+ playerId: string
334
+ lastSeenRevision: number
335
+ }): Promise<{ room: ActorSnapshot<TurnRoom>; changed: boolean } | null> {
336
+ const room = await runtime.ref(TurnRoom, roomId).snapshot({ authorizationContext: { playerId } })
337
+ if (!room.players.includes(playerId)) return null
338
+ return { room, changed: room.revision !== lastSeenRevision }
339
+ }
340
+ ```
341
+
342
+ After a reconnect or a server restart, the server reads the room with the player's authorization and sends it. `resumeRoom` reads a snapshot with `authorizationContext`. It returns `null` to a player who is not in the room. Keep this membership check on the path that sends room state to the client.
343
+
344
+ For a room member, `resumeRoom` returns the room and `changed`. It compares `revision` with `lastSeenRevision` to calculate `changed`. The client compares the current revision with the last revision it saw. A difference shows that the client missed a change.
345
+
346
+ Socket.IO connection state recovery restores the socket id, rooms, and `data` when recovery succeeds. The server must enable this feature. It also sends events that the client missed during a temporary disconnection. The documentation says recovery “will not always be successful”, so the application must still synchronize client and server state. [Socket.IO documentation](https://socket.io/docs/v4/connection-state-recovery).
347
+
348
+ Adapter support also matters:
349
+
350
+ - The in-memory adapter supports recovery.
351
+ - The Redis adapter does not support recovery.
352
+ - The Redis Streams adapter supports recovery.
353
+ - The MongoDB adapter supports recovery.
354
+
355
+ The [Socket.IO adapter table](https://socket.io/docs/v4/connection-state-recovery#compatibility-with-existing-adapters) lists this support. Socket.IO recovery and this pattern work together. Socket.IO restores the connection, and the actor restores the authorized room state.
356
+
357
+ ## Run the runtime process
358
+
359
+ The turn timer is a reminder. In normal operation, reminders run only while a process calls `runtime.run(signal)`. The `roomRuntime` function registers `TurnRoom` before the runtime starts. The process must know the actor class to execute its operations.
360
+
361
+ Run the background roles as described in [step 7 of the agent guide](../agents.md#7-run-the-background-roles). When no process runs, the due reminder waits in SQL. It runs when a process starts. The runtime needs a process to execute each timeout.
362
+
363
+ In tests, `runtime.testing.runDueReminders({ now })` finds due reminders at the supplied time. Then `runtime.testing.drain({ roles: ["actors"] })` runs the actor work. These calls test due timers without a wait for the real deadline.
364
+
365
+ ## What the tests prove
366
+
367
+ The [tests for persistent rooms](../../test/guide-persistent-rooms.test.ts) check these cases in this order:
368
+
369
+ 1. A new instance of the memory design has no room and no timer after a simulated restart.
370
+ 2. The SQL room survives a database reopen. A write from an old version fails, and the sweep finds the due room. A stored room with an unexpected shape fails to load.
371
+ 3. Two submissions for one turn produce one accepted move and one `stale_turn` rejection.
372
+ 4. A move from the wrong player rejects with `not_your_turn`.
373
+ 5. A caller cannot submit a move for another player.
374
+ 6. After a runtime restart, a due reminder skips turn zero and makes the second player current.
375
+ 7. After a move, a sweep before the next deadline leaves the turn unchanged and records no skipped turn.
376
+ 8. A caller cannot invoke `turnTimeout` directly.
377
+ 9. After a restart, a room member receives the current room, its move, and `changed: true`.
378
+ 10. A player outside the room receives `null` from `resumeRoom`.
379
+
380
+ The seventh test does not inject a late or repeated timer. The turn number check in `turnTimeout` handles that case.
381
+
382
+ ## Limits
383
+
384
+ Delivery is at least once. Write each operation so that it can run again. One room runs one write at a time. This fits turn-based play, not a high-frequency game loop or fast real-time physics.
385
+
386
+ The application owns the WebSocket server, authentication, and the display of the room. There are no transactions across two rooms. The package requires Node.js 24.4 or newer and ESM only. The package is pre-1.0.
387
+
388
+ See [Correctness and delivery semantics](../correctness.md) and [Virtual actors in TypeScript and Node.js](../virtual-actors.md).
389
+
390
+ ## Sources
391
+
392
+ Socket.IO, [Connection state recovery](https://socket.io/docs/v4/connection-state-recovery), checked October 9, 2026.