@vite-hub/realtime 0.4.1 → 0.5.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.
- package/README.md +8 -4
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +1 -2
- package/dist/{bus-CKv8gQZf.js → bus-DJ3dOQAZ.js} +11 -22
- package/dist/{bus-protocol-wXkXW28q.d.ts → bus-protocol-juNrVJDF.d.ts} +0 -2
- package/dist/bus.d.ts +1 -3
- package/dist/bus.js +1 -2
- package/dist/client/browser.js +3 -3
- package/dist/client.d.ts +2 -4
- package/dist/client.js +15 -9
- package/dist/{conflict-DYC_qXzM.js → conflict-BqdKFrkE.js} +3 -5
- package/dist/{conflict-CmZizTYl.d.ts → conflict-C5KRv-J1.d.ts} +0 -2
- package/dist/{document-BfMW1zYU.d.ts → document-CbqgNO_0.d.ts} +2 -4
- package/dist/document-CfrQbB03.js +1736 -0
- package/dist/durability.d.ts +1 -3
- package/dist/durability.js +1 -6
- package/dist/{editor-BM5-vHqf.js → editor-DzhKM4Gt.js} +2 -5
- package/dist/{error-diagnostics-Cd-XWNf7.js → error-diagnostics-we8V1O-X.js} +1 -2
- package/dist/index.d.ts +3 -7
- package/dist/index.js +3 -3
- package/dist/internal/runtime/unavailable.d.ts +1 -3
- package/dist/internal/runtime/unavailable.js +1 -2
- package/dist/internal/server.d.ts +7 -0
- package/dist/internal/server.js +6 -0
- package/dist/{keepalive-B4ONG6AD.js → keepalive-BYkk6Ax8.js} +3 -5
- package/dist/{layout-DNaxppTZ.js → layout-BQwRLTH0.js} +1 -2
- package/dist/{layout-B7i6-FnH.d.ts → layout-BZtKNqiC.d.ts} +1 -3
- package/dist/log-NlQi6kow.js +157 -0
- package/dist/{object-BgPPDLDE.js → object-DfrneieE.js} +2 -4
- package/dist/{presence-B6rvkHqd.js → presence-DZ21pPKm.js} +3 -4
- package/dist/{request-C_bQc4NE.js → request-DM6xHTaU.js} +5 -10
- package/dist/{request-BwaohsJS.d.ts → request-PrMHOYFK.d.ts} +1 -3
- package/dist/server-CLdYV7Md.d.ts +126 -0
- package/dist/server-yQp02XNp.js +2599 -0
- package/dist/server.d.ts +4 -142
- package/dist/server.js +3 -2588
- package/dist/{types-Cvm0G3VJ.d.ts → types-oUyN-CJR.d.ts} +1 -27
- package/dist/vite.d.ts +4 -15
- package/dist/vite.js +64 -63
- package/dist/vue.d.ts +2 -7
- package/dist/vue.js +47 -40
- package/package.json +44 -39
- package/dist/document-U5rzg2vG.js +0 -2041
package/dist/server.js
CHANGED
|
@@ -1,2588 +1,3 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
import { n as realtimeDocumentLayout, t as readRealtimeStatus } from "./layout-DNaxppTZ.js";
|
|
5
|
-
import { t as createRealtimeIdentity } from "./presence-B6rvkHqd.js";
|
|
6
|
-
import { i as assertRealtimeCheckpoint, n as isRealtimeDocumentConflict, r as assertRealtimeAccess, t as RealtimeDocumentConflict } from "./conflict-DYC_qXzM.js";
|
|
7
|
-
import { r as realtimeMarkdownEditor } from "./editor-BM5-vHqf.js";
|
|
8
|
-
import { a as keepRealtimeFinalNewline, c as realtimeJsonEqual, d as writeRealtimeStatus, i as diffRealtimeYDoc, l as realtimeStatusFingerprint, n as containsRealtimeState, o as readRealtimeYDoc, r as createRealtimeYDoc, s as realtimeCodecReadsBack, t as checkRealtimeBody, u as writeRealtimeFields } from "./document-U5rzg2vG.js";
|
|
9
|
-
import { getViteHubErrorShape } from "@vite-hub/runtime";
|
|
10
|
-
import * as decoding from "lib0/decoding";
|
|
11
|
-
import * as encoding from "lib0/encoding";
|
|
12
|
-
import * as awarenessProtocol from "y-protocols/awareness";
|
|
13
|
-
import * as Y from "yjs";
|
|
14
|
-
import { Diagnostic } from "nostics";
|
|
15
|
-
import { assertAuthOrigin } from "@vite-hub/auth/internal/server";
|
|
16
|
-
import { isWorkspaceConflict, normalizeSafeWorkspacePath, resolveWorkspaceStoreTarget, useWorkspaceFiles } from "@vite-hub/workspace/files";
|
|
17
|
-
import { HTTPError, defineEventHandler, defineWebSocketHandler } from "nitro/h3";
|
|
18
|
-
import * as syncProtocol from "y-protocols/sync";
|
|
19
|
-
import { getStandardContext } from "@vite-hub/runtime/internal/h3";
|
|
20
|
-
//#region src/awareness.ts
|
|
21
|
-
const maxRoomAwarenessBytes = 8388608;
|
|
22
|
-
/**
|
|
23
|
-
* Records that `peer` owns `clients`. A client that another peer owns is a conflict, unless `transferable` accepts its
|
|
24
|
-
* owner, such as another server instance that the client left.
|
|
25
|
-
*/
|
|
26
|
-
function claimAwarenessClientIds(owners, peer, clients, transferable = () => false) {
|
|
27
|
-
for (const client of clients) {
|
|
28
|
-
const owner = owners.get(client);
|
|
29
|
-
if (owner && owner !== peer && !transferable(owner)) throw new AwarenessOwnershipConflict();
|
|
30
|
-
}
|
|
31
|
-
const ownedClients = new Set([...owners].filter(([, owner]) => owner === peer).map(([client]) => client));
|
|
32
|
-
for (const client of clients) ownedClients.add(client);
|
|
33
|
-
if (ownedClients.size > 1024) throw realtimeErrorDiagnostics.REALTIME_TOO_MANY_AWARENESS_CLIENTS();
|
|
34
|
-
const claimed = clients.filter((client) => !owners.has(client));
|
|
35
|
-
for (const client of clients) owners.set(client, peer);
|
|
36
|
-
return claimed;
|
|
37
|
-
}
|
|
38
|
-
var AwarenessOwnershipConflict = class AwarenessOwnershipConflict extends Diagnostic {
|
|
39
|
-
constructor() {
|
|
40
|
-
const { code, docs, fix, why } = realtimeErrorDiagnostics.REALTIME_AWARENESS_OWNERSHIP_CONFLICT();
|
|
41
|
-
super({
|
|
42
|
-
code,
|
|
43
|
-
docs,
|
|
44
|
-
fix,
|
|
45
|
-
why
|
|
46
|
-
}, AwarenessOwnershipConflict);
|
|
47
|
-
this.name = "AwarenessOwnershipConflict";
|
|
48
|
-
}
|
|
49
|
-
};
|
|
50
|
-
function bindAwarenessIdentity(update, identity) {
|
|
51
|
-
return awarenessProtocol.modifyAwarenessUpdate(update, (state) => {
|
|
52
|
-
if (state === null) return null;
|
|
53
|
-
if (!isRecord(state)) throw realtimeErrorDiagnostics.REALTIME_INVALID_AWARENESS();
|
|
54
|
-
return {
|
|
55
|
-
...state,
|
|
56
|
-
user: identity
|
|
57
|
-
};
|
|
58
|
-
});
|
|
59
|
-
}
|
|
60
|
-
function applyRealtimeAwarenessUpdate(awareness, update, origin, maxStateBytes = maxRoomAwarenessBytes) {
|
|
61
|
-
const candidateDocument = new Y.Doc();
|
|
62
|
-
const candidate = new awarenessProtocol.Awareness(candidateDocument);
|
|
63
|
-
candidate.setLocalState(null);
|
|
64
|
-
let stateBytes;
|
|
65
|
-
try {
|
|
66
|
-
const currentClients = [...awareness.getStates().keys()];
|
|
67
|
-
if (currentClients.length) awarenessProtocol.applyAwarenessUpdate(candidate, awarenessProtocol.encodeAwarenessUpdate(awareness, currentClients), origin);
|
|
68
|
-
awarenessProtocol.applyAwarenessUpdate(candidate, update, origin);
|
|
69
|
-
const candidateClients = [...candidate.getStates().keys()];
|
|
70
|
-
stateBytes = candidateClients.length ? awarenessProtocol.encodeAwarenessUpdate(candidate, candidateClients).byteLength : 0;
|
|
71
|
-
} finally {
|
|
72
|
-
candidate.destroy();
|
|
73
|
-
candidateDocument.destroy();
|
|
74
|
-
}
|
|
75
|
-
if (stateBytes > maxStateBytes) throw realtimeErrorDiagnostics.REALTIME_AWARENESS_TOO_LARGE();
|
|
76
|
-
awarenessProtocol.applyAwarenessUpdate(awareness, update, origin);
|
|
77
|
-
}
|
|
78
|
-
function compactRealtimeAwareness(awareness) {
|
|
79
|
-
const clients = [...awareness.getStates().keys()];
|
|
80
|
-
const update = clients.length ? awarenessProtocol.encodeAwarenessUpdate(awareness, clients) : void 0;
|
|
81
|
-
const compacted = new awarenessProtocol.Awareness(awareness.doc);
|
|
82
|
-
compacted.setLocalState(null);
|
|
83
|
-
if (update) awarenessProtocol.applyAwarenessUpdate(compacted, update, "compaction");
|
|
84
|
-
awareness.destroy();
|
|
85
|
-
return compacted;
|
|
86
|
-
}
|
|
87
|
-
/**
|
|
88
|
-
* Drops the entries of an awareness update that describe clients another peer owns. Stock y-websocket clients send
|
|
89
|
-
* every awareness change they see, other people's too, so an echo is normal and must not close the connection.
|
|
90
|
-
*/
|
|
91
|
-
function dropForeignAwareness(update, owners, peer, awareness) {
|
|
92
|
-
const decoder = decoding.createDecoder(update);
|
|
93
|
-
const length = decoding.readVarUint(decoder);
|
|
94
|
-
if (length > 1024) throw realtimeErrorDiagnostics.REALTIME_TOO_MANY_AWARENESS_CLIENTS({});
|
|
95
|
-
const kept = [];
|
|
96
|
-
for (let index = 0; index < length; index++) {
|
|
97
|
-
const client = decoding.readVarUint(decoder);
|
|
98
|
-
const clock = decoding.readVarUint(decoder);
|
|
99
|
-
const state = decoding.readVarString(decoder);
|
|
100
|
-
const owner = owners.get(client);
|
|
101
|
-
if (owner === peer || !owner && state.trim() !== "null" && clock > (awareness.meta.get(client)?.clock ?? -1)) kept.push([
|
|
102
|
-
client,
|
|
103
|
-
clock,
|
|
104
|
-
state
|
|
105
|
-
]);
|
|
106
|
-
}
|
|
107
|
-
if (kept.length === length) return update;
|
|
108
|
-
const encoder = encoding.createEncoder();
|
|
109
|
-
encoding.writeVarUint(encoder, kept.length);
|
|
110
|
-
for (const [client, clock, state] of kept) {
|
|
111
|
-
encoding.writeVarUint(encoder, client);
|
|
112
|
-
encoding.writeVarUint(encoder, clock);
|
|
113
|
-
encoding.writeVarString(encoder, state);
|
|
114
|
-
}
|
|
115
|
-
return encoding.toUint8Array(encoder);
|
|
116
|
-
}
|
|
117
|
-
/**
|
|
118
|
-
* Owns peer claims and commits them only after identity binding and quota checks succeed. With several server
|
|
119
|
-
* instances, an object that stands for another instance owns the clients of that instance's peers: `apply()` with
|
|
120
|
-
* `remote: true` records them. Ownership handoff is explicit through `claim()`, independent of awareness clocks.
|
|
121
|
-
* Awareness payloads never transfer an existing claim or claim a client from a null echo.
|
|
122
|
-
*/
|
|
123
|
-
function createRealtimeAwarenessOwners(options = {}) {
|
|
124
|
-
const owners = /* @__PURE__ */ new Map();
|
|
125
|
-
const peerClients = /* @__PURE__ */ new WeakMap();
|
|
126
|
-
const remoteOwners = /* @__PURE__ */ new WeakSet();
|
|
127
|
-
const transferable = (owner) => remoteOwners.has(owner);
|
|
128
|
-
function disown(client, owner) {
|
|
129
|
-
owners.delete(client);
|
|
130
|
-
peerClients.get(owner)?.delete(client);
|
|
131
|
-
}
|
|
132
|
-
return {
|
|
133
|
-
/** A WebSocket declares its own client id at connection time; the bus relays that claim to retire the old socket. */
|
|
134
|
-
claim(awareness, peer, client, identity, remote = false) {
|
|
135
|
-
const state = awareness.getStates().get(client);
|
|
136
|
-
if (!remote && identity && state && (!isRecord(state.user) || state.user.id !== identity.id)) return false;
|
|
137
|
-
if (remote) remoteOwners.add(peer);
|
|
138
|
-
const owner = owners.get(client);
|
|
139
|
-
if (owner && owner !== peer) disown(client, owner);
|
|
140
|
-
claimAwarenessClientIds(owners, peer, [client]);
|
|
141
|
-
const clients = peerClients.get(peer) || /* @__PURE__ */ new Set();
|
|
142
|
-
clients.add(client);
|
|
143
|
-
peerClients.set(peer, clients);
|
|
144
|
-
return true;
|
|
145
|
-
},
|
|
146
|
-
apply(awareness, peer, input, identity, remote = false) {
|
|
147
|
-
if (remote) remoteOwners.add(peer);
|
|
148
|
-
const update = dropForeignAwareness(input, owners, peer, awareness);
|
|
149
|
-
const clients = readAwarenessClientIds(update);
|
|
150
|
-
if (!clients.length) return [];
|
|
151
|
-
const previous = new Map(clients.flatMap((client) => {
|
|
152
|
-
const owner = owners.get(client);
|
|
153
|
-
return owner && owner !== peer ? [[client, owner]] : [];
|
|
154
|
-
}));
|
|
155
|
-
const claimed = claimAwarenessClientIds(owners, peer, clients, transferable);
|
|
156
|
-
try {
|
|
157
|
-
applyRealtimeAwarenessUpdate(awareness, identity ? bindAwarenessIdentity(update, identity) : update, peer, options.maxStateBytes);
|
|
158
|
-
for (const [client, owner] of previous) peerClients.get(owner)?.delete(client);
|
|
159
|
-
const ownedClients = peerClients.get(peer) || /* @__PURE__ */ new Set();
|
|
160
|
-
for (const client of clients) ownedClients.add(client);
|
|
161
|
-
peerClients.set(peer, ownedClients);
|
|
162
|
-
return clients;
|
|
163
|
-
} catch (error) {
|
|
164
|
-
for (const client of claimed) if (owners.get(client) === peer) owners.delete(client);
|
|
165
|
-
for (const [client, owner] of previous) owners.set(client, owner);
|
|
166
|
-
throw error;
|
|
167
|
-
}
|
|
168
|
-
},
|
|
169
|
-
/** Whether a peer of this instance owns the client. */
|
|
170
|
-
ownsLocally(client) {
|
|
171
|
-
const owner = owners.get(client);
|
|
172
|
-
return !!owner && !remoteOwners.has(owner);
|
|
173
|
-
},
|
|
174
|
-
release(peer) {
|
|
175
|
-
const clients = [...peerClients.get(peer) || []];
|
|
176
|
-
peerClients.delete(peer);
|
|
177
|
-
for (const client of clients) if (owners.get(client) === peer) owners.delete(client);
|
|
178
|
-
return clients;
|
|
179
|
-
},
|
|
180
|
-
/** Forgets the clients that another instance owned, after their state was removed. */
|
|
181
|
-
releaseRemote(clients) {
|
|
182
|
-
for (const client of clients) {
|
|
183
|
-
const owner = owners.get(client);
|
|
184
|
-
if (owner && remoteOwners.has(owner)) disown(client, owner);
|
|
185
|
-
}
|
|
186
|
-
}
|
|
187
|
-
};
|
|
188
|
-
}
|
|
189
|
-
//#endregion
|
|
190
|
-
//#region src/transport.ts
|
|
191
|
-
const maxRequestStateBytes = 8388608;
|
|
192
|
-
const arrayBufferByteLengthGetter = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get;
|
|
193
|
-
const typedArrayByteLengthGetter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), "byteLength").get;
|
|
194
|
-
const typedArrayLengthGetter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), "length").get;
|
|
195
|
-
const typedArrayBufferGetter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), "buffer").get;
|
|
196
|
-
const typedArrayByteOffsetGetter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), "byteOffset").get;
|
|
197
|
-
function normalizeRealtimeStateChunk(value) {
|
|
198
|
-
if (ArrayBuffer.isView(value)) try {
|
|
199
|
-
let prototype = Object.getPrototypeOf(value);
|
|
200
|
-
let bytesPerElement;
|
|
201
|
-
while (prototype) {
|
|
202
|
-
const descriptor = Object.getOwnPropertyDescriptor(prototype, "BYTES_PER_ELEMENT");
|
|
203
|
-
if (descriptor && "value" in descriptor) bytesPerElement = descriptor.value;
|
|
204
|
-
prototype = Object.getPrototypeOf(prototype);
|
|
205
|
-
}
|
|
206
|
-
if (bytesPerElement !== 1) return void 0;
|
|
207
|
-
const byteLength = Reflect.apply(typedArrayByteLengthGetter, value, []);
|
|
208
|
-
if (byteLength !== Reflect.apply(typedArrayLengthGetter, value, [])) return void 0;
|
|
209
|
-
const buffer = Reflect.apply(typedArrayBufferGetter, value, []);
|
|
210
|
-
const byteOffset = Reflect.apply(typedArrayByteOffsetGetter, value, []);
|
|
211
|
-
return new Uint8Array(buffer, byteOffset, byteLength);
|
|
212
|
-
} catch {
|
|
213
|
-
return;
|
|
214
|
-
}
|
|
215
|
-
try {
|
|
216
|
-
Reflect.apply(arrayBufferByteLengthGetter, value, []);
|
|
217
|
-
return new Uint8Array(value);
|
|
218
|
-
} catch {
|
|
219
|
-
return;
|
|
220
|
-
}
|
|
221
|
-
}
|
|
222
|
-
async function readRealtimeRequestState(request, maxBytes = maxRequestStateBytes) {
|
|
223
|
-
if (Number(request.headers.get("content-length") || 0) > maxBytes) throw new HTTPError({
|
|
224
|
-
status: 413,
|
|
225
|
-
message: "Realtime request state exceeds 8 MiB."
|
|
226
|
-
});
|
|
227
|
-
if (!request.body) return /* @__PURE__ */ new Uint8Array();
|
|
228
|
-
const reader = request.body.getReader();
|
|
229
|
-
const chunks = [];
|
|
230
|
-
let byteLength = 0;
|
|
231
|
-
try {
|
|
232
|
-
while (true) {
|
|
233
|
-
const { done, value } = await reader.read();
|
|
234
|
-
if (done) break;
|
|
235
|
-
const chunk = normalizeRealtimeStateChunk(value);
|
|
236
|
-
if (!chunk) {
|
|
237
|
-
reader.cancel().catch(() => {});
|
|
238
|
-
throw new HTTPError({
|
|
239
|
-
status: 400,
|
|
240
|
-
message: "Realtime request body contains invalid bytes."
|
|
241
|
-
});
|
|
242
|
-
}
|
|
243
|
-
byteLength += chunk.byteLength;
|
|
244
|
-
if (byteLength > maxBytes) {
|
|
245
|
-
reader.cancel().catch(() => {});
|
|
246
|
-
throw new HTTPError({
|
|
247
|
-
status: 413,
|
|
248
|
-
message: "Realtime request state exceeds 8 MiB."
|
|
249
|
-
});
|
|
250
|
-
}
|
|
251
|
-
chunks.push(chunk);
|
|
252
|
-
}
|
|
253
|
-
} finally {
|
|
254
|
-
reader.releaseLock();
|
|
255
|
-
}
|
|
256
|
-
const state = new Uint8Array(byteLength);
|
|
257
|
-
let offset = 0;
|
|
258
|
-
for (const chunk of chunks) {
|
|
259
|
-
state.set(chunk, offset);
|
|
260
|
-
offset += chunk.byteLength;
|
|
261
|
-
}
|
|
262
|
-
return state;
|
|
263
|
-
}
|
|
264
|
-
//#endregion
|
|
265
|
-
//#region src/workspace-document.ts
|
|
266
|
-
async function readRealtimeWorkspaceDocument(readable, writable, documentId) {
|
|
267
|
-
const stat = async () => {
|
|
268
|
-
try {
|
|
269
|
-
return await writable.fs.stat(documentId);
|
|
270
|
-
} catch (error) {
|
|
271
|
-
const shape = getViteHubErrorShape(error);
|
|
272
|
-
if (shape?.code === "WORKSPACE_NOT_FOUND" && shape.details?.name === void 0) return void 0;
|
|
273
|
-
throw error;
|
|
274
|
-
}
|
|
275
|
-
};
|
|
276
|
-
for (let attempt = 0; attempt < 3; attempt++) {
|
|
277
|
-
const before = await stat();
|
|
278
|
-
let markdown = "";
|
|
279
|
-
const source = await readable.fs.exists(documentId) ? readable.fs : before ? writable.fs : void 0;
|
|
280
|
-
if (source) try {
|
|
281
|
-
markdown = await source.readFile(documentId, { encoding: "utf8" });
|
|
282
|
-
} catch (error) {
|
|
283
|
-
if (!await stat()) continue;
|
|
284
|
-
throw error;
|
|
285
|
-
}
|
|
286
|
-
const after = await stat();
|
|
287
|
-
if (before?.digest === after?.digest) return {
|
|
288
|
-
baselineDigest: after?.digest,
|
|
289
|
-
markdown
|
|
290
|
-
};
|
|
291
|
-
}
|
|
292
|
-
throw new HTTPError({
|
|
293
|
-
status: 409,
|
|
294
|
-
message: "The Workspace document changed while opening its realtime room."
|
|
295
|
-
});
|
|
296
|
-
}
|
|
297
|
-
const checkpointQueues = /* @__PURE__ */ new Map();
|
|
298
|
-
async function serializeWorkspace(workspaceName, operation) {
|
|
299
|
-
const previous = checkpointQueues.get(workspaceName) || Promise.resolve();
|
|
300
|
-
let release;
|
|
301
|
-
const current = new Promise((resolve) => {
|
|
302
|
-
release = resolve;
|
|
303
|
-
});
|
|
304
|
-
checkpointQueues.set(workspaceName, current);
|
|
305
|
-
await previous;
|
|
306
|
-
try {
|
|
307
|
-
return await operation();
|
|
308
|
-
} finally {
|
|
309
|
-
release();
|
|
310
|
-
if (checkpointQueues.get(workspaceName) === current) checkpointQueues.delete(workspaceName);
|
|
311
|
-
}
|
|
312
|
-
}
|
|
313
|
-
/**
|
|
314
|
-
* Stores each Realtime document as the Markdown file at its path in a Workspace working tree.
|
|
315
|
-
* `history.checkpoint()` commits the working tree to Workspace history with the Store's author by default.
|
|
316
|
-
* `document: { workspace }` in a Realtime Definition uses this adapter.
|
|
317
|
-
*/
|
|
318
|
-
function workspaceDocument(workspaceName, checkpointAuthor) {
|
|
319
|
-
return {
|
|
320
|
-
kind: "workspace",
|
|
321
|
-
workspace: workspaceName,
|
|
322
|
-
async load({ documentId }) {
|
|
323
|
-
const current = await readRealtimeWorkspaceDocument(useWorkspaceFiles(workspaceName), useWorkspaceFiles(workspaceName, { mode: "write" }), documentId);
|
|
324
|
-
return {
|
|
325
|
-
body: current.markdown,
|
|
326
|
-
digest: current.baselineDigest ?? null
|
|
327
|
-
};
|
|
328
|
-
},
|
|
329
|
-
async save(context, document, { ifDigest }) {
|
|
330
|
-
const { documentId } = context;
|
|
331
|
-
const workspace = useWorkspaceFiles(workspaceName, { mode: "write" });
|
|
332
|
-
if (!(await workspace.capabilities()).conditionalWrites) throw new HTTPError({
|
|
333
|
-
status: 501,
|
|
334
|
-
message: "Realtime saves require a Workspace Store with conditional writes."
|
|
335
|
-
});
|
|
336
|
-
if (context.authority !== "memory" && (await resolveWorkspaceStoreTarget(workspace))?.provider === "memory") throw new HTTPError({
|
|
337
|
-
status: 501,
|
|
338
|
-
message: "Durable and shared realtime rooms require a durable Workspace Store."
|
|
339
|
-
});
|
|
340
|
-
try {
|
|
341
|
-
const current = ifDigest ? await workspace.fs.stat(documentId).catch((error) => {
|
|
342
|
-
const shape = getViteHubErrorShape(error);
|
|
343
|
-
if (shape?.code === "WORKSPACE_NOT_FOUND" && shape.message.startsWith("[vitehub] Workspace path does not exist:")) throw new RealtimeDocumentConflict("The document changed in Workspace after this realtime room loaded it.");
|
|
344
|
-
throw error;
|
|
345
|
-
}) : void 0;
|
|
346
|
-
await workspace.fs.writeFile(documentId, document.body, {
|
|
347
|
-
ifDigest,
|
|
348
|
-
mediaType: current?.mediaType,
|
|
349
|
-
metadata: current?.metadata,
|
|
350
|
-
preservePath: true
|
|
351
|
-
});
|
|
352
|
-
} catch (error) {
|
|
353
|
-
if (isWorkspaceConflict(error)) throw new RealtimeDocumentConflict("The document changed in Workspace after this realtime room loaded it.");
|
|
354
|
-
throw error;
|
|
355
|
-
}
|
|
356
|
-
const written = await readRealtimeWorkspaceDocument(workspace, workspace, documentId);
|
|
357
|
-
if (!written.baselineDigest) throw realtimeErrorDiagnostics.REALTIME_MISSING_DIGEST({ operation: "save" });
|
|
358
|
-
return {
|
|
359
|
-
digest: written.baselineDigest,
|
|
360
|
-
stored: { body: written.markdown }
|
|
361
|
-
};
|
|
362
|
-
},
|
|
363
|
-
async checkpoint({ documentId }, { digest, message, user }) {
|
|
364
|
-
return await serializeWorkspace(workspaceName, async () => {
|
|
365
|
-
const workspace = useWorkspaceFiles(workspaceName, { mode: "write" });
|
|
366
|
-
const author = user && checkpointAuthor ? await checkpointAuthor(user) : void 0;
|
|
367
|
-
const options = {
|
|
368
|
-
message: message || `docs: checkpoint ${documentId}`,
|
|
369
|
-
...author ? { author } : {}
|
|
370
|
-
};
|
|
371
|
-
let snapshot;
|
|
372
|
-
try {
|
|
373
|
-
try {
|
|
374
|
-
snapshot = await workspace.history.checkpoint(options);
|
|
375
|
-
} catch (error) {
|
|
376
|
-
if (!isWorkspaceConflict(error)) throw error;
|
|
377
|
-
await workspace.history.rebase({ takeRemote: [documentId] });
|
|
378
|
-
snapshot = await workspace.history.checkpoint(options);
|
|
379
|
-
}
|
|
380
|
-
} catch (error) {
|
|
381
|
-
if (isWorkspaceConflict(error)) throw new RealtimeDocumentConflict("The Workspace changed while checkpointing this realtime document.");
|
|
382
|
-
throw error;
|
|
383
|
-
}
|
|
384
|
-
if (snapshot.entries[documentId]?.digest !== digest) throw new RealtimeDocumentConflict("The Workspace document changed while creating its realtime checkpoint.");
|
|
385
|
-
return snapshot;
|
|
386
|
-
});
|
|
387
|
-
}
|
|
388
|
-
};
|
|
389
|
-
}
|
|
390
|
-
function isRealtimeWorkspaceDocument(adapter) {
|
|
391
|
-
return adapter.kind === "workspace" && "workspace" in adapter && typeof adapter.workspace === "string";
|
|
392
|
-
}
|
|
393
|
-
//#endregion
|
|
394
|
-
//#region src/cloudflare-sql.ts
|
|
395
|
-
function hasCloudflareSqlExecInternal(sql, allowOwnExec) {
|
|
396
|
-
if (sql === null || Object(sql) !== sql) return false;
|
|
397
|
-
try {
|
|
398
|
-
const ownExec = Object.getOwnPropertyDescriptor(sql, "exec");
|
|
399
|
-
if (ownExec) return allowOwnExec && "value" in ownExec && typeof ownExec.value === "function";
|
|
400
|
-
const prototype = Object.getPrototypeOf(sql);
|
|
401
|
-
if (!prototype) return false;
|
|
402
|
-
const findDescriptor = (key) => {
|
|
403
|
-
let current = prototype;
|
|
404
|
-
while (current && current !== Object.prototype) {
|
|
405
|
-
const descriptor = Object.getOwnPropertyDescriptor(current, key);
|
|
406
|
-
if (descriptor) return {
|
|
407
|
-
descriptor,
|
|
408
|
-
owner: current
|
|
409
|
-
};
|
|
410
|
-
current = Object.getPrototypeOf(current);
|
|
411
|
-
}
|
|
412
|
-
};
|
|
413
|
-
const constructorEntry = findDescriptor("constructor");
|
|
414
|
-
const execEntry = findDescriptor("exec");
|
|
415
|
-
const databaseSizeEntry = findDescriptor("databaseSize");
|
|
416
|
-
const constructor = constructorEntry?.descriptor.value;
|
|
417
|
-
const exec = execEntry?.descriptor.value;
|
|
418
|
-
const databaseSize = databaseSizeEntry?.descriptor.get;
|
|
419
|
-
if (!constructorEntry || !execEntry || !databaseSizeEntry || !databaseSize) return false;
|
|
420
|
-
if (typeof constructor !== "function" || typeof exec !== "function" || typeof databaseSize !== "function") return false;
|
|
421
|
-
if (constructor.prototype !== prototype) return false;
|
|
422
|
-
if (constructor === Map || constructor === Set || constructor === ArrayBuffer || constructor === DataView || constructor === Uint8Array) return false;
|
|
423
|
-
if (typeof URLSearchParams === "function" && constructor === URLSearchParams) return false;
|
|
424
|
-
if (typeof SharedArrayBuffer === "function" && constructor === SharedArrayBuffer) return false;
|
|
425
|
-
if (!/^function(?:\s+[\w$]+)*\s*\(\s*\)\s*\{\s*\[native\s+code\]\s*\}$/.test(Function.prototype.toString.call(databaseSize))) return false;
|
|
426
|
-
if (!/^(?:|databaseSize|get databaseSize|get size)$/i.test(databaseSize.name)) return false;
|
|
427
|
-
const hasFiniteDatabaseSize = (createReceiver) => {
|
|
428
|
-
try {
|
|
429
|
-
return Number.isFinite(Reflect.apply(databaseSize, createReceiver(), []));
|
|
430
|
-
} catch {
|
|
431
|
-
return false;
|
|
432
|
-
}
|
|
433
|
-
};
|
|
434
|
-
if (hasFiniteDatabaseSize(() => /* @__PURE__ */ new Map())) return false;
|
|
435
|
-
if (hasFiniteDatabaseSize(() => /* @__PURE__ */ new Set())) return false;
|
|
436
|
-
if (typeof URLSearchParams === "function" && hasFiniteDatabaseSize(() => new URLSearchParams())) return false;
|
|
437
|
-
if (hasFiniteDatabaseSize(() => /* @__PURE__ */ new ArrayBuffer(0))) return false;
|
|
438
|
-
if (hasFiniteDatabaseSize(() => /* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(0)))) return false;
|
|
439
|
-
if (hasFiniteDatabaseSize(() => /* @__PURE__ */ new Uint8Array(0))) return false;
|
|
440
|
-
if (typeof SharedArrayBuffer === "function" && hasFiniteDatabaseSize(() => new SharedArrayBuffer(0))) return false;
|
|
441
|
-
try {
|
|
442
|
-
Reflect.apply(databaseSize, Object.create(prototype), []);
|
|
443
|
-
return false;
|
|
444
|
-
} catch {
|
|
445
|
-
return Number.isFinite(Reflect.apply(databaseSize, sql, []));
|
|
446
|
-
}
|
|
447
|
-
} catch {
|
|
448
|
-
return false;
|
|
449
|
-
}
|
|
450
|
-
}
|
|
451
|
-
/** Accept only the branded workerd SqlStorage receiver, never explicit adapters. */
|
|
452
|
-
function hasNativeCloudflareSql(sql) {
|
|
453
|
-
return hasCloudflareSqlExecInternal(sql, false);
|
|
454
|
-
}
|
|
455
|
-
//#endregion
|
|
456
|
-
//#region ../internal/src/runtime/request-origin.ts
|
|
457
|
-
function firstHeaderValue(headers, name) {
|
|
458
|
-
return headers.get(name)?.split(",", 1)[0]?.trim() || void 0;
|
|
459
|
-
}
|
|
460
|
-
/**
|
|
461
|
-
* The origin that the client used for `request`. A TLS-terminating proxy sends the client scheme in
|
|
462
|
-
* `X-Forwarded-Proto` and the client host in `X-Forwarded-Host`. Each proxy appends its value, so the first value wins.
|
|
463
|
-
* Without these headers, or with values that are not valid, the result is the origin of `request.url`.
|
|
464
|
-
*/
|
|
465
|
-
function forwardedRequestOrigin(request) {
|
|
466
|
-
const url = new URL(request.url);
|
|
467
|
-
const forwardedProtocol = firstHeaderValue(request.headers, "x-forwarded-proto")?.toLowerCase();
|
|
468
|
-
const protocol = forwardedProtocol === "http" || forwardedProtocol === "https" ? forwardedProtocol : url.protocol.slice(0, -1);
|
|
469
|
-
const host = firstHeaderValue(request.headers, "x-forwarded-host") ?? url.host;
|
|
470
|
-
if (/[\u0000-\u001F\s/\\?#@]/.test(host)) return url.origin;
|
|
471
|
-
try {
|
|
472
|
-
return new URL(`${protocol}://${host}`).origin;
|
|
473
|
-
} catch {
|
|
474
|
-
return url.origin;
|
|
475
|
-
}
|
|
476
|
-
}
|
|
477
|
-
//#endregion
|
|
478
|
-
//#region src/blob-document.ts
|
|
479
|
-
function errorCode(error) {
|
|
480
|
-
return error !== null && typeof error === "object" && "code" in error ? error.code : void 0;
|
|
481
|
-
}
|
|
482
|
-
async function digestOf(text) {
|
|
483
|
-
const bytes = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)));
|
|
484
|
-
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
485
|
-
}
|
|
486
|
-
/**
|
|
487
|
-
* Stores each Realtime document as one Blob file at `prefix + documentId`. Its digest is the SHA-256 of the
|
|
488
|
-
* body. `save()` reads the stored file and throws `RealtimeDocumentConflict` when its digest is not `ifDigest`. It
|
|
489
|
-
* writes only if the file still has the ETag that it read, so a writer outside the room that writes between that read
|
|
490
|
-
* and the save's write also makes the save throw `RealtimeDocumentConflict`, and keeps its file.
|
|
491
|
-
*/
|
|
492
|
-
function blobDocument(store, options = {}) {
|
|
493
|
-
const { contentType = "text/markdown; charset=utf-8", prefix = "" } = options;
|
|
494
|
-
const pathnameOf = (documentId) => (prefix + documentId).replaceAll("%", "%25");
|
|
495
|
-
const read = async (pathname) => {
|
|
496
|
-
const [error, file] = await store.get(pathname);
|
|
497
|
-
if (errorCode(error) === "BLOB_NOT_FOUND") return null;
|
|
498
|
-
if (error) throw error;
|
|
499
|
-
return file ? await file.text() : null;
|
|
500
|
-
};
|
|
501
|
-
return {
|
|
502
|
-
kind: "blob",
|
|
503
|
-
async load({ documentId }) {
|
|
504
|
-
const body = await read(pathnameOf(documentId));
|
|
505
|
-
return {
|
|
506
|
-
body: body ?? "",
|
|
507
|
-
digest: body === null ? null : await digestOf(body)
|
|
508
|
-
};
|
|
509
|
-
},
|
|
510
|
-
async save({ documentId }, { body }, { ifDigest }) {
|
|
511
|
-
const pathname = pathnameOf(documentId);
|
|
512
|
-
const [headError, object] = await store.head(pathname);
|
|
513
|
-
if (headError && errorCode(headError) !== "BLOB_NOT_FOUND") throw headError;
|
|
514
|
-
const stored = object ? await read(pathname) : null;
|
|
515
|
-
if ((stored === null ? null : await digestOf(stored)) !== ifDigest) throw new RealtimeDocumentConflict(stored === null ? "The Blob file of this document was deleted after the realtime room loaded it." : "The Blob file of this document changed after the realtime room loaded it.");
|
|
516
|
-
const etag = object?.httpEtag;
|
|
517
|
-
if (object && !etag) throw realtimeErrorDiagnostics.REALTIME_BLOB_ETAG_MISSING({ pathname });
|
|
518
|
-
const [error] = await store.put(pathname, body, etag ? {
|
|
519
|
-
contentType,
|
|
520
|
-
ifMatch: etag
|
|
521
|
-
} : {
|
|
522
|
-
contentType,
|
|
523
|
-
overwrite: false
|
|
524
|
-
});
|
|
525
|
-
if (errorCode(error) === "BLOB_CONFLICT") throw new RealtimeDocumentConflict("Another writer changed the Blob file of this document while the realtime room saved it.");
|
|
526
|
-
if (error) throw error;
|
|
527
|
-
return { digest: await digestOf(body) };
|
|
528
|
-
}
|
|
529
|
-
};
|
|
530
|
-
}
|
|
531
|
-
//#endregion
|
|
532
|
-
//#region src/server.ts
|
|
533
|
-
const maxMessageBytes = 1048576;
|
|
534
|
-
const maxRoomStateBytes = 8388608;
|
|
535
|
-
const maxMemoryRooms = 128;
|
|
536
|
-
const awarenessQueryIntervalMs = 1e4;
|
|
537
|
-
const awarenessUpdateIntervalMs = 50;
|
|
538
|
-
const workspaceChangeLimit = 100;
|
|
539
|
-
const workspaceChangeWindowMs = 1e3;
|
|
540
|
-
/**
|
|
541
|
-
* Document updates per connection: a burst of 40, refilled at 20 per second. Typing sends one update per keystroke, so
|
|
542
|
-
* fast typing fits. Updates past the budget wait, merged, until it refills (a held key repeats ~30 times a second); a
|
|
543
|
-
* peer that holds back more than one message's worth is closed rather than having updates dropped.
|
|
544
|
-
*/
|
|
545
|
-
const syncUpdateBurst = 40;
|
|
546
|
-
const syncUpdatesPerSecond = 20;
|
|
547
|
-
const durableUpdateCompactionInterval = 128;
|
|
548
|
-
const maxSaveRetryMs = 6e4;
|
|
549
|
-
const holdIntervalMs = 6e4;
|
|
550
|
-
const messageSync = 0;
|
|
551
|
-
const keepalivePing = new TextEncoder().encode(realtimeKeepalivePing);
|
|
552
|
-
/** Marks the request that `refreshRealtimeDocument()` sends to a Durable Object. The Worker strips it from client requests. */
|
|
553
|
-
const internalRefreshHeader = "x-vitehub-realtime-refresh";
|
|
554
|
-
const realtimePersistenceDefaults = Object.freeze({
|
|
555
|
-
debounce: 2e3,
|
|
556
|
-
maxWait: 1e4
|
|
557
|
-
});
|
|
558
|
-
/** Origin of updates that the server writes itself: seeds, stored-form merges, and status. */
|
|
559
|
-
const serverOrigin = Symbol("vitehub.realtime.server");
|
|
560
|
-
/** Origin of updates that another instance sent over the bus. */
|
|
561
|
-
const busOrigin = Symbol("vitehub.realtime.bus");
|
|
562
|
-
/** A Yjs update with no structs and no deletions. */
|
|
563
|
-
const emptyUpdateBytes = 2;
|
|
564
|
-
/** The epoch of rooms that hold no document: Workspace event rooms and the rooms of presence definitions. */
|
|
565
|
-
const eventsEpoch = "events";
|
|
566
|
-
/** The fields that the adapter loaded, without the ones it left undefined. */
|
|
567
|
-
function loadedFields(loaded) {
|
|
568
|
-
return Object.fromEntries(Object.entries(loaded.fields ?? {}).filter(([, value]) => value !== void 0));
|
|
569
|
-
}
|
|
570
|
-
/** True when the field map holds exactly these fields, including fields whose value is null. */
|
|
571
|
-
function holdsFields(map, fields) {
|
|
572
|
-
const keys = Object.keys(fields);
|
|
573
|
-
return map.size === keys.length && keys.every((key) => map.has(key) && realtimeJsonEqual(map.get(key), fields[key]));
|
|
574
|
-
}
|
|
575
|
-
const readOnlyDocumentMessage = "The editor cannot save this document without loss. The room is read-only.";
|
|
576
|
-
const readOnlyDocumentRejection = "This realtime document is read-only: the editor cannot save it without loss.";
|
|
577
|
-
const invalidDocumentMessage = "The room document does not fit the editor schema, so Realtime did not save it. Undo the last change or reload.";
|
|
578
|
-
const codecReadBackIssue = { message: "The editor cannot read back the Markdown that it saved. Some content can change when the document opens again." };
|
|
579
|
-
function encodeSyncUpdate(update) {
|
|
580
|
-
const encoder = encoding.createEncoder();
|
|
581
|
-
encoding.writeVarUint(encoder, messageSync);
|
|
582
|
-
syncProtocol.writeUpdate(encoder, update);
|
|
583
|
-
return encoding.toUint8Array(encoder);
|
|
584
|
-
}
|
|
585
|
-
function encodeSyncStep1(document) {
|
|
586
|
-
const encoder = encoding.createEncoder();
|
|
587
|
-
encoding.writeVarUint(encoder, messageSync);
|
|
588
|
-
syncProtocol.writeSyncStep1(encoder, document);
|
|
589
|
-
return encoding.toUint8Array(encoder);
|
|
590
|
-
}
|
|
591
|
-
function encodeAwarenessState(awareness, clients) {
|
|
592
|
-
return encodeAwareness(awarenessProtocol.encodeAwarenessUpdate(awareness, clients));
|
|
593
|
-
}
|
|
594
|
-
function encodeAwareness(update) {
|
|
595
|
-
const encoder = encoding.createEncoder();
|
|
596
|
-
encoding.writeVarUint(encoder, 1);
|
|
597
|
-
encoding.writeVarUint8Array(encoder, update);
|
|
598
|
-
return encoding.toUint8Array(encoder);
|
|
599
|
-
}
|
|
600
|
-
/**
|
|
601
|
-
* The clients that the awareness has a clock for. A client's first awareness update has clock 0, which Yjs does not
|
|
602
|
-
* apply, so the client has no clock yet and cannot be encoded.
|
|
603
|
-
*/
|
|
604
|
-
function knownAwarenessClients(awareness, clients) {
|
|
605
|
-
return clients.filter((client) => awareness.meta.has(client));
|
|
606
|
-
}
|
|
607
|
-
/** Whether a transaction changed only the server-written `status` map. */
|
|
608
|
-
function changesOnlyStatus(document, transaction) {
|
|
609
|
-
const status = document.getMap(realtimeDocumentLayout.status);
|
|
610
|
-
for (const type of transaction.changed.keys()) if (type !== status) return false;
|
|
611
|
-
return true;
|
|
612
|
-
}
|
|
613
|
-
/** A peer tried to write what it may not: a read-only connection, or the server-written status map. */
|
|
614
|
-
function isWriteRejected(error) {
|
|
615
|
-
return error instanceof Error && Reflect.get(error, "code") === "REALTIME_WRITE_REJECTED";
|
|
616
|
-
}
|
|
617
|
-
function applyRealtimeSyncMessage(data, document, origin, options = {}) {
|
|
618
|
-
const apply = (target) => {
|
|
619
|
-
const decoder = decoding.createDecoder(data);
|
|
620
|
-
decoding.readVarUint(decoder);
|
|
621
|
-
const encoder = encoding.createEncoder();
|
|
622
|
-
encoding.writeVarUint(encoder, messageSync);
|
|
623
|
-
syncProtocol.readSyncMessage(decoder, encoder, target, origin);
|
|
624
|
-
return encoding.length(encoder) > 1 ? encoding.toUint8Array(encoder) : void 0;
|
|
625
|
-
};
|
|
626
|
-
const messageDecoder = decoding.createDecoder(data);
|
|
627
|
-
decoding.readVarUint(messageDecoder);
|
|
628
|
-
if (decoding.readVarUint(messageDecoder) === 0) return apply(document);
|
|
629
|
-
const candidate = new Y.Doc();
|
|
630
|
-
try {
|
|
631
|
-
Y.applyUpdate(candidate, Y.encodeStateAsUpdate(document));
|
|
632
|
-
const before = Y.snapshot(candidate);
|
|
633
|
-
apply(candidate);
|
|
634
|
-
if (candidate.store.pendingStructs || candidate.store.pendingDs) throw realtimeErrorDiagnostics.REALTIME_WRITE_REJECTED({ problem: "missing-state" });
|
|
635
|
-
if (options.readOnly && !Y.equalSnapshots(before, Y.snapshot(candidate))) throw realtimeErrorDiagnostics.REALTIME_WRITE_REJECTED({
|
|
636
|
-
problem: "read-only",
|
|
637
|
-
...typeof options.readOnly === "string" ? { readOnly: options.readOnly } : {}
|
|
638
|
-
});
|
|
639
|
-
if (options.protectStatus !== false && realtimeStatusFingerprint(candidate) !== realtimeStatusFingerprint(document)) throw realtimeErrorDiagnostics.REALTIME_WRITE_REJECTED({ problem: "status" });
|
|
640
|
-
if (Y.encodeStateAsUpdate(candidate).byteLength > (options.maxStateBytes ?? maxRoomStateBytes)) throw realtimeErrorDiagnostics.REALTIME_DOCUMENT_TOO_LARGE();
|
|
641
|
-
} finally {
|
|
642
|
-
candidate.destroy();
|
|
643
|
-
}
|
|
644
|
-
return apply(document);
|
|
645
|
-
}
|
|
646
|
-
function assertRealtimeRoomStateQuota(document, maxStateBytes = maxRoomStateBytes) {
|
|
647
|
-
if (Y.encodeStateAsUpdate(document).byteLength > maxStateBytes) throw new HTTPError({
|
|
648
|
-
status: 413,
|
|
649
|
-
message: "Realtime document exceeds its 8 MiB room quota."
|
|
650
|
-
});
|
|
651
|
-
}
|
|
652
|
-
function realtimeRoomKey(definitionName, documentId, scope) {
|
|
653
|
-
return JSON.stringify(scope === void 0 ? [definitionName, documentId] : [
|
|
654
|
-
definitionName,
|
|
655
|
-
documentId,
|
|
656
|
-
scope
|
|
657
|
-
]);
|
|
658
|
-
}
|
|
659
|
-
/** The scope of a person's rooms in a Definition with `scope: "user"`, or `undefined` for shared rooms. */
|
|
660
|
-
function roomScope(definition, user) {
|
|
661
|
-
if (definition.document !== false || definition.scope !== "user") return void 0;
|
|
662
|
-
return user === null ? "anonymous" : `user:${user}`;
|
|
663
|
-
}
|
|
664
|
-
async function restoreRealtimeDocument(markdown, baselineDigest, stored) {
|
|
665
|
-
const update = storedUpdate(stored?.update_blob);
|
|
666
|
-
const storedDigest = typeof stored?.baseline_digest === "string" ? stored.baseline_digest : void 0;
|
|
667
|
-
if (!update || storedDigest !== baselineDigest) return await createRealtimeYDoc(realtimeMarkdownEditor, { body: markdown });
|
|
668
|
-
const document = new Y.Doc();
|
|
669
|
-
try {
|
|
670
|
-
Y.applyUpdate(document, update);
|
|
671
|
-
return document;
|
|
672
|
-
} catch (error) {
|
|
673
|
-
document.destroy();
|
|
674
|
-
throw error;
|
|
675
|
-
}
|
|
676
|
-
}
|
|
677
|
-
function storedUpdate(value) {
|
|
678
|
-
if (ArrayBuffer.isView(value)) try {
|
|
679
|
-
const typedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype);
|
|
680
|
-
const typedBuffer = Object.getOwnPropertyDescriptor(typedArrayPrototype, "buffer")?.get;
|
|
681
|
-
const typedOffset = Object.getOwnPropertyDescriptor(typedArrayPrototype, "byteOffset")?.get;
|
|
682
|
-
const typedLength = Object.getOwnPropertyDescriptor(typedArrayPrototype, "byteLength")?.get;
|
|
683
|
-
let buffer;
|
|
684
|
-
let byteOffset;
|
|
685
|
-
let byteLength;
|
|
686
|
-
try {
|
|
687
|
-
buffer = typedBuffer.call(value);
|
|
688
|
-
byteOffset = typedOffset.call(value);
|
|
689
|
-
byteLength = typedLength.call(value);
|
|
690
|
-
} catch {
|
|
691
|
-
const dataViewPrototype = DataView.prototype;
|
|
692
|
-
buffer = Object.getOwnPropertyDescriptor(dataViewPrototype, "buffer").get.call(value);
|
|
693
|
-
byteOffset = Object.getOwnPropertyDescriptor(dataViewPrototype, "byteOffset").get.call(value);
|
|
694
|
-
byteLength = Object.getOwnPropertyDescriptor(dataViewPrototype, "byteLength").get.call(value);
|
|
695
|
-
}
|
|
696
|
-
if (!buffer || byteOffset === void 0 || byteLength === void 0) return void 0;
|
|
697
|
-
return new Uint8Array(buffer, byteOffset, byteLength);
|
|
698
|
-
} catch {
|
|
699
|
-
return;
|
|
700
|
-
}
|
|
701
|
-
try {
|
|
702
|
-
if ((Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength")?.get)?.call(value) !== void 0) return new Uint8Array(value);
|
|
703
|
-
} catch {
|
|
704
|
-
return;
|
|
705
|
-
}
|
|
706
|
-
}
|
|
707
|
-
const resolvedDefinitions = /* @__PURE__ */ new WeakMap();
|
|
708
|
-
function isDocumentAdapter(document) {
|
|
709
|
-
return "load" in document && "save" in document;
|
|
710
|
-
}
|
|
711
|
-
function duration(value, fallback, name) {
|
|
712
|
-
if (value === void 0) return fallback;
|
|
713
|
-
if (typeof value !== "number" || !Number.isFinite(value) || value < 0) throw realtimeErrorDiagnostics.REALTIME_INVALID_PERSISTENCE({
|
|
714
|
-
name,
|
|
715
|
-
reason: "not-milliseconds"
|
|
716
|
-
});
|
|
717
|
-
return value;
|
|
718
|
-
}
|
|
719
|
-
/** Resolves the document adapter, editor codec, and persistence timing of a definition. */
|
|
720
|
-
function resolveRealtimeDefinition(definition) {
|
|
721
|
-
const cached = resolvedDefinitions.get(definition);
|
|
722
|
-
if (cached) return cached;
|
|
723
|
-
assertRealtimeCheckpoint(definition);
|
|
724
|
-
const document = definition.document;
|
|
725
|
-
const adapter = isDocumentAdapter(document) ? document : workspaceDocument(document.workspace, document.checkpointAuthor);
|
|
726
|
-
const persistence = definition.persistence === false ? false : {
|
|
727
|
-
debounce: duration(definition.persistence?.debounce, realtimePersistenceDefaults.debounce, "debounce"),
|
|
728
|
-
maxWait: duration(definition.persistence?.maxWait, realtimePersistenceDefaults.maxWait, "maxWait")
|
|
729
|
-
};
|
|
730
|
-
if (persistence && persistence.maxWait < persistence.debounce) throw realtimeErrorDiagnostics.REALTIME_INVALID_PERSISTENCE({
|
|
731
|
-
name: "maxWait",
|
|
732
|
-
reason: "below-debounce"
|
|
733
|
-
});
|
|
734
|
-
const configured = definition.editor ?? realtimeMarkdownEditor;
|
|
735
|
-
const resolved = {
|
|
736
|
-
adapter,
|
|
737
|
-
definition,
|
|
738
|
-
editor: configured instanceof Function ? configured : () => configured,
|
|
739
|
-
persistence
|
|
740
|
-
};
|
|
741
|
-
resolvedDefinitions.set(definition, resolved);
|
|
742
|
-
return resolved;
|
|
743
|
-
}
|
|
744
|
-
async function verifyDocument(editor, loaded) {
|
|
745
|
-
const result = await editor.verify?.(loaded.body, { fields: loaded.fields });
|
|
746
|
-
const finalNewline = loaded.body.endsWith("\n");
|
|
747
|
-
return {
|
|
748
|
-
clean: {
|
|
749
|
-
body: keepRealtimeFinalNewline(result?.canonical ?? loaded.body, finalNewline),
|
|
750
|
-
fields: loadedFields(loaded)
|
|
751
|
-
},
|
|
752
|
-
finalNewline,
|
|
753
|
-
issues: result?.issues ?? [],
|
|
754
|
-
readOnly: result?.writable === false
|
|
755
|
-
};
|
|
756
|
-
}
|
|
757
|
-
function guardStatus(guard) {
|
|
758
|
-
return {
|
|
759
|
-
error: guard.readOnly ? readOnlyDocumentMessage : null,
|
|
760
|
-
issues: guard.issues
|
|
761
|
-
};
|
|
762
|
-
}
|
|
763
|
-
function documentTables(sql) {
|
|
764
|
-
sql.exec("CREATE TABLE IF NOT EXISTS vitehub_realtime_documents (room_key TEXT PRIMARY KEY, epoch TEXT NOT NULL, digest TEXT, dirty INTEGER NOT NULL, update_blob BLOB NOT NULL, editor_version TEXT)");
|
|
765
|
-
try {
|
|
766
|
-
sql.exec("ALTER TABLE vitehub_realtime_documents ADD COLUMN editor_version TEXT");
|
|
767
|
-
} catch {}
|
|
768
|
-
sql.exec("CREATE TABLE IF NOT EXISTS vitehub_realtime_document_updates (sequence INTEGER PRIMARY KEY AUTOINCREMENT, room_key TEXT NOT NULL, update_blob BLOB NOT NULL, client_update INTEGER NOT NULL DEFAULT 1)");
|
|
769
|
-
try {
|
|
770
|
-
sql.exec("ALTER TABLE vitehub_realtime_document_updates ADD COLUMN client_update INTEGER NOT NULL DEFAULT 1");
|
|
771
|
-
return true;
|
|
772
|
-
} catch {
|
|
773
|
-
try {
|
|
774
|
-
sql.exec("SELECT client_update FROM vitehub_realtime_document_updates LIMIT 0").toArray();
|
|
775
|
-
return true;
|
|
776
|
-
} catch {
|
|
777
|
-
return false;
|
|
778
|
-
}
|
|
779
|
-
}
|
|
780
|
-
}
|
|
781
|
-
/** Copy the pre-adapter Durable Object journal before reading the new schema. */
|
|
782
|
-
function migrateLegacyDocument(sql, key, clientUpdateColumn) {
|
|
783
|
-
if (sql.exec("SELECT room_key FROM vitehub_realtime_documents WHERE room_key = ?", key).toArray().length) return;
|
|
784
|
-
let legacy;
|
|
785
|
-
try {
|
|
786
|
-
legacy = sql.exec("SELECT baseline_digest, update_blob FROM vitehub_realtime_rooms WHERE room_key = ?", key).toArray()[0];
|
|
787
|
-
} catch {}
|
|
788
|
-
if (!legacy) return;
|
|
789
|
-
let updates = [];
|
|
790
|
-
try {
|
|
791
|
-
updates = sql.exec("SELECT update_blob FROM vitehub_realtime_updates WHERE room_key = ? ORDER BY sequence", key).toArray();
|
|
792
|
-
} catch {}
|
|
793
|
-
const update = storedUpdate(legacy.update_blob);
|
|
794
|
-
if (!update) return;
|
|
795
|
-
sql.exec("INSERT INTO vitehub_realtime_documents (room_key, epoch, digest, dirty, update_blob) VALUES (?, ?, ?, ?, ?)", key, crypto.randomUUID(), text(legacy.baseline_digest) ?? null, updates.length ? 1 : 0, Uint8Array.from(update).buffer);
|
|
796
|
-
for (const row of updates) {
|
|
797
|
-
const legacyUpdate = storedUpdate(row.update_blob);
|
|
798
|
-
if (!legacyUpdate) continue;
|
|
799
|
-
const blob = Uint8Array.from(legacyUpdate).buffer;
|
|
800
|
-
if (clientUpdateColumn) try {
|
|
801
|
-
sql.exec("INSERT INTO vitehub_realtime_document_updates (room_key, update_blob, client_update) VALUES (?, ?, 1)", key, blob);
|
|
802
|
-
continue;
|
|
803
|
-
} catch {}
|
|
804
|
-
sql.exec("INSERT INTO vitehub_realtime_document_updates (room_key, update_blob) VALUES (?, ?)", key, blob);
|
|
805
|
-
}
|
|
806
|
-
}
|
|
807
|
-
function readStoredRoom(sql, key) {
|
|
808
|
-
try {
|
|
809
|
-
return sql.exec("SELECT epoch, digest, dirty, update_blob, editor_version FROM vitehub_realtime_documents WHERE room_key = ?", key).toArray()[0];
|
|
810
|
-
} catch {
|
|
811
|
-
return sql.exec("SELECT epoch, digest, dirty, update_blob FROM vitehub_realtime_documents WHERE room_key = ?", key).toArray()[0];
|
|
812
|
-
}
|
|
813
|
-
}
|
|
814
|
-
function parseRoomPath(url) {
|
|
815
|
-
const parsed = new URL(url);
|
|
816
|
-
const path = parsed.pathname;
|
|
817
|
-
const at = path.indexOf(routePrefix);
|
|
818
|
-
if (at === -1) throw new HTTPError({ status: 404 });
|
|
819
|
-
let parts;
|
|
820
|
-
try {
|
|
821
|
-
parts = path.slice(at + routePrefix.length).split("/").map(decodeURIComponent);
|
|
822
|
-
} catch {
|
|
823
|
-
throw new HTTPError({
|
|
824
|
-
status: 400,
|
|
825
|
-
message: "Realtime route components must be valid URL encoding."
|
|
826
|
-
});
|
|
827
|
-
}
|
|
828
|
-
const [definitionName, ...documentParts] = parts;
|
|
829
|
-
if (!definitionName || documentParts.length === 0 || documentParts.some((part) => !part)) throw new HTTPError({
|
|
830
|
-
status: 400,
|
|
831
|
-
message: "Realtime definition and document path are required."
|
|
832
|
-
});
|
|
833
|
-
const documentId = documentParts.join("/");
|
|
834
|
-
let safePath;
|
|
835
|
-
try {
|
|
836
|
-
safePath = normalizeSafeWorkspacePath(documentId);
|
|
837
|
-
} catch {}
|
|
838
|
-
if (safePath !== documentId) throw new HTTPError({
|
|
839
|
-
status: 400,
|
|
840
|
-
message: "Realtime document paths must be safe Workspace paths."
|
|
841
|
-
});
|
|
842
|
-
return {
|
|
843
|
-
definitionName,
|
|
844
|
-
documentId,
|
|
845
|
-
searchParams: parsed.searchParams,
|
|
846
|
-
workspaceEvents: parsed.searchParams.get("workspace") === "events"
|
|
847
|
-
};
|
|
848
|
-
}
|
|
849
|
-
function text(value) {
|
|
850
|
-
return typeof value === "string" && value ? value : void 0;
|
|
851
|
-
}
|
|
852
|
-
function toRealtimeUser(value) {
|
|
853
|
-
if (!value || !(value instanceof Object) || !("id" in value)) return null;
|
|
854
|
-
const id = text(value.id);
|
|
855
|
-
if (!id) return null;
|
|
856
|
-
const user = { id };
|
|
857
|
-
const name = "name" in value ? text(value.name) : void 0;
|
|
858
|
-
const email = "email" in value ? text(value.email) : void 0;
|
|
859
|
-
const image = "image" in value ? text(value.image) : void 0;
|
|
860
|
-
if (name) user.name = name;
|
|
861
|
-
if (email) user.email = email;
|
|
862
|
-
if (image) user.image = image;
|
|
863
|
-
return user;
|
|
864
|
-
}
|
|
865
|
-
async function identify(request, event, definitionName, definition) {
|
|
866
|
-
if (definition.authorize === true && !definition.identify) {
|
|
867
|
-
let auth;
|
|
868
|
-
try {
|
|
869
|
-
auth = await assertAuthOrigin(request, event);
|
|
870
|
-
} catch {
|
|
871
|
-
throw new HTTPError({ status: 403 });
|
|
872
|
-
}
|
|
873
|
-
const user = toRealtimeUser((await auth.api.getSession({ headers: request.headers }))?.user);
|
|
874
|
-
if (!user) throw new HTTPError({ status: 401 });
|
|
875
|
-
return user;
|
|
876
|
-
}
|
|
877
|
-
const origin = request.headers.get("origin");
|
|
878
|
-
const foreign = !!origin && origin !== forwardedRequestOrigin(request);
|
|
879
|
-
const readsCallbackSession = typeof definition.authorize === "function" && !definition.identify && !!origin && (!foreign || !definition.origins);
|
|
880
|
-
if (foreign && !readsCallbackSession && !await definition.origins?.({
|
|
881
|
-
definition: definitionName,
|
|
882
|
-
event,
|
|
883
|
-
origin,
|
|
884
|
-
request
|
|
885
|
-
})) throw new HTTPError({
|
|
886
|
-
status: 403,
|
|
887
|
-
message: "Realtime requests must come from the application origin."
|
|
888
|
-
});
|
|
889
|
-
if (definition.identify) {
|
|
890
|
-
const user = toRealtimeUser(await definition.identify({
|
|
891
|
-
definition: definitionName,
|
|
892
|
-
event,
|
|
893
|
-
request
|
|
894
|
-
}));
|
|
895
|
-
if (definition.authorize === true && !user) throw new HTTPError({ status: 401 });
|
|
896
|
-
return user;
|
|
897
|
-
}
|
|
898
|
-
if (!(typeof definition.authorize === "function" ? readsCallbackSession : definition.document === false && definition.scope === "user")) return null;
|
|
899
|
-
let auth;
|
|
900
|
-
try {
|
|
901
|
-
auth = await assertAuthOrigin(request, event);
|
|
902
|
-
} catch (error) {
|
|
903
|
-
if (!foreign && isMissingAuth(error)) return null;
|
|
904
|
-
throw new HTTPError({ status: 403 });
|
|
905
|
-
}
|
|
906
|
-
return toRealtimeUser((await auth.api.getSession({ headers: request.headers }))?.user);
|
|
907
|
-
}
|
|
908
|
-
/** The app has no Auth Definition (`AUTH_R0005`), so nobody is signed in. */
|
|
909
|
-
function isMissingAuth(error) {
|
|
910
|
-
return typeof error === "object" && error !== null && "code" in error && error.code === "AUTH_R0005";
|
|
911
|
-
}
|
|
912
|
-
async function allows(definition, context) {
|
|
913
|
-
if (definition.authorize === true) return true;
|
|
914
|
-
if (definition.authorize) return await definition.authorize(context) === true;
|
|
915
|
-
return definition.access === "public";
|
|
916
|
-
}
|
|
917
|
-
function errorMessage(error) {
|
|
918
|
-
if (error instanceof Error && error.message) return error.message;
|
|
919
|
-
return "The realtime document could not be saved.";
|
|
920
|
-
}
|
|
921
|
-
const localRefreshKey = Symbol.for("vitehub.realtime.local-refresh");
|
|
922
|
-
const refreshScope = globalThis;
|
|
923
|
-
function localRefreshers() {
|
|
924
|
-
refreshScope[localRefreshKey] ??= /* @__PURE__ */ new Set();
|
|
925
|
-
return refreshScope[localRefreshKey];
|
|
926
|
-
}
|
|
927
|
-
/**
|
|
928
|
-
* Tells the open room of a document that its stored copy changed outside the room, such as a save by an Agent or the
|
|
929
|
-
* CLI. A room without unsaved edits re-seeds at once and resets its clients. A room with unsaved edits finds the change
|
|
930
|
-
* at its next save, which also re-seeds it. A room that is not open loads the stored copy when it opens. Resolves
|
|
931
|
-
* whether a room re-seeded. It never throws: a failed refresh leaves the next save to find the change.
|
|
932
|
-
*/
|
|
933
|
-
async function refreshRealtimeDocument(definition, documentId, options = {}) {
|
|
934
|
-
const binding = options.durableObjects ?? workerDurableObjects();
|
|
935
|
-
if (binding) return await refreshDurableRoom(binding, definition, documentId);
|
|
936
|
-
let reseeded = false;
|
|
937
|
-
for (const reference of localRefreshers()) {
|
|
938
|
-
const refresh = reference.deref();
|
|
939
|
-
if (!refresh) {
|
|
940
|
-
localRefreshers().delete(reference);
|
|
941
|
-
continue;
|
|
942
|
-
}
|
|
943
|
-
try {
|
|
944
|
-
if (await refresh(definition, documentId)) reseeded = true;
|
|
945
|
-
} catch {}
|
|
946
|
-
}
|
|
947
|
-
return reseeded;
|
|
948
|
-
}
|
|
949
|
-
/**
|
|
950
|
-
* On Cloudflare the rooms belong to the Durable Object, even when it shares an isolate with the Worker that calls this.
|
|
951
|
-
* Only the Durable Object may refresh them: from the Worker's request, a room's sockets cannot receive the reset.
|
|
952
|
-
*/
|
|
953
|
-
async function refreshDurableRoom(binding, definition, documentId) {
|
|
954
|
-
try {
|
|
955
|
-
const room = documentId.split("/").map(encodeURIComponent).join("/");
|
|
956
|
-
const response = await binding.get(binding.idFromName(durableRoomsInstance)).fetch(new Request(`https://vitehub.internal${routePrefix}${encodeURIComponent(definition)}/${room}?document=refresh`, {
|
|
957
|
-
method: "POST",
|
|
958
|
-
headers: { [internalRefreshHeader]: "1" }
|
|
959
|
-
}));
|
|
960
|
-
const result = response.ok ? await response.json() : void 0;
|
|
961
|
-
return result instanceof Object && "reseeded" in result && result.reseeded === true;
|
|
962
|
-
} catch {
|
|
963
|
-
return false;
|
|
964
|
-
}
|
|
965
|
-
}
|
|
966
|
-
/**
|
|
967
|
-
* A rejected upgrade keeps its status, and carries crossws hooks that refuse the socket. Without hooks, crossws (and
|
|
968
|
-
* Nitro's adapters) still upgrade the request into a socket that never answers.
|
|
969
|
-
*/
|
|
970
|
-
function refuseUpgrade(request, status) {
|
|
971
|
-
const hooks = { upgrade: () => new Response(null, { status }) };
|
|
972
|
-
const target = request;
|
|
973
|
-
target[webSocketHooksKey] = hooks;
|
|
974
|
-
if (target.context) target.context[webSocketHooksKey] = hooks;
|
|
975
|
-
return Object.assign(new Response(null, { status }), { crossws: hooks });
|
|
976
|
-
}
|
|
977
|
-
const webSocketHooksKey = Symbol.for("crossws.hooks");
|
|
978
|
-
/** A request with no headers at all, like the stub that crossws restores a hibernated socket's peer with. Browsers always send some. */
|
|
979
|
-
function isBareRequest(request) {
|
|
980
|
-
return request.headers.keys().next().done === true;
|
|
981
|
-
}
|
|
982
|
-
function createRealtimeHandler(registry, options = {}) {
|
|
983
|
-
const inactiveMemoryRoomKeys = /* @__PURE__ */ new Set();
|
|
984
|
-
const memoryRoomKeys = /* @__PURE__ */ new Set();
|
|
985
|
-
const rooms = /* @__PURE__ */ new Map();
|
|
986
|
-
const peerAwarenessQueryAt = /* @__PURE__ */ new WeakMap();
|
|
987
|
-
const peerAwarenessUpdateAt = /* @__PURE__ */ new WeakMap();
|
|
988
|
-
const peerPendingAwareness = /* @__PURE__ */ new WeakMap();
|
|
989
|
-
const peerWorkspaceChanges = /* @__PURE__ */ new WeakMap();
|
|
990
|
-
const peerInitialSyncStep2 = /* @__PURE__ */ new WeakSet();
|
|
991
|
-
const peerSyncUpdates = /* @__PURE__ */ new WeakMap();
|
|
992
|
-
const peerHeldUpdates = /* @__PURE__ */ new WeakMap();
|
|
993
|
-
const terminalPeers = /* @__PURE__ */ new WeakSet();
|
|
994
|
-
function clearHeldUpdates(peer) {
|
|
995
|
-
const held = peerHeldUpdates.get(peer);
|
|
996
|
-
if (!held) return;
|
|
997
|
-
peerHeldUpdates.delete(peer);
|
|
998
|
-
clearTimeout(held.timer);
|
|
999
|
-
}
|
|
1000
|
-
let pendingBus;
|
|
1001
|
-
/** Rooms that finished opening, by key. */
|
|
1002
|
-
const openRooms = /* @__PURE__ */ new Map();
|
|
1003
|
-
/** One owner object per other instance, for the awareness clients of its peers. */
|
|
1004
|
-
const remoteOwners = /* @__PURE__ */ new Map();
|
|
1005
|
-
const repairRequestedAt = /* @__PURE__ */ new WeakMap();
|
|
1006
|
-
const syncing = /* @__PURE__ */ new WeakSet();
|
|
1007
|
-
/** The bus that shares rooms with other instances, connected and subscribed on first use. */
|
|
1008
|
-
function sharedBus() {
|
|
1009
|
-
if (!options.bus) return Promise.resolve(void 0);
|
|
1010
|
-
if (pendingBus) return pendingBus;
|
|
1011
|
-
const connect = options.bus;
|
|
1012
|
-
const pending = (async () => {
|
|
1013
|
-
const bus = await connect();
|
|
1014
|
-
if (!bus) return void 0;
|
|
1015
|
-
await bus.subscribe(receive, () => {
|
|
1016
|
-
for (const room of rooms.values()) room.then(requestSync, () => {});
|
|
1017
|
-
});
|
|
1018
|
-
bus.onClose(announceDeparture);
|
|
1019
|
-
const syncTimer = setInterval(() => {
|
|
1020
|
-
for (const room of openRooms.values()) if (room.peers.size || room.kind === "document" && room.dirty) requestSync(room);
|
|
1021
|
-
}, 1e4);
|
|
1022
|
-
syncTimer.unref?.();
|
|
1023
|
-
bus.onClose(async () => {
|
|
1024
|
-
clearInterval(syncTimer);
|
|
1025
|
-
});
|
|
1026
|
-
return bus;
|
|
1027
|
-
})();
|
|
1028
|
-
pendingBus = pending;
|
|
1029
|
-
pending.catch(() => {
|
|
1030
|
-
if (pendingBus === pending) pendingBus = void 0;
|
|
1031
|
-
});
|
|
1032
|
-
return pending;
|
|
1033
|
-
}
|
|
1034
|
-
function roomEpoch(room) {
|
|
1035
|
-
return room.kind === "document" ? room.epoch : eventsEpoch;
|
|
1036
|
-
}
|
|
1037
|
-
function publish(room, type, data) {
|
|
1038
|
-
room.bus?.publish({
|
|
1039
|
-
type,
|
|
1040
|
-
room: room.key,
|
|
1041
|
-
epoch: roomEpoch(room),
|
|
1042
|
-
data
|
|
1043
|
-
}).catch((error) => {
|
|
1044
|
-
console.error("[vitehub] Realtime could not send a room message to the other instances.", error);
|
|
1045
|
-
});
|
|
1046
|
-
}
|
|
1047
|
-
/** Asks the other instances for the document updates and the presence that this room lacks. */
|
|
1048
|
-
function requestSync(room) {
|
|
1049
|
-
if (!room.bus) return;
|
|
1050
|
-
if (room.kind !== "document") {
|
|
1051
|
-
publish(room, "sync", /* @__PURE__ */ new Uint8Array());
|
|
1052
|
-
return;
|
|
1053
|
-
}
|
|
1054
|
-
if (room.destroyed || syncing.has(room)) return;
|
|
1055
|
-
if (!room.peers.size && !room.dirty) {
|
|
1056
|
-
publish(room, "sync", Y.encodeStateVector(room.document));
|
|
1057
|
-
return;
|
|
1058
|
-
}
|
|
1059
|
-
syncing.add(room);
|
|
1060
|
-
enqueue(room, async () => {
|
|
1061
|
-
const record = await room.bus?.readRoom(room.key);
|
|
1062
|
-
if (room.destroyed) return;
|
|
1063
|
-
if (record && record.epoch !== room.epoch) await reseedRoom(room, "source-changed", void 0, false, true);
|
|
1064
|
-
if (!room.destroyed) publish(room, "sync", Y.encodeStateVector(room.document));
|
|
1065
|
-
}).catch((error) => {
|
|
1066
|
-
console.error("[vitehub] Realtime could not repair a shared room.", error);
|
|
1067
|
-
}).finally(() => syncing.delete(room));
|
|
1068
|
-
}
|
|
1069
|
-
/** Awareness clients of this instance's peers. */
|
|
1070
|
-
function localAwarenessClients(room) {
|
|
1071
|
-
return knownAwarenessClients(room.awareness, [...room.awareness.getStates().keys()].filter((client) => room.awarenessOwners.ownsLocally(client)));
|
|
1072
|
-
}
|
|
1073
|
-
/** Tells the other instances that the peers of this instance left, before the bus closes. */
|
|
1074
|
-
async function announceDeparture() {
|
|
1075
|
-
const sent = [];
|
|
1076
|
-
for (const pending of rooms.values()) {
|
|
1077
|
-
const room = await pending.catch(() => void 0);
|
|
1078
|
-
if (!room?.bus) continue;
|
|
1079
|
-
const clients = localAwarenessClients(room);
|
|
1080
|
-
if (!clients.length) continue;
|
|
1081
|
-
const update = awarenessProtocol.encodeAwarenessUpdate(room.awareness, clients, /* @__PURE__ */ new Map());
|
|
1082
|
-
sent.push(room.bus.publish({
|
|
1083
|
-
type: "awareness",
|
|
1084
|
-
room: room.key,
|
|
1085
|
-
epoch: roomEpoch(room),
|
|
1086
|
-
data: update
|
|
1087
|
-
}));
|
|
1088
|
-
}
|
|
1089
|
-
await Promise.allSettled(sent);
|
|
1090
|
-
}
|
|
1091
|
-
function remoteOwner(instance) {
|
|
1092
|
-
let owner = remoteOwners.get(instance);
|
|
1093
|
-
if (!owner) remoteOwners.set(instance, owner = { instance });
|
|
1094
|
-
return owner;
|
|
1095
|
-
}
|
|
1096
|
-
/**
|
|
1097
|
-
* Applies a message from another instance to the open room it names. A room that is still opening skips the
|
|
1098
|
-
* message: it asks for what it lacks when it opens.
|
|
1099
|
-
*/
|
|
1100
|
-
function receive(message) {
|
|
1101
|
-
if (message.type === "refresh") {
|
|
1102
|
-
const key = JSON.parse(message.room);
|
|
1103
|
-
const [definitionName, documentId] = Array.isArray(key) ? key : [];
|
|
1104
|
-
if (typeof definitionName === "string" && typeof documentId === "string") refreshOpenRoom(definitionName, documentId, false).catch(() => {});
|
|
1105
|
-
return;
|
|
1106
|
-
}
|
|
1107
|
-
if (message.type === "reset") {
|
|
1108
|
-
rooms.get(message.room)?.then((room) => {
|
|
1109
|
-
if (room.kind !== "document" || !room.bus || room.destroyed || room.epoch === message.epoch) return;
|
|
1110
|
-
enqueue(room, async () => {
|
|
1111
|
-
if (room.epoch !== message.epoch) await reseedRoom(room, "source-changed", void 0, false, true);
|
|
1112
|
-
}).catch(() => {});
|
|
1113
|
-
}, () => {});
|
|
1114
|
-
return;
|
|
1115
|
-
}
|
|
1116
|
-
const room = openRooms.get(message.room);
|
|
1117
|
-
if (!room?.bus || room.kind === "document" && room.destroyed) return;
|
|
1118
|
-
if (message.epoch !== roomEpoch(room)) {
|
|
1119
|
-
if (message.type === "sync") requestSync(room);
|
|
1120
|
-
return;
|
|
1121
|
-
}
|
|
1122
|
-
switch (message.type) {
|
|
1123
|
-
case "update":
|
|
1124
|
-
if (room.kind === "document") {
|
|
1125
|
-
Y.applyUpdate(room.document, message.data, busOrigin);
|
|
1126
|
-
if ((room.document.store.pendingStructs || room.document.store.pendingDs) && Date.now() - (repairRequestedAt.get(room) ?? -Infinity) >= 1e3) {
|
|
1127
|
-
repairRequestedAt.set(room, Date.now());
|
|
1128
|
-
requestSync(room);
|
|
1129
|
-
}
|
|
1130
|
-
}
|
|
1131
|
-
return;
|
|
1132
|
-
case "claim":
|
|
1133
|
-
try {
|
|
1134
|
-
const client = decoding.readVarUint(decoding.createDecoder(message.data));
|
|
1135
|
-
room.awarenessOwners.claim(room.awareness, remoteOwner(message.instance), client, void 0, true);
|
|
1136
|
-
} catch {}
|
|
1137
|
-
return;
|
|
1138
|
-
case "awareness": {
|
|
1139
|
-
let clients;
|
|
1140
|
-
try {
|
|
1141
|
-
clients = room.awarenessOwners.apply(room.awareness, remoteOwner(message.instance), message.data, void 0, true);
|
|
1142
|
-
} catch {
|
|
1143
|
-
return;
|
|
1144
|
-
}
|
|
1145
|
-
const known = knownAwarenessClients(room.awareness, clients);
|
|
1146
|
-
if (!known.length) return;
|
|
1147
|
-
const frame = encodeAwarenessState(room.awareness, known);
|
|
1148
|
-
for (const peer of room.peers) peer.send(frame);
|
|
1149
|
-
return;
|
|
1150
|
-
}
|
|
1151
|
-
case "sync": {
|
|
1152
|
-
if (room.kind === "document") {
|
|
1153
|
-
const missing = Y.encodeStateAsUpdate(room.document, message.data);
|
|
1154
|
-
if (missing.byteLength > emptyUpdateBytes) publish(room, "update", missing);
|
|
1155
|
-
}
|
|
1156
|
-
const clients = localAwarenessClients(room);
|
|
1157
|
-
if (clients.length) publish(room, "awareness", awarenessProtocol.encodeAwarenessUpdate(room.awareness, clients));
|
|
1158
|
-
return;
|
|
1159
|
-
}
|
|
1160
|
-
case "frame": for (const peer of room.peers) peer.send(message.data);
|
|
1161
|
-
}
|
|
1162
|
-
}
|
|
1163
|
-
/**
|
|
1164
|
-
* Relays the awareness changes that are not a peer's own message: clients that timed out, and clients that another
|
|
1165
|
-
* instance removed. Awareness removes a client 30 seconds after its last update, so the presence of an instance that
|
|
1166
|
-
* stopped without a goodbye expires on the others.
|
|
1167
|
-
*/
|
|
1168
|
-
function watchAwareness(room) {
|
|
1169
|
-
const awareness = room.awareness;
|
|
1170
|
-
awareness.on("update", ({ removed }, origin) => {
|
|
1171
|
-
if (room.awareness !== awareness || !removed.length) return;
|
|
1172
|
-
room.awarenessOwners.releaseRemote(removed);
|
|
1173
|
-
if (origin !== "timeout") return;
|
|
1174
|
-
const clients = knownAwarenessClients(awareness, removed);
|
|
1175
|
-
if (!clients.length) return;
|
|
1176
|
-
const frame = encodeAwarenessState(awareness, clients);
|
|
1177
|
-
for (const peer of room.peers) peer.send(frame);
|
|
1178
|
-
});
|
|
1179
|
-
}
|
|
1180
|
-
/** The Cloudflare bindings and execution context, or the Durable Object state, in the event's Standard Context. */
|
|
1181
|
-
function resolveCloudflare(event) {
|
|
1182
|
-
return getStandardContext(event).runtime?.cloudflare;
|
|
1183
|
-
}
|
|
1184
|
-
async function forwardToCloudflareDurableObject(event) {
|
|
1185
|
-
const cloudflare = resolveCloudflare(event);
|
|
1186
|
-
const context = cloudflare?.context;
|
|
1187
|
-
const binding = (cloudflare?.env)?.$DurableObject;
|
|
1188
|
-
if (!binding || !isRealtimeDurableObjectNamespace(binding) || typeof context === "object" && context !== null && "storage" in context) return;
|
|
1189
|
-
let request = event.req;
|
|
1190
|
-
if (request.headers.has(internalRefreshHeader) || request.headers.has("x-vitehub-realtime-request")) {
|
|
1191
|
-
const headers = new Headers(request.headers);
|
|
1192
|
-
headers.delete(internalRefreshHeader);
|
|
1193
|
-
headers.delete(internalRequestHeader);
|
|
1194
|
-
request = new Request(request, { headers });
|
|
1195
|
-
}
|
|
1196
|
-
return await binding.get(binding.idFromName(durableRoomsInstance)).fetch(request);
|
|
1197
|
-
}
|
|
1198
|
-
function resolveRealtimeRoomSql(event) {
|
|
1199
|
-
const context = resolveCloudflare(event)?.context;
|
|
1200
|
-
if (!context || typeof context !== "object" || !Object.hasOwn(context, "storage")) return void 0;
|
|
1201
|
-
const storageDescriptor = Object.getOwnPropertyDescriptor(context, "storage");
|
|
1202
|
-
if (!storageDescriptor || !("value" in storageDescriptor)) return void 0;
|
|
1203
|
-
const storage = storageDescriptor.value;
|
|
1204
|
-
if (!storage || typeof storage !== "object") return void 0;
|
|
1205
|
-
const readNativeSql = (descriptor, inherited = false) => {
|
|
1206
|
-
if ("value" in descriptor) return !inherited && hasNativeCloudflareSql(descriptor.value) ? descriptor.value : void 0;
|
|
1207
|
-
const getter = descriptor.get;
|
|
1208
|
-
if (typeof getter !== "function") return void 0;
|
|
1209
|
-
const source = Function.prototype.toString.call(getter);
|
|
1210
|
-
if (!/^function(?:\s+get(?:\s+\w+)?|\s+\w+)?\s*\(\s*\)\s*\{\s*\[native\s+code\]\s*\}$/.test(source)) return void 0;
|
|
1211
|
-
try {
|
|
1212
|
-
const sql = Reflect.get(storage, "sql");
|
|
1213
|
-
return hasNativeCloudflareSql(sql) ? sql : void 0;
|
|
1214
|
-
} catch {
|
|
1215
|
-
return;
|
|
1216
|
-
}
|
|
1217
|
-
};
|
|
1218
|
-
const descriptor = Object.getOwnPropertyDescriptor(storage, "sql");
|
|
1219
|
-
if (descriptor) return readNativeSql(descriptor);
|
|
1220
|
-
let prototype = Object.getPrototypeOf(storage);
|
|
1221
|
-
while (prototype && prototype !== Object.prototype) {
|
|
1222
|
-
const sqlDescriptor = Object.getOwnPropertyDescriptor(prototype, "sql");
|
|
1223
|
-
if (sqlDescriptor) return readNativeSql(sqlDescriptor, true);
|
|
1224
|
-
prototype = Object.getPrototypeOf(prototype);
|
|
1225
|
-
}
|
|
1226
|
-
}
|
|
1227
|
-
async function getDefinition(definitionName) {
|
|
1228
|
-
const module = await (Object.hasOwn(registry, definitionName) ? registry[definitionName] : void 0)?.();
|
|
1229
|
-
if (!module) throw new HTTPError({
|
|
1230
|
-
status: 404,
|
|
1231
|
-
message: `Unknown realtime definition ${JSON.stringify(definitionName)}.`
|
|
1232
|
-
});
|
|
1233
|
-
assertRealtimeAccess(module.default);
|
|
1234
|
-
return module.default;
|
|
1235
|
-
}
|
|
1236
|
-
async function reserveMemoryRoom() {
|
|
1237
|
-
if (memoryRoomKeys.size < maxMemoryRooms) return;
|
|
1238
|
-
const inactiveKey = inactiveMemoryRoomKeys.values().next().value;
|
|
1239
|
-
const inactive = inactiveKey ? await rooms.get(inactiveKey)?.catch(() => void 0) : void 0;
|
|
1240
|
-
if (inactive && inactiveMemoryRoomKeys.has(inactive.key) && inactive.peers.size === 0 && (inactive.kind === "events" || inactive.operations === 0 && !inactive.dirty)) destroyRoom(inactive);
|
|
1241
|
-
if (memoryRoomKeys.size >= maxMemoryRooms) throw new HTTPError({
|
|
1242
|
-
status: 503,
|
|
1243
|
-
message: "The in-memory realtime authority reached its active room limit."
|
|
1244
|
-
});
|
|
1245
|
-
}
|
|
1246
|
-
async function openRoom(key, sql, create) {
|
|
1247
|
-
let room = rooms.get(key);
|
|
1248
|
-
if (!room && !sql) {
|
|
1249
|
-
await reserveMemoryRoom();
|
|
1250
|
-
room = rooms.get(key);
|
|
1251
|
-
}
|
|
1252
|
-
if (!room) {
|
|
1253
|
-
if (!sql) memoryRoomKeys.add(key);
|
|
1254
|
-
room = create();
|
|
1255
|
-
rooms.set(key, room);
|
|
1256
|
-
room.catch(() => {
|
|
1257
|
-
if (rooms.get(key) === room) rooms.delete(key);
|
|
1258
|
-
inactiveMemoryRoomKeys.delete(key);
|
|
1259
|
-
memoryRoomKeys.delete(key);
|
|
1260
|
-
});
|
|
1261
|
-
}
|
|
1262
|
-
const value = await room;
|
|
1263
|
-
inactiveMemoryRoomKeys.delete(key);
|
|
1264
|
-
return value;
|
|
1265
|
-
}
|
|
1266
|
-
function getEventsRoom(key, workspace, sql) {
|
|
1267
|
-
return openRoom(key, sql, async () => {
|
|
1268
|
-
const bus = await sharedBus();
|
|
1269
|
-
const document = new Y.Doc();
|
|
1270
|
-
const awareness = new awarenessProtocol.Awareness(document);
|
|
1271
|
-
awareness.setLocalState(null);
|
|
1272
|
-
const room = {
|
|
1273
|
-
awareness,
|
|
1274
|
-
awarenessOwners: createRealtimeAwarenessOwners(),
|
|
1275
|
-
bus,
|
|
1276
|
-
channel: `vitehub:realtime:${key}`,
|
|
1277
|
-
document,
|
|
1278
|
-
key,
|
|
1279
|
-
kind: "events",
|
|
1280
|
-
peers: /* @__PURE__ */ new Set(),
|
|
1281
|
-
workspace
|
|
1282
|
-
};
|
|
1283
|
-
watchAwareness(room);
|
|
1284
|
-
openRooms.set(key, room);
|
|
1285
|
-
requestSync(room);
|
|
1286
|
-
return room;
|
|
1287
|
-
});
|
|
1288
|
-
}
|
|
1289
|
-
function createAwareness(document) {
|
|
1290
|
-
const awareness = new awarenessProtocol.Awareness(document);
|
|
1291
|
-
awareness.setLocalState(null);
|
|
1292
|
-
return awareness;
|
|
1293
|
-
}
|
|
1294
|
-
function roomPeer(room, origin) {
|
|
1295
|
-
for (const peer of room.peers) if (peer === origin) return peer;
|
|
1296
|
-
}
|
|
1297
|
-
function listen(room, document) {
|
|
1298
|
-
document.on("update", (update, origin, _document, transaction) => {
|
|
1299
|
-
if (room.document !== document) return;
|
|
1300
|
-
persistRoomUpdate(room, update, origin !== serverOrigin);
|
|
1301
|
-
const message = encodeSyncUpdate(update);
|
|
1302
|
-
const sender = roomPeer(room, origin);
|
|
1303
|
-
if (sender) sender.publish(room.channel, message);
|
|
1304
|
-
else for (const peer of room.peers) peer.send(message);
|
|
1305
|
-
if (origin === busOrigin) {
|
|
1306
|
-
if (!changesOnlyStatus(document, transaction)) markDirty(room, void 0);
|
|
1307
|
-
return;
|
|
1308
|
-
}
|
|
1309
|
-
publish(room, "update", update);
|
|
1310
|
-
if (origin !== serverOrigin) markDirty(room, sender && room.peerUsers.get(sender));
|
|
1311
|
-
});
|
|
1312
|
-
}
|
|
1313
|
-
function replaceDocument(room, document) {
|
|
1314
|
-
room.document = document;
|
|
1315
|
-
room.awareness = createAwareness(document);
|
|
1316
|
-
room.awarenessOwners = createRealtimeAwarenessOwners();
|
|
1317
|
-
watchAwareness(room);
|
|
1318
|
-
listen(room, document);
|
|
1319
|
-
}
|
|
1320
|
-
/**
|
|
1321
|
-
* The document of a shared room: the shared record when it holds the stored digest, else a new seed that becomes the
|
|
1322
|
-
* record. Instances that open a room at the same time agree on one record, so every instance edits one Yjs history.
|
|
1323
|
-
* `replaced` is true when this instance moved the record to a new epoch.
|
|
1324
|
-
*/
|
|
1325
|
-
async function sharedDocument(bus, key, editor, loaded, guard) {
|
|
1326
|
-
for (let attempt = 0; attempt < 5; attempt++) {
|
|
1327
|
-
const found = await bus.readRoom(key);
|
|
1328
|
-
const record = found && await recoverSharedRecord(bus, key, editor, loaded, found);
|
|
1329
|
-
if (record && record.digest === loaded.digest) {
|
|
1330
|
-
const document = new Y.Doc();
|
|
1331
|
-
try {
|
|
1332
|
-
Y.applyUpdate(document, record.state);
|
|
1333
|
-
if (readRealtimeStatus(document).digest !== record.digest) writeRealtimeStatus(document, { digest: record.digest }, serverOrigin);
|
|
1334
|
-
return {
|
|
1335
|
-
document,
|
|
1336
|
-
epoch: record.epoch,
|
|
1337
|
-
replaced: false,
|
|
1338
|
-
dirty: record.pending
|
|
1339
|
-
};
|
|
1340
|
-
} catch (error) {
|
|
1341
|
-
document.destroy();
|
|
1342
|
-
throw error;
|
|
1343
|
-
}
|
|
1344
|
-
}
|
|
1345
|
-
const document = await seedDocument(editor, loaded, guard);
|
|
1346
|
-
const epoch = crypto.randomUUID();
|
|
1347
|
-
if (await bus.writeRoom(key, {
|
|
1348
|
-
epoch,
|
|
1349
|
-
digest: loaded.digest,
|
|
1350
|
-
state: Y.encodeStateAsUpdate(document)
|
|
1351
|
-
}, record?.epoch ?? null)) return {
|
|
1352
|
-
document,
|
|
1353
|
-
epoch,
|
|
1354
|
-
replaced: !!record
|
|
1355
|
-
};
|
|
1356
|
-
document.destroy();
|
|
1357
|
-
}
|
|
1358
|
-
throw new HTTPError({
|
|
1359
|
-
status: 503,
|
|
1360
|
-
message: "Realtime instances changed this room at the same time. Connect again."
|
|
1361
|
-
});
|
|
1362
|
-
}
|
|
1363
|
-
/** All callers hold the room lock. Never report a save as clean when its record was not written. */
|
|
1364
|
-
async function writeSharedRecord(bus, key, record) {
|
|
1365
|
-
let failure;
|
|
1366
|
-
for (let attempt = 0; attempt < 3; attempt++) try {
|
|
1367
|
-
if (await bus.writeRoom(key, record, record.epoch)) return;
|
|
1368
|
-
console.error("[vitehub] Realtime room record compare-and-set failed.", key);
|
|
1369
|
-
throw realtimeErrorDiagnostics.REALTIME_ROOM_WRITE_CONFLICT();
|
|
1370
|
-
} catch (error) {
|
|
1371
|
-
failure = error;
|
|
1372
|
-
}
|
|
1373
|
-
console.error("[vitehub] Realtime could not write the shared room record.", failure);
|
|
1374
|
-
throw failure;
|
|
1375
|
-
}
|
|
1376
|
-
/** A process can stop between adapter.save() and the final record write. Recover that save without a new epoch. */
|
|
1377
|
-
async function recoverSharedRecord(bus, key, editor, loaded, record) {
|
|
1378
|
-
if (!record.pending || loaded.digest === record.digest) return record;
|
|
1379
|
-
const submitted = new Y.Doc();
|
|
1380
|
-
try {
|
|
1381
|
-
Y.applyUpdate(submitted, record.state);
|
|
1382
|
-
const snapshot = await readRealtimeYDoc(editor, submitted);
|
|
1383
|
-
if (keepRealtimeFinalNewline(snapshot.body, loaded.body.endsWith("\n")) !== loaded.body || !realtimeJsonEqual(snapshot.fields, loadedFields(loaded))) return record;
|
|
1384
|
-
writeRealtimeStatus(submitted, {
|
|
1385
|
-
digest: loaded.digest,
|
|
1386
|
-
error: null
|
|
1387
|
-
}, serverOrigin);
|
|
1388
|
-
const recovered = {
|
|
1389
|
-
...record,
|
|
1390
|
-
digest: loaded.digest,
|
|
1391
|
-
state: Y.encodeStateAsUpdate(submitted),
|
|
1392
|
-
pending: false
|
|
1393
|
-
};
|
|
1394
|
-
await writeSharedRecord(bus, key, recovered);
|
|
1395
|
-
return recovered;
|
|
1396
|
-
} finally {
|
|
1397
|
-
submitted.destroy();
|
|
1398
|
-
}
|
|
1399
|
-
}
|
|
1400
|
-
/**
|
|
1401
|
-
* Takes the saves of other instances into a shared room before it saves: their Yjs state, their digest, and the
|
|
1402
|
-
* stored form that a save with no edits keeps. Returns `false` when the room re-seeded on another instance, after
|
|
1403
|
-
* this room followed it.
|
|
1404
|
-
*/
|
|
1405
|
-
async function adoptSharedRecord(room, bus) {
|
|
1406
|
-
let record = await bus.readRoom(room.key);
|
|
1407
|
-
let pendingLoaded;
|
|
1408
|
-
if (!record) return true;
|
|
1409
|
-
if (record.epoch !== room.epoch) {
|
|
1410
|
-
room.unwrittenRecord = void 0;
|
|
1411
|
-
await reseedRoom(room, "source-changed", void 0, false, true);
|
|
1412
|
-
return false;
|
|
1413
|
-
}
|
|
1414
|
-
const unwritten = room.unwrittenRecord;
|
|
1415
|
-
if (unwritten) {
|
|
1416
|
-
const saved = new Y.Doc();
|
|
1417
|
-
try {
|
|
1418
|
-
Y.applyUpdate(saved, unwritten.state);
|
|
1419
|
-
if (record.pending && unwritten.epoch === record.epoch && containsRealtimeState(saved, record.state)) {
|
|
1420
|
-
if ((await room.resolved.adapter.load(room.context)).digest === unwritten.digest) {
|
|
1421
|
-
await writeSharedRecord(bus, room.key, unwritten);
|
|
1422
|
-
record = unwritten;
|
|
1423
|
-
}
|
|
1424
|
-
}
|
|
1425
|
-
room.unwrittenRecord = void 0;
|
|
1426
|
-
} finally {
|
|
1427
|
-
saved.destroy();
|
|
1428
|
-
}
|
|
1429
|
-
}
|
|
1430
|
-
if (record.pending) {
|
|
1431
|
-
const loaded = await room.resolved.adapter.load(room.context);
|
|
1432
|
-
pendingLoaded = loaded;
|
|
1433
|
-
record = await recoverSharedRecord(bus, room.key, room.editor, loaded, record);
|
|
1434
|
-
if (record.digest !== loaded.digest) {
|
|
1435
|
-
if (room.pendingRecovery?.digest !== loaded.digest) room.pendingRecovery = {
|
|
1436
|
-
digest: loaded.digest,
|
|
1437
|
-
since: Date.now()
|
|
1438
|
-
};
|
|
1439
|
-
if (Date.now() - room.pendingRecovery.since < 1e4) throw new HTTPError({
|
|
1440
|
-
status: 503,
|
|
1441
|
-
message: "Realtime is waiting for another instance to finish its interrupted save. Retry the save."
|
|
1442
|
-
});
|
|
1443
|
-
await reseedRoom(room, "source-changed", loaded);
|
|
1444
|
-
return false;
|
|
1445
|
-
}
|
|
1446
|
-
}
|
|
1447
|
-
room.pendingRecovery = void 0;
|
|
1448
|
-
const sameStored = record.digest === room.digest && !record.pending;
|
|
1449
|
-
const saved = new Y.Doc();
|
|
1450
|
-
try {
|
|
1451
|
-
Y.applyUpdate(saved, record.state);
|
|
1452
|
-
const stored = record.pending && pendingLoaded ? {
|
|
1453
|
-
body: pendingLoaded.body,
|
|
1454
|
-
fields: loadedFields(pendingLoaded)
|
|
1455
|
-
} : await readRealtimeYDoc(room.editor, saved);
|
|
1456
|
-
if (room.destroyed || room.epoch !== record.epoch) return false;
|
|
1457
|
-
Y.applyUpdate(room.document, record.state, busOrigin);
|
|
1458
|
-
room.digest = record.digest;
|
|
1459
|
-
if (readRealtimeStatus(room.document).digest !== record.digest) writeRealtimeStatus(room.document, { digest: record.digest }, serverOrigin);
|
|
1460
|
-
if (sameStored) return true;
|
|
1461
|
-
room.guard = {
|
|
1462
|
-
clean: {
|
|
1463
|
-
body: keepRealtimeFinalNewline(stored.body, room.guard.finalNewline),
|
|
1464
|
-
fields: stored.fields
|
|
1465
|
-
},
|
|
1466
|
-
finalNewline: room.guard.finalNewline,
|
|
1467
|
-
issues: [],
|
|
1468
|
-
readOnly: false
|
|
1469
|
-
};
|
|
1470
|
-
if (record.pending) markDirty(room, void 0);
|
|
1471
|
-
return true;
|
|
1472
|
-
} finally {
|
|
1473
|
-
saved.destroy();
|
|
1474
|
-
}
|
|
1475
|
-
}
|
|
1476
|
-
async function seedDocument(editor, loaded, guard) {
|
|
1477
|
-
const document = await createRealtimeYDoc(editor, loaded);
|
|
1478
|
-
writeRealtimeStatus(document, {
|
|
1479
|
-
digest: loaded.digest,
|
|
1480
|
-
...guardStatus(guard),
|
|
1481
|
-
savedAt: null,
|
|
1482
|
-
savedBy: null
|
|
1483
|
-
}, serverOrigin);
|
|
1484
|
-
assertRealtimeRoomStateQuota(document);
|
|
1485
|
-
return document;
|
|
1486
|
-
}
|
|
1487
|
-
function getDocumentRoom(definitionName, documentId, resolved, sql) {
|
|
1488
|
-
const key = realtimeRoomKey(definitionName, documentId);
|
|
1489
|
-
return openRoom(key, sql, async () => {
|
|
1490
|
-
const bus = sql ? void 0 : await sharedBus();
|
|
1491
|
-
const context = {
|
|
1492
|
-
authority: sql ? "cloudflare" : bus?.authority ?? "memory",
|
|
1493
|
-
definition: definitionName,
|
|
1494
|
-
documentId
|
|
1495
|
-
};
|
|
1496
|
-
const editor = resolved.editor(context);
|
|
1497
|
-
const { loaded, guard, shared } = bus ? await bus.withRoomLock(key, async () => {
|
|
1498
|
-
const loaded = await resolved.adapter.load(context);
|
|
1499
|
-
const guard = await verifyDocument(editor, loaded);
|
|
1500
|
-
return {
|
|
1501
|
-
loaded,
|
|
1502
|
-
guard,
|
|
1503
|
-
shared: await sharedDocument(bus, key, editor, loaded, guard)
|
|
1504
|
-
};
|
|
1505
|
-
}) : await (async () => {
|
|
1506
|
-
const loaded = await resolved.adapter.load(context);
|
|
1507
|
-
return {
|
|
1508
|
-
loaded,
|
|
1509
|
-
guard: await verifyDocument(editor, loaded),
|
|
1510
|
-
shared: void 0
|
|
1511
|
-
};
|
|
1512
|
-
})();
|
|
1513
|
-
if (sql) {
|
|
1514
|
-
const clientUpdateColumn = documentTables(sql);
|
|
1515
|
-
migrateLegacyDocument(sql, key, clientUpdateColumn);
|
|
1516
|
-
}
|
|
1517
|
-
const stored = sql && readStoredRoom(sql, key);
|
|
1518
|
-
const storedDigest = text(stored?.digest) ?? null;
|
|
1519
|
-
const storedEpoch = text(stored?.epoch);
|
|
1520
|
-
const storedState = storedUpdate(stored?.update_blob);
|
|
1521
|
-
const restores = !!sql && !!storedState && !!storedEpoch && storedDigest === loaded.digest && (text(stored?.editor_version) ?? null) === (editor.version ?? null);
|
|
1522
|
-
let document;
|
|
1523
|
-
let persistedUpdates = 0;
|
|
1524
|
-
let dirty = false;
|
|
1525
|
-
let refreshedFields = false;
|
|
1526
|
-
let sharedEpoch;
|
|
1527
|
-
let replacedEpoch = false;
|
|
1528
|
-
if (shared) {
|
|
1529
|
-
document = shared.document;
|
|
1530
|
-
sharedEpoch = shared.epoch;
|
|
1531
|
-
replacedEpoch = shared.replaced;
|
|
1532
|
-
dirty = shared.dirty ?? false;
|
|
1533
|
-
} else if (restores) {
|
|
1534
|
-
document = new Y.Doc();
|
|
1535
|
-
try {
|
|
1536
|
-
Y.applyUpdate(document, storedState);
|
|
1537
|
-
let updates;
|
|
1538
|
-
try {
|
|
1539
|
-
updates = sql.exec("SELECT update_blob, client_update FROM vitehub_realtime_document_updates WHERE room_key = ? ORDER BY sequence", key).toArray();
|
|
1540
|
-
} catch {
|
|
1541
|
-
updates = sql.exec("SELECT update_blob FROM vitehub_realtime_document_updates WHERE room_key = ? ORDER BY sequence", key).toArray();
|
|
1542
|
-
}
|
|
1543
|
-
for (const row of updates) {
|
|
1544
|
-
const update = storedUpdate(row.update_blob);
|
|
1545
|
-
if (update) Y.applyUpdate(document, update);
|
|
1546
|
-
}
|
|
1547
|
-
persistedUpdates = updates.length;
|
|
1548
|
-
dirty = Number(stored?.dirty) === 1 || updates.some((update) => update.client_update === void 0 || Number(update.client_update) === 1);
|
|
1549
|
-
const fields = document.getMap(realtimeDocumentLayout.fields);
|
|
1550
|
-
if (!dirty && !holdsFields(fields, guard.clean.fields)) {
|
|
1551
|
-
document.transact(() => writeRealtimeFields(fields, guard.clean.fields), serverOrigin);
|
|
1552
|
-
refreshedFields = true;
|
|
1553
|
-
}
|
|
1554
|
-
assertRealtimeRoomStateQuota(document);
|
|
1555
|
-
if (guard.readOnly || readRealtimeStatus(document).error === readOnlyDocumentMessage) writeRealtimeStatus(document, guardStatus(guard), serverOrigin);
|
|
1556
|
-
} catch (error) {
|
|
1557
|
-
document.destroy();
|
|
1558
|
-
throw error;
|
|
1559
|
-
}
|
|
1560
|
-
} else document = await seedDocument(editor, loaded, guard);
|
|
1561
|
-
const room = {
|
|
1562
|
-
awareness: createAwareness(document),
|
|
1563
|
-
awarenessOwners: createRealtimeAwarenessOwners(),
|
|
1564
|
-
bus,
|
|
1565
|
-
channel: `vitehub:realtime:${key}`,
|
|
1566
|
-
context,
|
|
1567
|
-
destroyed: false,
|
|
1568
|
-
digest: loaded.digest,
|
|
1569
|
-
document,
|
|
1570
|
-
dirty,
|
|
1571
|
-
editor,
|
|
1572
|
-
editors: /* @__PURE__ */ new Map(),
|
|
1573
|
-
epoch: sharedEpoch ?? (restores && storedEpoch ? storedEpoch : crypto.randomUUID()),
|
|
1574
|
-
guard,
|
|
1575
|
-
held: false,
|
|
1576
|
-
writers: /* @__PURE__ */ new Set(),
|
|
1577
|
-
key,
|
|
1578
|
-
kind: "document",
|
|
1579
|
-
operations: 0,
|
|
1580
|
-
peerUsers: /* @__PURE__ */ new WeakMap(),
|
|
1581
|
-
peers: /* @__PURE__ */ new Set(),
|
|
1582
|
-
persistedUpdates,
|
|
1583
|
-
queue: Promise.resolve(),
|
|
1584
|
-
resolved,
|
|
1585
|
-
retryDelay: 0,
|
|
1586
|
-
revision: 0,
|
|
1587
|
-
sql
|
|
1588
|
-
};
|
|
1589
|
-
watchAwareness(room);
|
|
1590
|
-
listen(room, document);
|
|
1591
|
-
if (sql && (!restores || refreshedFields)) persistRoom(room);
|
|
1592
|
-
if (dirty) scheduleSave(room);
|
|
1593
|
-
openRooms.set(key, room);
|
|
1594
|
-
if (replacedEpoch) publish(room, "reset", /* @__PURE__ */ new Uint8Array());
|
|
1595
|
-
requestSync(room);
|
|
1596
|
-
return room;
|
|
1597
|
-
});
|
|
1598
|
-
}
|
|
1599
|
-
function persistRoom(room) {
|
|
1600
|
-
if (!room.sql) return;
|
|
1601
|
-
const row = [
|
|
1602
|
-
room.key,
|
|
1603
|
-
room.epoch,
|
|
1604
|
-
room.digest,
|
|
1605
|
-
room.dirty ? 1 : 0,
|
|
1606
|
-
Uint8Array.from(Y.encodeStateAsUpdate(room.document)).buffer
|
|
1607
|
-
];
|
|
1608
|
-
try {
|
|
1609
|
-
room.sql.exec("INSERT OR REPLACE INTO vitehub_realtime_documents (room_key, epoch, digest, dirty, update_blob, editor_version) VALUES (?, ?, ?, ?, ?, ?)", ...row, room.editor.version ?? null);
|
|
1610
|
-
} catch {
|
|
1611
|
-
room.sql.exec("INSERT OR REPLACE INTO vitehub_realtime_documents (room_key, epoch, digest, dirty, update_blob) VALUES (?, ?, ?, ?, ?)", ...row);
|
|
1612
|
-
}
|
|
1613
|
-
room.sql.exec("DELETE FROM vitehub_realtime_document_updates WHERE room_key = ?", room.key);
|
|
1614
|
-
room.persistedUpdates = 0;
|
|
1615
|
-
}
|
|
1616
|
-
function persistRoomUpdate(room, update, clientUpdate) {
|
|
1617
|
-
if (!room.sql) return;
|
|
1618
|
-
const blob = Uint8Array.from(update).buffer;
|
|
1619
|
-
try {
|
|
1620
|
-
room.sql.exec("INSERT INTO vitehub_realtime_document_updates (room_key, update_blob, client_update) VALUES (?, ?, ?)", room.key, blob, clientUpdate ? 1 : 0);
|
|
1621
|
-
} catch {
|
|
1622
|
-
room.sql.exec("INSERT INTO vitehub_realtime_document_updates (room_key, update_blob) VALUES (?, ?)", room.key, blob);
|
|
1623
|
-
}
|
|
1624
|
-
room.persistedUpdates++;
|
|
1625
|
-
if (room.persistedUpdates >= durableUpdateCompactionInterval) persistRoom(room);
|
|
1626
|
-
}
|
|
1627
|
-
function destroyRoom(room) {
|
|
1628
|
-
if (room.kind === "document") {
|
|
1629
|
-
if (room.idleTimer) clearTimeout(room.idleTimer);
|
|
1630
|
-
room.idleTimer = void 0;
|
|
1631
|
-
if (room.holdTimer) clearInterval(room.holdTimer);
|
|
1632
|
-
room.holdTimer = void 0;
|
|
1633
|
-
room.destroyed = true;
|
|
1634
|
-
}
|
|
1635
|
-
room.awareness.destroy();
|
|
1636
|
-
room.document.destroy();
|
|
1637
|
-
rooms.delete(room.key);
|
|
1638
|
-
if (openRooms.get(room.key) === room) openRooms.delete(room.key);
|
|
1639
|
-
inactiveMemoryRoomKeys.delete(room.key);
|
|
1640
|
-
memoryRoomKeys.delete(room.key);
|
|
1641
|
-
}
|
|
1642
|
-
/** Releases an idle room: durable rooms leave memory; clean memory rooms become reclaimable. */
|
|
1643
|
-
function releaseRoom(room) {
|
|
1644
|
-
if (room.peers.size > 0) return;
|
|
1645
|
-
if (room.kind === "events" && (room.bus || !room.workspace)) {
|
|
1646
|
-
destroyRoom(room);
|
|
1647
|
-
return;
|
|
1648
|
-
}
|
|
1649
|
-
if (room.kind === "events") {
|
|
1650
|
-
inactiveMemoryRoomKeys.delete(room.key);
|
|
1651
|
-
inactiveMemoryRoomKeys.add(room.key);
|
|
1652
|
-
return;
|
|
1653
|
-
}
|
|
1654
|
-
if (room.operations > 0 || room.destroyed || room.held) return;
|
|
1655
|
-
if (room.sql) {
|
|
1656
|
-
persistRoom(room);
|
|
1657
|
-
destroyRoom(room);
|
|
1658
|
-
return;
|
|
1659
|
-
}
|
|
1660
|
-
if (room.bus && !room.dirty) {
|
|
1661
|
-
destroyRoom(room);
|
|
1662
|
-
return;
|
|
1663
|
-
}
|
|
1664
|
-
if (room.dirty) return;
|
|
1665
|
-
inactiveMemoryRoomKeys.delete(room.key);
|
|
1666
|
-
inactiveMemoryRoomKeys.add(room.key);
|
|
1667
|
-
}
|
|
1668
|
-
function enqueue(room, operation) {
|
|
1669
|
-
room.operations++;
|
|
1670
|
-
const run = room.queue.then(() => {
|
|
1671
|
-
if (room.destroyed) throw new HTTPError({
|
|
1672
|
-
status: 409,
|
|
1673
|
-
message: "The realtime room closed."
|
|
1674
|
-
});
|
|
1675
|
-
return operation();
|
|
1676
|
-
});
|
|
1677
|
-
room.queue = run.then(() => {}, () => {});
|
|
1678
|
-
return run.finally(() => {
|
|
1679
|
-
room.operations--;
|
|
1680
|
-
releaseRoom(room);
|
|
1681
|
-
});
|
|
1682
|
-
}
|
|
1683
|
-
function markDirty(room, user) {
|
|
1684
|
-
room.dirty = true;
|
|
1685
|
-
room.revision++;
|
|
1686
|
-
if (user) {
|
|
1687
|
-
room.editors.delete(user.id);
|
|
1688
|
-
room.editors.set(user.id, user);
|
|
1689
|
-
}
|
|
1690
|
-
scheduleSave(room);
|
|
1691
|
-
}
|
|
1692
|
-
/** Identified users of the writable clients, once each, in the order they joined. */
|
|
1693
|
-
function holdUsers(room) {
|
|
1694
|
-
const users = /* @__PURE__ */ new Map();
|
|
1695
|
-
for (const peer of room.writers) {
|
|
1696
|
-
const user = room.peerUsers.get(peer);
|
|
1697
|
-
if (user && !users.has(user.id)) users.set(user.id, user);
|
|
1698
|
-
}
|
|
1699
|
-
return [...users.values()];
|
|
1700
|
-
}
|
|
1701
|
-
/** Calls `adapter.hold()` for a room with writable clients, such as to keep a lease, and repeats it every minute. */
|
|
1702
|
-
function holdRoom(room) {
|
|
1703
|
-
const hold = room.resolved.adapter.hold;
|
|
1704
|
-
if (!hold || room.destroyed || room.guard.readOnly) return;
|
|
1705
|
-
if (room.writers.size === 0) {
|
|
1706
|
-
if (room.held) releaseHold(room);
|
|
1707
|
-
return;
|
|
1708
|
-
}
|
|
1709
|
-
room.held = true;
|
|
1710
|
-
room.holdTimer ??= setInterval(() => holdRoom(room), holdIntervalMs);
|
|
1711
|
-
enqueue(room, async () => {
|
|
1712
|
-
if (room.writers.size === 0) return;
|
|
1713
|
-
try {
|
|
1714
|
-
await hold.call(room.resolved.adapter, room.context, { users: holdUsers(room) });
|
|
1715
|
-
if (room.holdError !== void 0 && readRealtimeStatus(room.document).error === room.holdError) writeRealtimeStatus(room.document, { error: null }, serverOrigin);
|
|
1716
|
-
room.holdError = void 0;
|
|
1717
|
-
} catch (error) {
|
|
1718
|
-
room.holdError = errorMessage(error);
|
|
1719
|
-
writeRealtimeStatus(room.document, { error: room.holdError }, serverOrigin);
|
|
1720
|
-
}
|
|
1721
|
-
}).catch(() => {});
|
|
1722
|
-
}
|
|
1723
|
-
/** After the last writable client left: save what is left, then call `adapter.release()`. */
|
|
1724
|
-
function releaseHold(room) {
|
|
1725
|
-
if (room.holdTimer) clearInterval(room.holdTimer);
|
|
1726
|
-
room.holdTimer = void 0;
|
|
1727
|
-
if (room.dirty && room.resolved.persistence) enqueue(room, () => saveRoom(room, "leave", false)).catch(() => {});
|
|
1728
|
-
enqueue(room, async () => {
|
|
1729
|
-
if (room.writers.size > 0 || !room.held) return;
|
|
1730
|
-
room.held = false;
|
|
1731
|
-
await room.resolved.adapter.release?.(room.context);
|
|
1732
|
-
}).catch(() => {
|
|
1733
|
-
room.held = false;
|
|
1734
|
-
});
|
|
1735
|
-
}
|
|
1736
|
-
function scheduleSave(room, delay) {
|
|
1737
|
-
const persistence = room.resolved.persistence;
|
|
1738
|
-
if (!persistence || room.destroyed || room.guard.readOnly) return;
|
|
1739
|
-
const now = Date.now();
|
|
1740
|
-
room.firstDirtyAt ??= now;
|
|
1741
|
-
if (room.idleTimer) clearTimeout(room.idleTimer);
|
|
1742
|
-
const wait = delay ?? Math.max(0, Math.min(persistence.debounce, room.firstDirtyAt + persistence.maxWait - now));
|
|
1743
|
-
room.idleTimer = setTimeout(() => {
|
|
1744
|
-
room.idleTimer = void 0;
|
|
1745
|
-
enqueue(room, () => saveRoom(room, "idle", false)).catch(() => {});
|
|
1746
|
-
}, wait);
|
|
1747
|
-
}
|
|
1748
|
-
/** Runs `task` under the room lock of a shared room, or at once when this instance already holds it. */
|
|
1749
|
-
async function underRoomLock(room, task) {
|
|
1750
|
-
const bus = room.bus;
|
|
1751
|
-
if (!bus || room.locked) return await task();
|
|
1752
|
-
return await bus.withRoomLock(room.key, async () => {
|
|
1753
|
-
room.locked = true;
|
|
1754
|
-
try {
|
|
1755
|
-
return await task();
|
|
1756
|
-
} finally {
|
|
1757
|
-
room.locked = false;
|
|
1758
|
-
}
|
|
1759
|
-
});
|
|
1760
|
-
}
|
|
1761
|
-
/**
|
|
1762
|
-
* `follow` re-seeds a shared room at the epoch that another instance moved its record to. It replaces the document
|
|
1763
|
-
* also after a concurrent edit: a room at an older epoch cannot reach the other instances.
|
|
1764
|
-
*/
|
|
1765
|
-
async function reseedRoom(room, reason, loaded, preserveEdits = false, follow = false) {
|
|
1766
|
-
const revision = room.revision;
|
|
1767
|
-
const stale = () => room.destroyed || !follow && (room.revision !== revision || preserveEdits && room.dirty);
|
|
1768
|
-
let source;
|
|
1769
|
-
let guard;
|
|
1770
|
-
let next;
|
|
1771
|
-
let epoch;
|
|
1772
|
-
let replaced = false;
|
|
1773
|
-
let dirty = false;
|
|
1774
|
-
const bus = room.bus;
|
|
1775
|
-
if (bus) {
|
|
1776
|
-
const shared = await underRoomLock(room, async () => {
|
|
1777
|
-
const source = loaded ?? await room.resolved.adapter.load(room.context);
|
|
1778
|
-
const guard = await verifyDocument(room.editor, source);
|
|
1779
|
-
if (stale()) return void 0;
|
|
1780
|
-
return {
|
|
1781
|
-
source,
|
|
1782
|
-
guard,
|
|
1783
|
-
...await sharedDocument(bus, room.key, room.editor, source, guard)
|
|
1784
|
-
};
|
|
1785
|
-
});
|
|
1786
|
-
if (!shared) return false;
|
|
1787
|
-
({source, guard, document: next, epoch, replaced} = shared);
|
|
1788
|
-
dirty = shared.dirty ?? false;
|
|
1789
|
-
if (room.destroyed) {
|
|
1790
|
-
next.destroy();
|
|
1791
|
-
return false;
|
|
1792
|
-
}
|
|
1793
|
-
} else {
|
|
1794
|
-
source = loaded ?? await room.resolved.adapter.load(room.context);
|
|
1795
|
-
guard = await verifyDocument(room.editor, source);
|
|
1796
|
-
next = await seedDocument(room.editor, source, guard);
|
|
1797
|
-
epoch = crypto.randomUUID();
|
|
1798
|
-
}
|
|
1799
|
-
if (!room.bus && stale()) {
|
|
1800
|
-
next.destroy();
|
|
1801
|
-
return false;
|
|
1802
|
-
}
|
|
1803
|
-
const previous = {
|
|
1804
|
-
awareness: room.awareness,
|
|
1805
|
-
document: room.document
|
|
1806
|
-
};
|
|
1807
|
-
const peers = [...room.peers];
|
|
1808
|
-
room.epoch = epoch;
|
|
1809
|
-
room.unwrittenRecord = void 0;
|
|
1810
|
-
room.pendingRecovery = void 0;
|
|
1811
|
-
room.digest = source.digest;
|
|
1812
|
-
room.guard = guard;
|
|
1813
|
-
room.dirty = dirty;
|
|
1814
|
-
room.editors.clear();
|
|
1815
|
-
room.firstDirtyAt = void 0;
|
|
1816
|
-
room.retryDelay = 0;
|
|
1817
|
-
if (room.idleTimer) clearTimeout(room.idleTimer);
|
|
1818
|
-
room.idleTimer = void 0;
|
|
1819
|
-
replaceDocument(room, next);
|
|
1820
|
-
previous.awareness.destroy();
|
|
1821
|
-
previous.document.destroy();
|
|
1822
|
-
persistRoom(room);
|
|
1823
|
-
if (dirty) scheduleSave(room);
|
|
1824
|
-
if (replaced) publish(room, "reset", /* @__PURE__ */ new Uint8Array());
|
|
1825
|
-
requestSync(room);
|
|
1826
|
-
const reset = encodeRealtimeControl({
|
|
1827
|
-
type: "reset",
|
|
1828
|
-
epoch: room.epoch,
|
|
1829
|
-
reason
|
|
1830
|
-
});
|
|
1831
|
-
for (const peer of peers) {
|
|
1832
|
-
terminalPeers.add(peer);
|
|
1833
|
-
clearHeldUpdates(peer);
|
|
1834
|
-
peer.unsubscribe(room.channel);
|
|
1835
|
-
peer.send(reset);
|
|
1836
|
-
peer.close(realtimeResetCloseCode, "The realtime document was re-seeded.");
|
|
1837
|
-
}
|
|
1838
|
-
return true;
|
|
1839
|
-
}
|
|
1840
|
-
/**
|
|
1841
|
-
* Saves of a shared room run one at a time across instances, under the room lock. Each first takes in the saves of
|
|
1842
|
-
* the other instances, so its `ifDigest` is the stored digest, unless the document changed outside the room. After
|
|
1843
|
-
* the save, the record holds the saved state and digest for the next instance.
|
|
1844
|
-
*/
|
|
1845
|
-
async function saveRoom(room, reason, force) {
|
|
1846
|
-
const bus = room.bus;
|
|
1847
|
-
if (!bus) return await saveRoomNow(room, reason, force);
|
|
1848
|
-
try {
|
|
1849
|
-
return await underRoomLock(room, async () => {
|
|
1850
|
-
if (!await adoptSharedRecord(room, bus)) {
|
|
1851
|
-
if (!force) return void 0;
|
|
1852
|
-
throw new HTTPError({
|
|
1853
|
-
status: 409,
|
|
1854
|
-
message: "The document re-seeded on another instance. The room was re-seeded.",
|
|
1855
|
-
data: { code: realtimeSourceChangedCode }
|
|
1856
|
-
});
|
|
1857
|
-
}
|
|
1858
|
-
return await saveRoomNow(room, reason, force, async (digest, state) => {
|
|
1859
|
-
const record = {
|
|
1860
|
-
epoch: room.epoch,
|
|
1861
|
-
digest,
|
|
1862
|
-
state
|
|
1863
|
-
};
|
|
1864
|
-
room.unwrittenRecord = record;
|
|
1865
|
-
await writeSharedRecord(bus, room.key, record);
|
|
1866
|
-
room.unwrittenRecord = void 0;
|
|
1867
|
-
}, async (state) => {
|
|
1868
|
-
await writeSharedRecord(bus, room.key, {
|
|
1869
|
-
epoch: room.epoch,
|
|
1870
|
-
digest: room.digest,
|
|
1871
|
-
state,
|
|
1872
|
-
pending: true
|
|
1873
|
-
});
|
|
1874
|
-
});
|
|
1875
|
-
});
|
|
1876
|
-
} catch (error) {
|
|
1877
|
-
if (room.dirty && room.resolved.persistence && !room.idleTimer) {
|
|
1878
|
-
room.retryDelay = Math.min(Math.max(room.resolved.persistence.debounce, room.retryDelay * 2), maxSaveRetryMs);
|
|
1879
|
-
scheduleSave(room, room.retryDelay);
|
|
1880
|
-
}
|
|
1881
|
-
throw error;
|
|
1882
|
-
}
|
|
1883
|
-
}
|
|
1884
|
-
/** `onStored` gets the digest and the Yjs state of what the adapter stored, before later edits. */
|
|
1885
|
-
async function saveRoomNow(room, reason, force, onStored, onSubmitting) {
|
|
1886
|
-
const { adapter, persistence } = room.resolved;
|
|
1887
|
-
const editor = room.editor;
|
|
1888
|
-
if (room.guard.readOnly) {
|
|
1889
|
-
if (!force) return;
|
|
1890
|
-
throw new HTTPError({
|
|
1891
|
-
status: 409,
|
|
1892
|
-
message: readOnlyDocumentMessage,
|
|
1893
|
-
data: { code: realtimeReadOnlyCode }
|
|
1894
|
-
});
|
|
1895
|
-
}
|
|
1896
|
-
if (!room.dirty && !(force && room.digest === null)) {
|
|
1897
|
-
if (!force) return;
|
|
1898
|
-
return {
|
|
1899
|
-
...readRealtimeStatus(room.document),
|
|
1900
|
-
document: await readRealtimeYDoc(editor, room.document)
|
|
1901
|
-
};
|
|
1902
|
-
}
|
|
1903
|
-
if (room.idleTimer) clearTimeout(room.idleTimer);
|
|
1904
|
-
room.idleTimer = void 0;
|
|
1905
|
-
room.firstDirtyAt = void 0;
|
|
1906
|
-
const revision = room.revision;
|
|
1907
|
-
const editors = [...room.editors.values()];
|
|
1908
|
-
const user = editors.at(-1);
|
|
1909
|
-
const submitted = new Y.Doc();
|
|
1910
|
-
Y.applyUpdate(submitted, Y.encodeStateAsUpdate(room.document));
|
|
1911
|
-
const finishSave = () => {
|
|
1912
|
-
room.retryDelay = 0;
|
|
1913
|
-
if (room.revision === revision) {
|
|
1914
|
-
room.dirty = false;
|
|
1915
|
-
room.editors.clear();
|
|
1916
|
-
} else scheduleSave(room);
|
|
1917
|
-
persistRoom(room);
|
|
1918
|
-
};
|
|
1919
|
-
try {
|
|
1920
|
-
try {
|
|
1921
|
-
checkRealtimeBody(editor, submitted);
|
|
1922
|
-
} catch {
|
|
1923
|
-
throw new HTTPError({
|
|
1924
|
-
status: 422,
|
|
1925
|
-
message: invalidDocumentMessage,
|
|
1926
|
-
data: { code: realtimeInvalidDocumentCode }
|
|
1927
|
-
});
|
|
1928
|
-
}
|
|
1929
|
-
const written = await readRealtimeYDoc(editor, submitted);
|
|
1930
|
-
const document = {
|
|
1931
|
-
...written,
|
|
1932
|
-
body: keepRealtimeFinalNewline(written.body, room.guard.finalNewline)
|
|
1933
|
-
};
|
|
1934
|
-
const { clean } = room.guard;
|
|
1935
|
-
if (room.digest !== null && document.body === clean.body && realtimeJsonEqual(document.fields, clean.fields)) {
|
|
1936
|
-
writeRealtimeStatus(submitted, {
|
|
1937
|
-
digest: room.digest,
|
|
1938
|
-
error: null
|
|
1939
|
-
}, serverOrigin);
|
|
1940
|
-
await onStored?.(room.digest, Y.encodeStateAsUpdate(submitted));
|
|
1941
|
-
Y.applyUpdate(room.document, Y.encodeStateAsUpdate(submitted), serverOrigin);
|
|
1942
|
-
finishSave();
|
|
1943
|
-
return {
|
|
1944
|
-
...readRealtimeStatus(room.document),
|
|
1945
|
-
document
|
|
1946
|
-
};
|
|
1947
|
-
}
|
|
1948
|
-
const readsBack = await realtimeCodecReadsBack(editor, submitted, written.body);
|
|
1949
|
-
await onSubmitting?.(Y.encodeStateAsUpdate(submitted));
|
|
1950
|
-
let result;
|
|
1951
|
-
try {
|
|
1952
|
-
result = await adapter.save(room.context, document, {
|
|
1953
|
-
editors,
|
|
1954
|
-
ifDigest: room.digest,
|
|
1955
|
-
reason,
|
|
1956
|
-
user
|
|
1957
|
-
});
|
|
1958
|
-
} catch (error) {
|
|
1959
|
-
if (!isRealtimeDocumentConflict(error) && !isWorkspaceConflict(error)) throw error;
|
|
1960
|
-
await reseedRoom(room, "source-changed");
|
|
1961
|
-
throw new HTTPError({
|
|
1962
|
-
status: 409,
|
|
1963
|
-
message: "The stored document changed outside this realtime room. The room was re-seeded.",
|
|
1964
|
-
data: { code: realtimeSourceChangedCode }
|
|
1965
|
-
});
|
|
1966
|
-
}
|
|
1967
|
-
room.digest = result.digest;
|
|
1968
|
-
const storedBody = result.stored?.body ?? document.body;
|
|
1969
|
-
room.guard = {
|
|
1970
|
-
clean: {
|
|
1971
|
-
body: storedBody,
|
|
1972
|
-
fields: result.stored?.fields ?? document.fields
|
|
1973
|
-
},
|
|
1974
|
-
finalNewline: storedBody.endsWith("\n"),
|
|
1975
|
-
issues: [],
|
|
1976
|
-
readOnly: false
|
|
1977
|
-
};
|
|
1978
|
-
if (result.stored) {
|
|
1979
|
-
const update = await diffRealtimeYDoc(editor, submitted, result.stored);
|
|
1980
|
-
if (update.byteLength > 0) {
|
|
1981
|
-
Y.applyUpdate(room.document, update, serverOrigin);
|
|
1982
|
-
Y.applyUpdate(submitted, update, serverOrigin);
|
|
1983
|
-
}
|
|
1984
|
-
}
|
|
1985
|
-
const status = {
|
|
1986
|
-
digest: result.digest,
|
|
1987
|
-
error: null,
|
|
1988
|
-
issues: readsBack ? result.issues ?? [] : [...result.issues ?? [], codecReadBackIssue],
|
|
1989
|
-
savedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1990
|
-
savedBy: user ?? null
|
|
1991
|
-
};
|
|
1992
|
-
writeRealtimeStatus(submitted, status, serverOrigin);
|
|
1993
|
-
await onStored?.(result.digest, Y.encodeStateAsUpdate(submitted));
|
|
1994
|
-
Y.applyUpdate(room.document, Y.encodeStateAsUpdate(submitted), serverOrigin);
|
|
1995
|
-
finishSave();
|
|
1996
|
-
return {
|
|
1997
|
-
...status,
|
|
1998
|
-
document: {
|
|
1999
|
-
...document,
|
|
2000
|
-
...result.stored,
|
|
2001
|
-
fields: result.stored?.fields ?? document.fields
|
|
2002
|
-
}
|
|
2003
|
-
};
|
|
2004
|
-
} catch (error) {
|
|
2005
|
-
if (room.destroyed || !room.dirty) throw error;
|
|
2006
|
-
writeRealtimeStatus(room.document, { error: errorMessage(error) }, serverOrigin);
|
|
2007
|
-
if (persistence) {
|
|
2008
|
-
room.retryDelay = Math.min(Math.max(persistence.debounce, room.retryDelay * 2), maxSaveRetryMs);
|
|
2009
|
-
room.firstDirtyAt = void 0;
|
|
2010
|
-
scheduleSave(room, room.retryDelay);
|
|
2011
|
-
}
|
|
2012
|
-
throw error;
|
|
2013
|
-
} finally {
|
|
2014
|
-
submitted.destroy();
|
|
2015
|
-
}
|
|
2016
|
-
}
|
|
2017
|
-
/**
|
|
2018
|
-
* Shows a clean room's stored file with the fields that it loads now, when they differ from the room's: a schema can
|
|
2019
|
-
* read the same file differently. The new fields become the clean baseline. A state over the room quota changes nothing.
|
|
2020
|
-
*/
|
|
2021
|
-
function refreshFields(room, fields) {
|
|
2022
|
-
const map = room.document.getMap(realtimeDocumentLayout.fields);
|
|
2023
|
-
if (holdsFields(map, fields)) return;
|
|
2024
|
-
const candidate = new Y.Doc();
|
|
2025
|
-
try {
|
|
2026
|
-
Y.applyUpdate(candidate, Y.encodeStateAsUpdate(room.document));
|
|
2027
|
-
candidate.transact(() => writeRealtimeFields(candidate.getMap(realtimeDocumentLayout.fields), fields));
|
|
2028
|
-
assertRealtimeRoomStateQuota(candidate);
|
|
2029
|
-
} finally {
|
|
2030
|
-
candidate.destroy();
|
|
2031
|
-
}
|
|
2032
|
-
room.document.transact(() => writeRealtimeFields(map, fields), serverOrigin);
|
|
2033
|
-
room.guard = {
|
|
2034
|
-
...room.guard,
|
|
2035
|
-
clean: {
|
|
2036
|
-
...room.guard.clean,
|
|
2037
|
-
fields
|
|
2038
|
-
}
|
|
2039
|
-
};
|
|
2040
|
-
persistRoom(room);
|
|
2041
|
-
}
|
|
2042
|
-
/**
|
|
2043
|
-
* For a shared room, the whole refresh holds the room lock: a load from before another instance's reseed or save
|
|
2044
|
-
* would otherwise replace the newer record with stale state.
|
|
2045
|
-
*/
|
|
2046
|
-
async function refreshRoom(room) {
|
|
2047
|
-
return await underRoomLock(room, () => refreshRoomNow(room));
|
|
2048
|
-
}
|
|
2049
|
-
async function refreshRoomNow(room) {
|
|
2050
|
-
if (room.bus && !await adoptSharedRecord(room, room.bus)) return {
|
|
2051
|
-
digest: room.digest,
|
|
2052
|
-
reseeded: true
|
|
2053
|
-
};
|
|
2054
|
-
const revision = room.revision;
|
|
2055
|
-
const loaded = await room.resolved.adapter.load(room.context);
|
|
2056
|
-
if (room.dirty || room.revision !== revision) return {
|
|
2057
|
-
digest: room.digest,
|
|
2058
|
-
reseeded: false
|
|
2059
|
-
};
|
|
2060
|
-
if (loaded.digest === room.digest) {
|
|
2061
|
-
refreshFields(room, loadedFields(loaded));
|
|
2062
|
-
return {
|
|
2063
|
-
digest: room.digest,
|
|
2064
|
-
reseeded: false
|
|
2065
|
-
};
|
|
2066
|
-
}
|
|
2067
|
-
const reseeded = await reseedRoom(room, "source-changed", loaded, true);
|
|
2068
|
-
return {
|
|
2069
|
-
digest: room.digest,
|
|
2070
|
-
reseeded
|
|
2071
|
-
};
|
|
2072
|
-
}
|
|
2073
|
-
/**
|
|
2074
|
-
* Refreshes an open room without unsaved edits. A dirty room finds the outside change at its next save. With a bus,
|
|
2075
|
-
* the rooms of the other instances refresh too, unless the call came from the bus.
|
|
2076
|
-
*/
|
|
2077
|
-
async function refreshOpenRoom(definitionName, documentId, fanOut = true) {
|
|
2078
|
-
const key = realtimeRoomKey(definitionName, documentId);
|
|
2079
|
-
if (fanOut) await (await sharedBus().catch(() => void 0))?.publish({
|
|
2080
|
-
type: "refresh",
|
|
2081
|
-
room: key,
|
|
2082
|
-
epoch: "",
|
|
2083
|
-
data: /* @__PURE__ */ new Uint8Array()
|
|
2084
|
-
}).catch(() => {});
|
|
2085
|
-
const pending = rooms.get(key);
|
|
2086
|
-
const room = pending ? await pending.catch(() => void 0) : void 0;
|
|
2087
|
-
if (!room || room.kind !== "document" || room.destroyed) return false;
|
|
2088
|
-
return await enqueue(room, async () => !room.dirty && (await refreshRoom(room)).reseeded);
|
|
2089
|
-
}
|
|
2090
|
-
localRefreshers().add(new WeakRef(refreshOpenRoom));
|
|
2091
|
-
/** Requests that wait for a browser's answer, by request id, with the id of the peer that must answer. */
|
|
2092
|
-
const pendingRequests = /* @__PURE__ */ new Map();
|
|
2093
|
-
/**
|
|
2094
|
-
* The browsers in a room. Inside a Durable Object they come from its sockets and their crossws attachment (`i` is the
|
|
2095
|
-
* peer id, `t` the subscribed channels), which outlive hibernation; elsewhere from the open room.
|
|
2096
|
-
*/
|
|
2097
|
-
function requestTargets(key, durable) {
|
|
2098
|
-
const channel = `vitehub:realtime:${key}`;
|
|
2099
|
-
if (durable) return durable.getWebSockets().flatMap((socket) => {
|
|
2100
|
-
const state = socket.deserializeAttachment();
|
|
2101
|
-
if (!state || typeof state !== "object" || !("i" in state) || typeof state.i !== "string" || !("t" in state)) return [];
|
|
2102
|
-
const topics = state.t;
|
|
2103
|
-
return topics instanceof Set && topics.has(channel) ? [{
|
|
2104
|
-
id: state.i,
|
|
2105
|
-
send: (frame) => socket.send(frame)
|
|
2106
|
-
}] : [];
|
|
2107
|
-
});
|
|
2108
|
-
const room = openRooms.get(key);
|
|
2109
|
-
return room ? [...room.peers].map((peer) => ({
|
|
2110
|
-
id: peer.id,
|
|
2111
|
-
send: (frame) => peer.send(frame)
|
|
2112
|
-
})) : [];
|
|
2113
|
-
}
|
|
2114
|
-
/** Asks the one browser in a room of this process or Durable Object. `requestRealtimeRoom()` calls it. */
|
|
2115
|
-
async function requestRoom(definitionName, documentId, body, ask, durable) {
|
|
2116
|
-
let definition;
|
|
2117
|
-
try {
|
|
2118
|
-
definition = await getDefinition(definitionName);
|
|
2119
|
-
} catch {
|
|
2120
|
-
return roomRequestError("REALTIME_ROOM_REQUESTS_OFF", { definition: definitionName });
|
|
2121
|
-
}
|
|
2122
|
-
if (definition.document !== false || definition.requests !== true) return roomRequestError("REALTIME_ROOM_REQUESTS_OFF", { definition: definitionName });
|
|
2123
|
-
if (definition.scope === "user" && ask.user === void 0) return roomRequestError("REALTIME_ROOM_REFUSED", { reason: `the Definition "${definitionName}" keeps a room per person, so the request must name one with { user }.` });
|
|
2124
|
-
const key = realtimeRoomKey(definitionName, documentId, roomScope(definition, ask.user ?? null));
|
|
2125
|
-
const deadline = Date.now() + ask.wait;
|
|
2126
|
-
let targets = requestTargets(key, durable);
|
|
2127
|
-
while (targets.length !== 1 && Date.now() < deadline && !ask.signal?.aborted) {
|
|
2128
|
-
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
2129
|
-
targets = requestTargets(key, durable);
|
|
2130
|
-
}
|
|
2131
|
-
if (ask.signal?.aborted) return roomRequestError("REALTIME_ROOM_ABORTED");
|
|
2132
|
-
if (targets.length > 1) return roomRequestError("REALTIME_ROOM_CROWDED", { count: targets.length });
|
|
2133
|
-
const target = targets[0];
|
|
2134
|
-
if (!target) return roomRequestError(options.bus ? "REALTIME_ROOM_ELSEWHERE" : "REALTIME_ROOM_EMPTY");
|
|
2135
|
-
const id = crypto.randomUUID();
|
|
2136
|
-
return await new Promise((resolve) => {
|
|
2137
|
-
const finish = (result) => {
|
|
2138
|
-
clearTimeout(timer);
|
|
2139
|
-
ask.signal?.removeEventListener("abort", abort);
|
|
2140
|
-
pendingRequests.delete(id);
|
|
2141
|
-
resolve(result);
|
|
2142
|
-
};
|
|
2143
|
-
const abort = () => finish(roomRequestError("REALTIME_ROOM_ABORTED"));
|
|
2144
|
-
const timer = setTimeout(() => finish(roomRequestError("REALTIME_ROOM_TIMEOUT", { timeout: ask.timeout })), ask.timeout);
|
|
2145
|
-
ask.signal?.addEventListener("abort", abort, { once: true });
|
|
2146
|
-
pendingRequests.set(id, {
|
|
2147
|
-
peer: target.id,
|
|
2148
|
-
settle: finish
|
|
2149
|
-
});
|
|
2150
|
-
try {
|
|
2151
|
-
target.send(encodeRealtimeRequestFrame({
|
|
2152
|
-
kind: "request",
|
|
2153
|
-
id,
|
|
2154
|
-
body
|
|
2155
|
-
}));
|
|
2156
|
-
} catch {
|
|
2157
|
-
finish(roomRequestError("REALTIME_ROOM_EMPTY"));
|
|
2158
|
-
}
|
|
2159
|
-
});
|
|
2160
|
-
}
|
|
2161
|
-
localRequesters().add(new WeakRef(requestRoom));
|
|
2162
|
-
/** Settles the request that a browser's answer frame names, when that browser is the one asked. */
|
|
2163
|
-
function settleRequest(peer, data) {
|
|
2164
|
-
const decoder = decoding.createDecoder(data);
|
|
2165
|
-
let frame;
|
|
2166
|
-
try {
|
|
2167
|
-
decoding.readVarUint(decoder);
|
|
2168
|
-
frame = decodeRealtimeRequestFramePayload(decoder);
|
|
2169
|
-
} catch {
|
|
2170
|
-
return;
|
|
2171
|
-
}
|
|
2172
|
-
if (frame?.kind !== "answer") return;
|
|
2173
|
-
const pending = pendingRequests.get(frame.id);
|
|
2174
|
-
if (!pending || pending.peer !== peer.id) return;
|
|
2175
|
-
pending.settle(frame.ok ? [void 0, frame.body] : roomRequestError("REALTIME_ROOM_REFUSED", { reason: frame.why }));
|
|
2176
|
-
}
|
|
2177
|
-
const restoredPeerHandler = defineWebSocketHandler({ message(peer, message) {
|
|
2178
|
-
const data = message.uint8Array();
|
|
2179
|
-
if (data[0] === 6 && data.byteLength <= maxMessageBytes) settleRequest(peer, data);
|
|
2180
|
-
} });
|
|
2181
|
-
/** The browser asked has left: its requests fail now instead of at their timeout. */
|
|
2182
|
-
function settleRequestsOf(peer) {
|
|
2183
|
-
for (const pending of pendingRequests.values()) if (pending.peer === peer.id) pending.settle(roomRequestError("REALTIME_ROOM_EMPTY"));
|
|
2184
|
-
}
|
|
2185
|
-
async function checkpointRoom(room, user) {
|
|
2186
|
-
const { adapter, definition } = room.resolved;
|
|
2187
|
-
const configured = definition.history?.checkpoint;
|
|
2188
|
-
const saved = await saveRoom(room, "request", true);
|
|
2189
|
-
if (!saved.digest) throw realtimeErrorDiagnostics.REALTIME_MISSING_DIGEST({ operation: "checkpoint" });
|
|
2190
|
-
let snapshot;
|
|
2191
|
-
try {
|
|
2192
|
-
snapshot = await adapter.checkpoint(room.context, {
|
|
2193
|
-
digest: saved.digest,
|
|
2194
|
-
message: configured === true ? void 0 : configured?.message,
|
|
2195
|
-
user: user ?? void 0
|
|
2196
|
-
});
|
|
2197
|
-
} catch (error) {
|
|
2198
|
-
if (!isRealtimeDocumentConflict(error) && !isWorkspaceConflict(error)) throw error;
|
|
2199
|
-
await reseedRoom(room, "source-changed");
|
|
2200
|
-
throw new HTTPError({
|
|
2201
|
-
status: 409,
|
|
2202
|
-
message: "The stored document changed while checkpointing. The room was re-seeded.",
|
|
2203
|
-
data: { code: realtimeSourceChangedCode }
|
|
2204
|
-
});
|
|
2205
|
-
}
|
|
2206
|
-
return {
|
|
2207
|
-
...saved,
|
|
2208
|
-
digest: saved.digest,
|
|
2209
|
-
snapshot
|
|
2210
|
-
};
|
|
2211
|
-
}
|
|
2212
|
-
async function requestContext(event) {
|
|
2213
|
-
const { definitionName, documentId, searchParams, workspaceEvents } = parseRoomPath(event.req.url);
|
|
2214
|
-
const definition = await getDefinition(definitionName);
|
|
2215
|
-
const resolved = definition.document === false ? void 0 : resolveRealtimeDefinition(definition);
|
|
2216
|
-
const user = await identify(event.req, event, definitionName, definition);
|
|
2217
|
-
const access = (mode, id = workspaceEvents ? null : documentId) => allows(definition, {
|
|
2218
|
-
definition: definitionName,
|
|
2219
|
-
documentId: id,
|
|
2220
|
-
event,
|
|
2221
|
-
mode,
|
|
2222
|
-
request: event.req,
|
|
2223
|
-
user
|
|
2224
|
-
});
|
|
2225
|
-
return {
|
|
2226
|
-
access,
|
|
2227
|
-
definitionName,
|
|
2228
|
-
documentId,
|
|
2229
|
-
resolved,
|
|
2230
|
-
scope: roomScope(definition, user?.id ?? null),
|
|
2231
|
-
searchParams,
|
|
2232
|
-
user,
|
|
2233
|
-
workspaceEvents
|
|
2234
|
-
};
|
|
2235
|
-
}
|
|
2236
|
-
const httpHandler = defineEventHandler(async (event) => {
|
|
2237
|
-
const url = new URL(event.req.url);
|
|
2238
|
-
const action = url.searchParams.get("history") === "checkpoint" ? "checkpoint" : url.searchParams.get("document");
|
|
2239
|
-
if (event.req.method !== "POST" || action !== "checkpoint" && action !== "save" && action !== "refresh") throw new HTTPError({ status: 405 });
|
|
2240
|
-
const request = await requestContext(event);
|
|
2241
|
-
if (request.workspaceEvents) throw new HTTPError({
|
|
2242
|
-
status: 400,
|
|
2243
|
-
message: "Workspace events have no document to save."
|
|
2244
|
-
});
|
|
2245
|
-
const resolved = request.resolved;
|
|
2246
|
-
if (!resolved) throw new HTTPError({
|
|
2247
|
-
status: 404,
|
|
2248
|
-
message: "This Realtime Definition has no document."
|
|
2249
|
-
});
|
|
2250
|
-
if (action === "checkpoint" && !resolved.definition.history?.checkpoint) throw new HTTPError({ status: 404 });
|
|
2251
|
-
if (!await request.access("read") || action !== "refresh" && !await request.access("write")) throw new HTTPError({ status: request.user ? 403 : 401 });
|
|
2252
|
-
const state = action === "refresh" ? void 0 : await readRealtimeRequestState(event.req);
|
|
2253
|
-
if (state && !state.byteLength) throw new HTTPError({
|
|
2254
|
-
status: 400,
|
|
2255
|
-
message: "Realtime document state is required."
|
|
2256
|
-
});
|
|
2257
|
-
const room = await getDocumentRoom(request.definitionName, request.documentId, resolved, resolveRealtimeRoomSql(event));
|
|
2258
|
-
if (action === "refresh") return await enqueue(room, async () => room.dirty ? {
|
|
2259
|
-
digest: room.digest,
|
|
2260
|
-
reseeded: false
|
|
2261
|
-
} : refreshRoom(room));
|
|
2262
|
-
return await enqueue(room, async () => {
|
|
2263
|
-
if (!containsRealtimeState(room.document, state)) throw new HTTPError({
|
|
2264
|
-
status: 409,
|
|
2265
|
-
message: "The realtime document is still syncing.",
|
|
2266
|
-
data: { code: realtimeSyncPendingCode }
|
|
2267
|
-
});
|
|
2268
|
-
return action === "save" ? await saveRoom(room, "request", true) : await checkpointRoom(room, request.user);
|
|
2269
|
-
});
|
|
2270
|
-
});
|
|
2271
|
-
const websocketHandler = defineWebSocketHandler(async (event) => {
|
|
2272
|
-
const request = await requestContext(event);
|
|
2273
|
-
if (!await request.access("read")) throw new HTTPError({ status: request.user ? 403 : 401 });
|
|
2274
|
-
const writable = !request.workspaceEvents && !!request.resolved && await request.access("write");
|
|
2275
|
-
const identity = request.user ? createRealtimeIdentity({ ...request.user }) : void 0;
|
|
2276
|
-
const room = request.workspaceEvents ? await getEventsRoom(JSON.stringify([request.definitionName, { workspaceEvents: true }]), true, void 0) : request.resolved ? await getDocumentRoom(request.definitionName, request.documentId, request.resolved, resolveRealtimeRoomSql(event)) : await getEventsRoom(realtimeRoomKey(request.definitionName, request.documentId, request.scope), false, resolveRealtimeRoomSql(event));
|
|
2277
|
-
const clientEpoch = request.searchParams.get("epoch");
|
|
2278
|
-
const otherEditor = room.kind === "document" && request.searchParams.get("editor") !== (room.editor.version ?? null);
|
|
2279
|
-
const clientId = request.searchParams.get("clientId");
|
|
2280
|
-
const awarenessClient = clientId !== null && /^\d+$/.test(clientId) && Number.isSafeInteger(Number(clientId)) ? Number(clientId) : void 0;
|
|
2281
|
-
function leave(peer) {
|
|
2282
|
-
settleRequestsOf(peer);
|
|
2283
|
-
if (terminalPeers.has(peer)) clearHeldUpdates(peer);
|
|
2284
|
-
else applyHeldUpdates(peer);
|
|
2285
|
-
if (!room.peers.delete(peer)) return;
|
|
2286
|
-
const pendingAwareness = peerPendingAwareness.get(peer);
|
|
2287
|
-
if (pendingAwareness) clearTimeout(pendingAwareness.timer);
|
|
2288
|
-
peerPendingAwareness.delete(peer);
|
|
2289
|
-
const clients = room.awarenessOwners.release(peer);
|
|
2290
|
-
if (clients.length) {
|
|
2291
|
-
awarenessProtocol.removeAwarenessStates(room.awareness, clients, peer);
|
|
2292
|
-
const known = knownAwarenessClients(room.awareness, clients);
|
|
2293
|
-
if (known.length) {
|
|
2294
|
-
const update = awarenessProtocol.encodeAwarenessUpdate(room.awareness, known);
|
|
2295
|
-
peer.publish(room.channel, encodeAwareness(update));
|
|
2296
|
-
publish(room, "awareness", update);
|
|
2297
|
-
}
|
|
2298
|
-
room.awareness = compactRealtimeAwareness(room.awareness);
|
|
2299
|
-
watchAwareness(room);
|
|
2300
|
-
}
|
|
2301
|
-
peer.unsubscribe(room.channel);
|
|
2302
|
-
if (room.kind === "document" && room.writers.delete(peer) && room.held) {
|
|
2303
|
-
if (room.writers.size === 0) releaseHold(room);
|
|
2304
|
-
else holdRoom(room);
|
|
2305
|
-
return;
|
|
2306
|
-
}
|
|
2307
|
-
if (room.kind === "document" && room.peers.size === 0 && room.dirty && room.resolved.persistence) {
|
|
2308
|
-
enqueue(room, () => saveRoom(room, "leave", false)).catch(() => {});
|
|
2309
|
-
return;
|
|
2310
|
-
}
|
|
2311
|
-
releaseRoom(room);
|
|
2312
|
-
}
|
|
2313
|
-
function applyDocumentMessage(peer, data) {
|
|
2314
|
-
if (room.kind !== "document") return;
|
|
2315
|
-
try {
|
|
2316
|
-
const readOnly = room.guard.readOnly ? readOnlyDocumentRejection : !writable || otherEditor;
|
|
2317
|
-
const response = applyRealtimeSyncMessage(data, room.document, peer, { readOnly });
|
|
2318
|
-
if (response) peer.send(response);
|
|
2319
|
-
} catch (error) {
|
|
2320
|
-
if (isWriteRejected(error) && otherEditor) return;
|
|
2321
|
-
if (isWriteRejected(error)) peer.close(realtimeForbiddenWriteCloseCode, error.message);
|
|
2322
|
-
else peer.close(4400, "Realtime document exceeds its 8 MiB room quota.");
|
|
2323
|
-
}
|
|
2324
|
-
}
|
|
2325
|
-
function refillUpdates(peer) {
|
|
2326
|
-
const now = Date.now();
|
|
2327
|
-
const bucket = peerSyncUpdates.get(peer) ?? {
|
|
2328
|
-
at: now,
|
|
2329
|
-
tokens: syncUpdateBurst
|
|
2330
|
-
};
|
|
2331
|
-
bucket.tokens = Math.min(syncUpdateBurst, bucket.tokens + (now - bucket.at) * syncUpdatesPerSecond / 1e3);
|
|
2332
|
-
bucket.at = now;
|
|
2333
|
-
peerSyncUpdates.set(peer, bucket);
|
|
2334
|
-
return bucket;
|
|
2335
|
-
}
|
|
2336
|
-
function holdUpdate(peer, update, bucket) {
|
|
2337
|
-
const held = peerHeldUpdates.get(peer);
|
|
2338
|
-
const bytes = (held?.bytes ?? 0) + update.byteLength;
|
|
2339
|
-
if (bytes > maxMessageBytes) {
|
|
2340
|
-
terminalPeers.add(peer);
|
|
2341
|
-
clearHeldUpdates(peer);
|
|
2342
|
-
peer.close(1013, "Realtime updates are arriving too quickly.");
|
|
2343
|
-
return;
|
|
2344
|
-
}
|
|
2345
|
-
if (held) {
|
|
2346
|
-
held.updates.push(update);
|
|
2347
|
-
held.bytes = bytes;
|
|
2348
|
-
return;
|
|
2349
|
-
}
|
|
2350
|
-
const wait = Math.ceil((1 - bucket.tokens) * 1e3 / syncUpdatesPerSecond);
|
|
2351
|
-
peerHeldUpdates.set(peer, {
|
|
2352
|
-
bytes,
|
|
2353
|
-
timer: setTimeout(() => applyHeldUpdates(peer), wait),
|
|
2354
|
-
updates: [update]
|
|
2355
|
-
});
|
|
2356
|
-
}
|
|
2357
|
-
/** Applies the updates a peer sent past its budget as one merged update, for one token. */
|
|
2358
|
-
function applyHeldUpdates(peer) {
|
|
2359
|
-
if (terminalPeers.has(peer)) {
|
|
2360
|
-
clearHeldUpdates(peer);
|
|
2361
|
-
return;
|
|
2362
|
-
}
|
|
2363
|
-
const held = peerHeldUpdates.get(peer);
|
|
2364
|
-
if (!held) return;
|
|
2365
|
-
peerHeldUpdates.delete(peer);
|
|
2366
|
-
clearTimeout(held.timer);
|
|
2367
|
-
const bucket = refillUpdates(peer);
|
|
2368
|
-
bucket.tokens = Math.max(0, bucket.tokens - 1);
|
|
2369
|
-
applyDocumentMessage(peer, encodeSyncUpdate(held.updates.length === 1 ? held.updates[0] : Y.mergeUpdates(held.updates)));
|
|
2370
|
-
}
|
|
2371
|
-
function applyAwareness(peer, input) {
|
|
2372
|
-
let clients;
|
|
2373
|
-
try {
|
|
2374
|
-
clients = room.awarenessOwners.apply(room.awareness, peer, input, identity);
|
|
2375
|
-
} catch (error) {
|
|
2376
|
-
peer.close(error instanceof AwarenessOwnershipConflict ? 4500 : 4400, "Invalid awareness update.");
|
|
2377
|
-
return;
|
|
2378
|
-
}
|
|
2379
|
-
const known = knownAwarenessClients(room.awareness, clients);
|
|
2380
|
-
if (!known.length) return;
|
|
2381
|
-
const update = awarenessProtocol.encodeAwarenessUpdate(room.awareness, known);
|
|
2382
|
-
peer.publish(room.channel, encodeAwareness(update));
|
|
2383
|
-
publish(room, "awareness", update);
|
|
2384
|
-
}
|
|
2385
|
-
return {
|
|
2386
|
-
open(peer) {
|
|
2387
|
-
if (room.kind === "document") {
|
|
2388
|
-
if (clientEpoch && clientEpoch !== room.epoch) {
|
|
2389
|
-
peer.send(encodeRealtimeControl({
|
|
2390
|
-
type: "reset",
|
|
2391
|
-
epoch: room.epoch,
|
|
2392
|
-
reason: "stale"
|
|
2393
|
-
}));
|
|
2394
|
-
peer.close(realtimeResetCloseCode, "The realtime document was re-seeded.");
|
|
2395
|
-
releaseRoom(room);
|
|
2396
|
-
return;
|
|
2397
|
-
}
|
|
2398
|
-
if (request.user) room.peerUsers.set(peer, request.user);
|
|
2399
|
-
}
|
|
2400
|
-
room.peers.add(peer);
|
|
2401
|
-
peer.subscribe(room.channel);
|
|
2402
|
-
if (awarenessClient !== void 0 && room.awarenessOwners.claim(room.awareness, peer, awarenessClient, identity)) {
|
|
2403
|
-
const claim = encoding.createEncoder();
|
|
2404
|
-
encoding.writeVarUint(claim, awarenessClient);
|
|
2405
|
-
publish(room, "claim", encoding.toUint8Array(claim));
|
|
2406
|
-
}
|
|
2407
|
-
if (room.kind === "document") {
|
|
2408
|
-
const reason = room.guard.readOnly ? "document" : !writable ? "access" : otherEditor ? "version" : void 0;
|
|
2409
|
-
peer.send(encodeRealtimeControl(reason ? {
|
|
2410
|
-
type: "session",
|
|
2411
|
-
access: "read",
|
|
2412
|
-
epoch: room.epoch,
|
|
2413
|
-
reason
|
|
2414
|
-
} : {
|
|
2415
|
-
type: "session",
|
|
2416
|
-
access: "write",
|
|
2417
|
-
epoch: room.epoch
|
|
2418
|
-
}));
|
|
2419
|
-
if (!reason) {
|
|
2420
|
-
room.writers.add(peer);
|
|
2421
|
-
holdRoom(room);
|
|
2422
|
-
}
|
|
2423
|
-
}
|
|
2424
|
-
peer.send(encodeSyncStep1(room.document));
|
|
2425
|
-
const clients = [...room.awareness.getStates().keys()];
|
|
2426
|
-
if (clients.length) peer.send(encodeAwarenessState(room.awareness, clients));
|
|
2427
|
-
},
|
|
2428
|
-
message(peer, message) {
|
|
2429
|
-
const data = message.uint8Array();
|
|
2430
|
-
if (data[0] === 6) {
|
|
2431
|
-
if (data.byteLength <= maxMessageBytes) settleRequest(peer, data);
|
|
2432
|
-
return;
|
|
2433
|
-
}
|
|
2434
|
-
if (!room.peers.has(peer)) return;
|
|
2435
|
-
if (data.byteLength === keepalivePing.byteLength && data.every((byte, index) => byte === keepalivePing[index])) {
|
|
2436
|
-
peer.send(realtimeKeepalivePong);
|
|
2437
|
-
return;
|
|
2438
|
-
}
|
|
2439
|
-
if (data.byteLength > maxMessageBytes) {
|
|
2440
|
-
peer.close(4400, "Realtime message exceeds 1 MiB.");
|
|
2441
|
-
return;
|
|
2442
|
-
}
|
|
2443
|
-
const decoder = decoding.createDecoder(data);
|
|
2444
|
-
let messageType;
|
|
2445
|
-
try {
|
|
2446
|
-
messageType = decoding.readVarUint(decoder);
|
|
2447
|
-
} catch {
|
|
2448
|
-
peer.close(4400, "Invalid realtime message.");
|
|
2449
|
-
return;
|
|
2450
|
-
}
|
|
2451
|
-
if (messageType === 4) {
|
|
2452
|
-
if (room.kind !== "events" || !room.workspace) {
|
|
2453
|
-
peer.close(4400, "Workspace changes require the workspace room.");
|
|
2454
|
-
return;
|
|
2455
|
-
}
|
|
2456
|
-
let change;
|
|
2457
|
-
try {
|
|
2458
|
-
change = decodeWorkspaceChangePayload(decoder);
|
|
2459
|
-
} catch {
|
|
2460
|
-
peer.close(4400, "Invalid workspace change.");
|
|
2461
|
-
return;
|
|
2462
|
-
}
|
|
2463
|
-
if (!change) {
|
|
2464
|
-
peer.close(4400, "Invalid workspace change.");
|
|
2465
|
-
return;
|
|
2466
|
-
}
|
|
2467
|
-
const now = Date.now();
|
|
2468
|
-
let quota = peerWorkspaceChanges.get(peer);
|
|
2469
|
-
if (!quota || now - quota.startedAt >= workspaceChangeWindowMs) {
|
|
2470
|
-
quota = {
|
|
2471
|
-
count: 0,
|
|
2472
|
-
startedAt: now
|
|
2473
|
-
};
|
|
2474
|
-
peerWorkspaceChanges.set(peer, quota);
|
|
2475
|
-
}
|
|
2476
|
-
quota.count++;
|
|
2477
|
-
if (quota.count > workspaceChangeLimit) {
|
|
2478
|
-
peer.close(4429, "Workspace change rate limit exceeded.");
|
|
2479
|
-
return;
|
|
2480
|
-
}
|
|
2481
|
-
const frame = encodeWorkspaceChange(change);
|
|
2482
|
-
peer.publish(room.channel, frame);
|
|
2483
|
-
publish(room, "frame", frame);
|
|
2484
|
-
return;
|
|
2485
|
-
}
|
|
2486
|
-
if (messageType === 3) {
|
|
2487
|
-
const now = Date.now();
|
|
2488
|
-
const previous = peerAwarenessQueryAt.get(peer);
|
|
2489
|
-
if (previous !== void 0 && now - previous < awarenessQueryIntervalMs) return;
|
|
2490
|
-
peerAwarenessQueryAt.set(peer, now);
|
|
2491
|
-
const clients = [...room.awareness.getStates().keys()];
|
|
2492
|
-
if (clients.length) peer.send(encodeAwarenessState(room.awareness, clients));
|
|
2493
|
-
return;
|
|
2494
|
-
}
|
|
2495
|
-
if (messageType === 1) {
|
|
2496
|
-
let update;
|
|
2497
|
-
try {
|
|
2498
|
-
update = decoding.readVarUint8Array(decoder);
|
|
2499
|
-
} catch {
|
|
2500
|
-
peer.close(4400, "Invalid awareness update.");
|
|
2501
|
-
return;
|
|
2502
|
-
}
|
|
2503
|
-
const now = Date.now();
|
|
2504
|
-
const previous = peerAwarenessUpdateAt.get(peer);
|
|
2505
|
-
if (previous !== void 0 && now - previous < awarenessUpdateIntervalMs) {
|
|
2506
|
-
const pending = peerPendingAwareness.get(peer);
|
|
2507
|
-
if (pending) pending.update = update;
|
|
2508
|
-
else {
|
|
2509
|
-
const next = {
|
|
2510
|
-
timer: setTimeout(() => {
|
|
2511
|
-
peerPendingAwareness.delete(peer);
|
|
2512
|
-
peerAwarenessUpdateAt.set(peer, Date.now());
|
|
2513
|
-
if (room.peers.has(peer)) applyAwareness(peer, next.update);
|
|
2514
|
-
}, awarenessUpdateIntervalMs - (now - previous)),
|
|
2515
|
-
update
|
|
2516
|
-
};
|
|
2517
|
-
peerPendingAwareness.set(peer, next);
|
|
2518
|
-
}
|
|
2519
|
-
return;
|
|
2520
|
-
}
|
|
2521
|
-
peerAwarenessUpdateAt.set(peer, now);
|
|
2522
|
-
applyAwareness(peer, update);
|
|
2523
|
-
return;
|
|
2524
|
-
}
|
|
2525
|
-
if (messageType !== messageSync) return;
|
|
2526
|
-
try {
|
|
2527
|
-
const syncType = decoding.readVarUint(decoder);
|
|
2528
|
-
if (room.kind === "events") {
|
|
2529
|
-
if (syncType === syncProtocol.messageYjsSyncStep1) {
|
|
2530
|
-
const response = applyRealtimeSyncMessage(data, room.document, peer);
|
|
2531
|
-
if (response) peer.send(response);
|
|
2532
|
-
} else if (syncType !== syncProtocol.messageYjsSyncStep2) peer.close(4400, room.workspace ? "Document updates cannot use the workspace room." : "This Realtime Definition has no document.");
|
|
2533
|
-
return;
|
|
2534
|
-
}
|
|
2535
|
-
if (syncType === syncProtocol.messageYjsSyncStep2 && !peerInitialSyncStep2.has(peer)) peerInitialSyncStep2.add(peer);
|
|
2536
|
-
else if (syncType === syncProtocol.messageYjsSyncStep2 || syncType === syncProtocol.messageYjsUpdate) {
|
|
2537
|
-
const bucket = refillUpdates(peer);
|
|
2538
|
-
if (peerHeldUpdates.has(peer) || bucket.tokens < 1) {
|
|
2539
|
-
holdUpdate(peer, decoding.readVarUint8Array(decoder), bucket);
|
|
2540
|
-
return;
|
|
2541
|
-
}
|
|
2542
|
-
bucket.tokens--;
|
|
2543
|
-
}
|
|
2544
|
-
applyDocumentMessage(peer, data);
|
|
2545
|
-
} catch {
|
|
2546
|
-
peer.close(4400, "Invalid realtime message.");
|
|
2547
|
-
}
|
|
2548
|
-
},
|
|
2549
|
-
close(peer) {
|
|
2550
|
-
leave(peer);
|
|
2551
|
-
},
|
|
2552
|
-
error(peer) {
|
|
2553
|
-
leave(peer);
|
|
2554
|
-
}
|
|
2555
|
-
};
|
|
2556
|
-
});
|
|
2557
|
-
return defineEventHandler(async (event) => {
|
|
2558
|
-
const forwarded = await forwardToCloudflareDurableObject(event);
|
|
2559
|
-
if (forwarded) return forwarded;
|
|
2560
|
-
if (event.req.headers.has(internalRefreshHeader) && resolveRealtimeRoomSql(event)) {
|
|
2561
|
-
const { definitionName, documentId } = parseRoomPath(event.req.url);
|
|
2562
|
-
return { reseeded: await refreshOpenRoom(definitionName, documentId) };
|
|
2563
|
-
}
|
|
2564
|
-
if (event.req.headers.has("x-vitehub-realtime-request") && resolveRealtimeRoomSql(event)) {
|
|
2565
|
-
const { definitionName, documentId } = parseRoomPath(event.req.url);
|
|
2566
|
-
const input = await event.req.json().catch(() => void 0);
|
|
2567
|
-
const field = (name) => input && typeof input === "object" && name in input ? input[name] : void 0;
|
|
2568
|
-
const timeout = field("timeout");
|
|
2569
|
-
const wait = field("wait");
|
|
2570
|
-
const user = field("user");
|
|
2571
|
-
const context = resolveCloudflare(event)?.context;
|
|
2572
|
-
return toDurableRequestReply(await requestRoom(definitionName, documentId, field("body"), {
|
|
2573
|
-
timeout: typeof timeout === "number" && timeout > 0 ? timeout : defaultRequestTimeout,
|
|
2574
|
-
wait: typeof wait === "number" && wait >= 0 ? wait : defaultRequestWait,
|
|
2575
|
-
...typeof user === "string" || user === null ? { user } : {}
|
|
2576
|
-
}, isDurableSockets(context) ? context : void 0));
|
|
2577
|
-
}
|
|
2578
|
-
if (event.req.method === "GET" && isBareRequest(event.req)) return restoredPeerHandler(event);
|
|
2579
|
-
if (event.req.headers.get("upgrade")?.toLowerCase() !== "websocket") return httpHandler(event);
|
|
2580
|
-
try {
|
|
2581
|
-
return await websocketHandler(event);
|
|
2582
|
-
} catch (error) {
|
|
2583
|
-
return refuseUpgrade(event.req, error instanceof HTTPError ? error.status : 500);
|
|
2584
|
-
}
|
|
2585
|
-
});
|
|
2586
|
-
}
|
|
2587
|
-
//#endregion
|
|
2588
|
-
export { RealtimeDocumentConflict, applyRealtimeAwarenessUpdate, applyRealtimeSyncMessage, assertRealtimeRoomStateQuota, bindAwarenessIdentity, blobDocument, claimAwarenessClientIds, compactRealtimeAwareness, containsRealtimeState, createRealtimeHandler, createRealtimeYDoc, diffRealtimeYDoc, encodeAwarenessState, encodeSyncStep1, encodeSyncUpdate, isRealtimeAvailable, isRealtimeDocumentConflict, isRealtimeWorkspaceDocument, readRealtimeRequestState, readRealtimeStatus, readRealtimeWorkspaceDocument, readRealtimeYDoc, realtimeDocumentLayout, realtimePersistenceDefaults, realtimeRoomKey, refreshRealtimeDocument, requestRealtimeRoom, resolveRealtimeDefinition, restoreRealtimeDocument, workspaceDocument };
|
|
1
|
+
import { l as requestRealtimeRoom, m as isRealtimeAvailable } from "./request-DM6xHTaU.js";
|
|
2
|
+
import { f as blobDocument, h as workspaceDocument, l as refreshRealtimeDocument, r as createRealtimeHandler } from "./server-yQp02XNp.js";
|
|
3
|
+
export { blobDocument, createRealtimeHandler, isRealtimeAvailable, refreshRealtimeDocument, requestRealtimeRoom, workspaceDocument };
|