@loro-dev/roost 0.3.1 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +81 -275
- package/dist/identity.d.ts +1 -0
- package/dist/identity.js +13 -0
- package/dist/index.d.ts +1 -1
- package/dist/indexeddb.d.ts +6 -0
- package/dist/indexeddb.js +51 -0
- package/dist/lody-history.d.ts +249 -377
- package/dist/lody-history.js +2054 -2974
- package/dist/store.d.ts +23 -1
- package/dist/store.js +100 -2
- package/dist/sync/coverage.d.ts +11 -0
- package/dist/sync/coverage.js +77 -49
- package/dist/sync/execute.d.ts +14 -2
- package/dist/sync/execute.js +1 -1
- package/dist/sync/explicit.d.ts +66 -0
- package/dist/sync/explicit.js +486 -0
- package/dist/sync/history.d.ts +16 -51
- package/dist/sync/history.js +96 -172
- package/dist/sync/index.d.ts +4 -1
- package/dist/sync/index.js +2 -0
- package/dist/sync/link.js +6 -2
- package/dist/sync/mod.d.ts +4 -2
- package/dist/sync/mod.js +2 -1
- package/dist/sync/transport.d.ts +1 -4
- package/dist/sync/transport.js +15 -25
- package/dist/sync/work.d.ts +13 -2
- package/dist/sync/work.js +252 -3
- package/node/client.d.mts +1 -1
- package/package.json +6 -6
|
@@ -0,0 +1,486 @@
|
|
|
1
|
+
import { blake3 } from '@noble/hashes/blake3.js';
|
|
2
|
+
import { assembleFrames, decodeFrame, MAX_BATCH, MAX_FRAME, MAX_UPDATES, splitBatch } from '../codec.js';
|
|
3
|
+
import { MAX_PAGE_HEADERS, StoreError, _isRetryableImportStatus } from '../store.js';
|
|
4
|
+
import { CoverageError, CoverageStore } from './coverage.js';
|
|
5
|
+
import { ExecuteError, opsOfTurn } from './execute.js';
|
|
6
|
+
import { LinkError } from './link.js';
|
|
7
|
+
import { WorkError, WorkStore } from './work.js';
|
|
8
|
+
/**
|
|
9
|
+
* Network-free local sync primitives for host-carried transports (such as
|
|
10
|
+
* `@loro-dev/streams-crdt/effect` `makeDurableStream({ mode: "explicit" })`),
|
|
11
|
+
* the IndexedDB mirror of `src/sync/explicit.rs`.
|
|
12
|
+
*
|
|
13
|
+
* Each item exchanged across the host transport is one raw Roost v1 frame
|
|
14
|
+
* (`encodeFrame`). Upload batches obey the exact `encodeItems` plaintext byte
|
|
15
|
+
* ceiling `Σ(4 + item.length) <= maxBytes`. Remote imports mark `CoverageStore`
|
|
16
|
+
* directly without writing to `browser_inbox_*` or `browser_replay_*`.
|
|
17
|
+
*/
|
|
18
|
+
export class ExplicitSyncError extends Error {
|
|
19
|
+
code;
|
|
20
|
+
constructor(code, message = code, options) {
|
|
21
|
+
super(message, options);
|
|
22
|
+
this.code = code;
|
|
23
|
+
this.name = 'ExplicitSyncError';
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
const invalid = (message) => new ExplicitSyncError('invalid', message);
|
|
27
|
+
const rethrow = (e) => {
|
|
28
|
+
if (e instanceof ExplicitSyncError)
|
|
29
|
+
throw e;
|
|
30
|
+
if (e instanceof WorkError)
|
|
31
|
+
throw new ExplicitSyncError('work', `work store failure: ${e.message}`, { cause: e });
|
|
32
|
+
if (e instanceof CoverageError)
|
|
33
|
+
throw new ExplicitSyncError('coverage', `coverage failure: ${e.message}`, { cause: e });
|
|
34
|
+
if (e instanceof ExecuteError)
|
|
35
|
+
throw new ExplicitSyncError('execute', `executor failure: ${e.message}`, { cause: e });
|
|
36
|
+
if (e instanceof LinkError)
|
|
37
|
+
throw new ExplicitSyncError('link', `link failure: ${e.message}`, { cause: e });
|
|
38
|
+
if (e instanceof StoreError)
|
|
39
|
+
throw new ExplicitSyncError('store', `store failure: ${e.message}`, { cause: e });
|
|
40
|
+
throw e;
|
|
41
|
+
};
|
|
42
|
+
export class ExplicitSync {
|
|
43
|
+
#storage;
|
|
44
|
+
#work;
|
|
45
|
+
#coverage;
|
|
46
|
+
constructor(storage) {
|
|
47
|
+
this.#storage = storage;
|
|
48
|
+
this.#work = new WorkStore(storage);
|
|
49
|
+
this.#coverage = new CoverageStore(storage);
|
|
50
|
+
}
|
|
51
|
+
/** Discover pending local work and acquire the next dependency-ready batch
|
|
52
|
+
* of raw Roost v1 frames bounded by `options.maxBytes` and `options.maxItems`. */
|
|
53
|
+
async pullPendingBatch(stream, scope, options = {}) {
|
|
54
|
+
try {
|
|
55
|
+
checkScopeStream(stream, scope);
|
|
56
|
+
const maxBytes = options.maxBytes ?? MAX_FRAME;
|
|
57
|
+
const maxItems = options.maxItems ?? MAX_UPDATES;
|
|
58
|
+
const partial = options.partial ?? false;
|
|
59
|
+
if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0)
|
|
60
|
+
throw invalid('maxBytes must be positive');
|
|
61
|
+
if (!Number.isSafeInteger(maxItems) || maxItems <= 0)
|
|
62
|
+
throw invalid('maxItems must be positive');
|
|
63
|
+
const plan = await this.#work.resume(scope);
|
|
64
|
+
for (const token of plan.confirm)
|
|
65
|
+
await this.#work.confirm(token, false);
|
|
66
|
+
if (options.turnIds !== undefined) {
|
|
67
|
+
await this.#discoverExplicitTurns(stream, scope, options.turnIds);
|
|
68
|
+
}
|
|
69
|
+
else if (partial) {
|
|
70
|
+
await this.#discoverLocalEvents(stream, scope, 100);
|
|
71
|
+
}
|
|
72
|
+
else {
|
|
73
|
+
await this.#discoverFull(stream, scope, 100);
|
|
74
|
+
}
|
|
75
|
+
const acquired = await this.#work.acquireBatch(scope, maxBytes, maxItems);
|
|
76
|
+
if (acquired.length === 0)
|
|
77
|
+
return null;
|
|
78
|
+
const items = [];
|
|
79
|
+
const receipt = [];
|
|
80
|
+
for (const task of acquired) {
|
|
81
|
+
let frames;
|
|
82
|
+
try {
|
|
83
|
+
frames = splitBatch(task.bytes);
|
|
84
|
+
}
|
|
85
|
+
catch (e) {
|
|
86
|
+
throw new WorkError('corrupt', `task frozen batch invalid: ${e instanceof Error ? e.message : e}`);
|
|
87
|
+
}
|
|
88
|
+
if (frames.length !== 1)
|
|
89
|
+
throw new WorkError('corrupt', 'task frozen batch must contain one frame');
|
|
90
|
+
items.push(frames[0]);
|
|
91
|
+
receipt.push({
|
|
92
|
+
turnId: task.token.task.turn.slice(),
|
|
93
|
+
seq: task.token.task.seq,
|
|
94
|
+
attempt: task.token.attempt,
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
return { items, receipt };
|
|
98
|
+
}
|
|
99
|
+
catch (e) {
|
|
100
|
+
return rethrow(e);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
/** Atomically confirm a pulled batch in `WorkStore` + `CoverageStore` after
|
|
104
|
+
* the host transport receives durable server ACK. */
|
|
105
|
+
async confirmPendingBatch(scope, receipt) {
|
|
106
|
+
try {
|
|
107
|
+
const tokens = receipt.map(entry => ({
|
|
108
|
+
scope,
|
|
109
|
+
task: { turn: entry.turnId.slice(), seq: entry.seq },
|
|
110
|
+
attempt: entry.attempt,
|
|
111
|
+
}));
|
|
112
|
+
return await this.#work.confirmBatch(tokens, false);
|
|
113
|
+
}
|
|
114
|
+
catch (e) {
|
|
115
|
+
return rethrow(e);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
/** Import raw Roost v1 frames received from the remote transport directly
|
|
119
|
+
* into `stream` and mark `CoverageStore` without writing to `browser_inbox_*`
|
|
120
|
+
* or `browser_replay_*`. */
|
|
121
|
+
async importRemoteBatch(stream, scope, items, partial = false) {
|
|
122
|
+
try {
|
|
123
|
+
checkScopeStream(stream, scope);
|
|
124
|
+
const statuses = [];
|
|
125
|
+
const applied = [];
|
|
126
|
+
const conflicts = [];
|
|
127
|
+
const appliedTurns = [];
|
|
128
|
+
const appliedSeen = new Set();
|
|
129
|
+
const pendingTurns = [];
|
|
130
|
+
const pendingSeen = new Set();
|
|
131
|
+
let retryQuotaExceeded = false;
|
|
132
|
+
let idx = 0;
|
|
133
|
+
while (idx < items.length) {
|
|
134
|
+
const head = items[idx];
|
|
135
|
+
if (head.length > MAX_FRAME) {
|
|
136
|
+
statuses.push({ kind: 'rejected', reason: 'frame too large' });
|
|
137
|
+
idx += 1;
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
const chunk = [];
|
|
141
|
+
let framesLen = 0;
|
|
142
|
+
while (idx < items.length && chunk.length < MAX_UPDATES) {
|
|
143
|
+
const frame = items[idx];
|
|
144
|
+
if (frame.length > MAX_FRAME)
|
|
145
|
+
break;
|
|
146
|
+
const entryLen = varintLen(frame.length) + frame.length;
|
|
147
|
+
const nextLen = framesLen + entryLen;
|
|
148
|
+
const total = 4 + varintLen(chunk.length + 1) + nextLen;
|
|
149
|
+
if (total > MAX_BATCH) {
|
|
150
|
+
if (chunk.length === 0)
|
|
151
|
+
throw invalid('frame exceeds batch ceiling');
|
|
152
|
+
break;
|
|
153
|
+
}
|
|
154
|
+
chunk.push(frame);
|
|
155
|
+
framesLen = nextLen;
|
|
156
|
+
idx += 1;
|
|
157
|
+
}
|
|
158
|
+
if (chunk.length === 0)
|
|
159
|
+
continue;
|
|
160
|
+
const batch = assembleFrames(chunk);
|
|
161
|
+
const coverage = this.#coverage;
|
|
162
|
+
// Import frames, drain unlocked pending ops, record served receipts,
|
|
163
|
+
// and mark CoverageStore present all in ONE IndexedDB transaction so
|
|
164
|
+
// a crash or abort never leaves a drained pending op unmarked in coverage.
|
|
165
|
+
const report = await stream.importBatchWithTx(batch, partial, function* (tx, chunkReport) {
|
|
166
|
+
const served = [];
|
|
167
|
+
const work = [];
|
|
168
|
+
const seenWork = new Set();
|
|
169
|
+
for (let i = 0; i < Math.min(chunk.length, chunkReport.statuses.length); i++) {
|
|
170
|
+
const status = chunkReport.statuses[i];
|
|
171
|
+
if (status.kind === 'rejected')
|
|
172
|
+
continue;
|
|
173
|
+
const frame = chunk[i];
|
|
174
|
+
try {
|
|
175
|
+
const update = decodeFrame(frame);
|
|
176
|
+
if (update.seq <= 0xffffffffn) {
|
|
177
|
+
served.push({
|
|
178
|
+
turn: update.turnId,
|
|
179
|
+
seq: Number(update.seq),
|
|
180
|
+
fp: blake3(assembleFrames([frame])),
|
|
181
|
+
});
|
|
182
|
+
if (status.kind !== 'pending') {
|
|
183
|
+
const key = `${hexBytes(update.turnId)}:${update.seq}`;
|
|
184
|
+
if (!seenWork.has(key)) {
|
|
185
|
+
seenWork.add(key);
|
|
186
|
+
work.push({ turn: update.turnId, seq: update.seq });
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
catch {
|
|
192
|
+
// Unparseable frame would have been rejected; skip defensively.
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
for (const reference of chunkReport.applied) {
|
|
196
|
+
const key = `${hexBytes(reference.turnId)}:${reference.seq}`;
|
|
197
|
+
if (!seenWork.has(key)) {
|
|
198
|
+
seenWork.add(key);
|
|
199
|
+
work.push({ turn: reference.turnId, seq: reference.seq });
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
if (served.length > 0)
|
|
203
|
+
yield* coverage.recordServedIn(tx, scope, served);
|
|
204
|
+
yield* markWorkPresentInTx(stream, tx, coverage, scope, work, seenWork, partial);
|
|
205
|
+
});
|
|
206
|
+
for (let i = 0; i < Math.min(chunk.length, report.statuses.length); i++) {
|
|
207
|
+
const status = report.statuses[i];
|
|
208
|
+
if (status.kind === 'rejected')
|
|
209
|
+
continue;
|
|
210
|
+
try {
|
|
211
|
+
const update = decodeFrame(chunk[i]);
|
|
212
|
+
const h = hexBytes(update.turnId);
|
|
213
|
+
if (status.kind === 'pending') {
|
|
214
|
+
if (!pendingSeen.has(h)) {
|
|
215
|
+
pendingSeen.add(h);
|
|
216
|
+
pendingTurns.push(update.turnId);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
else if (!appliedSeen.has(h)) {
|
|
220
|
+
appliedSeen.add(h);
|
|
221
|
+
appliedTurns.push(update.turnId);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
catch {
|
|
225
|
+
// Unparseable frame would have been rejected.
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
for (const reference of report.applied) {
|
|
229
|
+
const h = hexBytes(reference.turnId);
|
|
230
|
+
if (!appliedSeen.has(h)) {
|
|
231
|
+
appliedSeen.add(h);
|
|
232
|
+
appliedTurns.push(reference.turnId);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
const chunkQuota = report.statuses.some(_isRetryableImportStatus);
|
|
236
|
+
statuses.push(...report.statuses);
|
|
237
|
+
applied.push(...report.applied);
|
|
238
|
+
conflicts.push(...report.conflicts);
|
|
239
|
+
if (chunkQuota) {
|
|
240
|
+
retryQuotaExceeded = true;
|
|
241
|
+
break;
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
const remainingPending = [];
|
|
245
|
+
for (const id of pendingTurns) {
|
|
246
|
+
if ((await stream.readTurnHeader(id)).kind === 'incomplete')
|
|
247
|
+
remainingPending.push(id);
|
|
248
|
+
}
|
|
249
|
+
const hasPendingDependencies = (await stream.pendingTurns(undefined, 1)).length > 0;
|
|
250
|
+
return {
|
|
251
|
+
report: { statuses, applied, conflicts },
|
|
252
|
+
appliedTurns,
|
|
253
|
+
pendingTurns: remainingPending,
|
|
254
|
+
hasPendingDependencies,
|
|
255
|
+
retryQuotaExceeded,
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
catch (e) {
|
|
259
|
+
return rethrow(e);
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
/** Clear `WorkStore` and `CoverageStore` state for `scope` in a single write
|
|
263
|
+
* transaction while preserving local stream Turns, events and indexes. */
|
|
264
|
+
async resetSyncState(scope) {
|
|
265
|
+
try {
|
|
266
|
+
return await this.#storage.transact(true, function* (tx) {
|
|
267
|
+
const workKeysRemoved = yield* WorkStore.clearScopeIn(tx, scope);
|
|
268
|
+
const coverageKeysRemoved = yield* CoverageStore.clearScopeIn(tx, scope);
|
|
269
|
+
return { workKeysRemoved, coverageKeysRemoved };
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
catch (e) {
|
|
273
|
+
return rethrow(e);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
async #discoverExplicitTurns(stream, scope, turnIds) {
|
|
277
|
+
for (const id of turnIds) {
|
|
278
|
+
const res = await stream.readTurnHeader(id);
|
|
279
|
+
const header = readableHeaderOrNull(res);
|
|
280
|
+
if (header === null)
|
|
281
|
+
continue;
|
|
282
|
+
try {
|
|
283
|
+
const ops = await opsOfTurn(stream, header, 0);
|
|
284
|
+
await this.#work.discoverBatch(scope, ops, undefined);
|
|
285
|
+
}
|
|
286
|
+
catch (e) {
|
|
287
|
+
if (e instanceof ExecuteError && e.code === 'invalid' && (e.message.includes('not readable') || e.message.includes('not sealed'))) {
|
|
288
|
+
continue;
|
|
289
|
+
}
|
|
290
|
+
throw e;
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
async #discoverLocalEvents(stream, scope, pageSize) {
|
|
295
|
+
const clamped = Math.max(1, Math.min(pageSize, MAX_PAGE_HEADERS));
|
|
296
|
+
let eventCursor = await this.#work.eventCursor(scope);
|
|
297
|
+
for (;;) {
|
|
298
|
+
const events = await stream.eventsAfter(eventCursor, clamped);
|
|
299
|
+
if (events.length === 0)
|
|
300
|
+
break;
|
|
301
|
+
const end = events[events.length - 1].cursor;
|
|
302
|
+
const ops = [];
|
|
303
|
+
for (const record of events) {
|
|
304
|
+
if (record.event.kind !== 'changed' || record.event.origin !== 'local')
|
|
305
|
+
continue;
|
|
306
|
+
const update = record.event.update;
|
|
307
|
+
const header = requireReadableHeader(await stream.readTurnHeader(update.turnId));
|
|
308
|
+
const seq = u32Seq(update.seq);
|
|
309
|
+
ops.push(...await opsOfTurn(stream, header, seq, update.seq + 1n));
|
|
310
|
+
}
|
|
311
|
+
const res = await this.#work.discoverEventBatch(scope, ops, eventCursor, end);
|
|
312
|
+
if (res === undefined) {
|
|
313
|
+
eventCursor = await this.#work.eventCursor(scope);
|
|
314
|
+
continue;
|
|
315
|
+
}
|
|
316
|
+
eventCursor = end;
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
async #discoverFull(stream, scope, pageSize) {
|
|
320
|
+
const clamped = Math.max(1, Math.min(pageSize, MAX_PAGE_HEADERS));
|
|
321
|
+
let eventCursor = await this.#work.eventCursor(scope);
|
|
322
|
+
for (;;) {
|
|
323
|
+
const events = await stream.eventsAfter(eventCursor, clamped);
|
|
324
|
+
if (events.length === 0)
|
|
325
|
+
break;
|
|
326
|
+
const end = events[events.length - 1].cursor;
|
|
327
|
+
const ops = [];
|
|
328
|
+
for (const record of events) {
|
|
329
|
+
if (record.event.kind !== 'changed')
|
|
330
|
+
continue;
|
|
331
|
+
const update = record.event.update;
|
|
332
|
+
const header = requireReadableHeader(await stream.readTurnHeader(update.turnId));
|
|
333
|
+
const seq = u32Seq(update.seq);
|
|
334
|
+
ops.push(...await opsOfTurn(stream, header, seq, update.seq + 1n));
|
|
335
|
+
}
|
|
336
|
+
const res = await this.#work.discoverEventBatch(scope, ops, eventCursor, end);
|
|
337
|
+
if (res === undefined) {
|
|
338
|
+
eventCursor = await this.#work.eventCursor(scope);
|
|
339
|
+
continue;
|
|
340
|
+
}
|
|
341
|
+
eventCursor = end;
|
|
342
|
+
}
|
|
343
|
+
let openAfter = undefined;
|
|
344
|
+
for (;;) {
|
|
345
|
+
const open = await this.#work.openTurns(scope, openAfter, clamped);
|
|
346
|
+
if (open.length === 0)
|
|
347
|
+
break;
|
|
348
|
+
openAfter = open[open.length - 1].turn;
|
|
349
|
+
for (const entry of open) {
|
|
350
|
+
const header = requireReadableHeader(await stream.readTurnHeader(entry.turn));
|
|
351
|
+
if (BigInt(entry.offeredUpto) >= header.nextSeq)
|
|
352
|
+
continue;
|
|
353
|
+
const ops = await opsOfTurn(stream, header, entry.offeredUpto);
|
|
354
|
+
await this.#work.discoverBatch(scope, ops, undefined);
|
|
355
|
+
}
|
|
356
|
+
if (open.length < clamped)
|
|
357
|
+
break;
|
|
358
|
+
}
|
|
359
|
+
const cursor = (await this.#work.discovery(scope)).cursor;
|
|
360
|
+
let start = cursor;
|
|
361
|
+
let last = cursor;
|
|
362
|
+
for (;;) {
|
|
363
|
+
const page = await stream.turnHeadersAfter(start, clamped);
|
|
364
|
+
if (page.length === 0)
|
|
365
|
+
break;
|
|
366
|
+
const ops = [];
|
|
367
|
+
let pageLast = last;
|
|
368
|
+
let scanLast = start;
|
|
369
|
+
for (const row of page) {
|
|
370
|
+
const header = readableHeaderOrNull(row);
|
|
371
|
+
if (header !== null) {
|
|
372
|
+
ops.push(...await opsOfTurn(stream, header, 0));
|
|
373
|
+
pageLast = header.turnId;
|
|
374
|
+
scanLast = header.turnId;
|
|
375
|
+
}
|
|
376
|
+
else if (row.kind !== 'found') {
|
|
377
|
+
scanLast = row.turnId;
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
if (ops.length > 0 || !sameOptionalBytes(pageLast, last)) {
|
|
381
|
+
const result = await this.#work.discoverBatch(scope, ops, pageLast);
|
|
382
|
+
last = result.cursor;
|
|
383
|
+
}
|
|
384
|
+
if (page.length < clamped || sameOptionalBytes(scanLast, start))
|
|
385
|
+
break;
|
|
386
|
+
start = scanLast;
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
function checkScopeStream(stream, scope) {
|
|
391
|
+
if (scope.stream !== stream.id)
|
|
392
|
+
throw invalid('scope stream does not match stream handle');
|
|
393
|
+
}
|
|
394
|
+
function readableHeaderOrNull(result) {
|
|
395
|
+
if (result.kind === 'found')
|
|
396
|
+
return result.turn;
|
|
397
|
+
if (result.kind === 'incomplete' && result.prefix !== null)
|
|
398
|
+
return result.prefix;
|
|
399
|
+
return null;
|
|
400
|
+
}
|
|
401
|
+
function requireReadableHeader(result) {
|
|
402
|
+
const header = readableHeaderOrNull(result);
|
|
403
|
+
if (header === null)
|
|
404
|
+
throw invalid(`turn header not readable: ${result.kind}`);
|
|
405
|
+
return header;
|
|
406
|
+
}
|
|
407
|
+
function u32Seq(seq) {
|
|
408
|
+
if (seq < 0n || seq > 0xffffffffn)
|
|
409
|
+
throw invalid('seq overflow');
|
|
410
|
+
return Number(seq);
|
|
411
|
+
}
|
|
412
|
+
function varintLen(n) {
|
|
413
|
+
let size = 1;
|
|
414
|
+
while (n >= 128) {
|
|
415
|
+
size += 1;
|
|
416
|
+
n = Math.floor(n / 128);
|
|
417
|
+
}
|
|
418
|
+
return size;
|
|
419
|
+
}
|
|
420
|
+
function* markWorkPresentInTx(stream, tx, coverage, scope, work, seen, localParentsOnly) {
|
|
421
|
+
while (work.length > 0) {
|
|
422
|
+
const item = work.pop();
|
|
423
|
+
const seq32 = u32Seq(item.seq);
|
|
424
|
+
const batch = yield* stream.exportSingleUpdateIn(tx, item.turn, item.seq);
|
|
425
|
+
if (batch === null)
|
|
426
|
+
continue; // Duplicate of a frame still sitting in `pending`.
|
|
427
|
+
const fp = blake3(batch);
|
|
428
|
+
if (!(yield* coverage.wasServedIn(tx, scope, item.turn, seq32, fp)))
|
|
429
|
+
continue;
|
|
430
|
+
const header = requireReadableHeader(yield* stream.headerResult(tx, item.turn));
|
|
431
|
+
const parents = [];
|
|
432
|
+
const unresolved = [];
|
|
433
|
+
for (const parent of header.parents) {
|
|
434
|
+
const parentResult = yield* stream.headerResult(tx, parent.id);
|
|
435
|
+
if (parentResult.kind !== 'found') {
|
|
436
|
+
if (localParentsOnly) {
|
|
437
|
+
unresolved.push({ turn: [...parent.id], hash: [...parent.hash] });
|
|
438
|
+
continue;
|
|
439
|
+
}
|
|
440
|
+
throw invalid(`parent ${hexBytes(parent.id)} of turn ${hexBytes(item.turn)} not readable`);
|
|
441
|
+
}
|
|
442
|
+
const parentHeader = parentResult.turn;
|
|
443
|
+
if (parentHeader.sealed === null || parentHeader.nextSeq === 0n) {
|
|
444
|
+
if (localParentsOnly) {
|
|
445
|
+
unresolved.push({ turn: [...parent.id], hash: [...parent.hash] });
|
|
446
|
+
continue;
|
|
447
|
+
}
|
|
448
|
+
throw invalid(`parent ${hexBytes(parent.id)} of turn ${hexBytes(item.turn)} is not sealed`);
|
|
449
|
+
}
|
|
450
|
+
if (hexBytes(parentHeader.sealed) !== hexBytes(parent.hash)) {
|
|
451
|
+
if (localParentsOnly) {
|
|
452
|
+
unresolved.push({ turn: [...parent.id], hash: [...parent.hash] });
|
|
453
|
+
continue;
|
|
454
|
+
}
|
|
455
|
+
throw invalid('parent declaration hash mismatch');
|
|
456
|
+
}
|
|
457
|
+
const sealBatch = yield* stream.exportSingleUpdateIn(tx, parent.id, parentHeader.nextSeq - 1n);
|
|
458
|
+
if (sealBatch === null)
|
|
459
|
+
throw invalid(`parent ${hexBytes(parent.id)} seal update missing`);
|
|
460
|
+
parents.push({ turnId: parent.id, sealFp: blake3(sealBatch) });
|
|
461
|
+
}
|
|
462
|
+
yield* coverage.markReceivedIn(tx, scope, item.turn, seq32, fp, header.sealed !== null && item.seq === header.nextSeq - 1n, parents, unresolved);
|
|
463
|
+
if (header.sealed !== null) {
|
|
464
|
+
for (const child of yield* coverage.unresolvedChildrenIn(tx, scope, item.turn)) {
|
|
465
|
+
const key = `${hexBytes(child)}:0`;
|
|
466
|
+
if (!seen.has(key)) {
|
|
467
|
+
seen.add(key);
|
|
468
|
+
work.push({ turn: child, seq: 0n });
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
function hexBytes(bytes) {
|
|
475
|
+
return Array.from(bytes, b => b.toString(16).padStart(2, '0')).join('');
|
|
476
|
+
}
|
|
477
|
+
function sameOptionalBytes(a, b) {
|
|
478
|
+
if (a === undefined || b === undefined)
|
|
479
|
+
return a === b;
|
|
480
|
+
if (a.length !== b.length)
|
|
481
|
+
return false;
|
|
482
|
+
for (let i = 0; i < a.length; i++)
|
|
483
|
+
if (a[i] !== b[i])
|
|
484
|
+
return false;
|
|
485
|
+
return true;
|
|
486
|
+
}
|
package/dist/sync/history.d.ts
CHANGED
|
@@ -17,23 +17,11 @@ import type { WorkScope } from './work.js';
|
|
|
17
17
|
*
|
|
18
18
|
* `BackwardByteSource` is an injectable, pure-byte primitive: return the
|
|
19
19
|
* ≤`limitBytes` immediately before an opaque offset (or before the tail).
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
* offsets are cumulative byte positions, not message ordinals); batch
|
|
26
|
-
* boundaries come from the provider itself (N011): every page carries a
|
|
27
|
-
* verifiable span list — one span per intersected message, tiling the
|
|
28
|
-
* payload exactly, each giving the message's total length and this
|
|
29
|
-
* fragment's offset within it. A magic/marker scan over the bytes is NOT
|
|
30
|
-
* a boundary proof (payloads may legitimately contain batch-looking
|
|
31
|
-
* bytes, and signature verification proves content authenticity, not
|
|
32
|
-
* server-side boundaries); that approach was abandoned and is kept only
|
|
33
|
-
* as a failure-study record in the goal log (N011). The client
|
|
34
|
-
* reassembles a message from its fragments (contiguity by
|
|
35
|
-
* msgOffset/messageLen arithmetic) and only hands COMPLETE messages to
|
|
36
|
-
* the codec — a fragment is transport state, never framed on spec.
|
|
20
|
+
* Each response stays within the byte limit and provides frame boundaries
|
|
21
|
+
* and continuation flags. Offsets are opaque to the history reader.
|
|
22
|
+
* A walk chains page cursors and only admits a message after all of its
|
|
23
|
+
* contiguous frames have arrived. The Streams message limit bounds wire
|
|
24
|
+
* reassembly, while Inbox limits apply to the decoded batch.
|
|
37
25
|
*
|
|
38
26
|
* # Intake model: collect during the walk, receive forward at its end
|
|
39
27
|
*
|
|
@@ -71,41 +59,19 @@ export declare class HistoryError extends Error {
|
|
|
71
59
|
readonly code: 'invalid' | 'transport' | 'inbox' | 'replay' | 'retryQuota' | 'coverage' | 'store' | 'link' | 'policyDenied' | 'policy';
|
|
72
60
|
constructor(code: 'invalid' | 'transport' | 'inbox' | 'replay' | 'retryQuota' | 'coverage' | 'store' | 'link' | 'policyDenied' | 'policy', message?: string, options?: ErrorOptions);
|
|
73
61
|
}
|
|
74
|
-
/**
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
relStart: number;
|
|
81
|
-
/** See `relStart`. */
|
|
82
|
-
relEnd: number;
|
|
83
|
-
/** The message's opaque absolute start offset (fragments of one
|
|
84
|
-
* message share it across pages; never parsed). */
|
|
85
|
-
messageStart: string;
|
|
86
|
-
/** Total byte length of the COMPLETE message. */
|
|
87
|
-
messageLen: number;
|
|
88
|
-
/** This fragment's byte offset WITHIN the message (`msgOffset +
|
|
89
|
-
* (relEnd - relStart) <= messageLen`): reassembly contiguity is plain
|
|
90
|
-
* arithmetic on these two integers. */
|
|
91
|
-
msgOffset: number;
|
|
62
|
+
/** A message or fragment, with its provider-issued start and continuation flags. */
|
|
63
|
+
export type BackwardFrame = {
|
|
64
|
+
data: Uint8Array;
|
|
65
|
+
startOffset: string;
|
|
66
|
+
continuesBefore: boolean;
|
|
67
|
+
continuesAfter: boolean;
|
|
92
68
|
};
|
|
93
|
-
/** One bounded
|
|
69
|
+
/** One bounded page in stream order. Continuations can only occur at its edges. */
|
|
94
70
|
export type BackwardPage = {
|
|
95
|
-
|
|
96
|
-
* ≤ the requested `limitBytes`, always — a message larger than the
|
|
97
|
-
* limit is fragmented across pages, never a budget exception. */
|
|
98
|
-
payload: Uint8Array;
|
|
99
|
-
/** The opaque offset at which `payload` ends (exclusive). */
|
|
71
|
+
frames: readonly BackwardFrame[];
|
|
100
72
|
endOffset: string;
|
|
101
|
-
/** The opaque offset at which `payload` starts: the `from` for the
|
|
102
|
-
* next (older) page. */
|
|
103
73
|
prevOffset: string;
|
|
104
|
-
/** True when no bytes exist before `prevOffset` (the log's start). */
|
|
105
74
|
reachedStart: boolean;
|
|
106
|
-
/** One span per message intersecting the payload, oldest first;
|
|
107
|
-
* verified to tile the payload (see `MessageSpan`). */
|
|
108
|
-
messages: MessageSpan[];
|
|
109
75
|
};
|
|
110
76
|
/** The injectable backward byte source (N2's only backend-coupled seam).
|
|
111
77
|
* Implementations perform no retries of their own and never run inside a
|
|
@@ -161,6 +127,7 @@ export declare class HistoryReader {
|
|
|
161
127
|
readonly replay: DurableReplay;
|
|
162
128
|
readonly coverage: CoverageStore;
|
|
163
129
|
readonly policy: PolicyStore;
|
|
130
|
+
/** Maximum plaintext batch size accepted by Inbox. */
|
|
164
131
|
readonly maxBatchBytes: number;
|
|
165
132
|
/** The intake is the partial-replica path (N3). Coverage marks use
|
|
166
133
|
* the exact local frames and bind a declared parent only where that
|
|
@@ -172,10 +139,8 @@ export declare class HistoryReader {
|
|
|
172
139
|
readonly storage: IndexedDbStorage;
|
|
173
140
|
private constructor();
|
|
174
141
|
/** Open the reader for one (stream, remote-generation) scope (the scope
|
|
175
|
-
* comes from `Executor.scope`). Reuses the link's
|
|
176
|
-
*
|
|
177
|
-
* boundary-discovery buffer (a missing chain past it is typed
|
|
178
|
-
* corruption). */
|
|
142
|
+
* comes from `Executor.scope`). Reuses the link's Inbox and replay limits
|
|
143
|
+
* for batches received after any configured decryption. */
|
|
179
144
|
static open(storage: IndexedDbStorage, stream: Stream, scope: WorkScope, limits: LinkLimits): HistoryReader;
|
|
180
145
|
/** The partial-replica intake (N3): receipts import through the
|
|
181
146
|
* partial path — parents are declared references and seals verify
|