@syncular/server-workers 0.57.0 → 0.59.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -13
- package/dist/index.d.ts +8 -0
- package/dist/index.js +7 -0
- package/dist/r2-stores.d.ts +7 -3
- package/dist/r2-stores.js +6 -3
- package/dist/realtime-do.d.ts +71 -17
- package/dist/realtime-do.js +197 -117
- package/package.json +4 -4
- package/src/index.ts +20 -0
- package/src/r2-stores.ts +8 -3
- package/src/realtime-do.ts +242 -118
package/src/realtime-do.ts
CHANGED
|
@@ -46,23 +46,45 @@
|
|
|
46
46
|
* an async generator draining over `ws.send`; while it is pending it holds
|
|
47
47
|
* the DO's event loop, so the DO cannot be evicted mid-round. (This is the
|
|
48
48
|
* same property the §8.7 "one round in flight" rule relies on.)
|
|
49
|
-
* - **
|
|
50
|
-
* HTTP sync round
|
|
51
|
-
*
|
|
52
|
-
*
|
|
53
|
-
*
|
|
54
|
-
*
|
|
55
|
-
*
|
|
56
|
-
*
|
|
57
|
-
*
|
|
58
|
-
*
|
|
59
|
-
*
|
|
60
|
-
*
|
|
61
|
-
*
|
|
49
|
+
* - **Before any entry point proceeds after a wake** (a socket frame or
|
|
50
|
+
* close, an HTTP sync round including a pull-only one, an upgrade, a
|
|
51
|
+
* command, an admin request), every accepted socket has a serialized
|
|
52
|
+
* attachment (`ws.serializeAttachment`: its identity, written at accept
|
|
53
|
+
* time, and its presence documents, rewritten on every change) but no
|
|
54
|
+
* live session. The host rebuilds the
|
|
55
|
+
* session of every socket in `getWebSockets()` once, through one promise
|
|
56
|
+
* every entry point awaits, so no commit fans out to a partly rebuilt hub
|
|
57
|
+
* and sockets that stayed quiet through the hibernation keep receiving
|
|
58
|
+
* deltas. `hub.restore(...)` reloads each registration list from the
|
|
59
|
+
* client record (the §8.1 load-at-upgrade rule), touches the partition
|
|
60
|
+
* and reads its latest sequence once, and sends no `hello`: the client
|
|
61
|
+
* was greeted at the real upgrade. Cursor/registration are the durable
|
|
62
|
+
* truth in storage; nothing in-flight is lost because nothing in-flight
|
|
63
|
+
* can be hibernated.
|
|
62
64
|
*
|
|
63
|
-
*
|
|
64
|
-
*
|
|
65
|
-
*
|
|
65
|
+
* The attachment holds what storage cannot: the identity `restore` needs and
|
|
66
|
+
* the connection's §8.6 presence documents, which `restore` seeds silently so
|
|
67
|
+
* a close after a wake still sends `leave` and a new socket still receives
|
|
68
|
+
* the snapshot. Everything else (`cursor`, `registrations`, `lastKnownSeq`)
|
|
69
|
+
* is re-derived from storage, which is authoritative.
|
|
70
|
+
*
|
|
71
|
+
* The attachment is one `Uint8Array`, so its structured-clone size is its
|
|
72
|
+
* byte length plus fixed framing: the identity as UTF-8 JSON and a newline,
|
|
73
|
+
* then per presence key a varint key length, the key's UTF-8 bytes, the
|
|
74
|
+
* document's UTF-8 JSON and a newline (a JSON text holds no raw newline).
|
|
75
|
+
* Each key costs at least 3 counted bytes (a non-empty key and `{}`) and at
|
|
76
|
+
* most 2 framing bytes below 128 key bytes, so a connection within
|
|
77
|
+
* `maxPresenceBytes` needs at most `cap + floor(2 * cap / 3)` presence
|
|
78
|
+
* bytes. The hub refuses a cap whose worst case leaves no room for an empty
|
|
79
|
+
* identity, and the upgrade refuses an identity that does not fit beside the
|
|
80
|
+
* worst case, so no presence change can overflow the attachment.
|
|
81
|
+
*
|
|
82
|
+
* ## Heartbeats (§8.5)
|
|
83
|
+
*
|
|
84
|
+
* The host arms the Durable Object alarm when a socket connects. `alarm()`
|
|
85
|
+
* sends `heartbeat` straight to every hibernatable socket, without rebuilding
|
|
86
|
+
* sessions, and re-arms while sockets remain. The host owns the alarm: a
|
|
87
|
+
* subclass that needs another alarm schedule cannot share it.
|
|
66
88
|
*
|
|
67
89
|
* ## The wake path (external-command fan-out)
|
|
68
90
|
*
|
|
@@ -78,6 +100,7 @@ import {
|
|
|
78
100
|
createRealtimeHub,
|
|
79
101
|
D1ServerStorage,
|
|
80
102
|
decodeRequestBody,
|
|
103
|
+
encodeHeartbeat,
|
|
81
104
|
errorBody,
|
|
82
105
|
eraseScopeValue,
|
|
83
106
|
type EraseScopeValueOptions,
|
|
@@ -86,6 +109,7 @@ import {
|
|
|
86
109
|
handleSyncRequest,
|
|
87
110
|
pruneCommitLog,
|
|
88
111
|
type PruneOptions,
|
|
112
|
+
type RealtimeConnectOptions,
|
|
89
113
|
type RealtimeHub,
|
|
90
114
|
type RealtimeHubConfig,
|
|
91
115
|
type RealtimeSession,
|
|
@@ -110,6 +134,12 @@ import { decodeMessage } from '@syncular/core';
|
|
|
110
134
|
export interface DurableObjectStateLike {
|
|
111
135
|
acceptWebSocket(ws: WebSocketLike, tags?: string[]): void;
|
|
112
136
|
getWebSockets(tag?: string): WebSocketLike[];
|
|
137
|
+
/** The alarm half of the DO storage API; the host owns the alarm and
|
|
138
|
+
* drives §8.5 heartbeats with it. */
|
|
139
|
+
readonly storage: {
|
|
140
|
+
getAlarm(): Promise<number | null>;
|
|
141
|
+
setAlarm(scheduledTime: number): Promise<void>;
|
|
142
|
+
};
|
|
113
143
|
}
|
|
114
144
|
|
|
115
145
|
export interface WebSocketLike {
|
|
@@ -165,6 +195,12 @@ export type RealtimeDOConfig<S extends RealtimeHostStorage = D1ServerStorage> =
|
|
|
165
195
|
* partition's rounds.
|
|
166
196
|
*/
|
|
167
197
|
readonly adminRingCapacity?: number;
|
|
198
|
+
/**
|
|
199
|
+
* §8.5 heartbeat interval in ms; default 30000. The host sends `heartbeat`
|
|
200
|
+
* to every socket from the Durable Object alarm, which stays armed while
|
|
201
|
+
* sockets are connected.
|
|
202
|
+
*/
|
|
203
|
+
readonly heartbeatIntervalMs?: number;
|
|
168
204
|
/**
|
|
169
205
|
* Registered remote queries and commands (REMOTE.md). The Worker forwards
|
|
170
206
|
* `POST <mount>/operations` here, so a command applies on the partition
|
|
@@ -181,21 +217,51 @@ export type RealtimeDOConfig<S extends RealtimeHostStorage = D1ServerStorage> =
|
|
|
181
217
|
*/
|
|
182
218
|
export type RealtimeHubConfigInput = Omit<RealtimeHubConfig, 'storage'>;
|
|
183
219
|
|
|
184
|
-
/**
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
220
|
+
/**
|
|
221
|
+
* Cloudflare's cap on a socket attachment's serialized size
|
|
222
|
+
* (https://developers.cloudflare.com/durable-objects/api/websockets/,
|
|
223
|
+
* `serializeAttachment`).
|
|
224
|
+
*/
|
|
225
|
+
const ATTACHMENT_LIMIT_BYTES = 16_384;
|
|
226
|
+
/** Room for the structured-clone framing around the attachment's one
|
|
227
|
+
* `Uint8Array`: format header, buffer and view tags, length varints. */
|
|
228
|
+
const ATTACHMENT_FRAMING_BYTES = 64;
|
|
229
|
+
|
|
230
|
+
/** `maxPresenceBytes` leaves no room in a socket attachment for an empty
|
|
231
|
+
* identity beside a full presence budget (§8.6.1). */
|
|
232
|
+
export class PresenceAttachmentError extends Error {
|
|
233
|
+
readonly code = 'realtime.presence_exceeds_attachment';
|
|
234
|
+
|
|
235
|
+
constructor(
|
|
236
|
+
readonly details: {
|
|
237
|
+
readonly maxPresenceBytes: number;
|
|
238
|
+
readonly attachmentLimitBytes: number;
|
|
239
|
+
},
|
|
240
|
+
) {
|
|
241
|
+
super('maxPresenceBytes does not fit a socket attachment (§8.6.1)');
|
|
242
|
+
this.name = 'PresenceAttachmentError';
|
|
243
|
+
}
|
|
189
244
|
}
|
|
190
245
|
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
246
|
+
/** A hibernatable socket's attachment bytes (layout: see the module doc). */
|
|
247
|
+
function encodeAttachment(
|
|
248
|
+
identity: RealtimeUpgradeIdentity,
|
|
249
|
+
presence: ReadonlyMap<string, string>,
|
|
250
|
+
): Uint8Array {
|
|
251
|
+
const utf8 = new TextEncoder();
|
|
252
|
+
const bytes = [
|
|
253
|
+
...utf8.encode(
|
|
254
|
+
JSON.stringify([identity.partition, identity.actorId, identity.clientId]),
|
|
255
|
+
),
|
|
256
|
+
0x0a,
|
|
257
|
+
];
|
|
258
|
+
for (const [scopeKey, json] of presence) {
|
|
259
|
+
const key = utf8.encode(scopeKey);
|
|
260
|
+
let length = key.length;
|
|
261
|
+
for (; length >= 0x80; length >>>= 7) bytes.push((length & 0x7f) | 0x80);
|
|
262
|
+
bytes.push(length, ...key, ...utf8.encode(json), 0x0a);
|
|
263
|
+
}
|
|
264
|
+
return Uint8Array.from(bytes);
|
|
199
265
|
}
|
|
200
266
|
|
|
201
267
|
/** The identity the upgrade request must carry (resolved by the Worker). */
|
|
@@ -246,6 +312,7 @@ function unsupportedEncoding(route: 'sync' | 'operations'): Response {
|
|
|
246
312
|
* }
|
|
247
313
|
* webSocketClose(ws: WebSocket) { return this.#impl.webSocketClose(ws); }
|
|
248
314
|
* webSocketError(ws: WebSocket) { return this.#impl.webSocketError(ws); }
|
|
315
|
+
* alarm() { return this.#impl.alarm(); }
|
|
249
316
|
* }
|
|
250
317
|
* ```
|
|
251
318
|
*
|
|
@@ -259,19 +326,17 @@ export class SyncularRealtimeHost<
|
|
|
259
326
|
readonly #storage: RealtimeHostStorage;
|
|
260
327
|
readonly #config: RealtimeDOConfig<RealtimeHostStorage>;
|
|
261
328
|
#hub: RealtimeHub | undefined;
|
|
329
|
+
/** Attachment bytes held back for framing and a full presence budget. */
|
|
330
|
+
#presenceReserve = 0;
|
|
262
331
|
#admin: SyncularAdmin | undefined;
|
|
263
332
|
/** Live sessions, keyed by their socket. Empty after a hibernation wake;
|
|
264
|
-
* rehydrated for every socket before
|
|
265
|
-
*
|
|
333
|
+
* rehydrated for every socket before any entry point proceeds (see the
|
|
334
|
+
* class doc). */
|
|
266
335
|
readonly #sessions = new Map<WebSocketLike, RealtimeSession>();
|
|
267
|
-
/** Sockets whose rehydration `hello` must be swallowed (already greeted at
|
|
268
|
-
* the real upgrade — rehydration is transparent to the client). */
|
|
269
|
-
readonly #swallowHello = new Set<WebSocketLike>();
|
|
270
336
|
readonly #closedSockets = new WeakSet<WebSocketLike>();
|
|
271
|
-
/**
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
#rehydrated = false;
|
|
337
|
+
/** This instance's one rebuild of hibernated sockets' sessions. Every entry
|
|
338
|
+
* point awaits it, so no commit fans out to a partly rebuilt hub. */
|
|
339
|
+
#rehydration: Promise<void> | undefined;
|
|
275
340
|
/** Explicit FIFO: Durable Object events may interleave at `await`. */
|
|
276
341
|
#partitionTail: Promise<void> = Promise.resolve();
|
|
277
342
|
|
|
@@ -334,6 +399,22 @@ export class SyncularRealtimeHost<
|
|
|
334
399
|
: ring,
|
|
335
400
|
};
|
|
336
401
|
const hub = createRealtimeHub(withRing);
|
|
402
|
+
const cap = hub.maxPresenceBytes;
|
|
403
|
+
this.#presenceReserve =
|
|
404
|
+
ATTACHMENT_FRAMING_BYTES + cap + Math.floor((2 * cap) / 3);
|
|
405
|
+
if (
|
|
406
|
+
this.#presenceReserve +
|
|
407
|
+
encodeAttachment(
|
|
408
|
+
{ partition: '', actorId: '', clientId: '' },
|
|
409
|
+
new Map(),
|
|
410
|
+
).byteLength >
|
|
411
|
+
ATTACHMENT_LIMIT_BYTES
|
|
412
|
+
) {
|
|
413
|
+
throw new PresenceAttachmentError({
|
|
414
|
+
maxPresenceBytes: cap,
|
|
415
|
+
attachmentLimitBytes: ATTACHMENT_LIMIT_BYTES,
|
|
416
|
+
});
|
|
417
|
+
}
|
|
337
418
|
this.#hub = hub;
|
|
338
419
|
this.#admin = SyncularAdmin.fromConfig(
|
|
339
420
|
{ ...withRing, realtime: hub },
|
|
@@ -350,9 +431,19 @@ export class SyncularRealtimeHost<
|
|
|
350
431
|
* and accepts external-command wakes at `/__syncular_realtime/wake`.
|
|
351
432
|
*/
|
|
352
433
|
async fetch(request: Request): Promise<Response> {
|
|
434
|
+
await this.#rehydrateSockets();
|
|
353
435
|
const url = new URL(request.url);
|
|
354
436
|
if (url.pathname === SYNC_DO_REQUEST_PATH) {
|
|
355
|
-
|
|
437
|
+
let bytes: Uint8Array | undefined;
|
|
438
|
+
try {
|
|
439
|
+
bytes = await decodeRequestBody(
|
|
440
|
+
request,
|
|
441
|
+
this.#getHub().limits.maxRequestBytes,
|
|
442
|
+
);
|
|
443
|
+
} catch (error) {
|
|
444
|
+
const sync = this.#syncError(error, 'sync');
|
|
445
|
+
return Response.json(errorBody(sync), { status: sync.httpStatus });
|
|
446
|
+
}
|
|
356
447
|
if (bytes === undefined) return unsupportedEncoding('sync');
|
|
357
448
|
// A round without PUSH_COMMIT frames writes only its own client
|
|
358
449
|
// record, so it runs beside the FIFO instead of queueing behind every
|
|
@@ -364,10 +455,7 @@ export class SyncularRealtimeHost<
|
|
|
364
455
|
(frame) => frame.type !== 'PUSH_COMMIT',
|
|
365
456
|
);
|
|
366
457
|
} catch {}
|
|
367
|
-
if (pullOnly)
|
|
368
|
-
await this.#rehydrateSockets();
|
|
369
|
-
return this.#handleSync(request, bytes);
|
|
370
|
-
}
|
|
458
|
+
if (pullOnly) return this.#handleSync(request, bytes);
|
|
371
459
|
return this.#serializePartition(() => this.#handleSync(request, bytes));
|
|
372
460
|
}
|
|
373
461
|
if (url.pathname === OPERATIONS_DO_REQUEST_PATH) {
|
|
@@ -447,23 +535,56 @@ export class SyncularRealtimeHost<
|
|
|
447
535
|
|
|
448
536
|
/**
|
|
449
537
|
* After a hibernation wake the session map is empty while sockets stay
|
|
450
|
-
* open. Rebuild every socket's session
|
|
451
|
-
*
|
|
452
|
-
*
|
|
453
|
-
* its client reconnects and catches up (§8.4).
|
|
538
|
+
* open. Rebuild every socket's session once, so a commit fans out to sockets
|
|
539
|
+
* that stayed quiet through the hibernation. A socket whose session cannot
|
|
540
|
+
* be rebuilt is closed; its client reconnects and catches up (§8.4).
|
|
454
541
|
*/
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
542
|
+
#rehydrateSockets(): Promise<void> {
|
|
543
|
+
this.#rehydration ??= (async () => {
|
|
544
|
+
const sockets = this.#state.getWebSockets().flatMap((ws) => {
|
|
545
|
+
const bytes = ws.deserializeAttachment();
|
|
546
|
+
if (!(bytes instanceof Uint8Array)) return [];
|
|
547
|
+
const utf8 = new TextDecoder();
|
|
548
|
+
let end = bytes.indexOf(0x0a);
|
|
549
|
+
const [partition, actorId, clientId] = JSON.parse(
|
|
550
|
+
utf8.decode(bytes.subarray(0, end)),
|
|
551
|
+
) as [string, string, string];
|
|
552
|
+
const presence = new Map<string, string>();
|
|
553
|
+
for (let at = end + 1; at < bytes.length; at = end + 1) {
|
|
554
|
+
let length = 0;
|
|
555
|
+
for (let shift = 0; ; shift += 7) {
|
|
556
|
+
const byte = bytes[at++]!;
|
|
557
|
+
length |= (byte & 0x7f) << shift;
|
|
558
|
+
if (byte < 0x80) break;
|
|
559
|
+
}
|
|
560
|
+
end = bytes.indexOf(0x0a, at + length);
|
|
561
|
+
presence.set(
|
|
562
|
+
utf8.decode(bytes.subarray(at, at + length)),
|
|
563
|
+
utf8.decode(bytes.subarray(at + length, end)),
|
|
564
|
+
);
|
|
565
|
+
}
|
|
566
|
+
return [{ ws, identity: { partition, actorId, clientId }, presence }];
|
|
567
|
+
});
|
|
568
|
+
if (sockets.length === 0) return;
|
|
569
|
+
const results = await this.#getHub().restore(
|
|
570
|
+
sockets.map(({ ws, identity, presence }) => ({
|
|
571
|
+
...this.#connectOptions(ws, identity),
|
|
572
|
+
presence,
|
|
573
|
+
})),
|
|
574
|
+
);
|
|
575
|
+
for (const [i, result] of results.entries()) {
|
|
576
|
+
const ws = sockets[i]!.ws;
|
|
577
|
+
if (result.status === 'rejected') {
|
|
578
|
+
ws.close(1011, 'realtime rehydration failed');
|
|
579
|
+
this.#syncError(result.reason, 'realtime');
|
|
580
|
+
} else if (this.#closedSockets.has(ws)) {
|
|
581
|
+
result.value.close();
|
|
582
|
+
} else {
|
|
583
|
+
this.#sessions.set(ws, result.value);
|
|
584
|
+
}
|
|
465
585
|
}
|
|
466
|
-
}
|
|
586
|
+
})();
|
|
587
|
+
return this.#rehydration;
|
|
467
588
|
}
|
|
468
589
|
|
|
469
590
|
/**
|
|
@@ -499,7 +620,10 @@ export class SyncularRealtimeHost<
|
|
|
499
620
|
return Response.json(errorBody(error), { status: error.httpStatus });
|
|
500
621
|
}
|
|
501
622
|
try {
|
|
502
|
-
const bytes = await decodeRequestBody(
|
|
623
|
+
const bytes = await decodeRequestBody(
|
|
624
|
+
request,
|
|
625
|
+
this.#getHub().limits.maxRequestBytes,
|
|
626
|
+
);
|
|
503
627
|
if (bytes === undefined) return unsupportedEncoding('operations');
|
|
504
628
|
const out = await handleRemoteOperation(
|
|
505
629
|
bytes,
|
|
@@ -606,24 +730,40 @@ export class SyncularRealtimeHost<
|
|
|
606
730
|
const pair = newWebSocketPair();
|
|
607
731
|
const client = pair[0];
|
|
608
732
|
const server = pair[1];
|
|
609
|
-
// Hand the server socket to the runtime for hibernation
|
|
610
|
-
//
|
|
611
|
-
const attachment
|
|
612
|
-
partition: identity.partition,
|
|
613
|
-
actorId: identity.actorId,
|
|
614
|
-
clientId: identity.clientId,
|
|
615
|
-
};
|
|
733
|
+
// Hand the server socket to the runtime for hibernation with the §8.1
|
|
734
|
+
// identity `restore` needs to rehydrate.
|
|
735
|
+
const attachment = encodeAttachment(identity, new Map());
|
|
616
736
|
server.serializeAttachment(attachment);
|
|
617
|
-
this.#upgrading.add(server);
|
|
618
737
|
this.#state.acceptWebSocket(server);
|
|
619
738
|
// Build the session now (first connect: hello IS delivered). Any failure
|
|
620
739
|
// closes the socket loudly — never a half-open realtime connection.
|
|
621
740
|
try {
|
|
622
|
-
const
|
|
741
|
+
const hub = this.#getHub();
|
|
742
|
+
// §8.6.1: the identity must fit the attachment beside a full presence
|
|
743
|
+
// budget, so no later presence change can overflow it.
|
|
744
|
+
if (
|
|
745
|
+
this.#presenceReserve + attachment.byteLength >
|
|
746
|
+
ATTACHMENT_LIMIT_BYTES
|
|
747
|
+
) {
|
|
748
|
+
throw new SyncError(
|
|
749
|
+
'sync.limit_exceeded',
|
|
750
|
+
'realtime identity does not fit the socket attachment (§8.6.1)',
|
|
751
|
+
JSON.stringify({
|
|
752
|
+
limit: 'attachmentBytes',
|
|
753
|
+
max: ATTACHMENT_LIMIT_BYTES,
|
|
754
|
+
}),
|
|
755
|
+
);
|
|
756
|
+
}
|
|
757
|
+
const session = await hub.connect(this.#connectOptions(server, identity));
|
|
623
758
|
this.#sessions.set(server, session);
|
|
624
|
-
this.#
|
|
759
|
+
if ((await this.#state.storage.getAlarm()) === null) {
|
|
760
|
+
await this.#state.storage.setAlarm(
|
|
761
|
+
Date.now() + (this.#config.heartbeatIntervalMs ?? 30_000),
|
|
762
|
+
);
|
|
763
|
+
}
|
|
625
764
|
} catch (error) {
|
|
626
|
-
this.#
|
|
765
|
+
this.#sessions.get(server)?.close();
|
|
766
|
+
this.#sessions.delete(server);
|
|
627
767
|
server.close(1011, 'realtime connect failed');
|
|
628
768
|
const sync = this.#syncError(error, 'realtime');
|
|
629
769
|
return Response.json(errorBody(sync), { status: sync.httpStatus });
|
|
@@ -634,49 +774,43 @@ export class SyncularRealtimeHost<
|
|
|
634
774
|
return new Response(null, init);
|
|
635
775
|
}
|
|
636
776
|
|
|
637
|
-
/**
|
|
638
|
-
|
|
777
|
+
/** The hub connect options of a hibernatable socket (§8.1). */
|
|
778
|
+
#connectOptions(
|
|
639
779
|
ws: WebSocketLike,
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
clientId: attachment.clientId,
|
|
648
|
-
send: (data) => {
|
|
649
|
-
// Swallow exactly one hello on a rehydrated socket — the client was
|
|
650
|
-
// greeted at the real upgrade; rehydration is transparent (§8.1).
|
|
651
|
-
if (this.#swallowHello.has(ws)) {
|
|
652
|
-
this.#swallowHello.delete(ws);
|
|
653
|
-
if (isHello(data)) return;
|
|
654
|
-
}
|
|
655
|
-
sendOverSocket(ws, data);
|
|
656
|
-
},
|
|
780
|
+
identity: RealtimeUpgradeIdentity,
|
|
781
|
+
): RealtimeConnectOptions {
|
|
782
|
+
return {
|
|
783
|
+
partition: identity.partition,
|
|
784
|
+
actorId: identity.actorId,
|
|
785
|
+
clientId: identity.clientId,
|
|
786
|
+
send: (data) => sendOverSocket(ws, data),
|
|
657
787
|
closeSocket: () => ws.close(1008, 'protocol violation (§8.7)'),
|
|
658
|
-
|
|
659
|
-
|
|
788
|
+
// §8.6.1: presence survives a hibernation in the socket's attachment.
|
|
789
|
+
onPresence: (presence) =>
|
|
790
|
+
ws.serializeAttachment(encodeAttachment(identity, presence)),
|
|
791
|
+
};
|
|
660
792
|
}
|
|
661
793
|
|
|
662
794
|
/**
|
|
663
|
-
*
|
|
664
|
-
*
|
|
795
|
+
* The Durable Object alarm: send a §8.5 heartbeat to every socket and re-arm
|
|
796
|
+
* while sockets remain. The frame goes straight to the hibernatable sockets,
|
|
797
|
+
* so a heartbeat rebuilds no session.
|
|
665
798
|
*/
|
|
666
|
-
async
|
|
667
|
-
|
|
668
|
-
const
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
799
|
+
async alarm(): Promise<void> {
|
|
800
|
+
const sockets = this.#state.getWebSockets();
|
|
801
|
+
const heartbeat = encodeHeartbeat(Date.now());
|
|
802
|
+
for (const ws of sockets) {
|
|
803
|
+
try {
|
|
804
|
+
ws.send(heartbeat);
|
|
805
|
+
} catch {
|
|
806
|
+
// A closing socket; its close callback cleans up.
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
if (sockets.length > 0) {
|
|
810
|
+
await this.#state.storage.setAlarm(
|
|
811
|
+
Date.now() + (this.#config.heartbeatIntervalMs ?? 30_000),
|
|
812
|
+
);
|
|
677
813
|
}
|
|
678
|
-
this.#sessions.set(ws, session);
|
|
679
|
-
return session;
|
|
680
814
|
}
|
|
681
815
|
|
|
682
816
|
/** Hibernation callback: an inbound frame. */
|
|
@@ -685,7 +819,7 @@ export class SyncularRealtimeHost<
|
|
|
685
819
|
message: ArrayBuffer | string,
|
|
686
820
|
): Promise<void> {
|
|
687
821
|
await this.#serializePartition(async () => {
|
|
688
|
-
const session =
|
|
822
|
+
const session = this.#sessions.get(ws);
|
|
689
823
|
if (session === undefined) return;
|
|
690
824
|
if (typeof message === 'string') {
|
|
691
825
|
session.handleMessage(message);
|
|
@@ -703,6 +837,7 @@ export class SyncularRealtimeHost<
|
|
|
703
837
|
/** Hibernation callback: the socket closed. */
|
|
704
838
|
async webSocketClose(ws: WebSocketLike): Promise<void> {
|
|
705
839
|
this.#closedSockets.add(ws);
|
|
840
|
+
await this.#rehydrateSockets();
|
|
706
841
|
const session = this.#sessions.get(ws);
|
|
707
842
|
if (session !== undefined) {
|
|
708
843
|
try {
|
|
@@ -715,7 +850,6 @@ export class SyncularRealtimeHost<
|
|
|
715
850
|
this.#sessions.delete(ws);
|
|
716
851
|
}
|
|
717
852
|
}
|
|
718
|
-
this.#swallowHello.delete(ws);
|
|
719
853
|
}
|
|
720
854
|
|
|
721
855
|
/** Hibernation callback: a socket error — treat as a close. */
|
|
@@ -775,16 +909,6 @@ function sendOverSocket(ws: WebSocketLike, data: string | Uint8Array): void {
|
|
|
775
909
|
ws.send(copy.buffer);
|
|
776
910
|
}
|
|
777
911
|
|
|
778
|
-
/** A `hello` control frame (text JSON) — used by the rehydration swallow. */
|
|
779
|
-
function isHello(data: string | Uint8Array): boolean {
|
|
780
|
-
if (typeof data !== 'string') return false;
|
|
781
|
-
try {
|
|
782
|
-
return (JSON.parse(data) as { event?: unknown }).event === 'hello';
|
|
783
|
-
} catch {
|
|
784
|
-
return false;
|
|
785
|
-
}
|
|
786
|
-
}
|
|
787
|
-
|
|
788
912
|
const REALTIME_ID_HEADER = {
|
|
789
913
|
partition: 'x-syncular-partition',
|
|
790
914
|
actorId: 'x-syncular-actor',
|