@brass-build/client 0.1.0 → 0.2.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/AGENTS.md +72 -63
- package/CHANGELOG.md +86 -0
- package/README.md +317 -231
- package/dist/auth-flow.d.ts +10 -1
- package/dist/auth-flow.d.ts.map +1 -1
- package/dist/auth-flow.js +64 -20
- package/dist/auth-flow.js.map +1 -1
- package/dist/client.d.ts +3 -0
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +217 -75
- package/dist/client.js.map +1 -1
- package/dist/document-engine.d.ts +4 -0
- package/dist/document-engine.d.ts.map +1 -0
- package/dist/document-engine.js +9 -0
- package/dist/document-engine.js.map +1 -0
- package/dist/document-streams.d.ts +8 -1
- package/dist/document-streams.d.ts.map +1 -1
- package/dist/document-streams.js +79 -8
- package/dist/document-streams.js.map +1 -1
- package/dist/documents-namespace.d.ts.map +1 -1
- package/dist/documents-namespace.js +19 -3
- package/dist/documents-namespace.js.map +1 -1
- package/dist/documents.d.ts +43 -14
- package/dist/documents.d.ts.map +1 -1
- package/dist/documents.js +871 -223
- package/dist/documents.js.map +1 -1
- package/dist/embed-protocol.d.ts +3 -0
- package/dist/embed-protocol.d.ts.map +1 -0
- package/dist/embed-protocol.js +26 -0
- package/dist/embed-protocol.js.map +1 -0
- package/dist/emitter.d.ts.map +1 -1
- package/dist/emitter.js +8 -1
- package/dist/emitter.js.map +1 -1
- package/dist/export-guest.d.ts.map +1 -1
- package/dist/export-guest.js +14 -6
- package/dist/export-guest.js.map +1 -1
- package/dist/fetch-deadline.d.ts +22 -0
- package/dist/fetch-deadline.d.ts.map +1 -0
- package/dist/fetch-deadline.js +96 -0
- package/dist/fetch-deadline.js.map +1 -0
- package/dist/fetch-retry.d.ts +1 -0
- package/dist/fetch-retry.d.ts.map +1 -1
- package/dist/fetch-retry.js +12 -5
- package/dist/fetch-retry.js.map +1 -1
- package/dist/handle-types.d.ts +150 -0
- package/dist/handle-types.d.ts.map +1 -0
- package/dist/handle-types.js +8 -0
- package/dist/handle-types.js.map +1 -0
- package/dist/handles.d.ts +48 -48
- package/dist/handles.d.ts.map +1 -1
- package/dist/handles.js +3122 -501
- package/dist/handles.js.map +1 -1
- package/dist/hosted-runtime.d.ts.map +1 -1
- package/dist/hosted-runtime.js +8 -12
- package/dist/hosted-runtime.js.map +1 -1
- package/dist/hosted-ui.d.ts +0 -1
- package/dist/hosted-ui.d.ts.map +1 -1
- package/dist/hosted-ui.js +29 -24
- package/dist/hosted-ui.js.map +1 -1
- package/dist/importer.d.ts.map +1 -1
- package/dist/importer.js +253 -8
- package/dist/importer.js.map +1 -1
- package/dist/index.d.ts +10 -10
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +11 -2
- package/dist/index.js.map +1 -1
- package/dist/internal.d.ts +1 -1
- package/dist/internal.d.ts.map +1 -1
- package/dist/internal.js.map +1 -1
- package/dist/join-coverage.d.ts +12 -0
- package/dist/join-coverage.d.ts.map +1 -0
- package/dist/join-coverage.js +37 -0
- package/dist/join-coverage.js.map +1 -0
- package/dist/jwt.d.ts.map +1 -1
- package/dist/jwt.js +5 -1
- package/dist/jwt.js.map +1 -1
- package/dist/launch-context.js +2 -2
- package/dist/launch-context.js.map +1 -1
- package/dist/mutate-batching.d.ts +25 -2
- package/dist/mutate-batching.d.ts.map +1 -1
- package/dist/mutate-batching.js +57 -10
- package/dist/mutate-batching.js.map +1 -1
- package/dist/open-document.d.ts +15 -1
- package/dist/open-document.d.ts.map +1 -1
- package/dist/open-document.js +1851 -321
- package/dist/open-document.js.map +1 -1
- package/dist/presence.d.ts +28 -0
- package/dist/presence.d.ts.map +1 -1
- package/dist/presence.js +149 -7
- package/dist/presence.js.map +1 -1
- package/dist/record-paging.d.ts +336 -71
- package/dist/record-paging.d.ts.map +1 -1
- package/dist/record-paging.js +591 -127
- package/dist/record-paging.js.map +1 -1
- package/dist/selection-persistence.d.ts.map +1 -1
- package/dist/selection-persistence.js +11 -1
- package/dist/selection-persistence.js.map +1 -1
- package/dist/serializer.d.ts +30 -1
- package/dist/serializer.d.ts.map +1 -1
- package/dist/session-persistence.d.ts.map +1 -1
- package/dist/session-persistence.js +9 -8
- package/dist/session-persistence.js.map +1 -1
- package/dist/session-toolbar.d.ts +0 -1
- package/dist/session-toolbar.d.ts.map +1 -1
- package/dist/session-toolbar.js +226 -75
- package/dist/session-toolbar.js.map +1 -1
- package/dist/session.d.ts.map +1 -1
- package/dist/session.js +87 -18
- package/dist/session.js.map +1 -1
- package/dist/tail-ops.d.ts +14 -4
- package/dist/tail-ops.d.ts.map +1 -1
- package/dist/tail-ops.js +75 -15
- package/dist/tail-ops.js.map +1 -1
- package/dist/topic-lifecycle.d.ts +4 -0
- package/dist/topic-lifecycle.d.ts.map +1 -1
- package/dist/topic-lifecycle.js +25 -1
- package/dist/topic-lifecycle.js.map +1 -1
- package/dist/types.d.ts +47 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/undo.d.ts +2 -3
- package/dist/undo.d.ts.map +1 -1
- package/dist/undo.js +11 -0
- package/dist/undo.js.map +1 -1
- package/dist/unload-guard.d.ts +5 -0
- package/dist/unload-guard.d.ts.map +1 -0
- package/dist/unload-guard.js +88 -0
- package/dist/unload-guard.js.map +1 -0
- package/dist/version-bar.d.ts +4 -3
- package/dist/version-bar.d.ts.map +1 -1
- package/dist/version-bar.js +140 -19
- package/dist/version-bar.js.map +1 -1
- package/dist/version.d.ts +2 -2
- package/dist/version.js +1 -1
- package/dist/vite.d.ts +18 -2
- package/dist/vite.d.ts.map +1 -1
- package/dist/vite.js +133 -8
- package/dist/vite.js.map +1 -1
- package/dist/ws-client.d.ts +23 -3
- package/dist/ws-client.d.ts.map +1 -1
- package/dist/ws-client.js +339 -89
- package/dist/ws-client.js.map +1 -1
- package/dist/ws-frame-limit.d.ts.map +1 -1
- package/dist/ws-frame-limit.js +19 -12
- package/dist/ws-frame-limit.js.map +1 -1
- package/docs/app-manifest.md +7 -8
- package/docs/custom-chrome.md +17 -20
- package/docs/hosted-ui-advanced.md +14 -17
- package/docs/imported-documents.md +53 -197
- package/docs/presence.md +45 -21
- package/docs/schemas.md +12 -17
- package/docs/streams.md +55 -57
- package/package.json +4 -3
- package/src/auth-flow.ts +90 -23
- package/src/client.ts +225 -78
- package/src/document-engine.ts +15 -0
- package/src/document-signals.ts +7 -7
- package/src/document-streams.ts +95 -9
- package/src/documents-namespace.ts +18 -3
- package/src/documents.ts +983 -277
- package/src/embed-protocol.ts +25 -0
- package/src/emitter.ts +8 -1
- package/src/export-guest.ts +15 -9
- package/src/fetch-deadline.ts +119 -0
- package/src/fetch-retry.ts +14 -5
- package/src/handle-types.ts +303 -0
- package/src/handles.ts +3406 -683
- package/src/hosted-runtime.ts +8 -12
- package/src/hosted-ui.ts +28 -32
- package/src/importer.ts +261 -8
- package/src/index.ts +29 -18
- package/src/internal.ts +1 -0
- package/src/join-coverage.ts +42 -0
- package/src/jwt.ts +8 -1
- package/src/launch-context.ts +2 -2
- package/src/mutate-batching.ts +60 -11
- package/src/open-document.ts +2355 -515
- package/src/presence.ts +210 -11
- package/src/record-paging.ts +687 -137
- package/src/selection-persistence.ts +10 -1
- package/src/serializer.ts +33 -1
- package/src/session-persistence.ts +9 -8
- package/src/session-toolbar.ts +249 -80
- package/src/session.ts +91 -17
- package/src/tail-ops.ts +76 -10
- package/src/topic-lifecycle.ts +31 -1
- package/src/types.ts +56 -4
- package/src/undo.ts +13 -5
- package/src/unload-guard.ts +91 -0
- package/src/version-bar.ts +163 -25
- package/src/version.ts +1 -1
- package/src/vite.ts +175 -10
- package/src/ws-client.ts +392 -92
- package/src/ws-frame-limit.ts +19 -12
package/dist/open-document.js
CHANGED
|
@@ -8,21 +8,90 @@ import { createPresenceController } from './presence.js';
|
|
|
8
8
|
import { applyAppAssertionHeader, applyClientVersionHeader } from './api-headers.js';
|
|
9
9
|
import { brassErrorFromBody } from './api-fetch.js';
|
|
10
10
|
import { fetchWithRetry, RETRY_IDEMPOTENT_WRITE } from './fetch-retry.js';
|
|
11
|
+
import { deadlineForUpload, fetchWithDeadline, OP_WRITE_TIMEOUT_MS, } from './fetch-deadline.js';
|
|
11
12
|
import { BrassError } from './errors.js';
|
|
12
13
|
import { perfStart } from './perf.js';
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
14
|
+
import { joinCoverageFloor, snapshotSeqOf } from './join-coverage.js';
|
|
15
|
+
import { declaredTailBytes, resolveTailOps } from './tail-ops.js';
|
|
16
|
+
import { opBlobExceedsDurableLimit, opBlobNeedsStaging, opFrameExceedsWsLimit, } from './ws-frame-limit.js';
|
|
17
|
+
// The terminal frame the platform sends when it clears a document's work
|
|
18
|
+
// status: the work finished and the content is in. The SDK emits the same
|
|
19
|
+
// shape wherever it settles that transition off its own import (a
|
|
20
|
+
// subscribe-time reconcile, a retried pull), so the app cannot tell the two
|
|
21
|
+
// apart. `blocking: false` is what releases the load lock.
|
|
22
|
+
const WORK_READY_STATUS = {
|
|
23
|
+
message: 'Ready',
|
|
24
|
+
pending: false,
|
|
25
|
+
blocking: false,
|
|
26
|
+
};
|
|
27
|
+
const CONTENT_PULL_ATTEMPTS = 5;
|
|
28
|
+
const CONTENT_PULL_BACKOFF_MS = 1000;
|
|
29
|
+
// Pull a document's content in after the platform reports its inbound work
|
|
30
|
+
// finished, retrying a transient fetch failure (a network blip, a dropped
|
|
31
|
+
// presigned download): the platform asserts the content exists, so a silent
|
|
32
|
+
// give-up would leave the doc empty behind a terminal status, reading as "the
|
|
33
|
+
// model never loaded" and invisible in every log. Emits `finalStatus` only
|
|
34
|
+
// once the import lands, so an app re-reading on `onStatus` sees the content.
|
|
35
|
+
// On exhaustion it reports the failure and emits a terminal failure status,
|
|
36
|
+
// which keeps the doc read-only. Returns whether the content is in.
|
|
37
|
+
async function pullContentWithRetry(args) {
|
|
38
|
+
let lastError = null;
|
|
39
|
+
for (let attempt = 1; attempt <= CONTENT_PULL_ATTEMPTS; attempt += 1) {
|
|
40
|
+
try {
|
|
41
|
+
const outcome = await args.fetchAndImport();
|
|
42
|
+
if (outcome.ok) {
|
|
43
|
+
args.doc._emitStatus(args.finalStatus, { contentLoaded: true });
|
|
44
|
+
return true;
|
|
45
|
+
}
|
|
46
|
+
lastError = new Error(outcome.reason);
|
|
47
|
+
}
|
|
48
|
+
catch (err) {
|
|
49
|
+
lastError = err instanceof Error ? err : new Error(String(err));
|
|
50
|
+
}
|
|
51
|
+
// A retrying attempt is exceptional, so this warn is quiet in normal
|
|
52
|
+
// operation and decisive in a bug report; without it a failure here is
|
|
53
|
+
// undiagnosable from any log.
|
|
54
|
+
console.warn(`[Brass] document content reload attempt ${attempt}/${CONTENT_PULL_ATTEMPTS} failed (doc ${args.docId}): ${lastError.message}`);
|
|
55
|
+
if (attempt < CONTENT_PULL_ATTEMPTS) {
|
|
56
|
+
await new Promise((r) => setTimeout(r, CONTENT_PULL_BACKOFF_MS * attempt));
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
const error = new BrassError(`Document content reload failed after ${CONTENT_PULL_ATTEMPTS} attempts: ${lastError?.message ?? 'unknown error'}`, { status: 0 });
|
|
60
|
+
if (args.reportError)
|
|
61
|
+
args.reportError(error);
|
|
62
|
+
else
|
|
63
|
+
console.error('[Brass]', error);
|
|
64
|
+
args.doc._emitStatus({
|
|
65
|
+
message: 'The model could not be loaded. Reload to try again.',
|
|
66
|
+
pending: false,
|
|
67
|
+
// The content never arrived, so this terminal status still locks the
|
|
68
|
+
// doc: an edit here would write into a document holding nothing.
|
|
69
|
+
blocking: true,
|
|
70
|
+
});
|
|
71
|
+
return false;
|
|
72
|
+
}
|
|
15
73
|
// Both join fetches and the `doc_init` frame funnel through this, so a
|
|
16
74
|
// tail op whose bytes spilled to storage is fetched once, here. Every
|
|
17
75
|
// reader downstream then sees the inline shape it already handles, and
|
|
18
76
|
// none of the seq bookkeeping has to learn a second representation.
|
|
19
|
-
async function resolveParsedTailOps(parsed) {
|
|
77
|
+
async function resolveParsedTailOps(parsed, onProgress) {
|
|
20
78
|
if (typeof parsed !== 'object' || parsed === null)
|
|
21
79
|
return;
|
|
22
80
|
const body = parsed;
|
|
23
81
|
if (!Array.isArray(body.tail_ops))
|
|
24
82
|
return;
|
|
25
|
-
|
|
83
|
+
const tailOps = body.tail_ops;
|
|
84
|
+
// The whole download, stated before any of it starts. A presigned snapshot
|
|
85
|
+
// names its decompressed size and each spilled op names its blob's, and both
|
|
86
|
+
// are fetched over the network with a reader waiting, so the load reports one
|
|
87
|
+
// figure against their sum. An inline snapshot contributes nothing: its bytes
|
|
88
|
+
// came with this response.
|
|
89
|
+
const snapshot = body.snapshot;
|
|
90
|
+
const snapshotBytes = typeof snapshot?.raw_bytes === 'number' ? snapshot.raw_bytes : 0;
|
|
91
|
+
const totalBytes = declaredTailBytes(tailOps) + snapshotBytes;
|
|
92
|
+
body.tail_ops = await resolveTailOps(tailOps, fetch, onProgress === undefined
|
|
93
|
+
? undefined
|
|
94
|
+
: (loadedBytes) => onProgress(loadedBytes, totalBytes > 0 ? totalBytes : null, 'tail'));
|
|
26
95
|
}
|
|
27
96
|
// Map the snake_case wire `drive` block to the public camelCase
|
|
28
97
|
// `DocumentDriveStatus`. `canPush` is derived once here (unbroken, two-way,
|
|
@@ -67,37 +136,63 @@ function isDocOpFrame(frame) {
|
|
|
67
136
|
typeof f.op_blob === 'string' &&
|
|
68
137
|
typeof f.seq === 'number');
|
|
69
138
|
}
|
|
70
|
-
|
|
139
|
+
// The frame in the shape its readers act on, or null when it carries nothing
|
|
140
|
+
// they can act on.
|
|
141
|
+
//
|
|
142
|
+
// Gated on the discriminant plus `current_seq`, with the tail degraded entry
|
|
143
|
+
// by entry. Most of what a `doc_init` does is carried by the frame itself
|
|
144
|
+
// rather than by any one entry: `current_seq` is the cursor, the tail's lower
|
|
145
|
+
// edge decides whether the reader re-imports the join, and the frame is the
|
|
146
|
+
// (re)subscribe signal that re-asserts every outstanding op and runs the
|
|
147
|
+
// durability handshake. So an entry whose shape this SDK does not recognise
|
|
148
|
+
// costs the one op it carries, which stays uncovered and is pulled over the
|
|
149
|
+
// HTTP join; refusing the frame over it would cost all of the above.
|
|
150
|
+
//
|
|
151
|
+
// `snapshot_version_vector` is likewise tolerated as absent when it is not a
|
|
152
|
+
// string: the handshake needs a vector it can decode, and skipping the
|
|
153
|
+
// handshake is a smaller loss than dropping the frame that drives it.
|
|
154
|
+
function parseDocInitFrame(frame) {
|
|
71
155
|
if (typeof frame !== 'object' || frame === null)
|
|
72
|
-
return
|
|
156
|
+
return null;
|
|
73
157
|
const f = frame;
|
|
74
158
|
if (f.type !== 'doc_init' || typeof f.topic !== 'string')
|
|
75
|
-
return
|
|
159
|
+
return null;
|
|
76
160
|
if (typeof f.current_seq !== 'number')
|
|
77
|
-
return
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
// an await this reader does not have, and sends `current_seq` alone
|
|
93
|
-
// so the client re-imports the join over HTTP instead. Tolerating
|
|
94
|
-
// the shape anyway keeps such a frame's `current_seq` usable rather
|
|
95
|
-
// than dropping the whole frame and with it the resync trigger.
|
|
96
|
-
if (typeof e.op_blob_b64 !== 'string' && typeof e.op_blob_url !== 'string') {
|
|
97
|
-
return false;
|
|
161
|
+
return null;
|
|
162
|
+
const tailOps = [];
|
|
163
|
+
if (Array.isArray(f.tail_ops)) {
|
|
164
|
+
for (const entry of f.tail_ops) {
|
|
165
|
+
if (typeof entry !== 'object' || entry === null)
|
|
166
|
+
continue;
|
|
167
|
+
const e = entry;
|
|
168
|
+
// The seq is what places an entry in the sequence the cursors and the
|
|
169
|
+
// resync trigger are computed from, so an entry without one is not an
|
|
170
|
+
// entry any reader here can use.
|
|
171
|
+
if (typeof e.seq !== 'number')
|
|
172
|
+
continue;
|
|
173
|
+
tailOps.push(typeof e.op_blob_b64 === 'string'
|
|
174
|
+
? { seq: e.seq, op_blob_b64: e.op_blob_b64 }
|
|
175
|
+
: { seq: e.seq });
|
|
98
176
|
}
|
|
99
177
|
}
|
|
100
|
-
return
|
|
178
|
+
return {
|
|
179
|
+
type: 'doc_init',
|
|
180
|
+
topic: f.topic,
|
|
181
|
+
current_seq: f.current_seq,
|
|
182
|
+
tail_ops: tailOps,
|
|
183
|
+
...(typeof f.snapshot_seq === 'number' ? { snapshot_seq: f.snapshot_seq } : {}),
|
|
184
|
+
...(typeof f.snapshot_version_vector === 'string'
|
|
185
|
+
? { snapshot_version_vector: f.snapshot_version_vector }
|
|
186
|
+
: {}),
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
function isDocCatchUpFrame(frame) {
|
|
190
|
+
if (typeof frame !== 'object' || frame === null)
|
|
191
|
+
return false;
|
|
192
|
+
const f = frame;
|
|
193
|
+
return (f.type === 'doc_catch_up' &&
|
|
194
|
+
typeof f.topic === 'string' &&
|
|
195
|
+
typeof f.current_seq === 'number');
|
|
101
196
|
}
|
|
102
197
|
function isOpAckFrame(frame) {
|
|
103
198
|
if (typeof frame !== 'object' || frame === null)
|
|
@@ -116,6 +211,59 @@ function isOpRejectedFrame(frame) {
|
|
|
116
211
|
typeof f.topic === 'string' &&
|
|
117
212
|
typeof f.client_op_id === 'string');
|
|
118
213
|
}
|
|
214
|
+
// Whether re-sending the same op is the right move. Two statuses refuse to
|
|
215
|
+
// write rather than answer about the op, and both leave the row untouched,
|
|
216
|
+
// so the op is still the client's to send: 503 (the store refused on
|
|
217
|
+
// capacity) and 429 (the caller is over the op-write cap, whose window
|
|
218
|
+
// resets). The WS transport reads its own rate refusal the same way, as an
|
|
219
|
+
// `unavailable` the shed recovery re-asserts, and the two transports carry
|
|
220
|
+
// the same ops, so a refusal cannot mean "later" on one and "never" on the
|
|
221
|
+
// other. Every other status is an answer about the op itself and repeats
|
|
222
|
+
// however many times it is sent.
|
|
223
|
+
function opWriteIsRetryable(status) {
|
|
224
|
+
return status === 503 || status === 429;
|
|
225
|
+
}
|
|
226
|
+
// The HTTP transport's rendering of the same refusal `op_rejected` carries on
|
|
227
|
+
// the socket: the document is full. 507 is the status, and the body's `code`
|
|
228
|
+
// is checked beside it so the classification does not rest on a status a
|
|
229
|
+
// proxy in front of the api could rewrite.
|
|
230
|
+
function isCapacityRefusal(status, parsed) {
|
|
231
|
+
if (status === 507)
|
|
232
|
+
return true;
|
|
233
|
+
return parsed?.code === 'at_capacity';
|
|
234
|
+
}
|
|
235
|
+
// A failure uploading an oversized op's blob to storage. It carries its own
|
|
236
|
+
// type because staging runs strictly BEFORE the op write, so what a replay
|
|
237
|
+
// means differs from a throw out of the write itself: nothing durable exists
|
|
238
|
+
// yet and the op is still the client's to send, where a throw mid-write
|
|
239
|
+
// leaves it unknown whether the row landed.
|
|
240
|
+
class OpStagingError extends Error {
|
|
241
|
+
name = 'OpStagingError';
|
|
242
|
+
// The upstream status, or null for a request that drew no answer at all.
|
|
243
|
+
status;
|
|
244
|
+
constructor(status, message) {
|
|
245
|
+
super(message);
|
|
246
|
+
this.status = status;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
// Whether staging the blob again is the right move: a status the op write
|
|
250
|
+
// itself replays replays here for the same reason, and a request that drew
|
|
251
|
+
// no answer wrote nothing either.
|
|
252
|
+
function opStagingIsRetryable(err) {
|
|
253
|
+
return err.status === null || opWriteIsRetryable(err.status);
|
|
254
|
+
}
|
|
255
|
+
function asOpStagingError(err) {
|
|
256
|
+
if (err instanceof OpStagingError)
|
|
257
|
+
return err;
|
|
258
|
+
const status = err instanceof BrassError ? err.status ?? null : null;
|
|
259
|
+
return new OpStagingError(status, err instanceof Error ? err.message : String(err));
|
|
260
|
+
}
|
|
261
|
+
function isServerUnavailableFrame(frame) {
|
|
262
|
+
if (typeof frame !== 'object' || frame === null)
|
|
263
|
+
return false;
|
|
264
|
+
const f = frame;
|
|
265
|
+
return f.type === 'error' && f.reason === 'unavailable';
|
|
266
|
+
}
|
|
119
267
|
// The message surfaced through the error reporter for a terminal op rejection.
|
|
120
268
|
// Prefers the server's copy; falls back to a generic, actionable line. The
|
|
121
269
|
// local edit already applied but can never persist, so the app's cue is to
|
|
@@ -126,6 +274,40 @@ function opRejectedMessage(frame) {
|
|
|
126
274
|
}
|
|
127
275
|
return 'A change could not be saved and will not be retried. Reload the document to continue.';
|
|
128
276
|
}
|
|
277
|
+
// The one rejection reason that describes the DOCUMENT rather than the op:
|
|
278
|
+
// every later write meets it too, so the app is told once about the document
|
|
279
|
+
// instead of once per refused edit. Matched on the reason string rather than
|
|
280
|
+
// on the message, which is copy and may be reworded.
|
|
281
|
+
const OP_REJECTED_AT_CAPACITY = 'at_capacity';
|
|
282
|
+
// Whether the document refused this write because of its size. The server
|
|
283
|
+
// distinguishes a branch that refuses everything from one that refuses only
|
|
284
|
+
// growth, and picks the wording accordingly; the client does not, because both
|
|
285
|
+
// leave refused work on this copy and nowhere else and the answer to that is
|
|
286
|
+
// the same one.
|
|
287
|
+
function isCapacityRejection(frame) {
|
|
288
|
+
return frame.reason === OP_REJECTED_AT_CAPACITY;
|
|
289
|
+
}
|
|
290
|
+
// Which refusals describe the WRITER rather than the op. The server reads
|
|
291
|
+
// write authority once, when the connection subscribes, so a refusal on
|
|
292
|
+
// either of these grounds answers every later op the same way: the reader
|
|
293
|
+
// cannot write to this document at all, and the Document says so through
|
|
294
|
+
// `readOnly` instead of letting the app offer edits that keep failing. A
|
|
295
|
+
// refusal about the op itself (too large, a bad topic) leaves the document
|
|
296
|
+
// writable, because the next op may well be accepted.
|
|
297
|
+
//
|
|
298
|
+
// A Map rather than an object literal because the key is a wire string: an
|
|
299
|
+
// object answers for the names it inherits, so a reason reading `constructor`
|
|
300
|
+
// or `toString` would resolve a function and lock the document, which is the
|
|
301
|
+
// opposite of what an unclassified refusal means.
|
|
302
|
+
const READ_ONLY_REJECTION_REASONS = new Map([
|
|
303
|
+
['role_denied', 'grant'],
|
|
304
|
+
['scope_denied', 'app'],
|
|
305
|
+
]);
|
|
306
|
+
function readOnlyReasonForRejection(frame) {
|
|
307
|
+
if (typeof frame.reason !== 'string')
|
|
308
|
+
return null;
|
|
309
|
+
return READ_ONLY_REJECTION_REASONS.get(frame.reason) ?? null;
|
|
310
|
+
}
|
|
129
311
|
function isDocGoneFrame(frame) {
|
|
130
312
|
if (typeof frame !== 'object' || frame === null)
|
|
131
313
|
return false;
|
|
@@ -164,6 +346,25 @@ function isDocStatusFrame(frame) {
|
|
|
164
346
|
// unvalidated, so this keeps the WS path from being the stricter of the two.
|
|
165
347
|
return typeof st.pending === 'boolean';
|
|
166
348
|
}
|
|
349
|
+
// `message` is typed non-null and rendered verbatim, while the wire gates
|
|
350
|
+
// only on `pending`, so default it here.
|
|
351
|
+
function normalizeWorkStatus(status) {
|
|
352
|
+
return {
|
|
353
|
+
...status,
|
|
354
|
+
message: typeof status.message === 'string' ? status.message : '',
|
|
355
|
+
};
|
|
356
|
+
}
|
|
357
|
+
// The opaque work status a join response carries, or `null` when it carries
|
|
358
|
+
// none. Gates on `pending` like `isDocStatusFrame`; the rest is display data
|
|
359
|
+
// read defensively at the use site.
|
|
360
|
+
function parseWorkStatus(value) {
|
|
361
|
+
if (typeof value !== 'object' || value === null)
|
|
362
|
+
return null;
|
|
363
|
+
const status = value;
|
|
364
|
+
if (typeof status.pending !== 'boolean')
|
|
365
|
+
return null;
|
|
366
|
+
return normalizeWorkStatus(status);
|
|
367
|
+
}
|
|
167
368
|
function isDocMetaFrame(frame) {
|
|
168
369
|
if (typeof frame !== 'object' || frame === null)
|
|
169
370
|
return false;
|
|
@@ -194,10 +395,10 @@ function isDocOpsDroppedFrame(frame) {
|
|
|
194
395
|
if (typeof frame !== 'object' || frame === null)
|
|
195
396
|
return false;
|
|
196
397
|
const f = frame;
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
398
|
+
// Gate on the discriminant alone. The handler reads no other field, so a
|
|
399
|
+
// frame whose informational half changed shape (or went away) must still
|
|
400
|
+
// prompt the durability re-check it is sent for.
|
|
401
|
+
return f.type === 'doc_ops_dropped' && typeof f.topic === 'string';
|
|
201
402
|
}
|
|
202
403
|
function defaultClientOpIdMinter() {
|
|
203
404
|
const g = globalThis;
|
|
@@ -241,6 +442,15 @@ function isSnapshotResponse(body) {
|
|
|
241
442
|
// snapshot validated structurally in materialise(); a null is fine.
|
|
242
443
|
return true;
|
|
243
444
|
}
|
|
445
|
+
// Fold the join's write verdict into the Document options, so a reader the
|
|
446
|
+
// server will not accept writes from opens read-only instead of learning it
|
|
447
|
+
// from the first refused op. Only ever ADDS the restriction: a caller that
|
|
448
|
+
// asked for a read-only Document keeps it whatever the grant says.
|
|
449
|
+
function readOnlyForGrant(body, options) {
|
|
450
|
+
if (body.can_edit !== false)
|
|
451
|
+
return options;
|
|
452
|
+
return { ...options, readOnly: true, readOnlyReason: 'grant' };
|
|
453
|
+
}
|
|
244
454
|
function isAtVersionResponse(body) {
|
|
245
455
|
if (typeof body !== 'object' || body === null)
|
|
246
456
|
return false;
|
|
@@ -285,13 +495,27 @@ export function createOpenDocument(opts) {
|
|
|
285
495
|
applyClientVersionHeader(headers);
|
|
286
496
|
await applyAppAssertionHeader(headers, opts.getAppAssertion);
|
|
287
497
|
const endFetch = perfStart('open: GET /documents (http + read body)');
|
|
288
|
-
// Idempotent read: ride out a
|
|
289
|
-
//
|
|
290
|
-
//
|
|
498
|
+
// Idempotent read: ride out a transient 5xx / 429 instead of failing the
|
|
499
|
+
// open on something that clears on its own.
|
|
500
|
+
//
|
|
501
|
+
// Longer than the default handful of attempts because of what a 503 means
|
|
502
|
+
// on this route: the document is intact and its storage is busy. Every op
|
|
503
|
+
// row a document has shares one partition, so the document most likely to
|
|
504
|
+
// answer 503 is one that was just written hard, which is exactly the
|
|
505
|
+
// moment a person reloads to see their work. That pressure clears over
|
|
506
|
+
// tens of seconds, not the one second the default budget spans, and the
|
|
507
|
+
// cost of giving up early is telling someone their document will not open
|
|
508
|
+
// when waiting would have opened it.
|
|
509
|
+
//
|
|
510
|
+
// A thrown request gets a short budget of its own: it never reached the
|
|
511
|
+
// API, so the busy partition is not what is wrong, and a blocked origin
|
|
512
|
+
// or a host that does not resolve answers the seventh attempt as it
|
|
513
|
+
// answered the first, with the reader watching a loading surface
|
|
514
|
+
// throughout.
|
|
291
515
|
const response = await fetchWithRetry(() => fetch(url, {
|
|
292
516
|
method: 'GET',
|
|
293
517
|
headers,
|
|
294
|
-
}));
|
|
518
|
+
}), { maxAttempts: 7, baseDelayMs: 700, maxNetworkAttempts: 3 });
|
|
295
519
|
const text = await response.text();
|
|
296
520
|
endFetch({ status: response.status, responseChars: text.length });
|
|
297
521
|
let parsed = undefined;
|
|
@@ -304,7 +528,7 @@ export function createOpenDocument(opts) {
|
|
|
304
528
|
parseFailed = true;
|
|
305
529
|
}
|
|
306
530
|
}
|
|
307
|
-
await resolveParsedTailOps(parsed);
|
|
531
|
+
await resolveParsedTailOps(parsed, options?.onSnapshotProgress);
|
|
308
532
|
return { status: response.status, parsed, parseFailed };
|
|
309
533
|
}
|
|
310
534
|
// `GET /documents/{docId}/at/{version}`: read-only materialization at a
|
|
@@ -430,35 +654,45 @@ export function createOpenDocument(opts) {
|
|
|
430
654
|
// key the op write names. The PUT carries no Brass headers: the URL is
|
|
431
655
|
// signed, and an extra header falls outside that signature.
|
|
432
656
|
async function stageOpBlob(docId, opBlobB64, token) {
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
657
|
+
// Everything in here happens before the op write, so every failure it
|
|
658
|
+
// can take is tagged as one: what the tag buys the writer is the right
|
|
659
|
+
// to send the op again, which a failure of the write itself does not
|
|
660
|
+
// carry.
|
|
661
|
+
try {
|
|
662
|
+
const headers = {
|
|
663
|
+
authorization: `Bearer ${token}`,
|
|
664
|
+
'content-type': 'application/json',
|
|
665
|
+
};
|
|
666
|
+
applyClientVersionHeader(headers);
|
|
667
|
+
await applyAppAssertionHeader(headers, opts.getAppAssertion);
|
|
668
|
+
const mint = await fetchWithDeadline(`${baseUrl}/documents/${encodeURIComponent(docId)}/ops/upload`, { method: 'POST', headers, body: '{}' }, OP_WRITE_TIMEOUT_MS);
|
|
669
|
+
let minted = undefined;
|
|
443
670
|
try {
|
|
444
|
-
|
|
671
|
+
minted = mint.text ? JSON.parse(mint.text) : undefined;
|
|
445
672
|
}
|
|
446
673
|
catch {
|
|
447
|
-
|
|
674
|
+
minted = undefined;
|
|
448
675
|
}
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
676
|
+
if (!mint.ok) {
|
|
677
|
+
throw brassErrorFromBody(mint.status, minted);
|
|
678
|
+
}
|
|
679
|
+
const body = (minted ?? {});
|
|
680
|
+
if (typeof body.upload_key !== 'string' || typeof body.url !== 'string') {
|
|
681
|
+
throw new BrassError('Malformed op upload response', { status: 500 });
|
|
682
|
+
}
|
|
683
|
+
const endUpload = perfStart('op: PUT staged op blob');
|
|
684
|
+
const put = await fetchWithDeadline(body.url, { method: 'PUT', body: opBlobB64 }, deadlineForUpload(opBlobB64.length));
|
|
685
|
+
endUpload({ status: put.status, opChars: opBlobB64.length });
|
|
686
|
+
if (!put.ok) {
|
|
687
|
+
throw new BrassError('Could not upload the update', {
|
|
688
|
+
status: put.status,
|
|
689
|
+
});
|
|
690
|
+
}
|
|
691
|
+
return body.upload_key;
|
|
454
692
|
}
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
endUpload({ status: put.status, opChars: opBlobB64.length });
|
|
458
|
-
if (!put.ok) {
|
|
459
|
-
throw new BrassError('Could not upload the update', { status: put.status });
|
|
693
|
+
catch (err) {
|
|
694
|
+
throw asOpStagingError(err);
|
|
460
695
|
}
|
|
461
|
-
return body.upload_key;
|
|
462
696
|
}
|
|
463
697
|
async function postDocumentOp(docId, branchId, opBlobB64, clientOpId, token) {
|
|
464
698
|
const headers = {
|
|
@@ -475,7 +709,7 @@ export function createOpenDocument(opts) {
|
|
|
475
709
|
stagedKey = await stageOpBlob(docId, opBlobB64, token);
|
|
476
710
|
}
|
|
477
711
|
const endFetch = perfStart('op: POST /documents/{id}/ops');
|
|
478
|
-
const response = await
|
|
712
|
+
const response = await fetchWithDeadline(`${baseUrl}/documents/${encodeURIComponent(docId)}/ops`, {
|
|
479
713
|
method: 'POST',
|
|
480
714
|
headers,
|
|
481
715
|
body: JSON.stringify({
|
|
@@ -485,12 +719,14 @@ export function createOpenDocument(opts) {
|
|
|
485
719
|
branch_id: branchId,
|
|
486
720
|
client_op_id: clientOpId,
|
|
487
721
|
}),
|
|
488
|
-
}
|
|
489
|
-
|
|
722
|
+
},
|
|
723
|
+
// An op under the staging threshold travels inline, so this request
|
|
724
|
+
// carries the blob and its deadline has to allow for sending it.
|
|
725
|
+
deadlineForUpload(stagedKey === undefined ? opBlobB64.length : 0));
|
|
490
726
|
endFetch({ status: response.status, opChars: opBlobB64.length });
|
|
491
727
|
let parsed = undefined;
|
|
492
728
|
try {
|
|
493
|
-
parsed = text ? JSON.parse(text) : undefined;
|
|
729
|
+
parsed = response.text ? JSON.parse(response.text) : undefined;
|
|
494
730
|
}
|
|
495
731
|
catch {
|
|
496
732
|
parsed = undefined;
|
|
@@ -638,7 +874,9 @@ export function createOpenDocument(opts) {
|
|
|
638
874
|
status: 500,
|
|
639
875
|
});
|
|
640
876
|
}
|
|
641
|
-
|
|
877
|
+
// A stream's write authority is the document's, so the line opens
|
|
878
|
+
// read-only for the same reader the document opens read-only for.
|
|
879
|
+
const doc = await materialise(parsed, readOnlyForGrant(parsed, undefined));
|
|
642
880
|
// A stream line materializes at a historical seq the same way the
|
|
643
881
|
// default line does, so the parent's version preview can bring this
|
|
644
882
|
// stream to a point in time (`doc.stream(name)._previewAt(seq)`). The
|
|
@@ -649,7 +887,8 @@ export function createOpenDocument(opts) {
|
|
|
649
887
|
// line (see the comments there); scoped per line because each stream
|
|
650
888
|
// has its own seq space.
|
|
651
889
|
let currentSeq = Math.max(parsed.tail_ops.reduce((acc, entry) => (entry.seq > acc ? entry.seq : acc), 0), typeof parsed.current_seq === 'number' ? parsed.current_seq : 0);
|
|
652
|
-
|
|
890
|
+
const lineTailSeqs = parsed.tail_ops.map((entry) => entry.seq);
|
|
891
|
+
let coveredSeq = joinCoverageFloor(snapshotSeqOf(parsed.snapshot_seq, lineTailSeqs, typeof parsed.current_seq === 'number' ? parsed.current_seq : 0), lineTailSeqs);
|
|
653
892
|
const coverageParked = new Set();
|
|
654
893
|
const advanceCoverage = (seq) => {
|
|
655
894
|
if (seq <= coveredSeq)
|
|
@@ -660,50 +899,79 @@ export function createOpenDocument(opts) {
|
|
|
660
899
|
coveredSeq += 1;
|
|
661
900
|
}
|
|
662
901
|
};
|
|
902
|
+
const raiseCoverage = (floor) => {
|
|
903
|
+
if (floor > coveredSeq)
|
|
904
|
+
coveredSeq = floor;
|
|
905
|
+
for (const seq of coverageParked) {
|
|
906
|
+
if (seq <= coveredSeq)
|
|
907
|
+
coverageParked.delete(seq);
|
|
908
|
+
}
|
|
909
|
+
while (coverageParked.has(coveredSeq + 1)) {
|
|
910
|
+
coverageParked.delete(coveredSeq + 1);
|
|
911
|
+
coveredSeq += 1;
|
|
912
|
+
}
|
|
913
|
+
};
|
|
663
914
|
for (const entry of parsed.tail_ops)
|
|
664
915
|
advanceCoverage(entry.seq);
|
|
665
|
-
//
|
|
666
|
-
//
|
|
667
|
-
// clean merge.
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
916
|
+
// Re-import the line's join: the reconnect-across-compaction recovery,
|
|
917
|
+
// and the answer to a catch-up prompt. Loro imports are idempotent, so
|
|
918
|
+
// re-applying over live state is a clean merge.
|
|
919
|
+
//
|
|
920
|
+
// Coalesced and delivery-honest for the same reasons the default line
|
|
921
|
+
// is: a prompt during a fetch is the only notice of that op the line
|
|
922
|
+
// gets, and a join's `current_seq` names seqs whose rows the tail query
|
|
923
|
+
// could not see yet.
|
|
924
|
+
let lineResyncRun = null;
|
|
925
|
+
let lineResyncAgain = false;
|
|
926
|
+
const runLineResync = async () => {
|
|
927
|
+
try {
|
|
928
|
+
do {
|
|
929
|
+
lineResyncAgain = false;
|
|
930
|
+
try {
|
|
931
|
+
const t = await requireToken();
|
|
932
|
+
const res = await fetchSnapshot(docId, { branch: lineId }, t);
|
|
933
|
+
if (res.status < 200 || res.status >= 300)
|
|
934
|
+
continue;
|
|
935
|
+
if (!isSnapshotResponse(res.parsed))
|
|
936
|
+
continue;
|
|
937
|
+
const snap = res.parsed.snapshot;
|
|
938
|
+
if (snap !== null) {
|
|
939
|
+
const bytes = snap.kind === 'inline'
|
|
940
|
+
? base64ToBytes(snap.data_b64)
|
|
941
|
+
: await fetchPresignedSnapshot(snap.url);
|
|
942
|
+
doc._applySnapshot(bytes);
|
|
943
|
+
}
|
|
944
|
+
const seqs = [];
|
|
945
|
+
for (const entry of res.parsed.tail_ops) {
|
|
946
|
+
doc.applyRemoteOp(base64ToBytes(entry.op_blob_b64));
|
|
947
|
+
if (entry.seq > currentSeq)
|
|
948
|
+
currentSeq = entry.seq;
|
|
949
|
+
seqs.push(entry.seq);
|
|
950
|
+
}
|
|
951
|
+
const joined = res.parsed.current_seq;
|
|
952
|
+
if (typeof joined === 'number' && joined > currentSeq) {
|
|
693
953
|
currentSeq = joined;
|
|
694
|
-
if (joined > coveredSeq) {
|
|
695
|
-
coveredSeq = joined;
|
|
696
|
-
for (const seq of coverageParked) {
|
|
697
|
-
if (seq <= coveredSeq)
|
|
698
|
-
coverageParked.delete(seq);
|
|
699
|
-
}
|
|
700
954
|
}
|
|
955
|
+
raiseCoverage(joinCoverageFloor(snapshotSeqOf(res.parsed.snapshot_seq, seqs, currentSeq), seqs));
|
|
956
|
+
for (const seq of seqs)
|
|
957
|
+
advanceCoverage(seq);
|
|
701
958
|
}
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
}
|
|
706
|
-
}
|
|
959
|
+
catch {
|
|
960
|
+
// Best-effort; the next prompt or doc_init retries.
|
|
961
|
+
}
|
|
962
|
+
} while (lineResyncAgain);
|
|
963
|
+
}
|
|
964
|
+
finally {
|
|
965
|
+
lineResyncRun = null;
|
|
966
|
+
}
|
|
967
|
+
};
|
|
968
|
+
const resyncFromSnapshot = () => {
|
|
969
|
+
if (lineResyncRun !== null) {
|
|
970
|
+
lineResyncAgain = true;
|
|
971
|
+
return lineResyncRun;
|
|
972
|
+
}
|
|
973
|
+
lineResyncRun = runLineResync();
|
|
974
|
+
return lineResyncRun;
|
|
707
975
|
};
|
|
708
976
|
// Write an op the socket cannot carry. The op stays one commit and
|
|
709
977
|
// one seq; only the transport differs, and the response carries the
|
|
@@ -712,11 +980,23 @@ export function createOpenDocument(opts) {
|
|
|
712
980
|
const token = await requireToken();
|
|
713
981
|
const { status, parsed: opResult } = await postDocumentOp(docId, lineId, opBlobB64, clientOpId, token);
|
|
714
982
|
if (status < 200 || status >= 300) {
|
|
715
|
-
return {
|
|
983
|
+
return {
|
|
984
|
+
ok: false,
|
|
985
|
+
message: opWriteFailureMessage(status, opResult),
|
|
986
|
+
retryable: opWriteIsRetryable(status),
|
|
987
|
+
atCapacity: isCapacityRefusal(status, opResult),
|
|
988
|
+
// The route answers 403 when the caller's grant carries no write
|
|
989
|
+
// access, which is the HTTP face of the socket's `role_denied`.
|
|
990
|
+
...(status === 403 ? { readOnly: 'grant' } : {}),
|
|
991
|
+
};
|
|
716
992
|
}
|
|
717
993
|
const seq = opResult?.seq;
|
|
718
994
|
if (typeof seq !== 'number') {
|
|
719
|
-
return {
|
|
995
|
+
return {
|
|
996
|
+
ok: false,
|
|
997
|
+
message: 'The server did not report a version for this change.',
|
|
998
|
+
retryable: false,
|
|
999
|
+
};
|
|
720
1000
|
}
|
|
721
1001
|
return { ok: true, seq };
|
|
722
1002
|
};
|
|
@@ -750,7 +1030,7 @@ export function createOpenDocument(opts) {
|
|
|
750
1030
|
if (!isSnapshotResponse(parsed)) {
|
|
751
1031
|
throw new BrassError('Malformed document snapshot response', { status: 500 });
|
|
752
1032
|
}
|
|
753
|
-
const doc = await materialise(parsed, options?.documentOptions, options?.onSnapshotProgress);
|
|
1033
|
+
const doc = await materialise(parsed, readOnlyForGrant(parsed, options?.documentOptions), options?.onSnapshotProgress);
|
|
754
1034
|
// Populate `doc.status` from the join before the first `doc_status` frame
|
|
755
1035
|
// (a stub opened mid-hydration returns `snapshot: null` + a `pending`
|
|
756
1036
|
// status).
|
|
@@ -771,9 +1051,14 @@ export function createOpenDocument(opts) {
|
|
|
771
1051
|
// then can't tell "caught up" from "missed ops since compacted into the
|
|
772
1052
|
// snapshot". The floor never overestimates, so the `doc_init` resync
|
|
773
1053
|
// check always detects such a hole (at worst a transient out-of-order
|
|
774
|
-
// arrival costs one idempotent re-fetch).
|
|
775
|
-
//
|
|
776
|
-
|
|
1054
|
+
// arrival costs one idempotent re-fetch).
|
|
1055
|
+
//
|
|
1056
|
+
// Seeded from what this join DELIVERED, which is its snapshot plus the
|
|
1057
|
+
// unbroken run of tail seqs above it, never from `current_seq`: a join
|
|
1058
|
+
// read while someone writes in bulk reports a counter above the rows it
|
|
1059
|
+
// could see, and seeding from the counter opens the document already
|
|
1060
|
+
// claiming ops it does not hold.
|
|
1061
|
+
let coveredSeq = joinCoverageFloor(snapshotSeqOf(parsed.snapshot_seq, parsed.tail_ops.map((entry) => entry.seq), typeof parsed.current_seq === 'number' ? parsed.current_seq : 0), parsed.tail_ops.map((entry) => entry.seq));
|
|
777
1062
|
// Seqs applied above the floor, parked until the gap below fills.
|
|
778
1063
|
const coverageParked = new Set();
|
|
779
1064
|
const drainCoverage = () => {
|
|
@@ -788,9 +1073,11 @@ export function createOpenDocument(opts) {
|
|
|
788
1073
|
coverageParked.add(seq);
|
|
789
1074
|
drainCoverage();
|
|
790
1075
|
};
|
|
791
|
-
// Mark everything at or below `floor` covered
|
|
792
|
-
//
|
|
793
|
-
//
|
|
1076
|
+
// Mark everything at or below `floor` covered. The caller owes the
|
|
1077
|
+
// guarantee that goes with it: every seq under `floor` is applied, or
|
|
1078
|
+
// folded into a snapshot this doc imported. Coverage is what retires a
|
|
1079
|
+
// catch-up prompt, so a floor taken from anything looser than that is a
|
|
1080
|
+
// reader quietly deciding it holds ops nobody sent it.
|
|
794
1081
|
const raiseCoverage = (floor) => {
|
|
795
1082
|
if (floor > coveredSeq)
|
|
796
1083
|
coveredSeq = floor;
|
|
@@ -859,14 +1146,34 @@ export function createOpenDocument(opts) {
|
|
|
859
1146
|
if (entry.seq > maxTailSeq)
|
|
860
1147
|
maxTailSeq = entry.seq;
|
|
861
1148
|
}
|
|
862
|
-
// Raise both cursors so the floor reflects the import (this clears a
|
|
863
|
-
// detected missed-compaction hole).
|
|
864
1149
|
const fetchedSeq = typeof result.parsed.current_seq === 'number'
|
|
865
1150
|
? result.parsed.current_seq
|
|
866
1151
|
: maxTailSeq;
|
|
867
1152
|
if (fetchedSeq > currentSeq)
|
|
868
1153
|
currentSeq = fetchedSeq;
|
|
869
|
-
|
|
1154
|
+
// Coverage moves to what this response DELIVERED, not to the head it
|
|
1155
|
+
// reported. The two differ exactly when it matters: the head is the
|
|
1156
|
+
// branch's seq counter, bumped when a seq is handed out rather than
|
|
1157
|
+
// when its row is written, so a join read during a bulk write names
|
|
1158
|
+
// ops the tail query could not see. Crediting the head marks those
|
|
1159
|
+
// seqs covered, and the prompts that would fetch them then short
|
|
1160
|
+
// circuit, which is a reader left permanently short of a write it
|
|
1161
|
+
// watched land.
|
|
1162
|
+
//
|
|
1163
|
+
// The cost is that a seq allocated and never written (a failed op
|
|
1164
|
+
// write leaves a hole rather than a duplicate) now stalls the floor
|
|
1165
|
+
// under it. That resolves at the next compaction, which folds the tail
|
|
1166
|
+
// past the hole and raises `snapshot_seq` over it; until then the gap
|
|
1167
|
+
// pull's own budget is what stops the reader asking forever.
|
|
1168
|
+
const tailSeqs = sortedTail.map((entry) => entry.seq);
|
|
1169
|
+
// A snapshot only counts as a floor once its bytes are in: a shape this
|
|
1170
|
+
// pin does not decode leaves `snapshot_seq` describing content the doc
|
|
1171
|
+
// never received, and the tail alone is then what it holds.
|
|
1172
|
+
if (snapshotBytes !== null || result.parsed.snapshot === null) {
|
|
1173
|
+
raiseCoverage(joinCoverageFloor(snapshotSeqOf(result.parsed.snapshot_seq, tailSeqs, fetchedSeq), tailSeqs));
|
|
1174
|
+
}
|
|
1175
|
+
for (const seq of tailSeqs)
|
|
1176
|
+
advanceCoverage(seq);
|
|
870
1177
|
endPerf({
|
|
871
1178
|
ok: true,
|
|
872
1179
|
snapshotBytes: snapshotBytes?.byteLength ?? 0,
|
|
@@ -897,90 +1204,106 @@ export function createOpenDocument(opts) {
|
|
|
897
1204
|
}
|
|
898
1205
|
return out;
|
|
899
1206
|
};
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
1207
|
+
// Coalesced, not skipped. A prompt that lands while a join is in flight
|
|
1208
|
+
// is a statement that the document has moved past what that join can
|
|
1209
|
+
// possibly carry, so dropping it loses the only notice this reader gets:
|
|
1210
|
+
// the server posts each prompt once, and a passive reader has no ack or
|
|
1211
|
+
// op of its own to notice the shortfall from. A bulk write is a run of
|
|
1212
|
+
// prompts (every op past the frame bound takes the HTTP route and
|
|
1213
|
+
// prompts each subscriber), and under a plain skip-if-in-flight the
|
|
1214
|
+
// whole run collapses into the one or two joins that happened not to be
|
|
1215
|
+
// busy, which is a reader stranded partway through a write it watched.
|
|
1216
|
+
//
|
|
1217
|
+
// `resyncAgain` is a flag rather than a queue because a join reads the
|
|
1218
|
+
// whole document: one more pass answers every prompt that arrived during
|
|
1219
|
+
// this one. The loop therefore runs at most one extra fetch after the
|
|
1220
|
+
// last prompt, and settles when the writer stops.
|
|
1221
|
+
//
|
|
1222
|
+
// The returned promise settles when the last pass this call is
|
|
1223
|
+
// responsible for has landed, so a caller deciding whether the reader is
|
|
1224
|
+
// still short reads the floor after the work rather than during it.
|
|
1225
|
+
let resyncRun = null;
|
|
1226
|
+
let resyncAgain = false;
|
|
1227
|
+
const runResync = async () => {
|
|
1228
|
+
try {
|
|
1229
|
+
do {
|
|
1230
|
+
resyncAgain = false;
|
|
1231
|
+
try {
|
|
1232
|
+
const outcome = await refetchAndImport();
|
|
1233
|
+
if (!outcome.ok) {
|
|
1234
|
+
console.error('Brass: document resync after reconnect failed; state may lag until the next reconnect or reload');
|
|
1235
|
+
}
|
|
910
1236
|
}
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
}
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
}
|
|
1237
|
+
catch (err) {
|
|
1238
|
+
console.error('Brass: document resync after reconnect failed; state may lag until the next reconnect or reload', err);
|
|
1239
|
+
}
|
|
1240
|
+
} while (resyncAgain);
|
|
1241
|
+
}
|
|
1242
|
+
finally {
|
|
1243
|
+
resyncRun = null;
|
|
1244
|
+
}
|
|
1245
|
+
};
|
|
1246
|
+
const resyncFromSnapshot = () => {
|
|
1247
|
+
if (resyncRun !== null) {
|
|
1248
|
+
resyncAgain = true;
|
|
1249
|
+
return resyncRun;
|
|
1250
|
+
}
|
|
1251
|
+
resyncRun = runResync();
|
|
1252
|
+
return resyncRun;
|
|
919
1253
|
};
|
|
920
1254
|
// When a doc opened mid-load finishes, pull the now-available content
|
|
921
1255
|
// into the live doc so it appears without the app reopening. Only ever
|
|
922
1256
|
// called on the server's authoritative `reload` hint, so it never has to
|
|
923
1257
|
// tell success from failure: a failure carries no `reload`, so no racy
|
|
924
1258
|
// read and no loop against a failed hydration.
|
|
925
|
-
//
|
|
926
|
-
// A failed fetch here is transient (network, dropped presigned download)
|
|
927
|
-
// and is retried with backoff: a silent give-up would strand the doc
|
|
928
|
-
// empty-but-editable, reading as "the model never loaded" and invisible
|
|
929
|
-
// in every log. On exhaustion the failure is reported and the terminal
|
|
930
|
-
// status is an honest failure, not the server's success copy.
|
|
931
1259
|
let reloadInFlight = false;
|
|
932
|
-
|
|
933
|
-
|
|
1260
|
+
let reconcileInFlight = false;
|
|
1261
|
+
// A terminal frame that lands while the subscribe-time reconcile is still
|
|
1262
|
+
// fetching waits for it: two concurrent imports each clear the undo stack
|
|
1263
|
+
// and race their terminal emits, and dropping the frame would leave a
|
|
1264
|
+
// reconcile that read the row too early sitting on the pending overlay.
|
|
1265
|
+
let deferredReload = null;
|
|
1266
|
+
// Armed when the pull below gives up. The work is terminal server-side, so
|
|
1267
|
+
// no further status frame arrives, and later ops are causally dependent on
|
|
1268
|
+
// a snapshot this client never imported (Loro buffers them and the doc
|
|
1269
|
+
// stays empty), so the next frame on the topic drives one more attempt.
|
|
1270
|
+
let retryPullOnNextFrame = false;
|
|
934
1271
|
const reloadAfterHydration = (finalStatus) => {
|
|
935
1272
|
if (reloadInFlight)
|
|
936
1273
|
return;
|
|
1274
|
+
if (reconcileInFlight) {
|
|
1275
|
+
deferredReload = finalStatus;
|
|
1276
|
+
return;
|
|
1277
|
+
}
|
|
937
1278
|
reloadInFlight = true;
|
|
938
1279
|
void (async () => {
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
// Emit the terminal status AFTER the import settles, so an app
|
|
946
|
-
// re-reading on `onStatus` sees the content present and (with
|
|
947
|
-
// `readOnly` now false) clears its loading overlay.
|
|
948
|
-
doc._emitStatus(finalStatus);
|
|
949
|
-
return;
|
|
950
|
-
}
|
|
951
|
-
lastError = new Error(outcome.reason);
|
|
952
|
-
}
|
|
953
|
-
catch (err) {
|
|
954
|
-
lastError = err instanceof Error ? err : new Error(String(err));
|
|
955
|
-
}
|
|
956
|
-
// A retrying attempt is exceptional, so this warn is quiet in
|
|
957
|
-
// normal operation and decisive in a bug report; without it a
|
|
958
|
-
// failure here is undiagnosable from any log.
|
|
959
|
-
console.warn(`[Brass] document content reload attempt ${attempt}/${RELOAD_ATTEMPTS} failed (doc ${docId}): ${lastError.message}`);
|
|
960
|
-
if (attempt < RELOAD_ATTEMPTS) {
|
|
961
|
-
await new Promise((r) => setTimeout(r, RELOAD_BACKOFF_MS * attempt));
|
|
962
|
-
}
|
|
963
|
-
}
|
|
964
|
-
reloadInFlight = false;
|
|
965
|
-
const error = new BrassError(`Document content reload failed after ${RELOAD_ATTEMPTS} attempts: ${lastError?.message ?? 'unknown error'}`, { status: 0 });
|
|
966
|
-
if (opts.reportError)
|
|
967
|
-
opts.reportError(error);
|
|
968
|
-
else
|
|
969
|
-
console.error('[Brass]', error);
|
|
970
|
-
doc._emitStatus({
|
|
971
|
-
message: 'The model could not be loaded. Reload to try again.',
|
|
972
|
-
pending: false,
|
|
1280
|
+
const imported = await pullContentWithRetry({
|
|
1281
|
+
doc,
|
|
1282
|
+
docId,
|
|
1283
|
+
finalStatus,
|
|
1284
|
+
fetchAndImport: refetchAndImport,
|
|
1285
|
+
...(opts.reportError ? { reportError: opts.reportError } : {}),
|
|
973
1286
|
});
|
|
1287
|
+
reloadInFlight = false;
|
|
1288
|
+
retryPullOnNextFrame = !imported;
|
|
974
1289
|
})();
|
|
975
1290
|
};
|
|
1291
|
+
// Evidence the document moved on the server after a give-up: one more
|
|
1292
|
+
// pull, which on success imports the content and releases the lock the
|
|
1293
|
+
// failed terminal status left in place.
|
|
1294
|
+
const retryContentPull = () => {
|
|
1295
|
+
if (!retryPullOnNextFrame)
|
|
1296
|
+
return;
|
|
1297
|
+
retryPullOnNextFrame = false;
|
|
1298
|
+
reloadAfterHydration(WORK_READY_STATUS);
|
|
1299
|
+
};
|
|
976
1300
|
// Reconcile a pending open once the live subscription exists. The
|
|
977
1301
|
// terminal `doc_status` frame is best-effort: if hydration finishes
|
|
978
|
-
// before this client's
|
|
1302
|
+
// before this client's subscription record exists, the fan-out finds no subscriber
|
|
979
1303
|
// and drops the frame, stranding the app on the pending overlay. `doc_init`
|
|
980
|
-
// is posted only after the
|
|
1304
|
+
// is posted only after the subscription record is written, so one re-fetch here
|
|
981
1305
|
// closes the gap for a completion that landed before the row existed.
|
|
982
1306
|
// Only a pending open pays the extra fetch.
|
|
983
|
-
let reconcileInFlight = false;
|
|
984
1307
|
const reconcileStatusOnInit = () => {
|
|
985
1308
|
const current = doc.status;
|
|
986
1309
|
if (!current || !current.pending)
|
|
@@ -989,6 +1312,7 @@ export function createOpenDocument(opts) {
|
|
|
989
1312
|
return;
|
|
990
1313
|
reconcileInFlight = true;
|
|
991
1314
|
void (async () => {
|
|
1315
|
+
let settled = false;
|
|
992
1316
|
try {
|
|
993
1317
|
const outcome = await refetchAndImport();
|
|
994
1318
|
if (!outcome.ok)
|
|
@@ -997,10 +1321,15 @@ export function createOpenDocument(opts) {
|
|
|
997
1321
|
// fan-out delivers the terminal frame when the work finishes.
|
|
998
1322
|
if (outcome.status?.pending)
|
|
999
1323
|
return;
|
|
1000
|
-
|
|
1001
|
-
//
|
|
1002
|
-
// the
|
|
1003
|
-
|
|
1324
|
+
settled = true;
|
|
1325
|
+
// Terminal. A status the server still holds is a failure (success
|
|
1326
|
+
// clears the row), and its absence is the success this import just
|
|
1327
|
+
// pulled the content for, reported as the same terminal frame the
|
|
1328
|
+
// platform sends on that transition.
|
|
1329
|
+
if (outcome.status)
|
|
1330
|
+
doc._emitStatus(outcome.status);
|
|
1331
|
+
else
|
|
1332
|
+
doc._emitStatus(WORK_READY_STATUS, { contentLoaded: true });
|
|
1004
1333
|
}
|
|
1005
1334
|
catch {
|
|
1006
1335
|
// Best-effort; the live fan-out remains the primary path when
|
|
@@ -1008,6 +1337,12 @@ export function createOpenDocument(opts) {
|
|
|
1008
1337
|
}
|
|
1009
1338
|
finally {
|
|
1010
1339
|
reconcileInFlight = false;
|
|
1340
|
+
const deferred = deferredReload;
|
|
1341
|
+
deferredReload = null;
|
|
1342
|
+
// A settled reconcile imported the content itself, so the held
|
|
1343
|
+
// frame has nothing left to pull.
|
|
1344
|
+
if (deferred && !settled)
|
|
1345
|
+
reloadAfterHydration(deferred);
|
|
1011
1346
|
}
|
|
1012
1347
|
})();
|
|
1013
1348
|
};
|
|
@@ -1019,13 +1354,22 @@ export function createOpenDocument(opts) {
|
|
|
1019
1354
|
const token = await requireToken();
|
|
1020
1355
|
const { status, parsed: opResult } = await postDocumentOp(docId, parsed.branch_id, opBlobB64, clientOpId, token);
|
|
1021
1356
|
if (status < 200 || status >= 300) {
|
|
1022
|
-
return {
|
|
1357
|
+
return {
|
|
1358
|
+
ok: false,
|
|
1359
|
+
message: opWriteFailureMessage(status, opResult),
|
|
1360
|
+
retryable: opWriteIsRetryable(status),
|
|
1361
|
+
atCapacity: isCapacityRefusal(status, opResult),
|
|
1362
|
+
// The route answers 403 when the caller's grant carries no write
|
|
1363
|
+
// access, which is the HTTP face of the socket's `role_denied`.
|
|
1364
|
+
...(status === 403 ? { readOnly: 'grant' } : {}),
|
|
1365
|
+
};
|
|
1023
1366
|
}
|
|
1024
1367
|
const seq = opResult?.seq;
|
|
1025
1368
|
if (typeof seq !== 'number') {
|
|
1026
1369
|
return {
|
|
1027
1370
|
ok: false,
|
|
1028
1371
|
message: 'The server did not report a version for this change.',
|
|
1372
|
+
retryable: false,
|
|
1029
1373
|
};
|
|
1030
1374
|
}
|
|
1031
1375
|
return { ok: true, seq };
|
|
@@ -1043,6 +1387,10 @@ export function createOpenDocument(opts) {
|
|
|
1043
1387
|
? { requestedBranchId: options.branch }
|
|
1044
1388
|
: {}),
|
|
1045
1389
|
...(options?.stream !== undefined ? { requestedStream: options.stream } : {}),
|
|
1390
|
+
...(options?.documentOptions !== undefined
|
|
1391
|
+
? { documentOptions: options.documentOptions }
|
|
1392
|
+
: {}),
|
|
1393
|
+
...(opts.identity !== undefined ? { identity: opts.identity } : {}),
|
|
1046
1394
|
wsClient: opts.wsClient,
|
|
1047
1395
|
postOversizedOp,
|
|
1048
1396
|
newClientOpId: opts.newClientOpId ?? defaultClientOpIdMinter,
|
|
@@ -1057,6 +1405,7 @@ export function createOpenDocument(opts) {
|
|
|
1057
1405
|
refetchDurableFrontier,
|
|
1058
1406
|
reloadAfterHydration,
|
|
1059
1407
|
reconcileStatusOnInit,
|
|
1408
|
+
onDocumentMoved: retryContentPull,
|
|
1060
1409
|
});
|
|
1061
1410
|
}
|
|
1062
1411
|
// `doc._checkoutVersion(v)` calls back here to materialise historical
|
|
@@ -1189,6 +1538,11 @@ export function createOpenDocument(opts) {
|
|
|
1189
1538
|
parseFailed = true;
|
|
1190
1539
|
}
|
|
1191
1540
|
}
|
|
1541
|
+
// A tail op whose bytes spilled to storage arrives as a signed URL, and
|
|
1542
|
+
// a guest join carries them exactly as a signed-in one does. The URL
|
|
1543
|
+
// carries its own signature, so an anonymous reader fetches it with the
|
|
1544
|
+
// same call. Resolving here is what lets `materialise` see one shape.
|
|
1545
|
+
await resolveParsedTailOps(parsed);
|
|
1192
1546
|
return { status: response.status, parsed, parseFailed };
|
|
1193
1547
|
}
|
|
1194
1548
|
// `GET /links/{token}/streams`: the anonymous stream manifest, the guest
|
|
@@ -1242,7 +1596,7 @@ export function createOpenDocument(opts) {
|
|
|
1242
1596
|
// The link's grant decides read vs write. An `editor` link is anonymous
|
|
1243
1597
|
// EDIT: a live Document (not read-only) whose local mutations ship over
|
|
1244
1598
|
// the same token-authenticated socket, with the server admitting the
|
|
1245
|
-
// op-write because the guest's
|
|
1599
|
+
// op-write because the guest's subscription record carries `role: editor`. A
|
|
1246
1600
|
// `viewer` link (the default) is read-only: mutate throws and only
|
|
1247
1601
|
// inbound frames apply.
|
|
1248
1602
|
const canEdit = b.link_role === 'editor';
|
|
@@ -1256,7 +1610,20 @@ export function createOpenDocument(opts) {
|
|
|
1256
1610
|
// sees the title (the signed-in open gets this from `finalise`).
|
|
1257
1611
|
if (typeof b.name === 'string')
|
|
1258
1612
|
doc._setName(b.name);
|
|
1259
|
-
|
|
1613
|
+
// A link opened while the platform is still preparing the document
|
|
1614
|
+
// carries the same opaque work status the signed-in join does, and the
|
|
1615
|
+
// guest's own topic delivers the phases after it. Seeded before the
|
|
1616
|
+
// transport so the app renders the wait rather than an empty document.
|
|
1617
|
+
const linkStatus = parseWorkStatus(b.status);
|
|
1618
|
+
if (linkStatus)
|
|
1619
|
+
doc._emitStatus(linkStatus);
|
|
1620
|
+
// An edit link's writes fail the same ways a member's do (a shed the
|
|
1621
|
+
// budget outlived, a link revoked mid-edit), and the app hears those
|
|
1622
|
+
// through the same channel it hears a member's, so the reporter is
|
|
1623
|
+
// wired here as `finalise` wires it for a signed-in open.
|
|
1624
|
+
if (opts.reportError)
|
|
1625
|
+
doc.setErrorReporter(opts.reportError);
|
|
1626
|
+
wireGuestTransport(doc, token, b.doc_id, b.branch_id, canEdit);
|
|
1260
1627
|
// Streams: a guest resolves `doc.stream(name)` through the token
|
|
1261
1628
|
// routes. `list` hits the anonymous manifest; `openLine` joins the
|
|
1262
1629
|
// line read/write exactly like the default stream above, over the same
|
|
@@ -1284,7 +1651,9 @@ export function createOpenDocument(opts) {
|
|
|
1284
1651
|
snapshot: lb.snapshot,
|
|
1285
1652
|
tail_ops: lb.tail_ops,
|
|
1286
1653
|
}, { readOnly: !canEdit });
|
|
1287
|
-
|
|
1654
|
+
if (opts.reportError)
|
|
1655
|
+
inner.setErrorReporter(opts.reportError);
|
|
1656
|
+
wireGuestTransport(inner, token, lb.doc_id, lb.branch_id, canEdit);
|
|
1288
1657
|
return inner;
|
|
1289
1658
|
},
|
|
1290
1659
|
create: () => {
|
|
@@ -1295,68 +1664,263 @@ export function createOpenDocument(opts) {
|
|
|
1295
1664
|
});
|
|
1296
1665
|
return doc;
|
|
1297
1666
|
};
|
|
1667
|
+
// Write a guest's op over HTTP: `POST /links/{token}/ops`, the anonymous
|
|
1668
|
+
// counterpart of `POST /documents/{docId}/ops`. Sends NO Authorization
|
|
1669
|
+
// header (the token is the credential) and names the line the guest
|
|
1670
|
+
// opened, which is the branch its socket topic is scoped to.
|
|
1671
|
+
async function postLinkOp(token, lineId, opBlobB64, clientOpId) {
|
|
1672
|
+
const response = await fetch(`${baseUrl}/links/${encodeURIComponent(token)}/ops`, {
|
|
1673
|
+
method: 'POST',
|
|
1674
|
+
headers: { 'content-type': 'application/json' },
|
|
1675
|
+
body: JSON.stringify({
|
|
1676
|
+
op_blob: opBlobB64,
|
|
1677
|
+
branch_id: lineId,
|
|
1678
|
+
client_op_id: clientOpId,
|
|
1679
|
+
}),
|
|
1680
|
+
});
|
|
1681
|
+
const text = await response.text();
|
|
1682
|
+
let parsed = undefined;
|
|
1683
|
+
try {
|
|
1684
|
+
parsed = text ? JSON.parse(text) : undefined;
|
|
1685
|
+
}
|
|
1686
|
+
catch {
|
|
1687
|
+
parsed = undefined;
|
|
1688
|
+
}
|
|
1689
|
+
return { status: response.status, parsed };
|
|
1690
|
+
}
|
|
1298
1691
|
// Wire a guest Document (the default stream or a stream line) to the
|
|
1299
1692
|
// token-authenticated socket. Inbound frames (`doc_init` / `doc_op`)
|
|
1300
1693
|
// apply for both link kinds; an edit link ALSO wires the outbound path
|
|
1301
1694
|
// (`op_ack` resolves the outstanding-op tracker, `setLocalOpHook` ships
|
|
1302
|
-
// each local commit
|
|
1695
|
+
// each local commit). Best-effort on the read side (no resync / durability
|
|
1303
1696
|
// handshake, which need a signed-in token); a guest that misses ops
|
|
1304
|
-
// re-opens.
|
|
1305
|
-
//
|
|
1306
|
-
//
|
|
1307
|
-
|
|
1697
|
+
// re-opens. The WRITE side answers a refusal the way the signed-in
|
|
1698
|
+
// transport does, because a guest editor's edit is the same person's work
|
|
1699
|
+
// as a member's and the same two things can happen to it: a frame the
|
|
1700
|
+
// socket cannot carry takes the HTTP route, and a capacity shed is
|
|
1701
|
+
// re-asserted on the shared backoff and reported once the budget is out.
|
|
1702
|
+
// Patches `close` to detach, mirroring `wireDocTransport`, so `Document`
|
|
1703
|
+
// stays free of WS knowledge. A no-op with no WS client (a snapshot-only
|
|
1704
|
+
// guest).
|
|
1705
|
+
function wireGuestTransport(doc, token, docId, lineId, canEdit) {
|
|
1308
1706
|
const wsClient = opts.wsClient;
|
|
1309
1707
|
if (!wsClient)
|
|
1310
1708
|
return;
|
|
1311
1709
|
const topic = `doc:${docId}:${lineId}`;
|
|
1710
|
+
// Ops on the socket awaiting an answer, keyed by `client_op_id`. An
|
|
1711
|
+
// `unavailable` shed names no op, so re-asserting one needs the frames
|
|
1712
|
+
// in hand. Scoped to what the socket carried: an op that took the HTTP
|
|
1713
|
+
// write must never reach the socket, and that write re-asserts itself.
|
|
1714
|
+
const outstanding = new Map();
|
|
1715
|
+
let shedRounds = 0;
|
|
1716
|
+
let shedTimer = null;
|
|
1717
|
+
function clearShedRecovery() {
|
|
1718
|
+
if (shedTimer !== null) {
|
|
1719
|
+
clearTimeout(shedTimer);
|
|
1720
|
+
shedTimer = null;
|
|
1721
|
+
}
|
|
1722
|
+
shedRounds = 0;
|
|
1723
|
+
}
|
|
1724
|
+
// Every outstanding op is dead: drop the tracker entries and tell the
|
|
1725
|
+
// Document, which stops counting them in `savingCount` and reports each
|
|
1726
|
+
// through the error channel the app reads. The ids are taken first
|
|
1727
|
+
// because `_failOutstandingOp` re-enters app code.
|
|
1728
|
+
function failAllOutstanding(message) {
|
|
1729
|
+
const clientOpIds = [...outstanding.keys()];
|
|
1730
|
+
outstanding.clear();
|
|
1731
|
+
for (const clientOpId of clientOpIds) {
|
|
1732
|
+
doc._failOutstandingOp(clientOpId, message);
|
|
1733
|
+
}
|
|
1734
|
+
}
|
|
1735
|
+
// Put every op still awaiting an answer back on the wire. The client
|
|
1736
|
+
// DROPS an op frame it cannot send right now rather than buffering one
|
|
1737
|
+
// (`ownsFrameRetry` below), so this is the only thing that carries a
|
|
1738
|
+
// shed or reconnect-orphaned op across the window, and it is also what
|
|
1739
|
+
// keeps a frame from being written twice: a copy the client held would
|
|
1740
|
+
// flush on the `subscribed` ack while this re-asserts on the `doc_init`
|
|
1741
|
+
// behind it, and the server allocates a fresh seq per send.
|
|
1742
|
+
const resendAllOutstanding = () => {
|
|
1743
|
+
for (const frame of outstanding.values())
|
|
1744
|
+
wsClient.send(frame);
|
|
1745
|
+
};
|
|
1746
|
+
const onServerUnavailable = () => {
|
|
1747
|
+
if (outstanding.size === 0)
|
|
1748
|
+
return;
|
|
1749
|
+
if (shedTimer !== null)
|
|
1750
|
+
return;
|
|
1751
|
+
shedRounds += 1;
|
|
1752
|
+
if (shedRounds > UNAVAILABLE_MAX_ROUNDS) {
|
|
1753
|
+
clearShedRecovery();
|
|
1754
|
+
failAllOutstanding(UNAVAILABLE_GIVE_UP_MESSAGE);
|
|
1755
|
+
return;
|
|
1756
|
+
}
|
|
1757
|
+
shedTimer = setTimeout(() => {
|
|
1758
|
+
shedTimer = null;
|
|
1759
|
+
resendAllOutstanding();
|
|
1760
|
+
}, unavailableDelayMs(shedRounds));
|
|
1761
|
+
shedTimer.unref?.();
|
|
1762
|
+
};
|
|
1312
1763
|
const unsub = wsClient.subscribe(topic, (frame) => {
|
|
1313
|
-
|
|
1314
|
-
|
|
1764
|
+
const init = parseDocInitFrame(frame);
|
|
1765
|
+
if (init) {
|
|
1766
|
+
for (const entry of init.tail_ops) {
|
|
1315
1767
|
if (entry.op_blob_b64 === undefined)
|
|
1316
1768
|
continue;
|
|
1317
1769
|
doc.applyRemoteOp(base64ToBytes(entry.op_blob_b64));
|
|
1318
1770
|
}
|
|
1771
|
+
// `doc_init` follows every `subscribed` ack, so this is the point
|
|
1772
|
+
// the topic can carry frames again. A fresh connection also returns
|
|
1773
|
+
// the shed budget to full: this re-assert is the round a pending
|
|
1774
|
+
// one would have run.
|
|
1775
|
+
clearShedRecovery();
|
|
1776
|
+
resendAllOutstanding();
|
|
1777
|
+
return;
|
|
1319
1778
|
}
|
|
1320
|
-
|
|
1779
|
+
if (isDocOpFrame(frame)) {
|
|
1321
1780
|
doc.applyRemoteOp(base64ToBytes(frame.op_blob));
|
|
1322
1781
|
}
|
|
1323
1782
|
else if (isDocGoneFrame(frame)) {
|
|
1324
1783
|
// The server fans `doc_gone` to EVERY subscriber on the branched
|
|
1325
|
-
// content topic, guest-link connections included
|
|
1326
|
-
//
|
|
1784
|
+
// content topic, guest-link connections included, on a soft-delete /
|
|
1785
|
+
// move of the opened doc.
|
|
1327
1786
|
// Without this branch the guest keeps showing removed content and
|
|
1328
1787
|
// `doc.onGone(...)` never fires; for an edit link the next local op
|
|
1329
|
-
// would ship onto the evicted
|
|
1330
|
-
// `forbidden`.
|
|
1331
|
-
//
|
|
1332
|
-
//
|
|
1788
|
+
// would ship onto the evicted subscription record and bounce as a misleading
|
|
1789
|
+
// `forbidden`. Drop the shed recovery first so nothing re-asserts an
|
|
1790
|
+
// op onto an evicted subscription record, then mark the doc gone (mapping the
|
|
1791
|
+
// reason like the signed-in transport).
|
|
1792
|
+
clearShedRecovery();
|
|
1793
|
+
outstanding.clear();
|
|
1333
1794
|
doc._markGone(goneReasonOf(frame));
|
|
1334
1795
|
}
|
|
1796
|
+
else if (isDocStatusFrame(frame)) {
|
|
1797
|
+
// A guest can open a document whose inbound work is still running,
|
|
1798
|
+
// and hydration writes a SNAPSHOT rather than ops, so nothing on the
|
|
1799
|
+
// op stream would ever fill the view in. Same split as the signed-in
|
|
1800
|
+
// transport: the `reload` hint pulls the content and emits the
|
|
1801
|
+
// terminal status after the import, and anything else renders.
|
|
1802
|
+
const status = normalizeWorkStatus(frame.status);
|
|
1803
|
+
if (frame.reload)
|
|
1804
|
+
pullGuestContent(doc, token, lineId, status);
|
|
1805
|
+
else
|
|
1806
|
+
doc._emitStatus(status);
|
|
1807
|
+
}
|
|
1808
|
+
else if (isDocMetaFrame(frame)) {
|
|
1809
|
+
// `_setName` de-dupes, so a re-emit of the current name is a no-op.
|
|
1810
|
+
doc._setName(frame.name);
|
|
1811
|
+
}
|
|
1335
1812
|
else if (canEdit && isOpAckFrame(frame)) {
|
|
1813
|
+
outstanding.delete(frame.client_op_id);
|
|
1336
1814
|
doc.resolveOutstandingOp(frame.client_op_id);
|
|
1815
|
+
// The server is durably accepting writes again, so the shed budget
|
|
1816
|
+
// starts over. A round already scheduled still runs: the ops it
|
|
1817
|
+
// re-asserts are the ones this ack did not cover.
|
|
1818
|
+
shedRounds = 0;
|
|
1819
|
+
}
|
|
1820
|
+
else if (canEdit && isServerUnavailableFrame(frame)) {
|
|
1821
|
+
onServerUnavailable();
|
|
1337
1822
|
}
|
|
1338
1823
|
else if (canEdit && isOpRejectedFrame(frame)) {
|
|
1339
|
-
//
|
|
1340
|
-
//
|
|
1341
|
-
// "could not be saved" surfaces instead of a stuck saving count.
|
|
1824
|
+
// Terminal, not transient: stop re-asserting this op (retrying
|
|
1825
|
+
// would only draw the same rejection) and fail it on the Document
|
|
1826
|
+
// so "could not be saved" surfaces instead of a stuck saving count.
|
|
1827
|
+
// A refusal naming the writer (an edit link downgraded or revoked
|
|
1828
|
+
// while the guest had it open) turns the Document read-only, the
|
|
1829
|
+
// same way it does for a signed-in reader.
|
|
1830
|
+
outstanding.delete(frame.client_op_id);
|
|
1831
|
+
if (isCapacityRejection(frame))
|
|
1832
|
+
doc._markAtCapacity();
|
|
1833
|
+
const readOnly = readOnlyReasonForRejection(frame);
|
|
1834
|
+
if (readOnly !== null)
|
|
1835
|
+
doc._markReadOnly(readOnly);
|
|
1342
1836
|
doc._failOutstandingOp(frame.client_op_id, opRejectedMessage(frame));
|
|
1343
1837
|
}
|
|
1344
|
-
}
|
|
1838
|
+
},
|
|
1839
|
+
// The guest owns its outstanding ops: `resendAllOutstanding` on the
|
|
1840
|
+
// `doc_init` behind every `subscribed` ack IS this topic's
|
|
1841
|
+
// re-assertion, so the client drops an op frame it cannot send now
|
|
1842
|
+
// rather than buffering a second copy of it.
|
|
1843
|
+
{ ownsFrameRetry: true });
|
|
1844
|
+
// An op the socket cannot carry, written over HTTP on the same policy
|
|
1845
|
+
// the signed-in path runs: refuse locally what no write can hold, and
|
|
1846
|
+
// re-assert a capacity refusal on the shared backoff before reporting it.
|
|
1847
|
+
async function writeOversizedGuestOp(opBlobB64, clientOpId) {
|
|
1848
|
+
// Yield before any outcome resolves the op. The hook's caller records
|
|
1849
|
+
// the outstanding op AFTER the hook returns, and an async function body
|
|
1850
|
+
// runs synchronously up to its first await, so an exit taken inline
|
|
1851
|
+
// would find nothing tracked and leave the entry behind with
|
|
1852
|
+
// `savingCount` stuck above zero.
|
|
1853
|
+
await Promise.resolve();
|
|
1854
|
+
// Both sizes are known here, so refuse without spending a round trip
|
|
1855
|
+
// on a blob that can only come back 400.
|
|
1856
|
+
if (opBlobExceedsDurableLimit(opBlobB64)) {
|
|
1857
|
+
doc._failOutstandingOp(clientOpId, TOO_LARGE_MESSAGE);
|
|
1858
|
+
return;
|
|
1859
|
+
}
|
|
1860
|
+
if (opBlobNeedsStaging(opBlobB64)) {
|
|
1861
|
+
doc._failOutstandingOp(clientOpId, LINK_OP_TOO_LARGE_MESSAGE);
|
|
1862
|
+
return;
|
|
1863
|
+
}
|
|
1864
|
+
let status = 0;
|
|
1865
|
+
let parsed = undefined;
|
|
1866
|
+
for (let round = 0; round <= UNAVAILABLE_MAX_ROUNDS; round += 1) {
|
|
1867
|
+
if (round > 0) {
|
|
1868
|
+
await new Promise((resolve) => {
|
|
1869
|
+
const timer = setTimeout(resolve, unavailableDelayMs(round));
|
|
1870
|
+
timer.unref?.();
|
|
1871
|
+
});
|
|
1872
|
+
}
|
|
1873
|
+
try {
|
|
1874
|
+
({ status, parsed } = await postLinkOp(token, lineId, opBlobB64, clientOpId));
|
|
1875
|
+
}
|
|
1876
|
+
catch (err) {
|
|
1877
|
+
// A throw leaves it unknown whether the handler ran, and this op
|
|
1878
|
+
// carries no idempotency the server dedupes on, so replaying it
|
|
1879
|
+
// could double-apply.
|
|
1880
|
+
doc._failOutstandingOp(clientOpId, err instanceof Error ? err.message : String(err));
|
|
1881
|
+
return;
|
|
1882
|
+
}
|
|
1883
|
+
if (status >= 200 && status < 300)
|
|
1884
|
+
break;
|
|
1885
|
+
if (!opWriteIsRetryable(status))
|
|
1886
|
+
break;
|
|
1887
|
+
}
|
|
1888
|
+
if (status < 200 || status >= 300) {
|
|
1889
|
+
doc._failOutstandingOp(clientOpId, opWriteIsRetryable(status)
|
|
1890
|
+
? UNAVAILABLE_GIVE_UP_MESSAGE
|
|
1891
|
+
: opWriteFailureMessage(status, parsed));
|
|
1892
|
+
return;
|
|
1893
|
+
}
|
|
1894
|
+
doc.resolveOutstandingOp(clientOpId);
|
|
1895
|
+
}
|
|
1345
1896
|
if (canEdit) {
|
|
1346
1897
|
const minter = opts.newClientOpId ?? defaultClientOpIdMinter;
|
|
1347
1898
|
doc.setLocalOpHook((opBlob) => {
|
|
1348
1899
|
const clientOpId = minter();
|
|
1349
|
-
|
|
1900
|
+
const opBlobB64 = bytesToBase64(opBlob);
|
|
1901
|
+
const sendFrame = {
|
|
1350
1902
|
type: 'op',
|
|
1351
1903
|
topic,
|
|
1352
|
-
op_blob:
|
|
1904
|
+
op_blob: opBlobB64,
|
|
1353
1905
|
client_op_id: clientOpId,
|
|
1354
|
-
}
|
|
1906
|
+
};
|
|
1907
|
+
// A frame past the transport's cap is not delivered and takes the
|
|
1908
|
+
// connection down with it, so it must never reach the socket: a
|
|
1909
|
+
// guest's document, presence and every other op ride that one
|
|
1910
|
+
// connection. `mutate` batches to a budget well above what a frame
|
|
1911
|
+
// carries, so an ordinary bulk edit arrives here.
|
|
1912
|
+
if (opFrameExceedsWsLimit(sendFrame)) {
|
|
1913
|
+
void writeOversizedGuestOp(opBlobB64, clientOpId);
|
|
1914
|
+
return clientOpId;
|
|
1915
|
+
}
|
|
1916
|
+
outstanding.set(clientOpId, sendFrame);
|
|
1917
|
+
wsClient.send(sendFrame);
|
|
1355
1918
|
return clientOpId;
|
|
1356
1919
|
});
|
|
1357
1920
|
}
|
|
1358
1921
|
const originalClose = doc.close.bind(doc);
|
|
1359
1922
|
doc.close = () => {
|
|
1923
|
+
clearShedRecovery();
|
|
1360
1924
|
try {
|
|
1361
1925
|
unsub();
|
|
1362
1926
|
}
|
|
@@ -1366,13 +1930,71 @@ export function createOpenDocument(opts) {
|
|
|
1366
1930
|
originalClose();
|
|
1367
1931
|
};
|
|
1368
1932
|
}
|
|
1933
|
+
// Guest documents with a content pull running, so a repeated terminal frame
|
|
1934
|
+
// does not stack a second pull on one document.
|
|
1935
|
+
const guestPullInFlight = new WeakSet();
|
|
1936
|
+
function pullGuestContent(doc, token, lineId, finalStatus) {
|
|
1937
|
+
if (guestPullInFlight.has(doc))
|
|
1938
|
+
return;
|
|
1939
|
+
guestPullInFlight.add(doc);
|
|
1940
|
+
void (async () => {
|
|
1941
|
+
await pullContentWithRetry({
|
|
1942
|
+
doc,
|
|
1943
|
+
docId: doc.id ?? '',
|
|
1944
|
+
finalStatus,
|
|
1945
|
+
fetchAndImport: () => importLinkView(doc, token, lineId),
|
|
1946
|
+
...(opts.reportError ? { reportError: opts.reportError } : {}),
|
|
1947
|
+
});
|
|
1948
|
+
guestPullInFlight.delete(doc);
|
|
1949
|
+
})();
|
|
1950
|
+
}
|
|
1951
|
+
// Re-read the link view and import it into the live guest Document: the
|
|
1952
|
+
// anonymous counterpart of the signed-in `refetchAndImport`, over the same
|
|
1953
|
+
// envelope. Named on the line the guest opened, which is the line its topic
|
|
1954
|
+
// is scoped to.
|
|
1955
|
+
async function importLinkView(doc, token, lineId) {
|
|
1956
|
+
const result = await fetchLinkView(token, lineId);
|
|
1957
|
+
if (result.status < 200 || result.status >= 300) {
|
|
1958
|
+
return { ok: false, reason: `link view returned ${result.status}` };
|
|
1959
|
+
}
|
|
1960
|
+
const b = result.parsed;
|
|
1961
|
+
if (!Array.isArray(b.tail_ops)) {
|
|
1962
|
+
return { ok: false, reason: 'malformed link view response' };
|
|
1963
|
+
}
|
|
1964
|
+
const snap = b.snapshot;
|
|
1965
|
+
let snapshotBytes = null;
|
|
1966
|
+
if (snap !== null && snap !== undefined && snap.kind === 'inline') {
|
|
1967
|
+
snapshotBytes = base64ToBytes(snap.data_b64);
|
|
1968
|
+
}
|
|
1969
|
+
else if (snap !== null && snap !== undefined && snap.kind === 'presigned') {
|
|
1970
|
+
try {
|
|
1971
|
+
snapshotBytes = await fetchPresignedSnapshot(snap.url);
|
|
1972
|
+
}
|
|
1973
|
+
catch (err) {
|
|
1974
|
+
const status = err instanceof BrassError ? err.status ?? 0 : 0;
|
|
1975
|
+
return {
|
|
1976
|
+
ok: false,
|
|
1977
|
+
reason: status > 0
|
|
1978
|
+
? `presigned snapshot fetch returned ${status}`
|
|
1979
|
+
: `presigned snapshot fetch failed: ${err instanceof Error ? err.message : String(err)}`,
|
|
1980
|
+
};
|
|
1981
|
+
}
|
|
1982
|
+
}
|
|
1983
|
+
if (snapshotBytes)
|
|
1984
|
+
doc._applySnapshot(snapshotBytes);
|
|
1985
|
+
const tail = b.tail_ops;
|
|
1986
|
+
for (const entry of [...tail].sort((x, y) => x.seq - y.seq)) {
|
|
1987
|
+
doc.applyRemoteOp(base64ToBytes(entry.op_blob_b64));
|
|
1988
|
+
}
|
|
1989
|
+
return { ok: true };
|
|
1990
|
+
}
|
|
1369
1991
|
// Strict open: a 404 propagates as `BrassError`. A `version` option
|
|
1370
1992
|
// diverts to the read-only at-version path.
|
|
1371
1993
|
const open = async (docId, options) => {
|
|
1372
1994
|
// Cache hit: return the parked Document. Its subscription stayed alive
|
|
1373
1995
|
// while parked, and the UndoController + outstanding-op map survived, so
|
|
1374
1996
|
// undo works as if the user never switched away.
|
|
1375
|
-
const parked = takeParkedDocument(docId, options);
|
|
1997
|
+
const parked = takeParkedDocument(docId, options, opts.identity?.() ?? null);
|
|
1376
1998
|
if (parked) {
|
|
1377
1999
|
parked._resume();
|
|
1378
2000
|
return parked;
|
|
@@ -1438,6 +2060,13 @@ export function createOpenDocument(opts) {
|
|
|
1438
2060
|
// state to keep. Module-scoped so it persists across factory invocations in
|
|
1439
2061
|
// one process; keys are app-supplied so no cross-app leak within a tab.
|
|
1440
2062
|
const PARK_CACHE_CAPACITY = 4;
|
|
2063
|
+
function documentOptionsSig(options) {
|
|
2064
|
+
return JSON.stringify([
|
|
2065
|
+
options?.rootKey ?? null,
|
|
2066
|
+
options?.readOnly ?? null,
|
|
2067
|
+
options?.undo ?? null,
|
|
2068
|
+
]);
|
|
2069
|
+
}
|
|
1441
2070
|
const parkedDocs = new Map();
|
|
1442
2071
|
function parkCacheKey(docId, branchId, streamName) {
|
|
1443
2072
|
// Skip caching when the branch is unknown: the next open() may resolve to
|
|
@@ -1451,7 +2080,23 @@ function parkCacheKey(docId, branchId, streamName) {
|
|
|
1451
2080
|
// caller's document out from under it.
|
|
1452
2081
|
return `${docId}/${branchId}/${streamName ?? DEFAULT_STREAM_NAME}`;
|
|
1453
2082
|
}
|
|
2083
|
+
function evictParked(entry) {
|
|
2084
|
+
if (!entry)
|
|
2085
|
+
return;
|
|
2086
|
+
parkedDocs.delete(entry.key);
|
|
2087
|
+
try {
|
|
2088
|
+
entry.teardown();
|
|
2089
|
+
}
|
|
2090
|
+
catch {
|
|
2091
|
+
// Teardown errors must not strand the cache; the evicted Doc is gone
|
|
2092
|
+
// from the user's perspective either way.
|
|
2093
|
+
}
|
|
2094
|
+
}
|
|
1454
2095
|
function parkDocument(entry) {
|
|
2096
|
+
// One Document per key: whatever sat here is unreachable the moment this
|
|
2097
|
+
// entry replaces it, so it is torn down rather than left holding a live
|
|
2098
|
+
// subscription nothing can close.
|
|
2099
|
+
evictParked(parkedDocs.get(entry.key));
|
|
1455
2100
|
parkedDocs.set(entry.key, entry);
|
|
1456
2101
|
// Map iteration is insertion order, so evicting the front entry is LRU
|
|
1457
2102
|
// (a newly parked entry is the most-recent; a hit removes the entry
|
|
@@ -1460,18 +2105,10 @@ function parkDocument(entry) {
|
|
|
1460
2105
|
const oldestKey = parkedDocs.keys().next().value;
|
|
1461
2106
|
if (oldestKey === undefined)
|
|
1462
2107
|
break;
|
|
1463
|
-
|
|
1464
|
-
parkedDocs.delete(oldestKey);
|
|
1465
|
-
try {
|
|
1466
|
-
oldest?.teardown();
|
|
1467
|
-
}
|
|
1468
|
-
catch {
|
|
1469
|
-
// Teardown errors must not strand the cache; the evicted Doc is gone
|
|
1470
|
-
// from the user's perspective either way.
|
|
1471
|
-
}
|
|
2108
|
+
evictParked(parkedDocs.get(oldestKey));
|
|
1472
2109
|
}
|
|
1473
2110
|
}
|
|
1474
|
-
function takeParkedDocument(docId, options) {
|
|
2111
|
+
function takeParkedDocument(docId, options, identity) {
|
|
1475
2112
|
if (options?.version !== undefined)
|
|
1476
2113
|
return null;
|
|
1477
2114
|
const key = parkCacheKey(docId, options?.branch, options?.stream);
|
|
@@ -1480,22 +2117,36 @@ function takeParkedDocument(docId, options) {
|
|
|
1480
2117
|
const entry = parkedDocs.get(key);
|
|
1481
2118
|
if (!entry)
|
|
1482
2119
|
return null;
|
|
2120
|
+
// A Document the server evicted while it was parked describes a document
|
|
2121
|
+
// that is no longer there, one built from different `documentOptions` is
|
|
2122
|
+
// not the Document this caller asked for, and one opened for a different
|
|
2123
|
+
// person is not this caller's to read. All three take the fresh open, which
|
|
2124
|
+
// for the last is the request that establishes the new caller may have it;
|
|
2125
|
+
// the parked copy goes with its subscription.
|
|
2126
|
+
if (entry.doc._goneReason !== null ||
|
|
2127
|
+
entry.optionsSig !== documentOptionsSig(options?.documentOptions) ||
|
|
2128
|
+
entry.identity !== identity) {
|
|
2129
|
+
evictParked(entry);
|
|
2130
|
+
return null;
|
|
2131
|
+
}
|
|
1483
2132
|
parkedDocs.delete(key);
|
|
1484
2133
|
return entry.doc;
|
|
1485
2134
|
}
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
2135
|
+
/** Retire every parked Document. The client calls this as an identity leaves
|
|
2136
|
+
* the page, so what the previous person opened is torn down rather than left
|
|
2137
|
+
* resident for the rest of the tab's life.
|
|
2138
|
+
* @internal */
|
|
2139
|
+
export function clearParkedDocuments() {
|
|
1489
2140
|
for (const entry of parkedDocs.values()) {
|
|
1490
|
-
|
|
1491
|
-
entry.teardown();
|
|
1492
|
-
}
|
|
1493
|
-
catch {
|
|
1494
|
-
// ignore
|
|
1495
|
-
}
|
|
2141
|
+
evictParked(entry);
|
|
1496
2142
|
}
|
|
1497
2143
|
parkedDocs.clear();
|
|
1498
2144
|
}
|
|
2145
|
+
// Test-only: drop the parking cache. Used by unit tests that need
|
|
2146
|
+
// a clean slate between cases.
|
|
2147
|
+
export function _resetParkCacheForTesting() {
|
|
2148
|
+
clearParkedDocuments();
|
|
2149
|
+
}
|
|
1499
2150
|
// Wire the WS transport onto a materialised Document. Three pieces:
|
|
1500
2151
|
// 1. WS subscribe on the doc topic; the server sends `doc_op` (other
|
|
1501
2152
|
// clients' edits) and `op_ack` (our ops), topic-scoped so the
|
|
@@ -1519,17 +2170,76 @@ export const PERIODIC_REVERIFY_INTERVAL_MS = 5 * 60_000;
|
|
|
1519
2170
|
// delay is an op the server will not send again. Exported for the
|
|
1520
2171
|
// fake-timer test.
|
|
1521
2172
|
export const MISSED_OP_RESYNC_DELAY_MS = 2_000;
|
|
2173
|
+
// Per-op resend backoff: 1.5s, ~1.6x per attempt, to a 30s ceiling. The
|
|
2174
|
+
// ceiling keeps a doc on a dead connection from hammering; the
|
|
2175
|
+
// reconnect-driven resend (`resendAllOutstanding`) fires the instant
|
|
2176
|
+
// `doc_init` arrives, so the ceiling never delays recovery past the next
|
|
2177
|
+
// reconnect. Exported for the fake-timer tests.
|
|
2178
|
+
export const RESEND_BASE_DELAY_MS = 1_500;
|
|
2179
|
+
export const RESEND_MAX_DELAY_MS = 30_000;
|
|
2180
|
+
// How long the oldest op on the socket may go unacked before its resend
|
|
2181
|
+
// timer spends an attempt even though the connection is answering other
|
|
2182
|
+
// ops. See `scheduleResend` for what this bounds and why only the oldest op
|
|
2183
|
+
// reaches it.
|
|
2184
|
+
//
|
|
2185
|
+
// The value sits above every latency a working connection produces. Acks
|
|
2186
|
+
// measured on a deployed environment run 175 ms at p99 and 1.6 s at their
|
|
2187
|
+
// worst, and an op whose own backoff has grown to `RESEND_MAX_DELAY_MS` is
|
|
2188
|
+
// still well inside this, so a queue that is merely slow never reaches it and
|
|
2189
|
+
// the timer keeps re-arming free. Sitting above the backoff ceiling is also
|
|
2190
|
+
// what makes this value, rather than the backoff, the interval a forced
|
|
2191
|
+
// resend is paced at: the timer fires several times inside one window, and
|
|
2192
|
+
// the first expiry past the window is the one that spends.
|
|
2193
|
+
//
|
|
2194
|
+
// What a false positive costs bounds the risk of setting it at all: one
|
|
2195
|
+
// duplicate op per document per window, which is a Loro no-op on import. The
|
|
2196
|
+
// failure this replaces is unbounded in the other direction, an op the
|
|
2197
|
+
// server never received and nothing ever sends again.
|
|
2198
|
+
// Exported for the fake-timer tests.
|
|
2199
|
+
export const RESEND_FORCE_CEILING_MS = 60_000;
|
|
2200
|
+
// Server-shed recovery policy, driven by `unavailable` error frames. The
|
|
2201
|
+
// frame names no op, so a round re-asserts every outstanding op at once and
|
|
2202
|
+
// any further frame arriving before that round runs is part of the same shed
|
|
2203
|
+
// batch: coalescing them is what keeps N shed ops from fanning out into N
|
|
2204
|
+
// rounds of N resends. Backoff is 1s doubling to a 30s ceiling, so the budget
|
|
2205
|
+
// spans roughly a minute and a half of sustained shedding. An `op_ack` (the
|
|
2206
|
+
// server taking writes again) or a reconnect returns the budget to full.
|
|
2207
|
+
//
|
|
2208
|
+
// Module-scoped because both transports answer a shed on it: the signed-in
|
|
2209
|
+
// one, the HTTP write for an op past the frame cap, and the guest-link one.
|
|
2210
|
+
// A shed costs an edit the same nothing whoever wrote it and whichever
|
|
2211
|
+
// transport carried it.
|
|
2212
|
+
const UNAVAILABLE_MAX_ROUNDS = 6;
|
|
2213
|
+
const UNAVAILABLE_BASE_DELAY_MS = 1000;
|
|
2214
|
+
const UNAVAILABLE_MAX_DELAY_MS = 30_000;
|
|
2215
|
+
const UNAVAILABLE_GIVE_UP_MESSAGE = 'The server could not store this change, and re-sending it did not ' +
|
|
2216
|
+
'help. Reload the document to continue from the last saved state.';
|
|
2217
|
+
// Reported for every op left behind when the server ends this document's
|
|
2218
|
+
// subscription (it refused the subscribe, or evicted it again after the one
|
|
2219
|
+
// silent re-subscribe a connection grants). The ops can never be acked on a
|
|
2220
|
+
// subscription that is over, and a fresh one arrives only with a fresh open,
|
|
2221
|
+
// so the app's cue is to reload.
|
|
2222
|
+
const SUBSCRIPTION_ENDED_MESSAGE = 'The live connection to this document ended, so this change was not ' +
|
|
2223
|
+
'saved. Reload the document to continue from the last saved state.';
|
|
2224
|
+
/** How long the Nth (1-based) recovery round waits before re-asserting. */
|
|
2225
|
+
function unavailableDelayMs(round) {
|
|
2226
|
+
return Math.min(UNAVAILABLE_BASE_DELAY_MS * Math.pow(2, round - 1), UNAVAILABLE_MAX_DELAY_MS);
|
|
2227
|
+
}
|
|
1522
2228
|
// A mutation carrying many records commits as it goes, so the only write
|
|
1523
2229
|
// that reaches this is one record nothing can split.
|
|
1524
2230
|
const TOO_LARGE_MESSAGE = 'This record is too large to save. A single record must fit in one ' +
|
|
1525
2231
|
'update; store the bulk of it as a file instead, or split it across ' +
|
|
1526
2232
|
'several records.';
|
|
2233
|
+
// What a guest hears for an op no request body can carry. A signed-in
|
|
2234
|
+
// editor stages such an op to storage first; that route is behind the
|
|
2235
|
+
// sign-in gate, so the anonymous tier writes ops that fit one request.
|
|
2236
|
+
const LINK_OP_TOO_LARGE_MESSAGE = 'This change is too large to save over a shared link. Sign in to the ' +
|
|
2237
|
+
'document to make a change this size.';
|
|
1527
2238
|
function wireDocTransport(args) {
|
|
1528
2239
|
const topic = `doc:${args.docId}:${args.branchId}`;
|
|
1529
|
-
// Per-op retry tracker. The op-write endpoint
|
|
1530
|
-
//
|
|
1531
|
-
//
|
|
1532
|
-
// That frame has no `type`, so the multiplexer drops it,
|
|
2240
|
+
// Per-op retry tracker. The op-write endpoint can answer with an untyped
|
|
2241
|
+
// error frame instead of reaching the handler. That frame has no `type`, so
|
|
2242
|
+
// the multiplexer drops it,
|
|
1533
2243
|
// leaving the op stuck in `Document._outstandingByClientId` and the
|
|
1534
2244
|
// actor's lamport stream with a gap that blocks other subscribers' Loro
|
|
1535
2245
|
// imports from converging (Loro requires per-actor causal contiguity).
|
|
@@ -1541,7 +2251,130 @@ function wireDocTransport(args) {
|
|
|
1541
2251
|
// retry lands the dependent chain converges everywhere. `doc.savingCount`
|
|
1542
2252
|
// stays above zero until the `op_ack` lands (the "Saving…" surface); there
|
|
1543
2253
|
// is no give-up to surface because the SDK keeps trying.
|
|
2254
|
+
// When each op this transport shipped was first committed, keyed the same
|
|
2255
|
+
// way the tracker is. The tracker itself carries no commit time (its
|
|
2256
|
+
// `dispatchedAt` restarts on every resend, which is the right basis for
|
|
2257
|
+
// deciding a resend and the wrong one for reporting how long a reader has
|
|
2258
|
+
// been waiting), and an op past the frame cap is never in the tracker at
|
|
2259
|
+
// all. Entries are dropped as their op settles, so the map's size is the
|
|
2260
|
+
// work outstanding on either transport.
|
|
2261
|
+
const opStartedAt = new Map();
|
|
2262
|
+
// Reconnects the socket had made when this transport last saw a
|
|
2263
|
+
// `doc_init`. The frame itself is not a reconnect signal: it rides every
|
|
2264
|
+
// `subscribed` ack, including the opening one and the silent re-subscribe
|
|
2265
|
+
// a connection grants after a mid-stream eviction, neither of which
|
|
2266
|
+
// involved the socket dropping. A report keyed off the frame therefore
|
|
2267
|
+
// fires when nothing is wrong, which is the fault this latch exists to
|
|
2268
|
+
// avoid, so it is keyed off the socket instead.
|
|
2269
|
+
let docInitReconnectCount = null;
|
|
1544
2270
|
const outstandingResends = new Map();
|
|
2271
|
+
// How many bytes of op frames may be on the socket unacked at once.
|
|
2272
|
+
//
|
|
2273
|
+
// The transport drops the connection when a client pushes at it hard
|
|
2274
|
+
// enough, and it takes everything multiplexed onto that socket with it;
|
|
2275
|
+
// every op then goes unacked, the reconnect re-asserts them, and that
|
|
2276
|
+
// burst drops the connection again, so nothing is ever persisted.
|
|
2277
|
+
// Measured against one write, a client pushing 26 frames in 320 ms lost
|
|
2278
|
+
// the socket where one spreading 90 frames over 5.3 s did not, so what
|
|
2279
|
+
// this bounds is the RATE rather than any one frame's size.
|
|
2280
|
+
//
|
|
2281
|
+
// Which shape reaches it is worth knowing before tuning it. A bulk write
|
|
2282
|
+
// does not: `mutate` batches to a budget far above what a frame carries,
|
|
2283
|
+
// so its ops take the HTTP write and never enter this queue. What does is
|
|
2284
|
+
// an app issuing many separate mutations that each land under the frame
|
|
2285
|
+
// cap, a drag loop or a per-row import, where the op count is set by how
|
|
2286
|
+
// often the app calls rather than by how much it writes.
|
|
2287
|
+
//
|
|
2288
|
+
// A byte budget rather than a rate is what makes this self-tuning: sends
|
|
2289
|
+
// resume as acks land, so the client goes exactly as fast as the server
|
|
2290
|
+
// is answering and no faster, whatever that speed turns out to be. The
|
|
2291
|
+
// budget is generous enough to keep several ops in flight, so an ack's
|
|
2292
|
+
// round trip is not serialised into the write.
|
|
2293
|
+
const IN_FLIGHT_BUDGET_BYTES = 256 * 1024;
|
|
2294
|
+
// Ops committed but not yet on the socket, oldest first.
|
|
2295
|
+
const sendQueue = [];
|
|
2296
|
+
let inFlightBytes = 0;
|
|
2297
|
+
/** Put an op on the socket if the budget allows, else queue it. */
|
|
2298
|
+
function dispatchOp(clientOpId) {
|
|
2299
|
+
const entry = outstandingResends.get(clientOpId);
|
|
2300
|
+
if (!entry || entry.inFlight > 0)
|
|
2301
|
+
return;
|
|
2302
|
+
const size = entry.frame.op_blob.length;
|
|
2303
|
+
// An op larger than the whole budget goes on its own rather than
|
|
2304
|
+
// waiting for room that can never appear.
|
|
2305
|
+
if (inFlightBytes > 0 && inFlightBytes + size > IN_FLIGHT_BUDGET_BYTES) {
|
|
2306
|
+
if (!entry.queued) {
|
|
2307
|
+
entry.queued = true;
|
|
2308
|
+
entry.dispatchedAt = 0;
|
|
2309
|
+
sendQueue.push(clientOpId);
|
|
2310
|
+
}
|
|
2311
|
+
return;
|
|
2312
|
+
}
|
|
2313
|
+
entry.queued = false;
|
|
2314
|
+
entry.inFlight = size;
|
|
2315
|
+
entry.dispatchedAt = Date.now();
|
|
2316
|
+
inFlightBytes += size;
|
|
2317
|
+
args.wsClient.send(entry.frame);
|
|
2318
|
+
scheduleResend(clientOpId);
|
|
2319
|
+
}
|
|
2320
|
+
/** The oldest op currently on the socket, which is the one a gap blocks
|
|
2321
|
+
* the rest of this actor's stream behind. Map order is commit order, and
|
|
2322
|
+
* an op waiting on the in-flight budget carries no timer, so the first
|
|
2323
|
+
* dispatched entry is that op. */
|
|
2324
|
+
function isOldestDispatchedOp(clientOpId) {
|
|
2325
|
+
for (const [id, entry] of outstandingResends) {
|
|
2326
|
+
if (entry.dispatchedAt === 0)
|
|
2327
|
+
continue;
|
|
2328
|
+
return id === clientOpId;
|
|
2329
|
+
}
|
|
2330
|
+
return false;
|
|
2331
|
+
}
|
|
2332
|
+
/** Send whatever the freed budget now has room for. */
|
|
2333
|
+
function drainSendQueue() {
|
|
2334
|
+
while (sendQueue.length > 0) {
|
|
2335
|
+
const next = sendQueue[0];
|
|
2336
|
+
const entry = outstandingResends.get(next);
|
|
2337
|
+
// An op acked, rejected or abandoned while queued leaves its id behind;
|
|
2338
|
+
// dropping it here is what keeps `forgetOp` off a queue scan.
|
|
2339
|
+
if (!entry || !entry.queued) {
|
|
2340
|
+
sendQueue.shift();
|
|
2341
|
+
continue;
|
|
2342
|
+
}
|
|
2343
|
+
const size = entry.frame.op_blob.length;
|
|
2344
|
+
if (inFlightBytes > 0 && inFlightBytes + size > IN_FLIGHT_BUDGET_BYTES) {
|
|
2345
|
+
return;
|
|
2346
|
+
}
|
|
2347
|
+
sendQueue.shift();
|
|
2348
|
+
entry.queued = false;
|
|
2349
|
+
dispatchOp(next);
|
|
2350
|
+
}
|
|
2351
|
+
}
|
|
2352
|
+
/** Drop one op from the tracker, returning its budget. */
|
|
2353
|
+
function forgetOp(clientOpId) {
|
|
2354
|
+
const entry = outstandingResends.get(clientOpId);
|
|
2355
|
+
if (!entry)
|
|
2356
|
+
return;
|
|
2357
|
+
clearTimeout(entry.timer);
|
|
2358
|
+
inFlightBytes -= entry.inFlight;
|
|
2359
|
+
entry.inFlight = 0;
|
|
2360
|
+
entry.queued = false;
|
|
2361
|
+
outstandingResends.delete(clientOpId);
|
|
2362
|
+
opStartedAt.delete(clientOpId);
|
|
2363
|
+
drainSendQueue();
|
|
2364
|
+
}
|
|
2365
|
+
/** Drop every tracked op and reset the budget with them. */
|
|
2366
|
+
function forgetAllOps() {
|
|
2367
|
+
for (const [clientOpId, entry] of outstandingResends) {
|
|
2368
|
+
clearTimeout(entry.timer);
|
|
2369
|
+
// Only the ops this tracker holds. An op past the frame cap is
|
|
2370
|
+
// travelling over HTTP and is not in here, so clearing the whole
|
|
2371
|
+
// timing map would report it settled while its write is still going.
|
|
2372
|
+
opStartedAt.delete(clientOpId);
|
|
2373
|
+
}
|
|
2374
|
+
outstandingResends.clear();
|
|
2375
|
+
sendQueue.length = 0;
|
|
2376
|
+
inFlightBytes = 0;
|
|
2377
|
+
}
|
|
1545
2378
|
// Ops this client is writing over HTTP, and the highest seq a catch-up
|
|
1546
2379
|
// prompt named while one was in flight.
|
|
1547
2380
|
//
|
|
@@ -1564,44 +2397,388 @@ function wireDocTransport(args) {
|
|
|
1564
2397
|
const seq = heldCatchUpSeq;
|
|
1565
2398
|
heldCatchUpSeq = 0;
|
|
1566
2399
|
if (seq > 0 && args.getCoveredSeq() < seq)
|
|
1567
|
-
|
|
1568
|
-
}
|
|
1569
|
-
//
|
|
1570
|
-
//
|
|
1571
|
-
//
|
|
1572
|
-
//
|
|
1573
|
-
|
|
1574
|
-
|
|
2400
|
+
pullJoin();
|
|
2401
|
+
}
|
|
2402
|
+
// Pull the join, and ask again if it left the reader short.
|
|
2403
|
+
//
|
|
2404
|
+
// A join read while a peer writes in bulk is a torn cut: the branch's seq
|
|
2405
|
+
// counter has run ahead of the op rows, so the response reports a head it
|
|
2406
|
+
// could not deliver the tail for. The reader applies what arrived and its
|
|
2407
|
+
// floor lands below that head, and nothing re-sends the difference. So
|
|
2408
|
+
// whatever the reader still lacks after an import is a hole it has to ask
|
|
2409
|
+
// about itself, which is what a passive reader has instead of the `doc_op`
|
|
2410
|
+
// and `op_ack` frames a writing client arms its checks from.
|
|
2411
|
+
function pullJoin() {
|
|
2412
|
+
void Promise.resolve(args.resyncFromSnapshot?.()).then(() => {
|
|
2413
|
+
scheduleGapCheck();
|
|
2414
|
+
}, () => {
|
|
2415
|
+
// `resyncFromSnapshot` reports its own failures and resolves; a
|
|
2416
|
+
// rejection is a caller that does not, and asking again is still the
|
|
2417
|
+
// right move.
|
|
2418
|
+
scheduleGapCheck();
|
|
2419
|
+
});
|
|
2420
|
+
}
|
|
2421
|
+
// Re-import the join for ops this client cannot bridge to from what it
|
|
2422
|
+
// holds, deferring the judgement while one of its own HTTP writes is still
|
|
2423
|
+
// in flight. Shared by the catch-up prompt and by the reconnect handshake,
|
|
2424
|
+
// which reaches the same conclusion off its tail.
|
|
2425
|
+
// Re-import when the durable frontier names an author whose changes never
|
|
2426
|
+
// came through the op stream. Separate from the coverage check because it
|
|
2427
|
+
// answers a different question: not "did I miss an op" but "did what I hold
|
|
2428
|
+
// stop being how this document is stored".
|
|
2429
|
+
function maybeResyncPastRewrite(vectorB64) {
|
|
2430
|
+
if (!vectorB64)
|
|
2431
|
+
return;
|
|
2432
|
+
let unseen = false;
|
|
2433
|
+
try {
|
|
2434
|
+
unseen = args.doc._snapshotHasUnseenAuthor(base64ToBytes(vectorB64));
|
|
2435
|
+
}
|
|
2436
|
+
catch {
|
|
2437
|
+
return;
|
|
2438
|
+
}
|
|
2439
|
+
if (unseen)
|
|
2440
|
+
pullJoin();
|
|
2441
|
+
}
|
|
2442
|
+
function resyncPastSeq(seq) {
|
|
2443
|
+
if (httpOpWritesInFlight > 0) {
|
|
2444
|
+
if (seq > heldCatchUpSeq)
|
|
2445
|
+
heldCatchUpSeq = seq;
|
|
2446
|
+
return;
|
|
2447
|
+
}
|
|
2448
|
+
pullJoin();
|
|
2449
|
+
}
|
|
1575
2450
|
function resendDelayMs(attempts) {
|
|
1576
2451
|
const grown = RESEND_BASE_DELAY_MS * Math.pow(1.6, attempts - 1);
|
|
1577
2452
|
return Math.min(grown, RESEND_MAX_DELAY_MS);
|
|
1578
2453
|
}
|
|
2454
|
+
// When this connection last proved it was working: any `op_ack`, from any
|
|
2455
|
+
// op on this topic.
|
|
2456
|
+
//
|
|
2457
|
+
// What this timer is for is a server that answered NOTHING, which is a
|
|
2458
|
+
// real case (an op frame can draw the opaque `{"message":"Internal server
|
|
2459
|
+
// error"}` reply the multiplexer drops). What it must not read as silence
|
|
2460
|
+
// is an ack that is merely behind, because with many ops in flight one
|
|
2461
|
+
// op's latency is the queue's depth times its service time, not evidence
|
|
2462
|
+
// about that op. Resending on that reading writes the op a second time,
|
|
2463
|
+
// which deepens the queue, which slows the next ack, which fires more
|
|
2464
|
+
// resends.
|
|
2465
|
+
//
|
|
2466
|
+
// Measured on a 500,000-element write: the same content went through in
|
|
2467
|
+
// 1,320 op writes on a run whose acks stayed under 375 ms, and in 3,600 on
|
|
2468
|
+
// a run whose acks reached 1,615 ms, just past this backoff's first step.
|
|
2469
|
+
// The extra writes are durable duplicates, so they inflate the document's
|
|
2470
|
+
// history, and every later compaction pays for them: the run that tripled
|
|
2471
|
+
// its ops left a tail compaction could not absorb inside its memory, and
|
|
2472
|
+
// the document stopped opening.
|
|
2473
|
+
//
|
|
2474
|
+
// So the timer fires on silence rather than on slowness: an ack that
|
|
2475
|
+
// arrived after this op's timer was armed re-arms it without spending an
|
|
2476
|
+
// attempt, within the bound `forceResendDue` puts on how long one op may
|
|
2477
|
+
// ride that evidence.
|
|
2478
|
+
let lastAckAt = 0;
|
|
1579
2479
|
function scheduleResend(clientOpId) {
|
|
1580
2480
|
const entry = outstandingResends.get(clientOpId);
|
|
1581
2481
|
if (!entry)
|
|
1582
2482
|
return;
|
|
2483
|
+
entry.armedAt = Date.now();
|
|
1583
2484
|
entry.timer = setTimeout(() => {
|
|
1584
2485
|
const current = outstandingResends.get(clientOpId);
|
|
1585
2486
|
if (!current)
|
|
1586
2487
|
return;
|
|
2488
|
+
const forced = forceResendDue(clientOpId, current);
|
|
2489
|
+
if (lastAckAt >= current.armedAt && !forced) {
|
|
2490
|
+
scheduleResend(clientOpId);
|
|
2491
|
+
return;
|
|
2492
|
+
}
|
|
2493
|
+
// A forced resend is the transport concluding this op was lost, which
|
|
2494
|
+
// is the one condition here the server cannot infer, so it is what the
|
|
2495
|
+
// report is pinned to.
|
|
2496
|
+
if (forced)
|
|
2497
|
+
reportSyncHealth('op_stuck');
|
|
1587
2498
|
current.attempts += 1;
|
|
2499
|
+
current.dispatchedAt = Date.now();
|
|
1588
2500
|
args.wsClient.send(current.frame);
|
|
1589
2501
|
scheduleResend(clientOpId);
|
|
1590
2502
|
}, resendDelayMs(entry.attempts));
|
|
1591
2503
|
}
|
|
2504
|
+
// The one case where an answering connection is still evidence this op was
|
|
2505
|
+
// lost: it is the oldest op on the socket and it has been there longer than
|
|
2506
|
+
// any working connection takes to answer.
|
|
2507
|
+
//
|
|
2508
|
+
// The evidence `lastAckAt` carries is that the connection is working, not
|
|
2509
|
+
// that it received this op, so an app committing faster than the backoff
|
|
2510
|
+
// supplies that evidence continuously and a dropped op would re-arm free
|
|
2511
|
+
// forever. The server's copy of the document then stops at the gap (Loro
|
|
2512
|
+
// requires per-actor causal contiguity, so every later op is stored and
|
|
2513
|
+
// never applied), the tracker entry never reaches a terminal state, and the
|
|
2514
|
+
// app is told nothing.
|
|
2515
|
+
//
|
|
2516
|
+
// Ack ORDER cannot stand in for that evidence. Acks overtake heavily: 24
|
|
2517
|
+
// ops sent back to back on a deployed environment came back with 10 of 23
|
|
2518
|
+
// adjacent pairs out of send order, and the op sent first was acked 23rd. A
|
|
2519
|
+
// rule reading a later op's ack as proof this one was skipped re-sends ops
|
|
2520
|
+
// that are merely in flight, which is the write-it-twice failure the gate
|
|
2521
|
+
// above exists to prevent.
|
|
2522
|
+
//
|
|
2523
|
+
// Restricting this to the oldest dispatched op is what keeps the traffic
|
|
2524
|
+
// bounded and is sufficient. Bounded: one op per ceiling window however
|
|
2525
|
+
// many ops are outstanding, which matters because this resend hands the
|
|
2526
|
+
// frame straight to `wsClient.send` and so spends none of the in-flight
|
|
2527
|
+
// budget, and a simultaneous round of them is the burst that drops the
|
|
2528
|
+
// socket. Sufficient: the gap at the oldest op is what holds the rest of
|
|
2529
|
+
// this actor's stream unapplied, and an op behind it becomes the oldest in
|
|
2530
|
+
// its turn as the ops in front retire.
|
|
2531
|
+
function forceResendDue(clientOpId, entry) {
|
|
2532
|
+
if (entry.dispatchedAt === 0)
|
|
2533
|
+
return false;
|
|
2534
|
+
if (Date.now() - entry.dispatchedAt <= RESEND_FORCE_CEILING_MS)
|
|
2535
|
+
return false;
|
|
2536
|
+
return isOldestDispatchedOp(clientOpId);
|
|
2537
|
+
}
|
|
2538
|
+
// What this transport knows about its own sync, for a reader whose save
|
|
2539
|
+
// is taking longer than it should. Everything here is closure state the
|
|
2540
|
+
// transport already keeps; collecting it costs a walk of the outstanding
|
|
2541
|
+
// ops, so it is safe to call from a render.
|
|
2542
|
+
function collectDiagnostics() {
|
|
2543
|
+
const now = Date.now();
|
|
2544
|
+
let oldestClientOpId = null;
|
|
2545
|
+
let oldestStartedAt = 0;
|
|
2546
|
+
// Insertion order is commit order, so the first entry is the oldest.
|
|
2547
|
+
for (const [clientOpId, startedAt] of opStartedAt) {
|
|
2548
|
+
oldestClientOpId = clientOpId;
|
|
2549
|
+
oldestStartedAt = startedAt;
|
|
2550
|
+
break;
|
|
2551
|
+
}
|
|
2552
|
+
return {
|
|
2553
|
+
unackedOps: opStartedAt.size,
|
|
2554
|
+
oldestUnackedMs: oldestClientOpId === null ? 0 : Math.max(0, now - oldestStartedAt),
|
|
2555
|
+
oldestClientOpId,
|
|
2556
|
+
reconnects: args.wsClient.reconnectCount ?? 0,
|
|
2557
|
+
lastAckAgeMs: lastAckAt === 0 ? null : Math.max(0, now - lastAckAt),
|
|
2558
|
+
inFlightBytes,
|
|
2559
|
+
httpOpsInFlight: httpOpWritesInFlight,
|
|
2560
|
+
healRounds: divergenceHealRound,
|
|
2561
|
+
hidden: args.wsClient.pageHidden ?? false,
|
|
2562
|
+
};
|
|
2563
|
+
}
|
|
2564
|
+
// Push the same picture to the server, so an incident on a device with no
|
|
2565
|
+
// console attached leaves a record an operator can find. Sent on the
|
|
2566
|
+
// conditions the client can recognise and the server cannot, each of
|
|
2567
|
+
// which is already bounded by the machinery that detects it: a forced
|
|
2568
|
+
// resend fires at most once per ceiling window, a reconnect is one
|
|
2569
|
+
// socket, and a heal round is one push. The server drops the excess
|
|
2570
|
+
// anyway.
|
|
2571
|
+
//
|
|
2572
|
+
// Fire-and-forget by design. The frame carries no `client_op_id` of its
|
|
2573
|
+
// own and draws no reply, so it never joins the outstanding-op tracker
|
|
2574
|
+
// and a report cannot become one more thing a stuck document is waiting
|
|
2575
|
+
// on.
|
|
2576
|
+
function reportSyncHealth(reason) {
|
|
2577
|
+
// Only worth sending while the socket can carry it. Held through an
|
|
2578
|
+
// outage, a report flushes on the re-subscribe describing state from
|
|
2579
|
+
// before the outage, and it arrives on the new connection ahead of the
|
|
2580
|
+
// accurate one the reconnect itself produces, so the stale figures are
|
|
2581
|
+
// what the server's one-per-connection budget accepts.
|
|
2582
|
+
if (args.wsClient.connected === false)
|
|
2583
|
+
return;
|
|
2584
|
+
const d = collectDiagnostics();
|
|
2585
|
+
args.wsClient.send({
|
|
2586
|
+
type: 'client_report',
|
|
2587
|
+
topic,
|
|
2588
|
+
client_report: {
|
|
2589
|
+
reason,
|
|
2590
|
+
unacked_ops: d.unackedOps,
|
|
2591
|
+
oldest_unacked_ms: d.oldestUnackedMs,
|
|
2592
|
+
...(d.oldestClientOpId === null
|
|
2593
|
+
? {}
|
|
2594
|
+
: { oldest_client_op_id: d.oldestClientOpId }),
|
|
2595
|
+
reconnects: d.reconnects,
|
|
2596
|
+
last_ack_age_ms: d.lastAckAgeMs,
|
|
2597
|
+
in_flight_bytes: d.inFlightBytes,
|
|
2598
|
+
http_ops_in_flight: d.httpOpsInFlight,
|
|
2599
|
+
heal_rounds: d.healRounds,
|
|
2600
|
+
hidden: d.hidden,
|
|
2601
|
+
},
|
|
2602
|
+
});
|
|
2603
|
+
}
|
|
2604
|
+
args.doc._setDiagnosticsProvider(collectDiagnostics);
|
|
1592
2605
|
// Resend every outstanding op now and restart its backoff. Called on
|
|
1593
2606
|
// reconnect (`doc_init`): a dropped-and-restored connection is the most
|
|
1594
2607
|
// common reason an op went unacked, and the backoff may have grown to its
|
|
1595
2608
|
// ceiling while the socket was down, so re-asserting immediately is the
|
|
1596
2609
|
// fast recovery path.
|
|
1597
2610
|
function resendAllOutstanding() {
|
|
2611
|
+
// Nothing is on the wire any more, whether this follows a reconnect or a
|
|
2612
|
+
// shed, so the budget starts empty and every op re-enters through it.
|
|
2613
|
+
// Sending them all at once is what turns one dropped connection into a
|
|
2614
|
+
// loop that never persists anything: the burst that lost the socket is
|
|
2615
|
+
// exactly the burst the reconnect would repeat.
|
|
2616
|
+
inFlightBytes = 0;
|
|
2617
|
+
sendQueue.length = 0;
|
|
2618
|
+
// Insertion order is the order the ops were committed in, so a round
|
|
2619
|
+
// re-asserts them oldest-first.
|
|
1598
2620
|
for (const [clientOpId, entry] of outstandingResends) {
|
|
1599
2621
|
clearTimeout(entry.timer);
|
|
1600
2622
|
entry.attempts += 1;
|
|
1601
|
-
|
|
1602
|
-
|
|
2623
|
+
entry.inFlight = 0;
|
|
2624
|
+
entry.queued = false;
|
|
2625
|
+
dispatchOp(clientOpId);
|
|
1603
2626
|
}
|
|
1604
2627
|
}
|
|
2628
|
+
let unavailableRounds = 0;
|
|
2629
|
+
let unavailableTimer = null;
|
|
2630
|
+
function clearUnavailableRecovery() {
|
|
2631
|
+
if (unavailableTimer !== null) {
|
|
2632
|
+
clearTimeout(unavailableTimer);
|
|
2633
|
+
unavailableTimer = null;
|
|
2634
|
+
}
|
|
2635
|
+
unavailableRounds = 0;
|
|
2636
|
+
}
|
|
2637
|
+
// Every outstanding op is dead: drop the tracker entries and tell the
|
|
2638
|
+
// Document, which stops counting them in `savingCount` and reports each
|
|
2639
|
+
// through the error channel the app reads (`Brass.onError`). The ids are
|
|
2640
|
+
// taken first because `_failOutstandingOp` re-enters app code.
|
|
2641
|
+
//
|
|
2642
|
+
// Dropping the ops is what opens the divergence, so the heal is armed here
|
|
2643
|
+
// rather than at the call site: the local doc keeps the abandoned ops and
|
|
2644
|
+
// keeps accepting edits that depend on them, and only the handshake can
|
|
2645
|
+
// hand the server the slice it needs to apply any of it.
|
|
2646
|
+
function failAllOutstanding(message) {
|
|
2647
|
+
const clientOpIds = [...outstandingResends.keys()];
|
|
2648
|
+
forgetAllOps();
|
|
2649
|
+
for (const clientOpId of clientOpIds) {
|
|
2650
|
+
args.doc._failOutstandingOp(clientOpId, message);
|
|
2651
|
+
}
|
|
2652
|
+
if (clientOpIds.length > 0) {
|
|
2653
|
+
divergenceHealRound = 0;
|
|
2654
|
+
scheduleDivergenceHeal();
|
|
2655
|
+
}
|
|
2656
|
+
}
|
|
2657
|
+
// One op is dead: report it and arm the heal, for the same reason
|
|
2658
|
+
// `failAllOutstanding` does. The op stays applied locally and every edit
|
|
2659
|
+
// made after it depends on it, so the server holds a stream it can store
|
|
2660
|
+
// and never apply, and its own escape for an op nothing can apply is to
|
|
2661
|
+
// discard it. Most refusals do not change that: the handshake pushes
|
|
2662
|
+
// whatever slice the durable frontier is missing and splits it under the
|
|
2663
|
+
// frame cap, so it heals the dependents even where the op itself is
|
|
2664
|
+
// irreducibly too large to re-send.
|
|
2665
|
+
//
|
|
2666
|
+
// `healable: false` is for the refusal where pushing again is asking the
|
|
2667
|
+
// same question. A full document refuses every op whatever its size, so
|
|
2668
|
+
// the handshake's own chunks come back refused, and the counter reset
|
|
2669
|
+
// below turns that into a loop rather than a bounded retry. What recovers
|
|
2670
|
+
// that document is the periodic re-verify, once the server can take a
|
|
2671
|
+
// write at all.
|
|
2672
|
+
// A refusal the heal cannot work around leaves the writer holding a change
|
|
2673
|
+
// that reached no database and no other reader, so the writer is the only
|
|
2674
|
+
// copy of the document that shows it. Left editable it reads as applied: the
|
|
2675
|
+
// element is on screen, the count includes it, every later edit builds on
|
|
2676
|
+
// it, and a reader who opens the document sees none of it. Nothing local
|
|
2677
|
+
// removes it either, because a CRDT merges rather than replaces and an undo
|
|
2678
|
+
// inverts an operation instead of discarding it, so the only state holding
|
|
2679
|
+
// exactly what is durable is one built from the server.
|
|
2680
|
+
//
|
|
2681
|
+
// Stopping the divergence and resolving it are separated, because they cost
|
|
2682
|
+
// different things and doing them in one silent step is what made a refusal
|
|
2683
|
+
// read as the platform losing work. Stopping is free and immediate:
|
|
2684
|
+
// `readOnly` turns true, which closes an app's existing edit gate, so the
|
|
2685
|
+
// copy cannot drift further. Resolving discards the refused work and swaps
|
|
2686
|
+
// the document under whoever was working in it, so the user is told first
|
|
2687
|
+
// and the reload follows their acknowledgement.
|
|
2688
|
+
//
|
|
2689
|
+
// The telling is the SDK's job rather than each app's. A copy left showing a
|
|
2690
|
+
// change nothing else has is the failure being closed, so an app that
|
|
2691
|
+
// renders no surface for this cannot be the reason a user stays on one.
|
|
2692
|
+
//
|
|
2693
|
+
// Once per document. The first refusal is what diverged this copy, so the
|
|
2694
|
+
// later ones describe the same state and have nothing to add.
|
|
2695
|
+
let lockedForRefusal = false;
|
|
2696
|
+
function lockForUnhealableRefusal(message) {
|
|
2697
|
+
if (lockedForRefusal)
|
|
2698
|
+
return;
|
|
2699
|
+
lockedForRefusal = true;
|
|
2700
|
+
// Torn down in the order the `doc_gone` handler uses, and for the same
|
|
2701
|
+
// reason: every one of these keeps working against a copy that is now
|
|
2702
|
+
// read-only, and the resync push in particular would re-offer the refused
|
|
2703
|
+
// op this exists to stop.
|
|
2704
|
+
forgetAllOps();
|
|
2705
|
+
clearUnavailableRecovery();
|
|
2706
|
+
if (reverifyTimer !== null) {
|
|
2707
|
+
clearInterval(reverifyTimer);
|
|
2708
|
+
reverifyTimer = null;
|
|
2709
|
+
}
|
|
2710
|
+
clearDivergenceHeal();
|
|
2711
|
+
if (gapTimer !== null) {
|
|
2712
|
+
clearTimeout(gapTimer);
|
|
2713
|
+
gapTimer = null;
|
|
2714
|
+
}
|
|
2715
|
+
args.doc._markReadOnly('unsaved');
|
|
2716
|
+
// The user is told by the SDK, not by each app, because an app that
|
|
2717
|
+
// renders nothing is exactly the case this has to cover: a document that
|
|
2718
|
+
// reloaded and a document that reloaded for a reason look the same
|
|
2719
|
+
// otherwise. `alert` holds the main thread until it is acknowledged, so
|
|
2720
|
+
// the reason cannot be missed and the reload lands on a page the user
|
|
2721
|
+
// is looking at. A browser that suppresses the dialog returns from it
|
|
2722
|
+
// immediately, which reloads rather than skipping, and a caller outside
|
|
2723
|
+
// a browser (a worker, a test) has nobody to tell and does the same.
|
|
2724
|
+
//
|
|
2725
|
+
// The reload survives a dialog that throws, which is the one way telling
|
|
2726
|
+
// the user could cost them the fix: `alert` is a page-global an app is
|
|
2727
|
+
// free to replace, and the copy this leaves behind is the diverged one
|
|
2728
|
+
// the reload exists to discard.
|
|
2729
|
+
try {
|
|
2730
|
+
if (typeof alert === 'function')
|
|
2731
|
+
alert(message);
|
|
2732
|
+
}
|
|
2733
|
+
catch {
|
|
2734
|
+
// Told or not, the copy is resolved.
|
|
2735
|
+
}
|
|
2736
|
+
args.doc.reload();
|
|
2737
|
+
}
|
|
2738
|
+
function failOpTerminally(clientOpId, message, opts = {}) {
|
|
2739
|
+
// Read before `_failOutstandingOp`, which clears the id from the
|
|
2740
|
+
// resync-push set on its way out.
|
|
2741
|
+
const wasHealPush = args.doc._isResyncPushOp(clientOpId);
|
|
2742
|
+
opStartedAt.delete(clientOpId);
|
|
2743
|
+
// A refusal the heal cannot answer is about the document, so it answers
|
|
2744
|
+
// every op in flight the same way and is reported once, by the lock. Per
|
|
2745
|
+
// op, a bulk write's outstanding ops each produce an identical error, so
|
|
2746
|
+
// the reader watches the same message arrive dozens of times before the
|
|
2747
|
+
// one dialog that explains it.
|
|
2748
|
+
args.doc._failOutstandingOp(clientOpId, message, {
|
|
2749
|
+
report: opts.report ?? true,
|
|
2750
|
+
});
|
|
2751
|
+
if (opts.healable === false) {
|
|
2752
|
+
lockForUnhealableRefusal(message);
|
|
2753
|
+
return;
|
|
2754
|
+
}
|
|
2755
|
+
// Restart the backoff only for a failure the heal did not itself
|
|
2756
|
+
// produce. A refused heal chunk that zeroed the round count would keep
|
|
2757
|
+
// the bound from ever binding: each round pushes, each push is refused,
|
|
2758
|
+
// and each refusal buys another round. Leaving the count alone lets the
|
|
2759
|
+
// rounds run out the way an unanswered handshake already does.
|
|
2760
|
+
if (!wasHealPush)
|
|
2761
|
+
divergenceHealRound = 0;
|
|
2762
|
+
scheduleDivergenceHeal();
|
|
2763
|
+
}
|
|
2764
|
+
function onServerUnavailable() {
|
|
2765
|
+
if (outstandingResends.size === 0)
|
|
2766
|
+
return;
|
|
2767
|
+
if (unavailableTimer !== null)
|
|
2768
|
+
return;
|
|
2769
|
+
unavailableRounds += 1;
|
|
2770
|
+
if (unavailableRounds > UNAVAILABLE_MAX_ROUNDS) {
|
|
2771
|
+
clearUnavailableRecovery();
|
|
2772
|
+
failAllOutstanding(UNAVAILABLE_GIVE_UP_MESSAGE);
|
|
2773
|
+
return;
|
|
2774
|
+
}
|
|
2775
|
+
const delay = unavailableDelayMs(unavailableRounds);
|
|
2776
|
+
unavailableTimer = setTimeout(() => {
|
|
2777
|
+
unavailableTimer = null;
|
|
2778
|
+
resendAllOutstanding();
|
|
2779
|
+
}, delay);
|
|
2780
|
+
unavailableTimer.unref?.();
|
|
2781
|
+
}
|
|
1605
2782
|
// Durability handshake, run on every `doc_init`. The persisted version
|
|
1606
2783
|
// vector + durable tail ops define the durable frontier; if the local doc
|
|
1607
2784
|
// holds CRDT knowledge beyond it (an op acked then discarded by the
|
|
@@ -1613,7 +2790,12 @@ function wireDocTransport(args) {
|
|
|
1613
2790
|
function maybeResyncPush(snapshotVersionVectorB64, durableTailBlobs) {
|
|
1614
2791
|
if (!snapshotVersionVectorB64)
|
|
1615
2792
|
return;
|
|
1616
|
-
args.doc.maybeResyncPush(base64ToBytes(snapshotVersionVectorB64), durableTailBlobs);
|
|
2793
|
+
const outcome = args.doc.maybeResyncPush(base64ToBytes(snapshotVersionVectorB64), durableTailBlobs);
|
|
2794
|
+
// Reported here as well as from the re-verify, or the record holds only
|
|
2795
|
+
// the heals that took the slower route and an operator reading it cannot
|
|
2796
|
+
// tell that the ordinary reconnect handshake is missing from the set.
|
|
2797
|
+
if (outcome === 'pushed')
|
|
2798
|
+
reportSyncHealth('divergence_healed');
|
|
1617
2799
|
}
|
|
1618
2800
|
// Re-fetch the durable frontier from the HTTP join and run the handshake.
|
|
1619
2801
|
// Shared by the `doc_ops_dropped` prompt path and the periodic re-verify:
|
|
@@ -1630,66 +2812,217 @@ function wireDocTransport(args) {
|
|
|
1630
2812
|
let reverifyAgain = false;
|
|
1631
2813
|
// Armed after the subscription is wired, cleared on `doc_gone` and teardown.
|
|
1632
2814
|
let reverifyTimer = null;
|
|
2815
|
+
// The last run's verdict, so a caller healing a known divergence can tell a
|
|
2816
|
+
// finished handshake from one that fetched nothing.
|
|
1633
2817
|
async function reverifyDurability() {
|
|
1634
2818
|
if (reverifyInFlight) {
|
|
1635
2819
|
reverifyAgain = true;
|
|
1636
|
-
return;
|
|
2820
|
+
return 'in-flight';
|
|
1637
2821
|
}
|
|
1638
2822
|
reverifyInFlight = true;
|
|
2823
|
+
let outcome = 'no-fetch';
|
|
1639
2824
|
try {
|
|
1640
2825
|
do {
|
|
1641
2826
|
reverifyAgain = false;
|
|
1642
2827
|
try {
|
|
1643
2828
|
const frontier = await args.refetchDurableFrontier?.();
|
|
1644
2829
|
if (frontier && frontier.snapshotVersionVector) {
|
|
1645
|
-
args.doc.maybeResyncPush(base64ToBytes(frontier.snapshotVersionVector), frontier.tailBlobs);
|
|
2830
|
+
outcome = args.doc.maybeResyncPush(base64ToBytes(frontier.snapshotVersionVector), frontier.tailBlobs);
|
|
2831
|
+
// The handshake having work to do means the server's copy was
|
|
2832
|
+
// behind this client's, which is the state a lost op leaves and
|
|
2833
|
+
// which nothing on the server side reports.
|
|
2834
|
+
if (outcome === 'pushed')
|
|
2835
|
+
reportSyncHealth('divergence_healed');
|
|
1646
2836
|
}
|
|
1647
2837
|
}
|
|
1648
2838
|
catch {
|
|
1649
2839
|
// Best-effort: a failed re-fetch defers the check to the next tick
|
|
1650
2840
|
// or reconnect's `doc_init` handshake. Swallowed so the timer's
|
|
1651
2841
|
// fire-and-forget never surfaces an unhandled rejection and one
|
|
1652
|
-
// failed tick does not wedge the loop guard.
|
|
2842
|
+
// failed tick does not wedge the loop guard. The `no-fetch` verdict
|
|
2843
|
+
// is what keeps a divergence heal asking.
|
|
2844
|
+
outcome = 'no-fetch';
|
|
1653
2845
|
}
|
|
1654
2846
|
} while (reverifyAgain);
|
|
1655
2847
|
}
|
|
1656
2848
|
finally {
|
|
1657
2849
|
reverifyInFlight = false;
|
|
1658
2850
|
}
|
|
2851
|
+
return outcome;
|
|
2852
|
+
}
|
|
2853
|
+
// Divergence heal. Giving up on an op leaves the local doc holding CRDT
|
|
2854
|
+
// knowledge the server does not, and Loro requires per-actor causal
|
|
2855
|
+
// contiguity, so every op the app writes afterwards reaches the server as
|
|
2856
|
+
// causally unapplyable and stays that way until the missing slice arrives.
|
|
2857
|
+
// The server's own escape for an op nothing can apply is to discard it, so
|
|
2858
|
+
// the window between the give-up and the next handshake is a window where
|
|
2859
|
+
// the app writes into a document that keeps none of it.
|
|
2860
|
+
//
|
|
2861
|
+
// The periodic re-verify would eventually close that window, but on its own
|
|
2862
|
+
// schedule: a bulk write finishes and the reader reloads well inside one
|
|
2863
|
+
// tick. A give-up is the moment the client knows it has diverged, so it
|
|
2864
|
+
// drives the handshake itself, and keeps driving it on a backoff until one
|
|
2865
|
+
// run reports the durable frontier covering the local doc. The first delay
|
|
2866
|
+
// is not zero because the give-up follows sustained shedding, so the fetch
|
|
2867
|
+
// this schedules would join the burst it is recovering from.
|
|
2868
|
+
const DIVERGENCE_HEAL_BASE_DELAY_MS = 2_000;
|
|
2869
|
+
const DIVERGENCE_HEAL_MAX_DELAY_MS = 30_000;
|
|
2870
|
+
// Roughly four minutes of attempts, after which the periodic re-verify is
|
|
2871
|
+
// the remaining backstop and the tab has long since reported the failure.
|
|
2872
|
+
const DIVERGENCE_HEAL_MAX_ROUNDS = 12;
|
|
2873
|
+
let divergenceHealRound = 0;
|
|
2874
|
+
let divergenceHealTimer = null;
|
|
2875
|
+
function scheduleDivergenceHeal() {
|
|
2876
|
+
if (divergenceHealTimer !== null)
|
|
2877
|
+
return;
|
|
2878
|
+
if (divergenceHealRound >= DIVERGENCE_HEAL_MAX_ROUNDS)
|
|
2879
|
+
return;
|
|
2880
|
+
divergenceHealRound += 1;
|
|
2881
|
+
const delay = Math.min(DIVERGENCE_HEAL_BASE_DELAY_MS * Math.pow(2, divergenceHealRound - 1), DIVERGENCE_HEAL_MAX_DELAY_MS);
|
|
2882
|
+
divergenceHealTimer = setTimeout(() => {
|
|
2883
|
+
divergenceHealTimer = null;
|
|
2884
|
+
void reverifyDurability().then((outcome) => {
|
|
2885
|
+
// `covered` is the only verdict that proves the hole is closed. A
|
|
2886
|
+
// push that just went out is not yet durable, so the next round
|
|
2887
|
+
// re-checks it rather than assuming its acks land, and the backoff
|
|
2888
|
+
// it comes back on is what keeps a push settling from being polled.
|
|
2889
|
+
if (outcome !== 'covered')
|
|
2890
|
+
scheduleDivergenceHeal();
|
|
2891
|
+
else
|
|
2892
|
+
divergenceHealRound = 0;
|
|
2893
|
+
});
|
|
2894
|
+
}, delay);
|
|
2895
|
+
divergenceHealTimer.unref?.();
|
|
2896
|
+
}
|
|
2897
|
+
function clearDivergenceHeal() {
|
|
2898
|
+
if (divergenceHealTimer !== null) {
|
|
2899
|
+
clearTimeout(divergenceHealTimer);
|
|
2900
|
+
divergenceHealTimer = null;
|
|
2901
|
+
}
|
|
2902
|
+
divergenceHealRound = 0;
|
|
1659
2903
|
}
|
|
1660
2904
|
// A coverage floor below the highest seq seen records ops this client
|
|
1661
2905
|
// applied nothing for, and the server posts each op once, so nothing
|
|
1662
2906
|
// re-sends them. Pull the join instead, after a delay long enough for an
|
|
1663
2907
|
// out-of-order arrival to close the hole itself.
|
|
2908
|
+
//
|
|
2909
|
+
// The delay is only meaningful against the hole this check was ARMED on,
|
|
2910
|
+
// which is why the seq it waits to reach is captured here rather than read
|
|
2911
|
+
// again when it fires. Holes are the ordinary state of a client that is
|
|
2912
|
+
// writing: acks overtake heavily, so the newest acked seq sits above the
|
|
2913
|
+
// contiguous floor almost continuously, and each such hole closes as the ack
|
|
2914
|
+
// below it lands. Asking on expiry whether ANY hole exists reads a
|
|
2915
|
+
// brand-new one, opened by ops sent since, as the original persisting, and a
|
|
2916
|
+
// client that keeps writing always has one. That answer costs a join
|
|
2917
|
+
// re-import, which discards the undo and redo stacks, so the reader loses
|
|
2918
|
+
// their history every couple of seconds while nothing is wrong.
|
|
2919
|
+
//
|
|
2920
|
+
// Rounds that move nothing back off and then stop, and any advance in the
|
|
2921
|
+
// floor starts the budget over. What separates the two cases is exactly
|
|
2922
|
+
// that: a hole left by a write still in flight fills as the rows land, so
|
|
2923
|
+
// each pull delivers more and earns the next one, while a seq the server
|
|
2924
|
+
// allocated and never wrote (a failed op write leaves a hole rather than a
|
|
2925
|
+
// duplicate) delivers nothing however often it is asked for. Without the
|
|
2926
|
+
// budget that second hole is a join re-import every couple of seconds for
|
|
2927
|
+
// the life of the tab, each one discarding the reader's undo history. It
|
|
2928
|
+
// clears at the next compaction, which folds the tail past the hole.
|
|
2929
|
+
const GAP_PULL_MAX_ROUNDS = 6;
|
|
2930
|
+
const GAP_PULL_MAX_DELAY_MS = 30_000;
|
|
1664
2931
|
let gapTimer = null;
|
|
2932
|
+
let gapPullRounds = 0;
|
|
2933
|
+
let gapPullFloor = -1;
|
|
1665
2934
|
function scheduleGapCheck() {
|
|
1666
2935
|
if (gapTimer !== null)
|
|
1667
2936
|
return;
|
|
1668
|
-
|
|
2937
|
+
const awaited = args.getCurrentSeq();
|
|
2938
|
+
const floor = args.getCoveredSeq();
|
|
2939
|
+
if (floor >= awaited) {
|
|
2940
|
+
gapPullRounds = 0;
|
|
2941
|
+
return;
|
|
2942
|
+
}
|
|
2943
|
+
if (floor > gapPullFloor)
|
|
2944
|
+
gapPullRounds = 0;
|
|
2945
|
+
if (gapPullRounds >= GAP_PULL_MAX_ROUNDS)
|
|
1669
2946
|
return;
|
|
2947
|
+
gapPullRounds += 1;
|
|
2948
|
+
gapPullFloor = floor;
|
|
2949
|
+
const delay = Math.min(MISSED_OP_RESYNC_DELAY_MS * Math.pow(2, gapPullRounds - 1), GAP_PULL_MAX_DELAY_MS);
|
|
1670
2950
|
gapTimer = setTimeout(() => {
|
|
1671
2951
|
gapTimer = null;
|
|
1672
|
-
|
|
2952
|
+
// Covered up to where the hole was: it closed on its own, whatever has
|
|
2953
|
+
// been sent since. Anything newer arms its own check.
|
|
2954
|
+
if (args.getCoveredSeq() >= awaited) {
|
|
2955
|
+
gapPullRounds = 0;
|
|
1673
2956
|
return;
|
|
1674
|
-
|
|
1675
|
-
|
|
2957
|
+
}
|
|
2958
|
+
pullJoin();
|
|
2959
|
+
}, delay);
|
|
1676
2960
|
gapTimer.unref?.();
|
|
1677
2961
|
}
|
|
2962
|
+
// The server ended this subscription: it refused the subscribe (a revoked
|
|
2963
|
+
// grant), or evicted it again after the one silent re-subscribe a
|
|
2964
|
+
// connection grants. The client detaches this transport from the topic as
|
|
2965
|
+
// it reports that, so no ack, no fanout and no reconnect reaches it again.
|
|
2966
|
+
//
|
|
2967
|
+
// Everything the transport is waiting on is therefore dead. The ops it
|
|
2968
|
+
// holds can never be acked, and re-sending them puts frames on a
|
|
2969
|
+
// subscription the server has refused while `savingCount` climbs and the
|
|
2970
|
+
// app hears nothing, so they are failed here and every later edit fails
|
|
2971
|
+
// the same way: the app reads one actionable error per unsaved change and
|
|
2972
|
+
// its cue to reload, rather than a document that looks like it is saving
|
|
2973
|
+
// forever. The ids are taken before the reports because
|
|
2974
|
+
// `_failOutstandingOp` re-enters app code.
|
|
2975
|
+
let subscriptionEnded = false;
|
|
2976
|
+
function endSubscription() {
|
|
2977
|
+
if (subscriptionEnded)
|
|
2978
|
+
return;
|
|
2979
|
+
subscriptionEnded = true;
|
|
2980
|
+
const clientOpIds = [...outstandingResends.keys()];
|
|
2981
|
+
forgetAllOps();
|
|
2982
|
+
clearUnavailableRecovery();
|
|
2983
|
+
// The heal and the gap pull both work through this transport, so they
|
|
2984
|
+
// are stopped rather than armed: what they would push or fetch has no
|
|
2985
|
+
// subscription left to travel on.
|
|
2986
|
+
clearDivergenceHeal();
|
|
2987
|
+
if (reverifyTimer !== null) {
|
|
2988
|
+
clearInterval(reverifyTimer);
|
|
2989
|
+
reverifyTimer = null;
|
|
2990
|
+
}
|
|
2991
|
+
if (gapTimer !== null) {
|
|
2992
|
+
clearTimeout(gapTimer);
|
|
2993
|
+
gapTimer = null;
|
|
2994
|
+
}
|
|
2995
|
+
for (const clientOpId of clientOpIds) {
|
|
2996
|
+
args.doc._failOutstandingOp(clientOpId, SUBSCRIPTION_ENDED_MESSAGE);
|
|
2997
|
+
}
|
|
2998
|
+
}
|
|
1678
2999
|
// 1. Subscribe to the doc topic. Frame routing:
|
|
1679
3000
|
// - `doc_init`: bridge the join-vs-fanout race. Ops committed between
|
|
1680
3001
|
// the HTTP join (T0) and the WS subscribe (T1) miss the HTTP tail and
|
|
1681
|
-
// can race the
|
|
3002
|
+
// can race the subscription record so the first `doc_op` fanout may arrive BEFORE
|
|
1682
3003
|
// doc_init (separate server invocations, no wire ordering). tail_ops
|
|
1683
3004
|
// apply unconditionally: filtering on `seq > currentSeq` would mask
|
|
1684
3005
|
// tail_ops a racing `doc_op` inflated the cursor past, leaving lamport
|
|
1685
3006
|
// gaps Loro cannot converge across (re-applying is an idempotent
|
|
1686
3007
|
// no-op).
|
|
3008
|
+
// - `doc_catch_up`: the document moved past this client's coverage on
|
|
3009
|
+
// an op the socket could not carry; re-import the join and nothing
|
|
3010
|
+
// more (see the branch).
|
|
1687
3011
|
// - `doc_op`: apply, advance cursor.
|
|
1688
3012
|
// - `op_ack`: resolve the outstanding-op tracker, advance cursor, cancel
|
|
1689
3013
|
// that op's resend timer.
|
|
1690
3014
|
// - everything else: handled by `BrassWsClient`.
|
|
1691
3015
|
const unsub = args.wsClient.subscribe(topic, (frame) => {
|
|
1692
|
-
|
|
3016
|
+
const init = parseDocInitFrame(frame);
|
|
3017
|
+
if (init) {
|
|
3018
|
+
// Recorded as the frame arrives rather than after the tail applies.
|
|
3019
|
+
// Importing a tail op can throw, and the client swallows it, so a
|
|
3020
|
+
// latch written further down would stay behind and read the NEXT
|
|
3021
|
+
// reconnect as the opening subscribe, suppressing the report this
|
|
3022
|
+
// exists to make.
|
|
3023
|
+
const reconnects = args.wsClient.reconnectCount ?? 0;
|
|
3024
|
+
const socketDropped = docInitReconnectCount !== null && reconnects > docInitReconnectCount;
|
|
3025
|
+
docInitReconnectCount = reconnects;
|
|
1693
3026
|
// Resync check BEFORE applying. The tail covers (snapshot_seq,
|
|
1694
3027
|
// current_seq]; if the coverage floor sits below the tail's lower edge
|
|
1695
3028
|
// (or below current_seq when the tail is empty), ops in between were
|
|
@@ -1697,16 +3030,23 @@ function wireDocTransport(args) {
|
|
|
1697
3030
|
// this tail or future fanout, so re-import the join's snapshot. The
|
|
1698
3031
|
// initial subscribe never trips this (the floor was just seeded), so
|
|
1699
3032
|
// the cost is paid only on a reconnect that crossed a compaction.
|
|
1700
|
-
const
|
|
1701
|
-
const snapshotFloor = minTailSeq !== null ? minTailSeq - 1 : frame.current_seq;
|
|
3033
|
+
const snapshotFloor = snapshotSeqOf(init.snapshot_seq, init.tail_ops.map((entry) => entry.seq), init.current_seq);
|
|
1702
3034
|
const needsResync = args.getCoveredSeq() < snapshotFloor;
|
|
1703
3035
|
const tailBlobs = [];
|
|
1704
|
-
|
|
3036
|
+
// Whether the frame's own entries can describe the durable frontier.
|
|
3037
|
+
// An entry the server withheld the bytes of still NAMES an op the
|
|
3038
|
+
// server holds, so a frontier folded from the inline entries alone
|
|
3039
|
+
// reports every withheld op as missing from the server. See the
|
|
3040
|
+
// handshake call below.
|
|
3041
|
+
let tailComplete = true;
|
|
3042
|
+
for (const entry of init.tail_ops) {
|
|
1705
3043
|
// An op with no inline bytes is deliberately left uncovered: it
|
|
1706
3044
|
// has not been applied, so marking it covered would retire the
|
|
1707
3045
|
// very resync that fetches it.
|
|
1708
|
-
if (entry.op_blob_b64 === undefined)
|
|
3046
|
+
if (entry.op_blob_b64 === undefined) {
|
|
3047
|
+
tailComplete = false;
|
|
1709
3048
|
continue;
|
|
3049
|
+
}
|
|
1710
3050
|
const blob = base64ToBytes(entry.op_blob_b64);
|
|
1711
3051
|
tailBlobs.push(blob);
|
|
1712
3052
|
args.doc.applyRemoteOp(blob);
|
|
@@ -1714,31 +3054,111 @@ function wireDocTransport(args) {
|
|
|
1714
3054
|
args.setCurrentSeq(entry.seq);
|
|
1715
3055
|
args.advanceCoveredSeq(entry.seq);
|
|
1716
3056
|
}
|
|
1717
|
-
|
|
1718
|
-
|
|
3057
|
+
// The frame also has to ACCOUNT for every seq the head names, not
|
|
3058
|
+
// merely carry bytes for the entries it lists. The server drops an
|
|
3059
|
+
// oversized or spilled tail from this frame ENTIRELY rather than
|
|
3060
|
+
// listing it byte-less (`document.tail.dropped`), so an empty tail on
|
|
3061
|
+
// a branch whose head sits above its snapshot is not a branch with
|
|
3062
|
+
// nothing in flight: it is the whole tail withheld. Measured on a
|
|
3063
|
+
// real document: snapshot_seq 565, current_seq 1089, 524 ops dropped
|
|
3064
|
+
// from the frame and every one of them already imported by the HTTP
|
|
3065
|
+
// join, so a frontier folded from this frame alone sat 524 ops behind
|
|
3066
|
+
// the local doc and pushed them back on every open.
|
|
3067
|
+
if (typeof init.snapshot_seq === 'number' &&
|
|
3068
|
+
tailBlobs.length < init.current_seq - init.snapshot_seq) {
|
|
3069
|
+
tailComplete = false;
|
|
3070
|
+
}
|
|
3071
|
+
if (init.current_seq > args.getCurrentSeq()) {
|
|
3072
|
+
args.setCurrentSeq(init.current_seq);
|
|
1719
3073
|
}
|
|
1720
3074
|
if (needsResync) {
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
|
|
1725
|
-
|
|
1726
|
-
|
|
1727
|
-
|
|
3075
|
+
resyncPastSeq(init.current_seq);
|
|
3076
|
+
}
|
|
3077
|
+
else {
|
|
3078
|
+
// A frame that named a head it did not carry the tail for leaves
|
|
3079
|
+
// the reader short with nothing further coming: the server drops an
|
|
3080
|
+
// oversized or spilled tail from this frame and posts each op once.
|
|
3081
|
+
// For a reader that never writes, this and the catch-up prompt are
|
|
3082
|
+
// the only two places a gap gets noticed at all.
|
|
3083
|
+
scheduleGapCheck();
|
|
1728
3084
|
}
|
|
1729
3085
|
// `doc_init` is the reconnect signal the retry-forever recovery hangs
|
|
1730
3086
|
// off: re-assert every outstanding op and run the durability handshake
|
|
1731
3087
|
// now, so a client holding work the server lost re-asserts it on
|
|
1732
|
-
// reconnect rather than waiting out the per-op backoff.
|
|
3088
|
+
// reconnect rather than waiting out the per-op backoff. A fresh
|
|
3089
|
+
// connection also returns the shed budget to full: this re-assert is
|
|
3090
|
+
// the round the pending one would have run.
|
|
3091
|
+
clearUnavailableRecovery();
|
|
3092
|
+
// A reconnect, rather than the initial subscribe: the socket dropped
|
|
3093
|
+
// while this document held work, which is the condition the server
|
|
3094
|
+
// has no way to see. The first `doc_init` arrives on the opening
|
|
3095
|
+
// subscribe, and an app that writes as soon as it opens already has
|
|
3096
|
+
// ops outstanding by then, so reporting on every `doc_init` would
|
|
3097
|
+
// fire routinely on a healthy first open and train a reader of the
|
|
3098
|
+
// log to discount the event.
|
|
3099
|
+
//
|
|
3100
|
+
// Before the round rather than after, so the counters describe the
|
|
3101
|
+
// work the reconnect found rather than the work it has just put back
|
|
3102
|
+
// on the wire.
|
|
3103
|
+
if (socketDropped && outstandingResends.size > 0) {
|
|
3104
|
+
reportSyncHealth('reconnected_unsaved');
|
|
3105
|
+
}
|
|
1733
3106
|
resendAllOutstanding();
|
|
1734
|
-
//
|
|
1735
|
-
//
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
//
|
|
3107
|
+
// The handshake needs the WHOLE durable tail, and this frame carries
|
|
3108
|
+
// it only when every entry came inline. A spilled op is named here
|
|
3109
|
+
// with its bytes withheld, and the HTTP join the reader already ran
|
|
3110
|
+
// resolves and imports it, so a frontier built from the inline
|
|
3111
|
+
// entries alone sits behind the local doc by exactly the ops that
|
|
3112
|
+
// spilled, and the handshake pushes the reader's copy of the server's
|
|
3113
|
+
// own tail back at it. On a branch at capacity every chunk is refused
|
|
3114
|
+
// and reported, which is an error on screen for someone who only
|
|
3115
|
+
// reopened the document; on any other branch it lands, writing a
|
|
3116
|
+
// second durable copy of every spilled op and growing the document
|
|
3117
|
+
// toward the ceiling on each open. `reverifyDurability` fetches
|
|
3118
|
+
// through `fetchSnapshot`, which resolves spilled entries, so the
|
|
3119
|
+
// frontier it diffs against is complete.
|
|
3120
|
+
if (tailComplete) {
|
|
3121
|
+
maybeResyncPush(init.snapshot_version_vector, tailBlobs);
|
|
3122
|
+
}
|
|
3123
|
+
else {
|
|
3124
|
+
void reverifyDurability();
|
|
3125
|
+
}
|
|
3126
|
+
// The tail has applied, so every author this client can hear from is
|
|
3127
|
+
// in its doc. An author left in the durable frontier is one whose
|
|
3128
|
+
// changes exist only inside the snapshot, which is the platform having
|
|
3129
|
+
// rewritten how the document stores what it stores. A client cannot
|
|
3130
|
+
// undo across that: its stack inverts the operations it made, and the
|
|
3131
|
+
// values those operations wrote have moved, so an undo would remove
|
|
3132
|
+
// nothing and report success. Re-import instead, which drops both
|
|
3133
|
+
// stacks and leaves the reader on fresh state with undo honestly
|
|
3134
|
+
// unavailable.
|
|
3135
|
+
//
|
|
3136
|
+
// Coverage does not catch this on its own, and the case it misses is
|
|
3137
|
+
// the ordinary one: the fold runs on a branch nobody has open, so the
|
|
3138
|
+
// client that returns to it missed no ops and has no gap to notice.
|
|
3139
|
+
if (!needsResync)
|
|
3140
|
+
maybeResyncPastRewrite(init.snapshot_version_vector);
|
|
3141
|
+
// Posted after the subscription record exists, so this is the safe point to
|
|
1740
3142
|
// reconcile a pending open whose terminal status frame was dropped.
|
|
1741
3143
|
args.reconcileStatusOnInit?.();
|
|
3144
|
+
args.onDocumentMoved?.();
|
|
3145
|
+
return;
|
|
3146
|
+
}
|
|
3147
|
+
if (isDocCatchUpFrame(frame)) {
|
|
3148
|
+
// The document moved past what this client can bridge to, so pull the
|
|
3149
|
+
// join. Nothing else: the prompt describes the document rather than
|
|
3150
|
+
// this subscription, and every subscriber gets one on each op the
|
|
3151
|
+
// socket could not carry. Re-asserting outstanding ops here writes a
|
|
3152
|
+
// second durable copy of each of them (the server allocates a fresh
|
|
3153
|
+
// seq per send) for every such op any writer makes, and cancelling
|
|
3154
|
+
// the shed recovery here parks a shed op on its per-op backoff
|
|
3155
|
+
// instead of the schedule the shed armed.
|
|
3156
|
+
if (frame.current_seq > args.getCurrentSeq()) {
|
|
3157
|
+
args.setCurrentSeq(frame.current_seq);
|
|
3158
|
+
}
|
|
3159
|
+
if (args.getCoveredSeq() < frame.current_seq) {
|
|
3160
|
+
resyncPastSeq(frame.current_seq);
|
|
3161
|
+
}
|
|
1742
3162
|
return;
|
|
1743
3163
|
}
|
|
1744
3164
|
if (isDocOpFrame(frame)) {
|
|
@@ -1753,20 +3173,28 @@ function wireDocTransport(args) {
|
|
|
1753
3173
|
args.setCurrentSeq(frame.seq);
|
|
1754
3174
|
args.advanceCoveredSeq(frame.seq);
|
|
1755
3175
|
scheduleGapCheck();
|
|
3176
|
+
args.onDocumentMoved?.();
|
|
1756
3177
|
return;
|
|
1757
3178
|
}
|
|
1758
3179
|
if (isOpAckFrame(frame)) {
|
|
3180
|
+
// Evidence the connection is working through its queue, which is what
|
|
3181
|
+
// the resend timers read to tell a slow ack from a silent server.
|
|
3182
|
+
lastAckAt = Date.now();
|
|
1759
3183
|
args.doc.resolveOutstandingOp(frame.client_op_id);
|
|
1760
3184
|
args.setCurrentSeq(frame.seq);
|
|
1761
3185
|
args.advanceCoveredSeq(frame.seq);
|
|
1762
3186
|
// An ack for a local op sits above any remote op this client never
|
|
1763
3187
|
// received, so the user's own next edit is a second chance to notice.
|
|
1764
3188
|
scheduleGapCheck();
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
3189
|
+
forgetOp(frame.client_op_id);
|
|
3190
|
+
// The server is durably accepting writes again, so the shed budget
|
|
3191
|
+
// starts over. A round already scheduled still runs: the ops it
|
|
3192
|
+
// re-asserts are the ones this ack did not cover.
|
|
3193
|
+
unavailableRounds = 0;
|
|
3194
|
+
return;
|
|
3195
|
+
}
|
|
3196
|
+
if (isServerUnavailableFrame(frame)) {
|
|
3197
|
+
onServerUnavailable();
|
|
1770
3198
|
return;
|
|
1771
3199
|
}
|
|
1772
3200
|
if (isOpRejectedFrame(frame)) {
|
|
@@ -1774,29 +3202,52 @@ function wireDocTransport(args) {
|
|
|
1774
3202
|
// draw the same rejection forever and pin `savingCount`) and fail it on
|
|
1775
3203
|
// the Document so the app hears "could not be saved" instead of a silent
|
|
1776
3204
|
// wedge. Scoped to this one op; the topic subscription stays live.
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
args.doc.
|
|
3205
|
+
forgetOp(frame.client_op_id);
|
|
3206
|
+
// The flip is the one moment the refusal is worth reporting: every op
|
|
3207
|
+
// in flight draws the same sentence, and a bulk write has as many of
|
|
3208
|
+
// those as it has unacked writes.
|
|
3209
|
+
const atCapacity = isCapacityRejection(frame);
|
|
3210
|
+
const firstCapacityRefusal = atCapacity && args.doc._markAtCapacity();
|
|
3211
|
+
// A refusal that names the writer rather than the op applies to
|
|
3212
|
+
// every op this reader will send, so it turns the whole Document
|
|
3213
|
+
// read-only before the failure is reported: the app's own
|
|
3214
|
+
// `doc.readOnly` gate then disables the editor in the same tick the
|
|
3215
|
+
// reader hears why, rather than letting them keep typing into a
|
|
3216
|
+
// surface nothing will save.
|
|
3217
|
+
const readOnly = readOnlyReasonForRejection(frame);
|
|
3218
|
+
if (readOnly !== null)
|
|
3219
|
+
args.doc._markReadOnly(readOnly);
|
|
3220
|
+
// NO capacity refusal is healable, whichever kind it is. The refused
|
|
3221
|
+
// work sits on this copy and nowhere else, and the heal is the only
|
|
3222
|
+
// thing that could place it: when it runs out of rounds it stops
|
|
3223
|
+
// silently, so a copy the handshake could not settle is one showing
|
|
3224
|
+
// work that a reload will not, with nothing said. Both kinds therefore
|
|
3225
|
+
// lock, tell and reload, which is what the server's own wording for
|
|
3226
|
+
// each of them already promises.
|
|
3227
|
+
//
|
|
3228
|
+
// The other refusals here stay healable: the handshake splits the
|
|
3229
|
+
// slice under the frame cap, which is what reaches the dependents of
|
|
3230
|
+
// an op that is itself too large to re-send.
|
|
3231
|
+
failOpTerminally(frame.client_op_id, opRejectedMessage(frame), {
|
|
3232
|
+
healable: !atCapacity,
|
|
3233
|
+
report: !atCapacity || firstCapacityRefusal,
|
|
3234
|
+
});
|
|
1783
3235
|
return;
|
|
1784
3236
|
}
|
|
1785
3237
|
if (isDocGoneFrame(frame)) {
|
|
1786
3238
|
// Cancel every resend timer FIRST so a doc that was saving when delete
|
|
1787
3239
|
// landed stops re-trying ops the server will only reject as `forbidden`
|
|
1788
|
-
// (the
|
|
3240
|
+
// (the subscription record was evicted at fanout). Draining before the `_markGone`
|
|
1789
3241
|
// listeners keeps the lifecycle observably clean.
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
}
|
|
1793
|
-
outstandingResends.clear();
|
|
3242
|
+
forgetAllOps();
|
|
3243
|
+
clearUnavailableRecovery();
|
|
1794
3244
|
// Stop re-verifying durability against an evicted doc: a resync push
|
|
1795
3245
|
// would only bounce as `forbidden`, and a gap pull would only 404.
|
|
1796
3246
|
if (reverifyTimer !== null) {
|
|
1797
3247
|
clearInterval(reverifyTimer);
|
|
1798
3248
|
reverifyTimer = null;
|
|
1799
3249
|
}
|
|
3250
|
+
clearDivergenceHeal();
|
|
1800
3251
|
if (gapTimer !== null) {
|
|
1801
3252
|
clearTimeout(gapTimer);
|
|
1802
3253
|
gapTimer = null;
|
|
@@ -1805,13 +3256,7 @@ function wireDocTransport(args) {
|
|
|
1805
3256
|
return;
|
|
1806
3257
|
}
|
|
1807
3258
|
if (isDocStatusFrame(frame)) {
|
|
1808
|
-
|
|
1809
|
-
// message-less status still carries a valid `DocumentWorkStatus`
|
|
1810
|
-
// (`message` is typed non-null and rendered verbatim).
|
|
1811
|
-
const status = {
|
|
1812
|
-
...frame.status,
|
|
1813
|
-
message: typeof frame.status.message === 'string' ? frame.status.message : '',
|
|
1814
|
-
};
|
|
3259
|
+
const status = normalizeWorkStatus(frame.status);
|
|
1815
3260
|
// `reload` is the server's authoritative "succeeded, content ready"
|
|
1816
3261
|
// hint: pull the content in and emit the terminal status only AFTER the
|
|
1817
3262
|
// import lands, so an app re-reading on `onStatus` sees content present.
|
|
@@ -1844,8 +3289,14 @@ function wireDocTransport(args) {
|
|
|
1844
3289
|
void reverifyDurability();
|
|
1845
3290
|
return;
|
|
1846
3291
|
}
|
|
1847
|
-
// Unknown frame: ignore, so server-side schema growth doesn't break
|
|
1848
|
-
// SDK builds.
|
|
3292
|
+
// Unknown frame: ignore, so server-side schema growth doesn't break
|
|
3293
|
+
// older SDK builds.
|
|
3294
|
+
}, {
|
|
3295
|
+
// `resendAllOutstanding` on the `doc_init` that follows every
|
|
3296
|
+
// `subscribed` ack IS this topic's re-assertion, so the client drops an
|
|
3297
|
+
// op frame it cannot send now rather than buffering a second copy.
|
|
3298
|
+
ownsFrameRetry: true,
|
|
3299
|
+
onEnded: endSubscription,
|
|
1849
3300
|
});
|
|
1850
3301
|
// Arm the periodic durability re-verify (the long-lived-tab backstop).
|
|
1851
3302
|
// `unref` so the interval never keeps a Node host alive (no-op in the
|
|
@@ -1859,6 +3310,22 @@ function wireDocTransport(args) {
|
|
|
1859
3310
|
// tracker so a silently-dropped server response triggers a retry.
|
|
1860
3311
|
args.doc.setLocalOpHook((opBlob) => {
|
|
1861
3312
|
const clientOpId = args.newClientOpId();
|
|
3313
|
+
// Nothing carries an op once the subscription is over, so it is failed
|
|
3314
|
+
// instead of tracked: an entry nothing can ack pins `savingCount` and
|
|
3315
|
+
// its resends reach a topic the server refused. The caller records the
|
|
3316
|
+
// entry AFTER this hook returns, so the failure waits a microtask for
|
|
3317
|
+
// there to be one to fail.
|
|
3318
|
+
//
|
|
3319
|
+
// Taken before the op is timed, because this path fails the op through
|
|
3320
|
+
// the Document directly rather than through `failOpTerminally`, so a
|
|
3321
|
+
// timing entry written here is one nothing ever drops.
|
|
3322
|
+
if (subscriptionEnded) {
|
|
3323
|
+
void Promise.resolve().then(() => {
|
|
3324
|
+
args.doc._failOutstandingOp(clientOpId, SUBSCRIPTION_ENDED_MESSAGE);
|
|
3325
|
+
});
|
|
3326
|
+
return clientOpId;
|
|
3327
|
+
}
|
|
3328
|
+
opStartedAt.set(clientOpId, Date.now());
|
|
1862
3329
|
const opBlobB64 = bytesToBase64(opBlob);
|
|
1863
3330
|
const sendFrame = {
|
|
1864
3331
|
type: 'op',
|
|
@@ -1876,14 +3343,18 @@ function wireDocTransport(args) {
|
|
|
1876
3343
|
void writeOversizedOp(opBlobB64, clientOpId);
|
|
1877
3344
|
return clientOpId;
|
|
1878
3345
|
}
|
|
1879
|
-
args.wsClient.send(sendFrame);
|
|
1880
3346
|
outstandingResends.set(clientOpId, {
|
|
1881
3347
|
frame: sendFrame,
|
|
1882
3348
|
attempts: 1,
|
|
1883
|
-
//
|
|
3349
|
+
// Placeholders, overwritten by `dispatchOp` and `scheduleResend` once
|
|
3350
|
+
// the op is actually on the socket.
|
|
1884
3351
|
timer: setTimeout(() => undefined, 0),
|
|
3352
|
+
armedAt: 0,
|
|
3353
|
+
dispatchedAt: 0,
|
|
3354
|
+
inFlight: 0,
|
|
3355
|
+
queued: false,
|
|
1885
3356
|
});
|
|
1886
|
-
|
|
3357
|
+
dispatchOp(clientOpId);
|
|
1887
3358
|
return clientOpId;
|
|
1888
3359
|
});
|
|
1889
3360
|
async function writeOversizedOp(opBlobB64, clientOpId) {
|
|
@@ -1907,32 +3378,68 @@ function wireDocTransport(args) {
|
|
|
1907
3378
|
// The size is known here, so refuse without spending a round trip on a
|
|
1908
3379
|
// blob that can only come back 400.
|
|
1909
3380
|
if (opBlobExceedsDurableLimit(opBlobB64)) {
|
|
1910
|
-
|
|
3381
|
+
failOpTerminally(clientOpId, TOO_LARGE_MESSAGE);
|
|
1911
3382
|
return;
|
|
1912
3383
|
}
|
|
1913
3384
|
if (!args.postOversizedOp) {
|
|
1914
|
-
|
|
3385
|
+
failOpTerminally(clientOpId, TOO_LARGE_MESSAGE);
|
|
1915
3386
|
return;
|
|
1916
3387
|
}
|
|
3388
|
+
// An oversized op is deliberately kept out of `outstandingResends` (a
|
|
3389
|
+
// frame past the cap must never reach the socket), so the shed recovery
|
|
3390
|
+
// that re-asserts the tracker cannot reach this one. It runs its own
|
|
3391
|
+
// round of the same policy instead, on the same budget and backoff, so a
|
|
3392
|
+
// capacity refusal costs an op the same nothing whichever transport
|
|
3393
|
+
// carried it.
|
|
1917
3394
|
let result;
|
|
1918
|
-
|
|
1919
|
-
|
|
3395
|
+
for (let round = 0; round <= UNAVAILABLE_MAX_ROUNDS; round += 1) {
|
|
3396
|
+
if (round > 0) {
|
|
3397
|
+
await new Promise((resolve) => {
|
|
3398
|
+
const timer = setTimeout(resolve, unavailableDelayMs(round));
|
|
3399
|
+
timer.unref?.();
|
|
3400
|
+
});
|
|
3401
|
+
}
|
|
3402
|
+
try {
|
|
3403
|
+
result = await args.postOversizedOp(opBlobB64, clientOpId);
|
|
3404
|
+
}
|
|
3405
|
+
catch (err) {
|
|
3406
|
+
result = {
|
|
3407
|
+
ok: false,
|
|
3408
|
+
message: err instanceof Error ? err.message : String(err),
|
|
3409
|
+
// Staging the blob runs strictly before the op write, so a failure
|
|
3410
|
+
// there wrote nothing and the op is still the client's to send: it
|
|
3411
|
+
// is priced the way the write prices its own refusals. Any other
|
|
3412
|
+
// throw leaves it unknown whether the handler ran, and this op
|
|
3413
|
+
// carries no idempotency the server dedupes on, so replaying it
|
|
3414
|
+
// could double-apply.
|
|
3415
|
+
retryable: err instanceof OpStagingError && opStagingIsRetryable(err),
|
|
3416
|
+
};
|
|
3417
|
+
}
|
|
3418
|
+
if (result.ok || !result.retryable)
|
|
3419
|
+
break;
|
|
1920
3420
|
}
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
message: err instanceof Error ? err.message : String(err),
|
|
1925
|
-
};
|
|
3421
|
+
if (result === undefined) {
|
|
3422
|
+
opStartedAt.delete(clientOpId);
|
|
3423
|
+
return;
|
|
1926
3424
|
}
|
|
1927
3425
|
if (!result.ok) {
|
|
1928
3426
|
// Terminal for this op, the same way `op_rejected` is: the local
|
|
1929
3427
|
// commit stays applied but never persists, so the app hears about it
|
|
1930
|
-
// instead of watching `savingCount` sit above zero forever.
|
|
1931
|
-
|
|
3428
|
+
// instead of watching `savingCount` sit above zero forever. A refusal
|
|
3429
|
+
// about the writer turns the Document read-only first, so the app's
|
|
3430
|
+
// own gate closes the editor as the reader is told why.
|
|
3431
|
+
const firstCapacityRefusal = result.atCapacity === true && args.doc._markAtCapacity();
|
|
3432
|
+
if (result.readOnly)
|
|
3433
|
+
args.doc._markReadOnly(result.readOnly);
|
|
3434
|
+
failOpTerminally(clientOpId, result.retryable ? UNAVAILABLE_GIVE_UP_MESSAGE : result.message, {
|
|
3435
|
+
healable: result.atCapacity !== true,
|
|
3436
|
+
report: result.atCapacity !== true || firstCapacityRefusal,
|
|
3437
|
+
});
|
|
1932
3438
|
return;
|
|
1933
3439
|
}
|
|
1934
3440
|
// Same bookkeeping an `op_ack` does: resolve the outstanding entry and
|
|
1935
3441
|
// advance both cursors past the seq the server allocated.
|
|
3442
|
+
opStartedAt.delete(clientOpId);
|
|
1936
3443
|
args.doc.resolveOutstandingOp(clientOpId);
|
|
1937
3444
|
args.setCurrentSeq(result.seq);
|
|
1938
3445
|
args.advanceCoveredSeq(result.seq);
|
|
@@ -1985,14 +3492,13 @@ function wireDocTransport(args) {
|
|
|
1985
3492
|
clearInterval(reverifyTimer);
|
|
1986
3493
|
reverifyTimer = null;
|
|
1987
3494
|
}
|
|
3495
|
+
clearDivergenceHeal();
|
|
1988
3496
|
if (gapTimer !== null) {
|
|
1989
3497
|
clearTimeout(gapTimer);
|
|
1990
3498
|
gapTimer = null;
|
|
1991
3499
|
}
|
|
1992
|
-
|
|
1993
|
-
|
|
1994
|
-
}
|
|
1995
|
-
outstandingResends.clear();
|
|
3500
|
+
forgetAllOps();
|
|
3501
|
+
clearUnavailableRecovery();
|
|
1996
3502
|
originalClose();
|
|
1997
3503
|
};
|
|
1998
3504
|
args.doc.close = () => {
|
|
@@ -2006,15 +3512,39 @@ function wireDocTransport(args) {
|
|
|
2006
3512
|
// (its lifecycle is the parent Document's). Keying on the REQUESTED branch
|
|
2007
3513
|
// (not the resolved one) keeps park and take symmetric; a default-branch
|
|
2008
3514
|
// open has no requested branch and so skips the cache.
|
|
2009
|
-
|
|
2010
|
-
|
|
2011
|
-
|
|
3515
|
+
//
|
|
3516
|
+
// A doc with work still running skips it too: parking clears the status
|
|
3517
|
+
// listeners, and the SDK's own waiters on that work (the import runner
|
|
3518
|
+
// waits for the phase that produces the file it imports) are keyed to
|
|
3519
|
+
// this instance, so a reopen would hand back a Document whose wait can
|
|
3520
|
+
// never fire. A fresh open re-attaches everything.
|
|
3521
|
+
//
|
|
3522
|
+
// So does one the server has evicted. `takeParkedDocument` refuses such an
|
|
3523
|
+
// entry, so parking it buys nothing and costs everything parking keeps
|
|
3524
|
+
// alive: the topic subscription (which goes on delivering every op of a
|
|
3525
|
+
// document nobody is reading) and the LoroDoc's heap, until some later
|
|
3526
|
+
// open or eviction reaches that key. A move is the case that makes this
|
|
3527
|
+
// routine rather than terminal, because the session follows it by
|
|
3528
|
+
// reopening the same id, so the evicted copy is retired on every move.
|
|
3529
|
+
const parkable = !args.doc.readOnly &&
|
|
3530
|
+
args.parkable !== false &&
|
|
3531
|
+
args.doc.status?.pending !== true &&
|
|
3532
|
+
args.doc._goneReason === null;
|
|
3533
|
+
const cacheKey = parkable
|
|
3534
|
+
? parkCacheKey(args.docId, args.requestedBranchId, args.requestedStream)
|
|
3535
|
+
: null;
|
|
2012
3536
|
if (cacheKey === null) {
|
|
2013
3537
|
fullTeardown();
|
|
2014
3538
|
return;
|
|
2015
3539
|
}
|
|
2016
3540
|
args.doc._suspend();
|
|
2017
|
-
parkDocument({
|
|
3541
|
+
parkDocument({
|
|
3542
|
+
doc: args.doc,
|
|
3543
|
+
teardown: fullTeardown,
|
|
3544
|
+
key: cacheKey,
|
|
3545
|
+
optionsSig: documentOptionsSig(args.documentOptions),
|
|
3546
|
+
identity: args.identity?.() ?? null,
|
|
3547
|
+
});
|
|
2018
3548
|
};
|
|
2019
3549
|
}
|
|
2020
3550
|
/**
|