@loro-dev/roost 0.1.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/LICENSE +21 -0
- package/README.md +397 -0
- package/dist/codec.d.ts +66 -0
- package/dist/codec.js +275 -0
- package/dist/crypto.d.ts +21 -0
- package/dist/crypto.js +103 -0
- package/dist/durable-framing.d.ts +44 -0
- package/dist/durable-framing.js +207 -0
- package/dist/framing.d.ts +28 -0
- package/dist/framing.js +144 -0
- package/dist/history-publication.d.ts +58 -0
- package/dist/history-publication.js +234 -0
- package/dist/identity.d.ts +14 -0
- package/dist/identity.js +62 -0
- package/dist/inbox.d.ts +69 -0
- package/dist/inbox.js +262 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +6 -0
- package/dist/indexeddb.d.ts +38 -0
- package/dist/indexeddb.js +299 -0
- package/dist/json.d.ts +23 -0
- package/dist/json.js +221 -0
- package/dist/lody-history.d.ts +397 -0
- package/dist/lody-history.js +1559 -0
- package/dist/projection.d.ts +53 -0
- package/dist/projection.js +543 -0
- package/dist/replay.d.ts +63 -0
- package/dist/replay.js +201 -0
- package/dist/sender.d.ts +26 -0
- package/dist/sender.js +67 -0
- package/dist/store.d.ts +384 -0
- package/dist/store.js +1437 -0
- package/dist/sync/coverage.d.ts +276 -0
- package/dist/sync/coverage.js +1084 -0
- package/dist/sync/crypto.d.ts +64 -0
- package/dist/sync/crypto.js +155 -0
- package/dist/sync/execute.d.ts +142 -0
- package/dist/sync/execute.js +321 -0
- package/dist/sync/history.d.ts +214 -0
- package/dist/sync/history.js +786 -0
- package/dist/sync/index.d.ts +17 -0
- package/dist/sync/index.js +9 -0
- package/dist/sync/link.d.ts +192 -0
- package/dist/sync/link.js +663 -0
- package/dist/sync/mod.d.ts +24 -0
- package/dist/sync/mod.js +15 -0
- package/dist/sync/policy.d.ts +62 -0
- package/dist/sync/policy.js +128 -0
- package/dist/sync/registry.d.ts +129 -0
- package/dist/sync/registry.js +333 -0
- package/dist/sync/transport.d.ts +91 -0
- package/dist/sync/transport.js +162 -0
- package/dist/sync/work.d.ts +351 -0
- package/dist/sync/work.js +1344 -0
- package/package.json +47 -0
|
@@ -0,0 +1,786 @@
|
|
|
1
|
+
import { blake3 } from '@noble/hashes/blake3.js';
|
|
2
|
+
import { decodeBatch } from '../codec.js';
|
|
3
|
+
import { Inbox, InboxError } from '../inbox.js';
|
|
4
|
+
import { DurableReplay, ReplayError } from '../replay.js';
|
|
5
|
+
import { StoreError } from '../store.js';
|
|
6
|
+
import { CoverageError, CoverageStore } from './coverage.js';
|
|
7
|
+
import { openEnvelopeAsync } from './crypto.js';
|
|
8
|
+
import { TransportError } from './execute.js';
|
|
9
|
+
import { markAdmittedFromBatch, markAdmittedFromBatchLocalParents, recordNextServed, intakeSource, replayReceipt, recordServedBatch } from './link.js';
|
|
10
|
+
import { PolicyError, PolicyStore } from './policy.js';
|
|
11
|
+
import { generationKeyFragment } from './registry.js';
|
|
12
|
+
/**
|
|
13
|
+
* On-demand reverse history (N2, small-scale through-path), the IndexedDB
|
|
14
|
+
* mirror of src/sync/history.rs: fetch the LATEST window of a remote's
|
|
15
|
+
* durable log without downloading it whole, layered on the same
|
|
16
|
+
* Inbox/Replay durable machinery as the live link.
|
|
17
|
+
*
|
|
18
|
+
* # Provider contract (the only backend-coupled seam)
|
|
19
|
+
*
|
|
20
|
+
* `BackwardByteSource` is an injectable, pure-byte primitive: return the
|
|
21
|
+
* ≤`limitBytes` immediately before an opaque offset (or before the tail).
|
|
22
|
+
* **No response ever exceeds `limitBytes`** — a message larger than the
|
|
23
|
+
* page budget is simply paged over (more requests, each bounded), never a
|
|
24
|
+
* budget exception. The interface carries no message-boundary information
|
|
25
|
+
* (the byte-level Durable-Streams protocol exposes none for
|
|
26
|
+
* `application/octet-stream`, and the backend audit (N008) confirms
|
|
27
|
+
* offsets are cumulative byte positions, not message ordinals); batch
|
|
28
|
+
* boundaries come from the provider itself (N011): every page carries a
|
|
29
|
+
* verifiable span list — one span per intersected message, tiling the
|
|
30
|
+
* payload exactly, each giving the message's total length and this
|
|
31
|
+
* fragment's offset within it. A magic/marker scan over the bytes is NOT
|
|
32
|
+
* a boundary proof (payloads may legitimately contain batch-looking
|
|
33
|
+
* bytes, and signature verification proves content authenticity, not
|
|
34
|
+
* server-side boundaries); that approach was abandoned and is kept only
|
|
35
|
+
* as a failure-study record in the goal log (N011). The client
|
|
36
|
+
* reassembles a message from its fragments (contiguity by
|
|
37
|
+
* msgOffset/messageLen arithmetic) and only hands COMPLETE messages to
|
|
38
|
+
* the codec — a fragment is transport state, never framed on spec.
|
|
39
|
+
*
|
|
40
|
+
* # Intake model: collect during the walk, receive forward at its end
|
|
41
|
+
*
|
|
42
|
+
* The walk only collects complete batches (newest pages first, chains
|
|
43
|
+
* prepended). After the byte budget, a Turn that appeared in that
|
|
44
|
+
* window but is missing Create or a contiguous seq prefix may keep
|
|
45
|
+
* paging for at most another `pageLimitBytes`, and only messages of those
|
|
46
|
+
* window turns are kept — intervening history is neither imported nor
|
|
47
|
+
* scanned without bound. If the prefix is still incomplete, the turn
|
|
48
|
+
* stays pending (honest missing-prefix). Receipts are written afterwards,
|
|
49
|
+
* oldest-first. Receipt order
|
|
50
|
+
* is therefore independent of page geometry and walk depth, and imports
|
|
51
|
+
* run in causal order (the pending machinery resolves whatever a window
|
|
52
|
+
* edge still lacks). A crash during the walk loses nothing durable (no
|
|
53
|
+
* receipts were written yet); a crash during the receive phase is healed
|
|
54
|
+
* by the ledger's content addressing: cursors are `0x03 || blake3(batch)`,
|
|
55
|
+
* so re-received batches are exact Inbox duplicates by construction and
|
|
56
|
+
* `Inbox.containsCursor` skips already-held batches without touching the
|
|
57
|
+
* receipt chain — identical batch bytes in the log twice (an op both
|
|
58
|
+
* bridged and self-uploaded) are received once, which is semantically
|
|
59
|
+
* sufficient (the import dedupes regardless). Coverage is marked
|
|
60
|
+
* present-exact from the local store for every admitted op through the
|
|
61
|
+
* same shared path as the live link.
|
|
62
|
+
*
|
|
63
|
+
* # Report honesty (Spec §8)
|
|
64
|
+
*
|
|
65
|
+
* The report states the byte range actually fetched and the turns actually
|
|
66
|
+
* applied or still pending — the log's tail, the globally latest TurnId
|
|
67
|
+
* and a complete local history are three different things, and nothing
|
|
68
|
+
* here claims the latter two.
|
|
69
|
+
*/
|
|
70
|
+
/** Errors of history reads. Semantic rejections roll their transaction
|
|
71
|
+
* back; nothing is half-committed. */
|
|
72
|
+
export class HistoryError extends Error {
|
|
73
|
+
code;
|
|
74
|
+
constructor(code, message = code, options) {
|
|
75
|
+
super(message, options);
|
|
76
|
+
this.code = code;
|
|
77
|
+
this.name = 'HistoryError';
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
const invalid = (message) => new HistoryError('invalid', message);
|
|
81
|
+
/** Re-throw a failure of one of the composed stores as its typed
|
|
82
|
+
* HistoryError, leaving HistoryErrors and unknown throws untouched. */
|
|
83
|
+
const rethrow = (e) => {
|
|
84
|
+
if (e instanceof HistoryError)
|
|
85
|
+
throw e;
|
|
86
|
+
if (e instanceof TransportError)
|
|
87
|
+
throw new HistoryError('transport', `transport failure: ${e.message}`, { cause: e });
|
|
88
|
+
if (e instanceof InboxError)
|
|
89
|
+
throw new HistoryError('inbox', `inbox failure: ${e.message}`, { cause: e });
|
|
90
|
+
if (e instanceof ReplayError)
|
|
91
|
+
throw new HistoryError('replay', `replay failure: ${e.message}`, { cause: e });
|
|
92
|
+
if (e instanceof CoverageError)
|
|
93
|
+
throw new HistoryError('coverage', `coverage failure: ${e.message}`, { cause: e });
|
|
94
|
+
if (e instanceof PolicyError)
|
|
95
|
+
throw new HistoryError('policy', `policy failure: ${e.message}`, { cause: e });
|
|
96
|
+
if (e instanceof StoreError)
|
|
97
|
+
throw new HistoryError('store', `store failure: ${e.message}`, { cause: e });
|
|
98
|
+
throw e;
|
|
99
|
+
};
|
|
100
|
+
const HISTORY_SPACE = 'rsync_history';
|
|
101
|
+
const PREFIX_RECORD_VERSION = 1;
|
|
102
|
+
const PREFIX_KEY_TAG = 0x01;
|
|
103
|
+
const utf8 = new TextEncoder();
|
|
104
|
+
const utf8d = new TextDecoder('utf-8', { fatal: true });
|
|
105
|
+
/** The receipt cursor of one batch (opaque to the Inbox):
|
|
106
|
+
* `0x03 || blake3(batch)[32]`. Content addressing makes every exact
|
|
107
|
+
* re-receipt an Inbox duplicate by construction, independent of page
|
|
108
|
+
* geometry, walk depth, or a moved tail. */
|
|
109
|
+
function receiptCursor(batch) {
|
|
110
|
+
const out = new Uint8Array(33);
|
|
111
|
+
out[0] = 0x03;
|
|
112
|
+
out.set(blake3(batch), 1);
|
|
113
|
+
return out;
|
|
114
|
+
}
|
|
115
|
+
const hex = (bytes) => Array.from(bytes, b => b.toString(16).padStart(2, '0')).join('');
|
|
116
|
+
const unhex = (text) => {
|
|
117
|
+
if (text.length % 2 !== 0)
|
|
118
|
+
throw invalid('prefix fragment hex');
|
|
119
|
+
const out = new Uint8Array(text.length / 2);
|
|
120
|
+
for (let i = 0; i < out.length; i++) {
|
|
121
|
+
const n = Number.parseInt(text.slice(i * 2, i * 2 + 2), 16);
|
|
122
|
+
if (!Number.isFinite(n))
|
|
123
|
+
throw invalid('prefix fragment hex');
|
|
124
|
+
out[i] = n;
|
|
125
|
+
}
|
|
126
|
+
return out;
|
|
127
|
+
};
|
|
128
|
+
const uuidString = (id) => {
|
|
129
|
+
const h = hex(id);
|
|
130
|
+
return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
|
|
131
|
+
};
|
|
132
|
+
const parseUuid = (id) => unhex(id.replace(/-/g, ''));
|
|
133
|
+
/** Push a turn id onto a report list at most once (Uint8Array identity is
|
|
134
|
+
* by content, not reference). */
|
|
135
|
+
function pushUnique(list, seen, id) {
|
|
136
|
+
const key = hex(id);
|
|
137
|
+
if (!seen.has(key)) {
|
|
138
|
+
seen.add(key);
|
|
139
|
+
list.push(id);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
/** The on-demand reverse-history reader for one (stream,
|
|
143
|
+
* remote-generation) scope. Opened over the device's single storage owner;
|
|
144
|
+
* the ledger namespace embeds the scope's full generation identity, so a
|
|
145
|
+
* rebound generation starts a fresh ledger while the old one stays
|
|
146
|
+
* retained. */
|
|
147
|
+
export class HistoryReader {
|
|
148
|
+
scope;
|
|
149
|
+
stream;
|
|
150
|
+
inbox;
|
|
151
|
+
replay;
|
|
152
|
+
coverage;
|
|
153
|
+
policy;
|
|
154
|
+
maxBatchBytes;
|
|
155
|
+
partial;
|
|
156
|
+
storage;
|
|
157
|
+
#crypto;
|
|
158
|
+
constructor(scope, stream, inbox, replay, coverage, policy, maxBatchBytes,
|
|
159
|
+
/** The intake is the partial-replica path (N3). Coverage marks use
|
|
160
|
+
* the exact local frames and bind a declared parent only where that
|
|
161
|
+
* parent's seal frame is local (N017 P1-C). A window turn whose
|
|
162
|
+
* parent sits below the window is still applied, but carries no
|
|
163
|
+
* mark — writing one without its parent edge would fabricate
|
|
164
|
+
* closure. */
|
|
165
|
+
partial, storage) {
|
|
166
|
+
this.scope = scope;
|
|
167
|
+
this.stream = stream;
|
|
168
|
+
this.inbox = inbox;
|
|
169
|
+
this.replay = replay;
|
|
170
|
+
this.coverage = coverage;
|
|
171
|
+
this.policy = policy;
|
|
172
|
+
this.maxBatchBytes = maxBatchBytes;
|
|
173
|
+
this.partial = partial;
|
|
174
|
+
this.storage = storage;
|
|
175
|
+
}
|
|
176
|
+
/** Open the reader for one (stream, remote-generation) scope (the scope
|
|
177
|
+
* comes from `Executor.scope`). Reuses the link's wire-derived ledger
|
|
178
|
+
* limits; `limits.inbox.maxBatchBytes` also bounds the
|
|
179
|
+
* boundary-discovery buffer (a missing chain past it is typed
|
|
180
|
+
* corruption). */
|
|
181
|
+
static open(storage, stream, scope, limits) {
|
|
182
|
+
let fragment;
|
|
183
|
+
try {
|
|
184
|
+
fragment = generationKeyFragment(scope.generation);
|
|
185
|
+
}
|
|
186
|
+
catch (e) {
|
|
187
|
+
throw invalid(`generation key: ${e instanceof Error ? e.message : e}`);
|
|
188
|
+
}
|
|
189
|
+
const source = `history:${hex(scope.remote)}/gen:${hex(fragment)}`;
|
|
190
|
+
const inbox = Inbox.open(storage, scope.stream, source, limits.inbox);
|
|
191
|
+
const replay = DurableReplay.open(inbox, stream, limits.replay);
|
|
192
|
+
return new HistoryReader(scope, stream, inbox, replay, new CoverageStore(storage), new PolicyStore(storage), limits.inbox.maxBatchBytes, false, storage);
|
|
193
|
+
}
|
|
194
|
+
/** The partial-replica intake (N3): receipts import through the
|
|
195
|
+
* partial path — parents are declared references and seals verify
|
|
196
|
+
* this turn only, so a reverse-history window becomes displayable
|
|
197
|
+
* `selfVerified` content (with honest `notRetrieved` parent markers
|
|
198
|
+
* below the window) instead of pending forever. */
|
|
199
|
+
static openPartial(storage, stream, scope, limits) {
|
|
200
|
+
let fragment;
|
|
201
|
+
try {
|
|
202
|
+
fragment = generationKeyFragment(scope.generation);
|
|
203
|
+
}
|
|
204
|
+
catch (e) {
|
|
205
|
+
throw invalid(`generation key: ${e instanceof Error ? e.message : e}`);
|
|
206
|
+
}
|
|
207
|
+
const source = `history:${hex(scope.remote)}/gen:${hex(fragment)}`;
|
|
208
|
+
const inbox = Inbox.open(storage, scope.stream, source, limits.inbox);
|
|
209
|
+
const replay = DurableReplay.openPartial(inbox, stream, limits.replay);
|
|
210
|
+
return new HistoryReader(scope, stream, inbox, replay, new CoverageStore(storage), new PolicyStore(storage), limits.inbox.maxBatchBytes, true, storage);
|
|
211
|
+
}
|
|
212
|
+
/** Decrypt complete stream messages with the same host crypto the
|
|
213
|
+
* upload path used. Never called inside a database transaction. */
|
|
214
|
+
withCrypto(crypto) {
|
|
215
|
+
this.#crypto = crypto;
|
|
216
|
+
return this;
|
|
217
|
+
}
|
|
218
|
+
/** Drain the replay runner to idle, marking coverage from every receipt
|
|
219
|
+
* it imports (the same shared store-derived marking as the live link). */
|
|
220
|
+
async #replayDrain(report, appliedSeen, pendingSeen) {
|
|
221
|
+
const source = intakeSource(this.scope, 'history');
|
|
222
|
+
for (;;) {
|
|
223
|
+
const next = await this.coverage.processedReports(this.scope, source);
|
|
224
|
+
const record = (await this.replay.records(next === 0n ? null : next - 1n, 1))[0];
|
|
225
|
+
if (record) {
|
|
226
|
+
const receipt = await replayReceipt(this.inbox, record.sequence);
|
|
227
|
+
await recordServedBatch(receipt.bytes, this.coverage, this.scope);
|
|
228
|
+
if (record.outcome.kind === 'imported') {
|
|
229
|
+
const mark = this.partial ? markAdmittedFromBatchLocalParents : markAdmittedFromBatch;
|
|
230
|
+
await mark(this.stream, this.coverage, this.scope, receipt.bytes, record.outcome.report.statuses, record.outcome.report.applied, report.appliedTurns, appliedSeen, report.pendingTurns, pendingSeen);
|
|
231
|
+
}
|
|
232
|
+
await this.coverage.finishReport(this.scope, source, record.sequence);
|
|
233
|
+
continue;
|
|
234
|
+
}
|
|
235
|
+
await recordNextServed(this.inbox, this.replay, this.coverage, this.scope);
|
|
236
|
+
const step = await this.replay.step();
|
|
237
|
+
if (step.kind === 'idle')
|
|
238
|
+
return;
|
|
239
|
+
if (step.kind === 'raced')
|
|
240
|
+
throw invalid('a second replay runner checkpointed first');
|
|
241
|
+
if (step.kind === 'retry')
|
|
242
|
+
throw new HistoryError('retryQuota', 'pending quota exceeded; a receipt remains unprocessed until the host resolves dependencies or capacity and retries');
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
/** Fetch the latest window of the remote's log: page backward from the
|
|
246
|
+
* tail until `budgetBytes` have been fetched this cycle, the log's
|
|
247
|
+
* start, or the stop token. A Turn that appears in that byte window
|
|
248
|
+
* but is missing Create or a contiguous seq prefix (the window cut
|
|
249
|
+
* through Edit/Seal) may keep paging for at most one more
|
|
250
|
+
* `pageLimitBytes` response — and only messages of those window turns
|
|
251
|
+
* are collected.
|
|
252
|
+
* Intervening turns are not imported; if the prefix is still
|
|
253
|
+
* incomplete the turn stays pending. Then receive the collected
|
|
254
|
+
* batches oldest-first, skipping any the ledger already holds by
|
|
255
|
+
* content hash.
|
|
256
|
+
* `pageLimitBytes` is the hard per-response cap of every provider call.
|
|
257
|
+
* Network, receipt persistence, import and coverage marks are atomic
|
|
258
|
+
* per batch; the walk's buffer is never persisted (a crash re-walks:
|
|
259
|
+
* the fetch cost is visible in `bytesFetched`, the ledger absorbs every
|
|
260
|
+
* re-receipt). */
|
|
261
|
+
async fetchWindow(source, budgetBytes, pageLimitBytes, stop) {
|
|
262
|
+
try {
|
|
263
|
+
return await this.#fetchWindow(source, budgetBytes, pageLimitBytes, stop);
|
|
264
|
+
}
|
|
265
|
+
catch (e) {
|
|
266
|
+
return rethrow(e);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
async #fetchWindow(source, budgetBytes, pageLimitBytes, stop) {
|
|
270
|
+
if (!await this.policy.allowsDownload(this.scope))
|
|
271
|
+
throw new HistoryError('policyDenied', 'mirror policy denies download for this scope');
|
|
272
|
+
if (pageLimitBytes === 0 || budgetBytes === 0)
|
|
273
|
+
throw invalid('page limit and budget must be positive');
|
|
274
|
+
const report = {
|
|
275
|
+
pages: 0, batches: 0, bytesFetched: 0, fetchedRange: undefined,
|
|
276
|
+
appliedTurns: [], pendingTurns: [], reachedStart: false, stopped: false,
|
|
277
|
+
};
|
|
278
|
+
const appliedSeen = new Set(), pendingSeen = new Set();
|
|
279
|
+
// A crash between a committed receipt and its replay left durable
|
|
280
|
+
// work behind: drain before any new fetch (idle when caught up).
|
|
281
|
+
await this.#replayDrain(report, appliedSeen, pendingSeen);
|
|
282
|
+
// Phase 1: the walk. Collect COMPLETE messages (newest pages
|
|
283
|
+
// first, oldest prepended), reassembling fragments across pages
|
|
284
|
+
// from the provider's verified spans; a fragment is transport
|
|
285
|
+
// state, never received.
|
|
286
|
+
let collected = [];
|
|
287
|
+
// The in-flight partial message: id, total length, the assembled
|
|
288
|
+
// bytes so far, and the message offset the NEXT (older) fragment
|
|
289
|
+
// must end at.
|
|
290
|
+
let partial;
|
|
291
|
+
let from;
|
|
292
|
+
let tail;
|
|
293
|
+
let oldestBoundary;
|
|
294
|
+
// Turns that appeared in the budget-bounded window. After the
|
|
295
|
+
// budget is spent, we may page at most another `pageLimitBytes`
|
|
296
|
+
// looking for those turns' missing prefix — not the rest of the
|
|
297
|
+
// log — and only keep messages of those turns.
|
|
298
|
+
let windowTurns;
|
|
299
|
+
let extraFetched = 0;
|
|
300
|
+
for (;;) {
|
|
301
|
+
const overBudget = report.bytesFetched >= budgetBytes;
|
|
302
|
+
if (overBudget) {
|
|
303
|
+
// Drop an in-flight fragment once the budget window's turns
|
|
304
|
+
// are displayable, or once the extra scan bound is spent.
|
|
305
|
+
// Include still-pending prefix jobs before extra paging so
|
|
306
|
+
// a later window cannot walk past their Create uncollected.
|
|
307
|
+
if (windowTurns === undefined) {
|
|
308
|
+
windowTurns = await turnsInWindow(this.#crypto, collected);
|
|
309
|
+
await this.#includePriorWanted(windowTurns);
|
|
310
|
+
}
|
|
311
|
+
if (windowTurns.size === 0 || await prefixesComplete(this.#crypto, collected, windowTurns)
|
|
312
|
+
|| extraFetched >= pageLimitBytes)
|
|
313
|
+
break;
|
|
314
|
+
}
|
|
315
|
+
if (stop.stopped) {
|
|
316
|
+
report.stopped = true;
|
|
317
|
+
break;
|
|
318
|
+
}
|
|
319
|
+
// Network outside every transaction; every response is
|
|
320
|
+
// hard-capped at pageLimitBytes by the provider contract.
|
|
321
|
+
// Completing a truncated Turn uses the same per-page cap and
|
|
322
|
+
// is also bounded by the leftover extra-scan budget.
|
|
323
|
+
const limit = overBudget
|
|
324
|
+
? Math.min(pageLimitBytes, pageLimitBytes - extraFetched)
|
|
325
|
+
: Math.min(pageLimitBytes, budgetBytes - report.bytesFetched);
|
|
326
|
+
const page = await source.readBackward(from, limit);
|
|
327
|
+
if (page.payload.length > limit)
|
|
328
|
+
throw invalid(`provider exceeded the page hard cap: ${page.payload.length} > ${limit}`);
|
|
329
|
+
if (from !== undefined && page.endOffset !== from)
|
|
330
|
+
throw invalid('provider page does not chain to the requested offset');
|
|
331
|
+
// Verify the span list tiles the payload exactly, oldest first.
|
|
332
|
+
let cursor = 0;
|
|
333
|
+
for (const span of page.messages) {
|
|
334
|
+
if (!Number.isSafeInteger(span.relStart) || !Number.isSafeInteger(span.relEnd)
|
|
335
|
+
|| !Number.isSafeInteger(span.messageLen) || !Number.isSafeInteger(span.msgOffset)
|
|
336
|
+
|| span.relStart < 0 || span.relEnd < span.relStart || span.messageLen < 0 || span.msgOffset < 0)
|
|
337
|
+
throw invalid('provider message span is not a safe non-negative integer');
|
|
338
|
+
if (span.relStart !== cursor || span.relEnd > page.payload.length)
|
|
339
|
+
throw invalid('provider message spans do not tile the page payload');
|
|
340
|
+
cursor = span.relEnd;
|
|
341
|
+
const fragLen = span.relEnd - span.relStart;
|
|
342
|
+
if (fragLen === 0 || fragLen > span.messageLen)
|
|
343
|
+
throw invalid('provider message span exceeds its message length');
|
|
344
|
+
if (span.msgOffset > span.messageLen || fragLen > span.messageLen - span.msgOffset)
|
|
345
|
+
throw invalid('provider message fragment overruns the message');
|
|
346
|
+
}
|
|
347
|
+
if (cursor !== page.payload.length)
|
|
348
|
+
throw invalid('provider message spans do not cover the page payload');
|
|
349
|
+
report.pages++;
|
|
350
|
+
report.bytesFetched += page.payload.length;
|
|
351
|
+
if (overBudget)
|
|
352
|
+
extraFetched += page.payload.length;
|
|
353
|
+
tail ??= page.endOffset;
|
|
354
|
+
// Consume spans newest-first: complete-in-page messages
|
|
355
|
+
// collect directly, fragments extend the in-flight partial.
|
|
356
|
+
for (let spanIndex = page.messages.length - 1; spanIndex >= 0; spanIndex--) {
|
|
357
|
+
const span = page.messages[spanIndex];
|
|
358
|
+
const frag = page.payload.subarray(span.relStart, span.relEnd);
|
|
359
|
+
const fragLen = frag.length;
|
|
360
|
+
if (span.msgOffset === 0 && fragLen === span.messageLen) {
|
|
361
|
+
// A complete message in one page. An unrelated NEWER
|
|
362
|
+
// message's partial may legitimately be open (its
|
|
363
|
+
// older fragments arrive in older pages).
|
|
364
|
+
await keepAssembled(this.#crypto, windowTurns, collected, (start) => { oldestBoundary = start; }, span.messageStart, Uint8Array.from(frag));
|
|
365
|
+
continue;
|
|
366
|
+
}
|
|
367
|
+
if (partial === undefined) {
|
|
368
|
+
// The message's END fragment must be its last bytes
|
|
369
|
+
// (fragLen <= messageLen is already enforced, so the
|
|
370
|
+
// subtraction cannot go negative).
|
|
371
|
+
if (span.msgOffset !== span.messageLen - fragLen)
|
|
372
|
+
throw invalid('provider fragment is not contiguous with the message end');
|
|
373
|
+
partial = { id: span.messageStart, len: span.messageLen, bytes: Uint8Array.from(frag), nextOffset: span.msgOffset };
|
|
374
|
+
}
|
|
375
|
+
else {
|
|
376
|
+
if (partial.id !== span.messageStart || partial.len !== span.messageLen
|
|
377
|
+
|| fragLen > partial.nextOffset
|
|
378
|
+
|| span.msgOffset !== partial.nextOffset - fragLen)
|
|
379
|
+
throw invalid('provider message fragments are not contiguous');
|
|
380
|
+
// Fragments arrive newest-first: PREPEND this (older)
|
|
381
|
+
// fragment so the bytes stay in log order.
|
|
382
|
+
const assembled = new Uint8Array(partial.bytes.length + frag.length);
|
|
383
|
+
assembled.set(frag, 0);
|
|
384
|
+
assembled.set(partial.bytes, frag.length);
|
|
385
|
+
partial.bytes = assembled;
|
|
386
|
+
partial.nextOffset = span.msgOffset;
|
|
387
|
+
if (partial.nextOffset === 0) {
|
|
388
|
+
if (partial.bytes.length !== partial.len)
|
|
389
|
+
throw invalid('reassembled message length mismatch');
|
|
390
|
+
await keepAssembled(this.#crypto, windowTurns, collected, (start) => { oldestBoundary = start; }, partial.id, partial.bytes);
|
|
391
|
+
partial = undefined;
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
if (page.reachedStart) {
|
|
396
|
+
if (partial !== undefined)
|
|
397
|
+
throw invalid('the log starts mid-message: provider boundaries contradict the bytes');
|
|
398
|
+
report.reachedStart = true;
|
|
399
|
+
break;
|
|
400
|
+
}
|
|
401
|
+
if (page.prevOffset === page.endOffset && page.payload.length === 0)
|
|
402
|
+
throw invalid('backward page made no progress');
|
|
403
|
+
from = page.prevOffset;
|
|
404
|
+
}
|
|
405
|
+
// A partial left at the walk's edge is transport state: not
|
|
406
|
+
// received, not reported as held.
|
|
407
|
+
if (tail !== undefined)
|
|
408
|
+
report.fetchedRange = oldestBoundary === undefined ? undefined : [oldestBoundary, tail];
|
|
409
|
+
// Phase 2: receive the collected batches oldest-first, skipping
|
|
410
|
+
// anything the ledger already holds (content-addressed dedupe), and
|
|
411
|
+
// replay every new receipt before the next.
|
|
412
|
+
let priorCursor = (await this.inbox.state()).cursor;
|
|
413
|
+
let imported = 0;
|
|
414
|
+
for (let collectedIndex = collected.length - 1; collectedIndex >= 0; collectedIndex--) {
|
|
415
|
+
const raw = collected[collectedIndex];
|
|
416
|
+
if (stop.stopped) {
|
|
417
|
+
report.stopped = true;
|
|
418
|
+
break;
|
|
419
|
+
}
|
|
420
|
+
let batch = raw;
|
|
421
|
+
if (this.#crypto !== undefined) {
|
|
422
|
+
try {
|
|
423
|
+
batch = await openEnvelopeAsync(this.#crypto, raw);
|
|
424
|
+
}
|
|
425
|
+
catch (e) {
|
|
426
|
+
throw new HistoryError('invalid', e instanceof Error ? e.message : String(e), { cause: e });
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
const cursor = receiptCursor(batch);
|
|
430
|
+
if (await this.inbox.containsCursor(cursor)) {
|
|
431
|
+
imported++;
|
|
432
|
+
continue;
|
|
433
|
+
}
|
|
434
|
+
const receipt = await this.inbox.receive(priorCursor, cursor, batch);
|
|
435
|
+
if (receipt.kind === 'received')
|
|
436
|
+
report.batches++;
|
|
437
|
+
priorCursor = cursor;
|
|
438
|
+
await this.#replayDrain(report, appliedSeen, pendingSeen);
|
|
439
|
+
imported++;
|
|
440
|
+
}
|
|
441
|
+
await this.#persistPrefixScan(from, windowTurns, partial, imported === collected.length);
|
|
442
|
+
return report;
|
|
443
|
+
}
|
|
444
|
+
/** The durable reverse-scan position for incomplete window-turn prefixes. */
|
|
445
|
+
async prefixScan() {
|
|
446
|
+
return await this.#loadPrefixScan();
|
|
447
|
+
}
|
|
448
|
+
/** Resume the reverse scan for pending window-turn prefixes. Each call
|
|
449
|
+
* fetches at most `budgetBytes` and keeps only messages of those
|
|
450
|
+
* pending turns. Sequential providers still deliver intervening bytes;
|
|
451
|
+
* recovering a Create G bytes behind the window takes about G bytes
|
|
452
|
+
* across calls. Does not re-read the tail window. */
|
|
453
|
+
async completePrefixes(source, budgetBytes, pageLimitBytes, stop) {
|
|
454
|
+
try {
|
|
455
|
+
return await this.#completePrefixes(source, budgetBytes, pageLimitBytes, stop);
|
|
456
|
+
}
|
|
457
|
+
catch (e) {
|
|
458
|
+
return rethrow(e);
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
async #completePrefixes(source, budgetBytes, pageLimitBytes, stop) {
|
|
462
|
+
if (!await this.policy.allowsDownload(this.scope))
|
|
463
|
+
throw new HistoryError('policyDenied', 'mirror policy denies download for this scope');
|
|
464
|
+
if (pageLimitBytes === 0 || budgetBytes === 0)
|
|
465
|
+
throw invalid('page limit and budget must be positive');
|
|
466
|
+
const scan = await this.#loadPrefixScan();
|
|
467
|
+
if (scan === undefined)
|
|
468
|
+
return { pages: 0, batches: 0, bytesFetched: 0, fetchedRange: undefined, appliedTurns: [], pendingTurns: [], reachedStart: false, stopped: false };
|
|
469
|
+
const wanted = new Set(scan.wanted.map(hex));
|
|
470
|
+
if (wanted.size === 0) {
|
|
471
|
+
await this.#clearPrefixScan();
|
|
472
|
+
return { pages: 0, batches: 0, bytesFetched: 0, fetchedRange: undefined, appliedTurns: [], pendingTurns: [], reachedStart: false, stopped: false };
|
|
473
|
+
}
|
|
474
|
+
const report = {
|
|
475
|
+
pages: 0, batches: 0, bytesFetched: 0, fetchedRange: undefined,
|
|
476
|
+
appliedTurns: [], pendingTurns: [], reachedStart: false, stopped: false,
|
|
477
|
+
};
|
|
478
|
+
const appliedSeen = new Set(), pendingSeen = new Set();
|
|
479
|
+
await this.#replayDrain(report, appliedSeen, pendingSeen);
|
|
480
|
+
const collected = [];
|
|
481
|
+
let partial = scan.partial;
|
|
482
|
+
let from = scan.from;
|
|
483
|
+
let tail;
|
|
484
|
+
let oldestBoundary;
|
|
485
|
+
const windowTurns = wanted;
|
|
486
|
+
for (;;) {
|
|
487
|
+
if (report.bytesFetched >= budgetBytes)
|
|
488
|
+
break;
|
|
489
|
+
if (await prefixesComplete(this.#crypto, collected, windowTurns))
|
|
490
|
+
break;
|
|
491
|
+
if (stop.stopped) {
|
|
492
|
+
report.stopped = true;
|
|
493
|
+
break;
|
|
494
|
+
}
|
|
495
|
+
const limit = Math.min(pageLimitBytes, budgetBytes - report.bytesFetched);
|
|
496
|
+
const page = await source.readBackward(from, limit);
|
|
497
|
+
if (page.payload.length > limit)
|
|
498
|
+
throw invalid(`provider exceeded the page hard cap: ${page.payload.length} > ${limit}`);
|
|
499
|
+
if (from !== undefined && page.endOffset !== from)
|
|
500
|
+
throw invalid('provider page does not chain to the requested offset');
|
|
501
|
+
let cursor = 0;
|
|
502
|
+
for (const span of page.messages) {
|
|
503
|
+
if (!Number.isSafeInteger(span.relStart) || !Number.isSafeInteger(span.relEnd)
|
|
504
|
+
|| !Number.isSafeInteger(span.messageLen) || !Number.isSafeInteger(span.msgOffset)
|
|
505
|
+
|| span.relStart < 0 || span.relEnd < span.relStart || span.messageLen < 0 || span.msgOffset < 0)
|
|
506
|
+
throw invalid('provider message span is not a safe non-negative integer');
|
|
507
|
+
if (span.relStart !== cursor || span.relEnd > page.payload.length)
|
|
508
|
+
throw invalid('provider message spans do not tile the page payload');
|
|
509
|
+
cursor = span.relEnd;
|
|
510
|
+
const fragLen = span.relEnd - span.relStart;
|
|
511
|
+
if (fragLen === 0 || fragLen > span.messageLen)
|
|
512
|
+
throw invalid('provider message span exceeds its message length');
|
|
513
|
+
if (span.msgOffset > span.messageLen || fragLen > span.messageLen - span.msgOffset)
|
|
514
|
+
throw invalid('provider message fragment overruns the message');
|
|
515
|
+
}
|
|
516
|
+
if (cursor !== page.payload.length)
|
|
517
|
+
throw invalid('provider message spans do not cover the page payload');
|
|
518
|
+
report.pages++;
|
|
519
|
+
report.bytesFetched += page.payload.length;
|
|
520
|
+
tail ??= page.endOffset;
|
|
521
|
+
for (let spanIndex = page.messages.length - 1; spanIndex >= 0; spanIndex--) {
|
|
522
|
+
const span = page.messages[spanIndex];
|
|
523
|
+
const frag = page.payload.subarray(span.relStart, span.relEnd);
|
|
524
|
+
const fragLen = frag.length;
|
|
525
|
+
if (span.msgOffset === 0 && fragLen === span.messageLen) {
|
|
526
|
+
await keepAssembled(this.#crypto, windowTurns, collected, (start) => { oldestBoundary = start; }, span.messageStart, Uint8Array.from(frag));
|
|
527
|
+
continue;
|
|
528
|
+
}
|
|
529
|
+
if (partial === undefined) {
|
|
530
|
+
if (span.msgOffset !== span.messageLen - fragLen)
|
|
531
|
+
throw invalid('provider fragment is not contiguous with the message end');
|
|
532
|
+
partial = { id: span.messageStart, len: span.messageLen, bytes: Uint8Array.from(frag), nextOffset: span.msgOffset };
|
|
533
|
+
}
|
|
534
|
+
else {
|
|
535
|
+
if (partial.id !== span.messageStart || partial.len !== span.messageLen
|
|
536
|
+
|| fragLen > partial.nextOffset
|
|
537
|
+
|| span.msgOffset !== partial.nextOffset - fragLen)
|
|
538
|
+
throw invalid('provider message fragments are not contiguous');
|
|
539
|
+
const assembled = new Uint8Array(partial.bytes.length + frag.length);
|
|
540
|
+
assembled.set(frag, 0);
|
|
541
|
+
assembled.set(partial.bytes, frag.length);
|
|
542
|
+
partial.bytes = assembled;
|
|
543
|
+
partial.nextOffset = span.msgOffset;
|
|
544
|
+
if (partial.nextOffset === 0) {
|
|
545
|
+
if (partial.bytes.length !== partial.len)
|
|
546
|
+
throw invalid('reassembled message length mismatch');
|
|
547
|
+
await keepAssembled(this.#crypto, windowTurns, collected, (start) => { oldestBoundary = start; }, partial.id, partial.bytes);
|
|
548
|
+
partial = undefined;
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
if (page.reachedStart) {
|
|
553
|
+
if (partial !== undefined)
|
|
554
|
+
throw invalid('the log starts mid-message: provider boundaries contradict the bytes');
|
|
555
|
+
report.reachedStart = true;
|
|
556
|
+
break;
|
|
557
|
+
}
|
|
558
|
+
if (page.prevOffset === page.endOffset && page.payload.length === 0)
|
|
559
|
+
throw invalid('backward page made no progress');
|
|
560
|
+
from = page.prevOffset;
|
|
561
|
+
}
|
|
562
|
+
if (tail !== undefined)
|
|
563
|
+
report.fetchedRange = oldestBoundary === undefined ? undefined : [oldestBoundary, tail];
|
|
564
|
+
let priorCursor = (await this.inbox.state()).cursor;
|
|
565
|
+
let imported = 0;
|
|
566
|
+
for (let collectedIndex = collected.length - 1; collectedIndex >= 0; collectedIndex--) {
|
|
567
|
+
const raw = collected[collectedIndex];
|
|
568
|
+
if (stop.stopped) {
|
|
569
|
+
report.stopped = true;
|
|
570
|
+
break;
|
|
571
|
+
}
|
|
572
|
+
let batch = raw;
|
|
573
|
+
if (this.#crypto !== undefined) {
|
|
574
|
+
try {
|
|
575
|
+
batch = await openEnvelopeAsync(this.#crypto, raw);
|
|
576
|
+
}
|
|
577
|
+
catch (e) {
|
|
578
|
+
throw new HistoryError('invalid', e instanceof Error ? e.message : String(e), { cause: e });
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
const cursor = receiptCursor(batch);
|
|
582
|
+
if (await this.inbox.containsCursor(cursor)) {
|
|
583
|
+
imported++;
|
|
584
|
+
continue;
|
|
585
|
+
}
|
|
586
|
+
const receipt = await this.inbox.receive(priorCursor, cursor, batch);
|
|
587
|
+
if (receipt.kind === 'received')
|
|
588
|
+
report.batches++;
|
|
589
|
+
priorCursor = cursor;
|
|
590
|
+
await this.#replayDrain(report, appliedSeen, pendingSeen);
|
|
591
|
+
imported++;
|
|
592
|
+
}
|
|
593
|
+
await this.#persistPrefixScan(from, windowTurns, partial, imported === collected.length);
|
|
594
|
+
return report;
|
|
595
|
+
}
|
|
596
|
+
async #persistPrefixScan(from, wanted, partial, committed) {
|
|
597
|
+
if (!committed)
|
|
598
|
+
return;
|
|
599
|
+
const thisRemaining = [];
|
|
600
|
+
if (wanted !== undefined) {
|
|
601
|
+
for (const idHex of wanted) {
|
|
602
|
+
const id = unhex(idHex);
|
|
603
|
+
if (await this.#turnNeedsPrefix(id))
|
|
604
|
+
thisRemaining.push(id);
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
const prior = await this.#loadPrefixScan();
|
|
608
|
+
const priorStill = [];
|
|
609
|
+
if (prior !== undefined) {
|
|
610
|
+
for (const id of prior.wanted) {
|
|
611
|
+
if (await this.#turnNeedsPrefix(id))
|
|
612
|
+
priorStill.push(id);
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
if (thisRemaining.length === 0) {
|
|
616
|
+
if (priorStill.length === 0) {
|
|
617
|
+
await this.#clearPrefixScan();
|
|
618
|
+
return;
|
|
619
|
+
}
|
|
620
|
+
await this.#storePrefixScan({ from: prior.from, wanted: priorStill, partial: prior.partial });
|
|
621
|
+
return;
|
|
622
|
+
}
|
|
623
|
+
if (from === undefined) {
|
|
624
|
+
if (priorStill.length === 0) {
|
|
625
|
+
await this.#clearPrefixScan();
|
|
626
|
+
return;
|
|
627
|
+
}
|
|
628
|
+
await this.#storePrefixScan({ from: prior.from, wanted: priorStill, partial: prior.partial });
|
|
629
|
+
return;
|
|
630
|
+
}
|
|
631
|
+
await this.#storePrefixScan({ from, wanted: thisRemaining, partial });
|
|
632
|
+
}
|
|
633
|
+
async #includePriorWanted(wanted) {
|
|
634
|
+
const prior = await this.#loadPrefixScan();
|
|
635
|
+
if (prior === undefined)
|
|
636
|
+
return;
|
|
637
|
+
for (const id of prior.wanted) {
|
|
638
|
+
if (await this.#turnNeedsPrefix(id))
|
|
639
|
+
wanted.add(hex(id));
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
async #turnNeedsPrefix(id) {
|
|
643
|
+
const header = await this.stream.readTurnHeader(id);
|
|
644
|
+
return header.kind === 'incomplete';
|
|
645
|
+
}
|
|
646
|
+
#prefixKey() {
|
|
647
|
+
if (this.scope.stream.length === 0)
|
|
648
|
+
throw invalid('empty stream');
|
|
649
|
+
const stream = utf8.encode(this.scope.stream);
|
|
650
|
+
const fragment = generationKeyFragment(this.scope.generation);
|
|
651
|
+
const key = new Uint8Array(1 + 16 + fragment.length + 4 + stream.length);
|
|
652
|
+
const view = new DataView(key.buffer);
|
|
653
|
+
key[0] = PREFIX_KEY_TAG;
|
|
654
|
+
key.set(this.scope.remote, 1);
|
|
655
|
+
key.set(fragment, 17);
|
|
656
|
+
view.setUint32(17 + fragment.length, stream.length, false);
|
|
657
|
+
key.set(stream, 21 + fragment.length);
|
|
658
|
+
return key;
|
|
659
|
+
}
|
|
660
|
+
async #loadPrefixScan() {
|
|
661
|
+
const key = this.#prefixKey();
|
|
662
|
+
const raw = await this.storage.transact(false, function* (tx) {
|
|
663
|
+
return yield* tx.get(HISTORY_SPACE, key);
|
|
664
|
+
});
|
|
665
|
+
if (raw === undefined)
|
|
666
|
+
return undefined;
|
|
667
|
+
if (raw.length === 0)
|
|
668
|
+
throw invalid('empty prefix-scan record');
|
|
669
|
+
if (raw[0] !== PREFIX_RECORD_VERSION)
|
|
670
|
+
throw invalid(`unsupported prefix-scan version ${raw[0]}`);
|
|
671
|
+
const dto = JSON.parse(utf8d.decode(raw.subarray(1)));
|
|
672
|
+
if (dto.v !== PREFIX_RECORD_VERSION)
|
|
673
|
+
throw invalid(`unsupported prefix-scan version ${dto.v}`);
|
|
674
|
+
if (typeof dto.from !== 'string' || !Array.isArray(dto.wanted))
|
|
675
|
+
throw invalid('prefix-scan JSON');
|
|
676
|
+
const wanted = dto.wanted.map((id) => {
|
|
677
|
+
if (typeof id !== 'string')
|
|
678
|
+
throw invalid('prefix-scan turn id');
|
|
679
|
+
return parseUuid(id);
|
|
680
|
+
});
|
|
681
|
+
const partial = dto.partial === undefined ? undefined : {
|
|
682
|
+
id: dto.partial.id,
|
|
683
|
+
len: dto.partial.len,
|
|
684
|
+
bytes: unhex(dto.partial.bytes),
|
|
685
|
+
nextOffset: dto.partial.next_offset,
|
|
686
|
+
};
|
|
687
|
+
return { from: dto.from, wanted, partial };
|
|
688
|
+
}
|
|
689
|
+
async #storePrefixScan(scan) {
|
|
690
|
+
const key = this.#prefixKey();
|
|
691
|
+
const wantedJson = scan.wanted.map(id => JSON.stringify(uuidString(id))).join(',');
|
|
692
|
+
let json = `{"v":1,"from":${JSON.stringify(scan.from)},"wanted":[${wantedJson}]`;
|
|
693
|
+
if (scan.partial !== undefined)
|
|
694
|
+
json += `,"partial":{"id":${JSON.stringify(scan.partial.id)},"len":${scan.partial.len},"bytes":${JSON.stringify(hex(scan.partial.bytes))},"next_offset":${scan.partial.nextOffset}}`;
|
|
695
|
+
json += '}';
|
|
696
|
+
const payload = utf8.encode(json);
|
|
697
|
+
const bytes = new Uint8Array(1 + payload.length);
|
|
698
|
+
bytes[0] = PREFIX_RECORD_VERSION;
|
|
699
|
+
bytes.set(payload, 1);
|
|
700
|
+
await this.storage.transact(true, function* (tx) {
|
|
701
|
+
yield* tx.put(HISTORY_SPACE, key, bytes);
|
|
702
|
+
});
|
|
703
|
+
}
|
|
704
|
+
async #clearPrefixScan() {
|
|
705
|
+
const key = this.#prefixKey();
|
|
706
|
+
await this.storage.transact(true, function* (tx) {
|
|
707
|
+
yield* tx.delete(HISTORY_SPACE, key);
|
|
708
|
+
});
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
async function keepAssembled(crypto, wanted, collected, setOldest, messageStart, wire) {
|
|
712
|
+
if (wanted !== undefined && !(await belongsToWanted(crypto, wire, wanted)))
|
|
713
|
+
return;
|
|
714
|
+
// The walk visits newest messages first. Append cheaply and reverse once
|
|
715
|
+
// at receive time instead of shifting every previously collected entry.
|
|
716
|
+
collected.push(wire);
|
|
717
|
+
setOldest(messageStart);
|
|
718
|
+
}
|
|
719
|
+
async function belongsToWanted(crypto, wire, wanted) {
|
|
720
|
+
const ops = await decodedOps(crypto, wire);
|
|
721
|
+
return ops !== undefined && ops.some(u => wanted.has(hex(u.turnId)));
|
|
722
|
+
}
|
|
723
|
+
async function decodedOps(crypto, wire) {
|
|
724
|
+
let plain = wire;
|
|
725
|
+
if (crypto !== undefined) {
|
|
726
|
+
try {
|
|
727
|
+
plain = await openEnvelopeAsync(crypto, wire);
|
|
728
|
+
}
|
|
729
|
+
catch (e) {
|
|
730
|
+
throw new HistoryError('invalid', e instanceof Error ? e.message : String(e), { cause: e });
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
try {
|
|
734
|
+
return decodeBatch(plain);
|
|
735
|
+
}
|
|
736
|
+
catch {
|
|
737
|
+
return undefined;
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
async function turnsInWindow(crypto, collected) {
|
|
741
|
+
const ids = new Set();
|
|
742
|
+
for (const batch of collected) {
|
|
743
|
+
const ops = await decodedOps(crypto, batch);
|
|
744
|
+
if (ops === undefined)
|
|
745
|
+
continue;
|
|
746
|
+
for (const update of ops)
|
|
747
|
+
ids.add(hex(update.turnId));
|
|
748
|
+
}
|
|
749
|
+
return ids;
|
|
750
|
+
}
|
|
751
|
+
async function prefixesComplete(crypto, collected, wanted) {
|
|
752
|
+
if (wanted.size === 0)
|
|
753
|
+
return true;
|
|
754
|
+
const seqs = new Map();
|
|
755
|
+
for (const batch of collected) {
|
|
756
|
+
const ops = await decodedOps(crypto, batch);
|
|
757
|
+
if (ops === undefined)
|
|
758
|
+
continue;
|
|
759
|
+
for (const update of ops) {
|
|
760
|
+
const id = hex(update.turnId);
|
|
761
|
+
if (!wanted.has(id))
|
|
762
|
+
continue;
|
|
763
|
+
let seen = seqs.get(id);
|
|
764
|
+
if (seen === undefined) {
|
|
765
|
+
seen = new Set();
|
|
766
|
+
seqs.set(id, seen);
|
|
767
|
+
}
|
|
768
|
+
seen.add(update.seq);
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
for (const id of wanted) {
|
|
772
|
+
const seen = seqs.get(id);
|
|
773
|
+
if (seen === undefined || seen.size === 0)
|
|
774
|
+
return false;
|
|
775
|
+
let max = 0n;
|
|
776
|
+
for (const seq of seen)
|
|
777
|
+
if (seq > max)
|
|
778
|
+
max = seq;
|
|
779
|
+
// Sequence values are unique in the set. A contiguous prefix from
|
|
780
|
+
// zero therefore has exactly `max + 1` entries; avoid iterating up to
|
|
781
|
+
// an attacker-controlled sequence number.
|
|
782
|
+
if (BigInt(seen.size) !== max + 1n)
|
|
783
|
+
return false;
|
|
784
|
+
}
|
|
785
|
+
return true;
|
|
786
|
+
}
|