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