@signe/room 3.1.1 → 3.2.1

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.
@@ -14,6 +14,7 @@ export type CloudflareRoomWorkerOptions = {
14
14
  partiesPath?: string;
15
15
  env?: Record<string, unknown>;
16
16
  rooms?: Record<string, CloudflareRoomServerConstructor>;
17
+ webSocketMode?: "standard" | "hibernate";
17
18
  };
18
19
 
19
20
  export type CloudflareRoomEnv = Record<string, unknown>;
@@ -33,10 +34,20 @@ type CloudflareRuntimeConfig = Required<Pick<CloudflareRoomWorkerOptions, "bindi
33
34
  ServerClass: CloudflareRoomServerConstructor;
34
35
  env: Record<string, unknown>;
35
36
  rooms: Record<string, CloudflareRoomServerConstructor>;
37
+ webSocketMode: "standard" | "hibernate";
36
38
  };
37
39
 
38
40
  const DEFAULT_PARTIES_PATH = "/parties/main";
39
41
  const WEBSOCKET_OPEN = 1;
42
+ const ROUTE_STORAGE_KEY = "$signe:cloudflare-route";
43
+
44
+ type CloudflareConnectionAttachment = {
45
+ id: string;
46
+ sessionId: string;
47
+ uri: string;
48
+ state: unknown;
49
+ customAttachment: unknown;
50
+ };
40
51
 
41
52
  let runtimeConfig: CloudflareRuntimeConfig | undefined;
42
53
 
@@ -70,7 +81,7 @@ export async function dispatchCloudflareRoomRequest(
70
81
  }
71
82
 
72
83
  const namespace = getNamespace(env, config.binding);
73
- const stub = namespace.get(namespace.idFromName(parsed.roomId));
84
+ const stub = namespace.get(namespace.idFromName(getDurableObjectName(parsed)));
74
85
  return fetchDurableObjectStub(stub, request);
75
86
  }
76
87
 
@@ -100,10 +111,51 @@ export class SigneRoomDurableObject {
100
111
  }
101
112
 
102
113
  async alarm(): Promise<void> {
103
- const record = await this.recordPromise;
114
+ const record = await this.getStoredRecord();
104
115
  await record?.server.onAlarm?.();
105
116
  }
106
117
 
118
+ async webSocketMessage(
119
+ webSocket: CloudflareWebSocket,
120
+ message: string | ArrayBuffer
121
+ ): Promise<void> {
122
+ const record = await this.getStoredRecord();
123
+ if (!record) return;
124
+ const connection = record.room.connectionForWebSocket(webSocket);
125
+ await record.server.onMessage?.(
126
+ normalizeWebSocketMessage(message),
127
+ connection as unknown as Party.Connection
128
+ );
129
+ }
130
+
131
+ async webSocketClose(
132
+ webSocket: CloudflareWebSocket,
133
+ _code: number,
134
+ _reason: string,
135
+ _wasClean: boolean
136
+ ): Promise<void> {
137
+ const record = await this.getStoredRecord();
138
+ if (!record) return;
139
+ const connection = record.room.connectionForWebSocket(webSocket);
140
+ await record.server.onClose?.(connection as unknown as Party.Connection);
141
+ }
142
+
143
+ async webSocketError(
144
+ webSocket: CloudflareWebSocket,
145
+ error: unknown
146
+ ): Promise<void> {
147
+ const record = await this.getStoredRecord();
148
+ if (!record) return;
149
+ const connection = record.room.connectionForWebSocket(webSocket);
150
+ const normalizedError = error instanceof Error
151
+ ? error
152
+ : new Error(String(error));
153
+ await record.server.onError?.(
154
+ connection as unknown as Party.Connection,
155
+ normalizedError
156
+ );
157
+ }
158
+
107
159
  private async acceptWebSocket(
108
160
  request: Request,
109
161
  parsed: ParsedPartyPath
@@ -114,35 +166,42 @@ export class SigneRoomDurableObject {
114
166
  CloudflareWebSocket,
115
167
  ];
116
168
  const record = await this.getRecord(parsed);
117
- const connection = new CloudflareConnection(
118
- server,
119
- request.url,
120
- getConnectionIdFromUrl(request.url)
121
- );
169
+ const hibernating = getRuntimeConfig().webSocketMode === "hibernate";
170
+ const connection = new CloudflareConnection(server, {
171
+ uri: request.url,
172
+ sessionId: getConnectionIdFromUrl(request.url),
173
+ });
122
174
 
123
- server.accept();
175
+ if (hibernating) {
176
+ this.ctx.acceptWebSocket(server);
177
+ connection.persistAttachment();
178
+ } else {
179
+ server.accept();
180
+ }
124
181
 
125
182
  await record.server.onConnect?.(connection as unknown as Party.Connection, {
126
183
  request: request as unknown as Party.Request,
127
184
  });
128
185
 
129
- server.addEventListener("message", (event) => {
130
- void record.server.onMessage?.(
131
- normalizeWebSocketMessage(event.data),
132
- connection as unknown as Party.Connection
133
- );
134
- });
135
- server.addEventListener("close", () => {
136
- record.room.deleteConnection(connection.id, connection);
137
- void record.server.onClose?.(connection as unknown as Party.Connection);
138
- });
139
- server.addEventListener("error", (event) => {
140
- const errorData = (event as { error?: unknown; message?: string }).error;
141
- const error = errorData instanceof Error
142
- ? errorData
143
- : new Error((event as { message?: string }).message ?? "Cloudflare WebSocket error");
144
- void record.server.onError?.(connection as unknown as Party.Connection, error);
145
- });
186
+ if (!hibernating) {
187
+ server.addEventListener("message", (event) => {
188
+ void record.server.onMessage?.(
189
+ normalizeWebSocketMessage(event.data),
190
+ connection as unknown as Party.Connection
191
+ );
192
+ });
193
+ server.addEventListener("close", () => {
194
+ record.room.deleteConnection(connection.id, connection);
195
+ void record.server.onClose?.(connection as unknown as Party.Connection);
196
+ });
197
+ server.addEventListener("error", (event) => {
198
+ const errorData = (event as { error?: unknown; message?: string }).error;
199
+ const error = errorData instanceof Error
200
+ ? errorData
201
+ : new Error((event as { message?: string }).message ?? "Cloudflare WebSocket error");
202
+ void record.server.onError?.(connection as unknown as Party.Connection, error);
203
+ });
204
+ }
146
205
  record.room.addConnection(connection);
147
206
 
148
207
  return new Response(null, {
@@ -153,12 +212,21 @@ export class SigneRoomDurableObject {
153
212
 
154
213
  private async getRecord(parsed: ParsedPartyPath): Promise<CloudflareRoomRecord> {
155
214
  if (!this.recordPromise) {
215
+ await this.ctx.storage.put(ROUTE_STORAGE_KEY, parsed);
156
216
  this.recordPromise = this.createRecord(parsed);
157
217
  }
158
218
 
159
219
  return this.recordPromise;
160
220
  }
161
221
 
222
+ private async getStoredRecord(): Promise<CloudflareRoomRecord | undefined> {
223
+ if (this.recordPromise) return this.recordPromise;
224
+ const parsed = await this.ctx.storage.get<ParsedPartyPath>(ROUTE_STORAGE_KEY);
225
+ if (!parsed) return undefined;
226
+ this.recordPromise = this.createRecord(parsed);
227
+ return this.recordPromise;
228
+ }
229
+
162
230
  private async createRecord(parsed: ParsedPartyPath): Promise<CloudflareRoomRecord> {
163
231
  const config = getRuntimeConfig();
164
232
  const ServerClass = config.rooms[parsed.namespace] ?? config.ServerClass;
@@ -195,6 +263,8 @@ export class CloudflareRoom implements Party.Room {
195
263
  readonly connections = new Map<string, Party.Connection>();
196
264
  readonly parties: Party.Context["parties"];
197
265
  readonly analytics = {} as Party.Room["analytics"];
266
+ private readonly hibernating: boolean;
267
+ private readonly state: DurableObjectState;
198
268
 
199
269
  constructor(options: {
200
270
  id: string;
@@ -224,12 +294,14 @@ export class CloudflareRoom implements Party.Room {
224
294
  },
225
295
  } as Party.Context;
226
296
  this.blockConcurrencyWhile = options.state.blockConcurrencyWhile.bind(options.state);
297
+ this.state = options.state;
298
+ this.hibernating = getRuntimeConfig().webSocketMode === "hibernate";
227
299
  }
228
300
 
229
301
  blockConcurrencyWhile: Party.Room["blockConcurrencyWhile"];
230
302
 
231
303
  broadcast(msg: string | ArrayBuffer | ArrayBufferView, without: string[] = []) {
232
- for (const connection of this.connections.values()) {
304
+ for (const connection of this.getConnections()) {
233
305
  if (!without.includes(connection.id)) {
234
306
  connection.send(msg);
235
307
  }
@@ -238,7 +310,7 @@ export class CloudflareRoom implements Party.Room {
238
310
 
239
311
  getConnection<TState = unknown>(id: string): Party.Connection<TState> | undefined {
240
312
  let connection: Party.Connection | undefined;
241
- for (const current of this.connections.values()) {
313
+ for (const current of this.getConnections()) {
242
314
  if (current.id === id || current.sessionId === id) {
243
315
  connection = current;
244
316
  }
@@ -247,14 +319,21 @@ export class CloudflareRoom implements Party.Room {
247
319
  }
248
320
 
249
321
  getConnections<TState = unknown>(): Iterable<Party.Connection<TState>> {
322
+ if (this.hibernating) {
323
+ return this.state.getWebSockets().map((webSocket) =>
324
+ this.connectionForWebSocket(webSocket as CloudflareWebSocket)
325
+ ) as unknown as Party.Connection<TState>[];
326
+ }
250
327
  return Array.from(this.connections.values()) as Party.Connection<TState>[];
251
328
  }
252
329
 
253
330
  addConnection(connection: CloudflareConnection) {
331
+ if (this.hibernating) return;
254
332
  this.connections.set(connection.id, connection as unknown as Party.Connection);
255
333
  }
256
334
 
257
335
  deleteConnection(id: string, connection?: CloudflareConnection) {
336
+ if (this.hibernating) return;
258
337
  if (connection) {
259
338
  this.connections.delete(connection.id);
260
339
  return;
@@ -266,23 +345,52 @@ export class CloudflareRoom implements Party.Room {
266
345
  }
267
346
  }
268
347
  }
348
+
349
+
350
+ connectionForWebSocket(webSocket: CloudflareWebSocket): CloudflareConnection {
351
+ return CloudflareConnection.restore(webSocket);
352
+ }
269
353
  }
270
354
 
271
355
  export class CloudflareConnection<TState = unknown> {
272
- readonly id = createConnectionId();
356
+ readonly id: string;
273
357
  readonly sessionId: string;
274
358
  readonly socket: this = this;
275
359
  readonly uri: string;
276
- state: Party.ConnectionState<TState> | TState | null = null;
277
- private attachment: unknown = null;
360
+ state: Party.ConnectionState<TState> | TState | null;
361
+ private attachment: unknown;
278
362
 
279
363
  constructor(
280
364
  private readonly webSocket: CloudflareWebSocket,
281
- uri: string,
282
- sessionId?: string
365
+ options: {
366
+ id?: string;
367
+ uri: string;
368
+ sessionId?: string;
369
+ state?: Party.ConnectionState<TState> | TState | null;
370
+ attachment?: unknown;
371
+ }
283
372
  ) {
284
- this.sessionId = sessionId || this.id;
285
- this.uri = uri;
373
+ this.id = options.id ?? createConnectionId();
374
+ this.sessionId = options.sessionId || this.id;
375
+ this.uri = options.uri;
376
+ this.state = options.state ?? null;
377
+ this.attachment = options.attachment ?? null;
378
+ }
379
+
380
+ static restore(webSocket: CloudflareWebSocket): CloudflareConnection {
381
+ const attachment = webSocket.deserializeAttachment?.() as
382
+ | CloudflareConnectionAttachment
383
+ | undefined;
384
+ if (!attachment) {
385
+ throw new Error("Missing Signe WebSocket attachment");
386
+ }
387
+ return new CloudflareConnection(webSocket, {
388
+ id: attachment.id,
389
+ sessionId: attachment.sessionId,
390
+ uri: attachment.uri,
391
+ state: attachment.state,
392
+ attachment: attachment.customAttachment,
393
+ });
286
394
  }
287
395
 
288
396
  send(data: string | ArrayBuffer | ArrayBufferView) {
@@ -302,16 +410,28 @@ export class CloudflareConnection<TState = unknown> {
302
410
  this.state = typeof state === "function"
303
411
  ? (state as Party.ConnectionSetStateFn<TState>)(this.state as Party.ConnectionState<TState>)
304
412
  : state;
413
+ this.persistAttachment();
305
414
  return this.state as Party.ConnectionState<TState>;
306
415
  }
307
416
 
308
417
  serializeAttachment<T = unknown>(attachment: T): void {
309
418
  this.attachment = attachment;
419
+ this.persistAttachment();
310
420
  }
311
421
 
312
422
  deserializeAttachment<T = unknown>(): T | null {
313
423
  return this.attachment as T | null;
314
424
  }
425
+
426
+ persistAttachment(): void {
427
+ this.webSocket.serializeAttachment?.({
428
+ id: this.id,
429
+ sessionId: this.sessionId,
430
+ uri: this.uri,
431
+ state: this.state,
432
+ customAttachment: this.attachment,
433
+ } satisfies CloudflareConnectionAttachment);
434
+ }
315
435
  }
316
436
 
317
437
  function createRuntimeConfig<TServer extends Party.Server>(
@@ -327,6 +447,7 @@ function createRuntimeConfig<TServer extends Party.Server>(
327
447
  main: ServerClass as CloudflareRoomServerConstructor,
328
448
  ...(options.rooms ?? {}),
329
449
  },
450
+ webSocketMode: options.webSocketMode ?? "standard",
330
451
  };
331
452
  }
332
453
 
@@ -358,7 +479,10 @@ function createPartiesContext(
358
479
  },
359
480
  fetch(pathOrInit?: string | RequestInit | Request, init?: RequestInit) {
360
481
  const namespaceBinding = getNamespace(env, binding);
361
- const stub = namespaceBinding.get(namespaceBinding.idFromName(roomId));
482
+ const parsed = { namespace, roomId };
483
+ const stub = namespaceBinding.get(
484
+ namespaceBinding.idFromName(getDurableObjectName(parsed))
485
+ );
362
486
  if (pathOrInit instanceof Request) {
363
487
  return fetchDurableObjectStub(stub, pathOrInit);
364
488
  }
@@ -377,6 +501,10 @@ function createPartiesContext(
377
501
  }) as Party.Context["parties"];
378
502
  }
379
503
 
504
+ function getDurableObjectName(parsed: ParsedPartyPath): string {
505
+ return `${parsed.namespace}:${parsed.roomId}`;
506
+ }
507
+
380
508
  function getNamespace(env: Record<string, unknown>, binding: string) {
381
509
  const namespace = env[binding] as DurableObjectNamespace | undefined;
382
510
 
package/src/node/index.ts CHANGED
@@ -744,7 +744,11 @@ export class NodeConnection<TState = unknown> {
744
744
  readonly sessionId: string;
745
745
  readonly socket: this = this;
746
746
  readonly uri: string;
747
- state: Party.ConnectionState<TState> | TState | null = null;
747
+ /**
748
+ * Application-owned state associated with this connection.
749
+ * Read it as immutable data and use `setState()` to replace it.
750
+ */
751
+ state: Party.ConnectionState<TState> = null;
748
752
  private attachment: unknown = null;
749
753
 
750
754
  constructor(
@@ -766,11 +770,12 @@ export class NodeConnection<TState = unknown> {
766
770
  this.webSocket.close(code, reason);
767
771
  }
768
772
 
769
- setState(state: TState | Party.ConnectionSetStateFn<TState> | null) {
770
- this.state = typeof state === "function"
771
- ? (state as Party.ConnectionSetStateFn<TState>)(this.state as Party.ConnectionState<TState>)
773
+ setState(state: TState | Party.ConnectionSetStateFn<TState> | null): Party.ConnectionState<TState> {
774
+ const next = typeof state === "function"
775
+ ? (state as Party.ConnectionSetStateFn<TState>)(this.state)
772
776
  : state;
773
- return this.state as Party.ConnectionState<TState>;
777
+ this.state = next as Party.ConnectionState<TState>;
778
+ return this.state;
774
779
  }
775
780
 
776
781
  serializeAttachment<T = unknown>(attachment: T): void {
@@ -147,7 +147,7 @@ import type {
147
147
  export type ConnectionSetStateFn<T> = (prevState: ConnectionState<T>) => T;
148
148
 
149
149
  /** A WebSocket connected to the Room */
150
- export type Connection<TState = unknown> = WebSocket & {
150
+ export interface Connection<TState = unknown> extends WebSocket {
151
151
  /** Connection identifier */
152
152
  id: string;
153
153
 
@@ -178,7 +178,7 @@ import type {
178
178
 
179
179
  /** @deprecated use Connection.state instead */
180
180
  deserializeAttachment<T = unknown>(): T | null;
181
- };
181
+ }
182
182
 
183
183
  type CustomBindings = {
184
184
  r2: Record<string, R2Bucket>;