@syncular/server-workers 0.58.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/dist/realtime-do.js
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
|
*
|
|
@@ -72,15 +94,44 @@
|
|
|
72
94
|
* partition serialization may call `/__wake` after its own commit so sockets
|
|
73
95
|
* re-pull. See `durableObjectRealtimeNotifier` for that caller side.
|
|
74
96
|
*/
|
|
75
|
-
import { adapterSyncError, composeEvents, createRealtimeHub, D1ServerStorage, decodeRequestBody, errorBody, eraseScopeValue, handleRemoteOperation, handleSyncRequest, pruneCommitLog, RingBufferEvents, SSP2_CONTENT_TYPE, SyncError, SyncularAdmin, } from '@syncular/server';
|
|
97
|
+
import { adapterSyncError, composeEvents, createRealtimeHub, D1ServerStorage, decodeRequestBody, encodeHeartbeat, errorBody, eraseScopeValue, handleRemoteOperation, handleSyncRequest, pruneCommitLog, RingBufferEvents, SSP2_CONTENT_TYPE, SyncError, SyncularAdmin, } from '@syncular/server';
|
|
76
98
|
import { createSyncularAdminRoutes } from '@syncular/server-hono';
|
|
77
99
|
import { decodeMessage } from '@syncular/core';
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
100
|
+
/**
|
|
101
|
+
* Cloudflare's cap on a socket attachment's serialized size
|
|
102
|
+
* (https://developers.cloudflare.com/durable-objects/api/websockets/,
|
|
103
|
+
* `serializeAttachment`).
|
|
104
|
+
*/
|
|
105
|
+
const ATTACHMENT_LIMIT_BYTES = 16_384;
|
|
106
|
+
/** Room for the structured-clone framing around the attachment's one
|
|
107
|
+
* `Uint8Array`: format header, buffer and view tags, length varints. */
|
|
108
|
+
const ATTACHMENT_FRAMING_BYTES = 64;
|
|
109
|
+
/** `maxPresenceBytes` leaves no room in a socket attachment for an empty
|
|
110
|
+
* identity beside a full presence budget (§8.6.1). */
|
|
111
|
+
export class PresenceAttachmentError extends Error {
|
|
112
|
+
details;
|
|
113
|
+
code = 'realtime.presence_exceeds_attachment';
|
|
114
|
+
constructor(details) {
|
|
115
|
+
super('maxPresenceBytes does not fit a socket attachment (§8.6.1)');
|
|
116
|
+
this.details = details;
|
|
117
|
+
this.name = 'PresenceAttachmentError';
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
/** A hibernatable socket's attachment bytes (layout: see the module doc). */
|
|
121
|
+
function encodeAttachment(identity, presence) {
|
|
122
|
+
const utf8 = new TextEncoder();
|
|
123
|
+
const bytes = [
|
|
124
|
+
...utf8.encode(JSON.stringify([identity.partition, identity.actorId, identity.clientId])),
|
|
125
|
+
0x0a,
|
|
126
|
+
];
|
|
127
|
+
for (const [scopeKey, json] of presence) {
|
|
128
|
+
const key = utf8.encode(scopeKey);
|
|
129
|
+
let length = key.length;
|
|
130
|
+
for (; length >= 0x80; length >>>= 7)
|
|
131
|
+
bytes.push((length & 0x7f) | 0x80);
|
|
132
|
+
bytes.push(length, ...key, ...utf8.encode(json), 0x0a);
|
|
133
|
+
}
|
|
134
|
+
return Uint8Array.from(bytes);
|
|
84
135
|
}
|
|
85
136
|
/** Internal control-request paths on the DO stub (never client-facing). */
|
|
86
137
|
export const REALTIME_DO_WAKE_PATH = '/__syncular_realtime/wake';
|
|
@@ -117,6 +168,7 @@ function unsupportedEncoding(route) {
|
|
|
117
168
|
* }
|
|
118
169
|
* webSocketClose(ws: WebSocket) { return this.#impl.webSocketClose(ws); }
|
|
119
170
|
* webSocketError(ws: WebSocket) { return this.#impl.webSocketError(ws); }
|
|
171
|
+
* alarm() { return this.#impl.alarm(); }
|
|
120
172
|
* }
|
|
121
173
|
* ```
|
|
122
174
|
*
|
|
@@ -128,19 +180,17 @@ export class SyncularRealtimeHost {
|
|
|
128
180
|
#storage;
|
|
129
181
|
#config;
|
|
130
182
|
#hub;
|
|
183
|
+
/** Attachment bytes held back for framing and a full presence budget. */
|
|
184
|
+
#presenceReserve = 0;
|
|
131
185
|
#admin;
|
|
132
186
|
/** Live sessions, keyed by their socket. Empty after a hibernation wake;
|
|
133
|
-
* rehydrated for every socket before
|
|
134
|
-
*
|
|
187
|
+
* rehydrated for every socket before any entry point proceeds (see the
|
|
188
|
+
* class doc). */
|
|
135
189
|
#sessions = new Map();
|
|
136
|
-
/** Sockets whose rehydration `hello` must be swallowed (already greeted at
|
|
137
|
-
* the real upgrade — rehydration is transparent to the client). */
|
|
138
|
-
#swallowHello = new Set();
|
|
139
190
|
#closedSockets = new WeakSet();
|
|
140
|
-
/**
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
#rehydrated = false;
|
|
191
|
+
/** This instance's one rebuild of hibernated sockets' sessions. Every entry
|
|
192
|
+
* point awaits it, so no commit fans out to a partly rebuilt hub. */
|
|
193
|
+
#rehydration;
|
|
144
194
|
/** Explicit FIFO: Durable Object events may interleave at `await`. */
|
|
145
195
|
#partitionTail = Promise.resolve();
|
|
146
196
|
constructor(state, storage, config) {
|
|
@@ -174,6 +224,17 @@ export class SyncularRealtimeHost {
|
|
|
174
224
|
: ring,
|
|
175
225
|
};
|
|
176
226
|
const hub = createRealtimeHub(withRing);
|
|
227
|
+
const cap = hub.maxPresenceBytes;
|
|
228
|
+
this.#presenceReserve =
|
|
229
|
+
ATTACHMENT_FRAMING_BYTES + cap + Math.floor((2 * cap) / 3);
|
|
230
|
+
if (this.#presenceReserve +
|
|
231
|
+
encodeAttachment({ partition: '', actorId: '', clientId: '' }, new Map()).byteLength >
|
|
232
|
+
ATTACHMENT_LIMIT_BYTES) {
|
|
233
|
+
throw new PresenceAttachmentError({
|
|
234
|
+
maxPresenceBytes: cap,
|
|
235
|
+
attachmentLimitBytes: ATTACHMENT_LIMIT_BYTES,
|
|
236
|
+
});
|
|
237
|
+
}
|
|
177
238
|
this.#hub = hub;
|
|
178
239
|
this.#admin = SyncularAdmin.fromConfig({ ...withRing, realtime: hub }, { ring });
|
|
179
240
|
}
|
|
@@ -186,9 +247,17 @@ export class SyncularRealtimeHost {
|
|
|
186
247
|
* and accepts external-command wakes at `/__syncular_realtime/wake`.
|
|
187
248
|
*/
|
|
188
249
|
async fetch(request) {
|
|
250
|
+
await this.#rehydrateSockets();
|
|
189
251
|
const url = new URL(request.url);
|
|
190
252
|
if (url.pathname === SYNC_DO_REQUEST_PATH) {
|
|
191
|
-
|
|
253
|
+
let bytes;
|
|
254
|
+
try {
|
|
255
|
+
bytes = await decodeRequestBody(request, this.#getHub().limits.maxRequestBytes);
|
|
256
|
+
}
|
|
257
|
+
catch (error) {
|
|
258
|
+
const sync = this.#syncError(error, 'sync');
|
|
259
|
+
return Response.json(errorBody(sync), { status: sync.httpStatus });
|
|
260
|
+
}
|
|
192
261
|
if (bytes === undefined)
|
|
193
262
|
return unsupportedEncoding('sync');
|
|
194
263
|
// A round without PUSH_COMMIT frames writes only its own client
|
|
@@ -200,10 +269,8 @@ export class SyncularRealtimeHost {
|
|
|
200
269
|
pullOnly = decodeMessage(bytes).frames.every((frame) => frame.type !== 'PUSH_COMMIT');
|
|
201
270
|
}
|
|
202
271
|
catch { }
|
|
203
|
-
if (pullOnly)
|
|
204
|
-
await this.#rehydrateSockets();
|
|
272
|
+
if (pullOnly)
|
|
205
273
|
return this.#handleSync(request, bytes);
|
|
206
|
-
}
|
|
207
274
|
return this.#serializePartition(() => this.#handleSync(request, bytes));
|
|
208
275
|
}
|
|
209
276
|
if (url.pathname === OPERATIONS_DO_REQUEST_PATH) {
|
|
@@ -261,26 +328,54 @@ export class SyncularRealtimeHost {
|
|
|
261
328
|
}
|
|
262
329
|
/**
|
|
263
330
|
* After a hibernation wake the session map is empty while sockets stay
|
|
264
|
-
* open. Rebuild every socket's session
|
|
265
|
-
*
|
|
266
|
-
*
|
|
267
|
-
* its client reconnects and catches up (§8.4).
|
|
331
|
+
* open. Rebuild every socket's session once, so a commit fans out to sockets
|
|
332
|
+
* that stayed quiet through the hibernation. A socket whose session cannot
|
|
333
|
+
* be rebuilt is closed; its client reconnects and catches up (§8.4).
|
|
268
334
|
*/
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
335
|
+
#rehydrateSockets() {
|
|
336
|
+
this.#rehydration ??= (async () => {
|
|
337
|
+
const sockets = this.#state.getWebSockets().flatMap((ws) => {
|
|
338
|
+
const bytes = ws.deserializeAttachment();
|
|
339
|
+
if (!(bytes instanceof Uint8Array))
|
|
340
|
+
return [];
|
|
341
|
+
const utf8 = new TextDecoder();
|
|
342
|
+
let end = bytes.indexOf(0x0a);
|
|
343
|
+
const [partition, actorId, clientId] = JSON.parse(utf8.decode(bytes.subarray(0, end)));
|
|
344
|
+
const presence = new Map();
|
|
345
|
+
for (let at = end + 1; at < bytes.length; at = end + 1) {
|
|
346
|
+
let length = 0;
|
|
347
|
+
for (let shift = 0;; shift += 7) {
|
|
348
|
+
const byte = bytes[at++];
|
|
349
|
+
length |= (byte & 0x7f) << shift;
|
|
350
|
+
if (byte < 0x80)
|
|
351
|
+
break;
|
|
352
|
+
}
|
|
353
|
+
end = bytes.indexOf(0x0a, at + length);
|
|
354
|
+
presence.set(utf8.decode(bytes.subarray(at, at + length)), utf8.decode(bytes.subarray(at + length, end)));
|
|
355
|
+
}
|
|
356
|
+
return [{ ws, identity: { partition, actorId, clientId }, presence }];
|
|
357
|
+
});
|
|
358
|
+
if (sockets.length === 0)
|
|
359
|
+
return;
|
|
360
|
+
const results = await this.#getHub().restore(sockets.map(({ ws, identity, presence }) => ({
|
|
361
|
+
...this.#connectOptions(ws, identity),
|
|
362
|
+
presence,
|
|
363
|
+
})));
|
|
364
|
+
for (const [i, result] of results.entries()) {
|
|
365
|
+
const ws = sockets[i].ws;
|
|
366
|
+
if (result.status === 'rejected') {
|
|
367
|
+
ws.close(1011, 'realtime rehydration failed');
|
|
368
|
+
this.#syncError(result.reason, 'realtime');
|
|
369
|
+
}
|
|
370
|
+
else if (this.#closedSockets.has(ws)) {
|
|
371
|
+
result.value.close();
|
|
372
|
+
}
|
|
373
|
+
else {
|
|
374
|
+
this.#sessions.set(ws, result.value);
|
|
375
|
+
}
|
|
282
376
|
}
|
|
283
|
-
}
|
|
377
|
+
})();
|
|
378
|
+
return this.#rehydration;
|
|
284
379
|
}
|
|
285
380
|
/**
|
|
286
381
|
* Map a host failure to its catalog error. The reporters are read inside
|
|
@@ -309,7 +404,7 @@ export class SyncularRealtimeHost {
|
|
|
309
404
|
return Response.json(errorBody(error), { status: error.httpStatus });
|
|
310
405
|
}
|
|
311
406
|
try {
|
|
312
|
-
const bytes = await decodeRequestBody(request);
|
|
407
|
+
const bytes = await decodeRequestBody(request, this.#getHub().limits.maxRequestBytes);
|
|
313
408
|
if (bytes === undefined)
|
|
314
409
|
return unsupportedEncoding('operations');
|
|
315
410
|
const out = await handleRemoteOperation(bytes, this.#getHub().requestContextFor(identity), registry);
|
|
@@ -401,25 +496,33 @@ export class SyncularRealtimeHost {
|
|
|
401
496
|
const pair = newWebSocketPair();
|
|
402
497
|
const client = pair[0];
|
|
403
498
|
const server = pair[1];
|
|
404
|
-
// Hand the server socket to the runtime for hibernation
|
|
405
|
-
//
|
|
406
|
-
const attachment =
|
|
407
|
-
partition: identity.partition,
|
|
408
|
-
actorId: identity.actorId,
|
|
409
|
-
clientId: identity.clientId,
|
|
410
|
-
};
|
|
499
|
+
// Hand the server socket to the runtime for hibernation with the §8.1
|
|
500
|
+
// identity `restore` needs to rehydrate.
|
|
501
|
+
const attachment = encodeAttachment(identity, new Map());
|
|
411
502
|
server.serializeAttachment(attachment);
|
|
412
|
-
this.#upgrading.add(server);
|
|
413
503
|
this.#state.acceptWebSocket(server);
|
|
414
504
|
// Build the session now (first connect: hello IS delivered). Any failure
|
|
415
505
|
// closes the socket loudly — never a half-open realtime connection.
|
|
416
506
|
try {
|
|
417
|
-
const
|
|
507
|
+
const hub = this.#getHub();
|
|
508
|
+
// §8.6.1: the identity must fit the attachment beside a full presence
|
|
509
|
+
// budget, so no later presence change can overflow it.
|
|
510
|
+
if (this.#presenceReserve + attachment.byteLength >
|
|
511
|
+
ATTACHMENT_LIMIT_BYTES) {
|
|
512
|
+
throw new SyncError('sync.limit_exceeded', 'realtime identity does not fit the socket attachment (§8.6.1)', JSON.stringify({
|
|
513
|
+
limit: 'attachmentBytes',
|
|
514
|
+
max: ATTACHMENT_LIMIT_BYTES,
|
|
515
|
+
}));
|
|
516
|
+
}
|
|
517
|
+
const session = await hub.connect(this.#connectOptions(server, identity));
|
|
418
518
|
this.#sessions.set(server, session);
|
|
419
|
-
this.#
|
|
519
|
+
if ((await this.#state.storage.getAlarm()) === null) {
|
|
520
|
+
await this.#state.storage.setAlarm(Date.now() + (this.#config.heartbeatIntervalMs ?? 30_000));
|
|
521
|
+
}
|
|
420
522
|
}
|
|
421
523
|
catch (error) {
|
|
422
|
-
this.#
|
|
524
|
+
this.#sessions.get(server)?.close();
|
|
525
|
+
this.#sessions.delete(server);
|
|
423
526
|
server.close(1011, 'realtime connect failed');
|
|
424
527
|
const sync = this.#syncError(error, 'realtime');
|
|
425
528
|
return Response.json(errorBody(sync), { status: sync.httpStatus });
|
|
@@ -429,54 +532,42 @@ export class SyncularRealtimeHost {
|
|
|
429
532
|
const init = { status: 101, webSocket: client };
|
|
430
533
|
return new Response(null, init);
|
|
431
534
|
}
|
|
432
|
-
/**
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
clientId: attachment.clientId,
|
|
440
|
-
send: (data) => {
|
|
441
|
-
// Swallow exactly one hello on a rehydrated socket — the client was
|
|
442
|
-
// greeted at the real upgrade; rehydration is transparent (§8.1).
|
|
443
|
-
if (this.#swallowHello.has(ws)) {
|
|
444
|
-
this.#swallowHello.delete(ws);
|
|
445
|
-
if (isHello(data))
|
|
446
|
-
return;
|
|
447
|
-
}
|
|
448
|
-
sendOverSocket(ws, data);
|
|
449
|
-
},
|
|
535
|
+
/** The hub connect options of a hibernatable socket (§8.1). */
|
|
536
|
+
#connectOptions(ws, identity) {
|
|
537
|
+
return {
|
|
538
|
+
partition: identity.partition,
|
|
539
|
+
actorId: identity.actorId,
|
|
540
|
+
clientId: identity.clientId,
|
|
541
|
+
send: (data) => sendOverSocket(ws, data),
|
|
450
542
|
closeSocket: () => ws.close(1008, 'protocol violation (§8.7)'),
|
|
451
|
-
|
|
452
|
-
|
|
543
|
+
// §8.6.1: presence survives a hibernation in the socket's attachment.
|
|
544
|
+
onPresence: (presence) => ws.serializeAttachment(encodeAttachment(identity, presence)),
|
|
545
|
+
};
|
|
453
546
|
}
|
|
454
547
|
/**
|
|
455
|
-
*
|
|
456
|
-
*
|
|
548
|
+
* The Durable Object alarm: send a §8.5 heartbeat to every socket and re-arm
|
|
549
|
+
* while sockets remain. The frame goes straight to the hibernatable sockets,
|
|
550
|
+
* so a heartbeat rebuilds no session.
|
|
457
551
|
*/
|
|
458
|
-
async
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
const
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
this.#
|
|
471
|
-
return undefined;
|
|
552
|
+
async alarm() {
|
|
553
|
+
const sockets = this.#state.getWebSockets();
|
|
554
|
+
const heartbeat = encodeHeartbeat(Date.now());
|
|
555
|
+
for (const ws of sockets) {
|
|
556
|
+
try {
|
|
557
|
+
ws.send(heartbeat);
|
|
558
|
+
}
|
|
559
|
+
catch {
|
|
560
|
+
// A closing socket; its close callback cleans up.
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
if (sockets.length > 0) {
|
|
564
|
+
await this.#state.storage.setAlarm(Date.now() + (this.#config.heartbeatIntervalMs ?? 30_000));
|
|
472
565
|
}
|
|
473
|
-
this.#sessions.set(ws, session);
|
|
474
|
-
return session;
|
|
475
566
|
}
|
|
476
567
|
/** Hibernation callback: an inbound frame. */
|
|
477
568
|
async webSocketMessage(ws, message) {
|
|
478
569
|
await this.#serializePartition(async () => {
|
|
479
|
-
const session =
|
|
570
|
+
const session = this.#sessions.get(ws);
|
|
480
571
|
if (session === undefined)
|
|
481
572
|
return;
|
|
482
573
|
if (typeof message === 'string') {
|
|
@@ -495,6 +586,7 @@ export class SyncularRealtimeHost {
|
|
|
495
586
|
/** Hibernation callback: the socket closed. */
|
|
496
587
|
async webSocketClose(ws) {
|
|
497
588
|
this.#closedSockets.add(ws);
|
|
589
|
+
await this.#rehydrateSockets();
|
|
498
590
|
const session = this.#sessions.get(ws);
|
|
499
591
|
if (session !== undefined) {
|
|
500
592
|
try {
|
|
@@ -508,7 +600,6 @@ export class SyncularRealtimeHost {
|
|
|
508
600
|
this.#sessions.delete(ws);
|
|
509
601
|
}
|
|
510
602
|
}
|
|
511
|
-
this.#swallowHello.delete(ws);
|
|
512
603
|
}
|
|
513
604
|
/** Hibernation callback: a socket error — treat as a close. */
|
|
514
605
|
async webSocketError(ws) {
|
|
@@ -555,17 +646,6 @@ function sendOverSocket(ws, data) {
|
|
|
555
646
|
copy.set(data);
|
|
556
647
|
ws.send(copy.buffer);
|
|
557
648
|
}
|
|
558
|
-
/** A `hello` control frame (text JSON) — used by the rehydration swallow. */
|
|
559
|
-
function isHello(data) {
|
|
560
|
-
if (typeof data !== 'string')
|
|
561
|
-
return false;
|
|
562
|
-
try {
|
|
563
|
-
return JSON.parse(data).event === 'hello';
|
|
564
|
-
}
|
|
565
|
-
catch {
|
|
566
|
-
return false;
|
|
567
|
-
}
|
|
568
|
-
}
|
|
569
649
|
const REALTIME_ID_HEADER = {
|
|
570
650
|
partition: 'x-syncular-partition',
|
|
571
651
|
actorId: 'x-syncular-actor',
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@syncular/server-workers",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.59.0",
|
|
4
4
|
"description": "Cloudflare Workers adapter for the Syncular sync server",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "Benjamin Kniffler",
|
|
@@ -45,9 +45,9 @@
|
|
|
45
45
|
"!dist/**/*.test.d.ts"
|
|
46
46
|
],
|
|
47
47
|
"dependencies": {
|
|
48
|
-
"@syncular/core": "0.
|
|
49
|
-
"@syncular/server": "0.
|
|
50
|
-
"@syncular/server-hono": "0.
|
|
48
|
+
"@syncular/core": "0.59.0",
|
|
49
|
+
"@syncular/server": "0.59.0",
|
|
50
|
+
"@syncular/server-hono": "0.59.0"
|
|
51
51
|
},
|
|
52
52
|
"devDependencies": {
|
|
53
53
|
"@electric-sql/pglite": "^0.5.4",
|
package/src/index.ts
CHANGED
|
@@ -119,6 +119,14 @@ export interface WorkersRealtimeOptions {
|
|
|
119
119
|
| Promise<RealtimeUpgradeIdentity | undefined>;
|
|
120
120
|
/** The mount path segment for the upgrade route; default `/realtime`. */
|
|
121
121
|
readonly path?: string;
|
|
122
|
+
/**
|
|
123
|
+
* Origins a browser upgrade may come from, such as
|
|
124
|
+
* `['https://app.example.com']`. When set, an upgrade whose `Origin` header
|
|
125
|
+
* names another origin answers 403 before `authenticate` runs. Native
|
|
126
|
+
* clients send no `Origin` and pass. Set it whenever `authenticate` reads a
|
|
127
|
+
* cookie.
|
|
128
|
+
*/
|
|
129
|
+
readonly allowedOrigins?: readonly string[];
|
|
122
130
|
}
|
|
123
131
|
|
|
124
132
|
/** Resolve the per-env realtime wiring for one Worker invocation. */
|
|
@@ -393,6 +401,18 @@ async function handleRealtimeUpgrade(
|
|
|
393
401
|
if (request.headers.get('upgrade')?.toLowerCase() !== 'websocket') {
|
|
394
402
|
return new Response('expected a websocket upgrade', { status: 426 });
|
|
395
403
|
}
|
|
404
|
+
const origin = request.headers.get('origin');
|
|
405
|
+
if (
|
|
406
|
+
origin !== null &&
|
|
407
|
+
realtime.allowedOrigins !== undefined &&
|
|
408
|
+
!realtime.allowedOrigins.includes(origin)
|
|
409
|
+
) {
|
|
410
|
+
const error = new SyncError(
|
|
411
|
+
'sync.forbidden',
|
|
412
|
+
'realtime upgrade origin is not allowed',
|
|
413
|
+
);
|
|
414
|
+
return Response.json(errorBody(error), { status: error.httpStatus });
|
|
415
|
+
}
|
|
396
416
|
const identity = await realtime.authenticate(request);
|
|
397
417
|
if (identity === undefined) {
|
|
398
418
|
return new Response('unauthorized', { status: 401 });
|
package/src/r2-stores.ts
CHANGED
|
@@ -15,9 +15,11 @@
|
|
|
15
15
|
*
|
|
16
16
|
* There are no `presign*` methods here. A binding cannot mint a provider URL,
|
|
17
17
|
* so segments and blobs are served inline through `GET /segments/:id` and
|
|
18
|
-
* `GET /blobs/:id
|
|
19
|
-
* in the isolate
|
|
20
|
-
*
|
|
18
|
+
* `GET /blobs/:id`. Both routes stream the R2 object body through `open`
|
|
19
|
+
* without buffering it in the isolate; the blob route checks existence and
|
|
20
|
+
* authorizes the referencing rows before it opens the object. Configure no
|
|
21
|
+
* `signedUrls` / `blobSignedUrls` for a binding deployment, so the core
|
|
22
|
+
* serves inline.
|
|
21
23
|
*
|
|
22
24
|
* The binding surface is declared structurally below, so this package keeps
|
|
23
25
|
* taking no `@cloudflare/workers-types` dependency. Cloudflare's `R2Bucket`
|
|
@@ -47,6 +49,8 @@ export interface R2ObjectLike {
|
|
|
47
49
|
/** Unquoted object ETag (the CAS token; R2 also reports `httpEtag`). */
|
|
48
50
|
readonly etag: string;
|
|
49
51
|
readonly size: number;
|
|
52
|
+
/** Upload time; the blob sweep's age for an object without metadata. */
|
|
53
|
+
readonly uploaded: Date;
|
|
50
54
|
readonly customMetadata?: Readonly<Record<string, string>>;
|
|
51
55
|
}
|
|
52
56
|
|
|
@@ -130,6 +134,7 @@ function r2ObjectBucket(bucket: R2BucketLike): ObjectBucket {
|
|
|
130
134
|
return {
|
|
131
135
|
etag: object.etag,
|
|
132
136
|
size: object.size,
|
|
137
|
+
lastModifiedMs: object.uploaded.getTime(),
|
|
133
138
|
metadata: metadataOf(object),
|
|
134
139
|
};
|
|
135
140
|
},
|