@loro-dev/roost 0.3.0 → 0.3.2
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 +36 -11
- package/dist/lody-history.d.ts +65 -0
- package/dist/lody-history.js +425 -55
- package/dist/sync/history.d.ts +16 -51
- package/dist/sync/history.js +96 -172
- package/dist/sync/index.d.ts +1 -1
- package/dist/sync/mod.d.ts +1 -1
- package/dist/sync/transport.d.ts +1 -4
- package/dist/sync/transport.js +15 -25
- package/node/client.d.mts +8 -2
- package/node/client.mjs +23 -2
- package/package.json +6 -6
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
|
package/dist/sync/history.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { DEFAULT_BACKWARD_MAX_MESSAGE_BYTES } from '@loro-dev/streams-client';
|
|
1
2
|
import { blake3 } from '@noble/hashes/blake3.js';
|
|
2
3
|
import { decodeBatch } from '../codec.js';
|
|
3
4
|
import { Inbox, InboxError } from '../inbox.js';
|
|
@@ -19,23 +20,11 @@ import { generationKeyFragment } from './registry.js';
|
|
|
19
20
|
*
|
|
20
21
|
* `BackwardByteSource` is an injectable, pure-byte primitive: return the
|
|
21
22
|
* ≤`limitBytes` immediately before an opaque offset (or before the tail).
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
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.
|
|
23
|
+
* Each response stays within the byte limit and provides frame boundaries
|
|
24
|
+
* and continuation flags. Offsets are opaque to the history reader.
|
|
25
|
+
* A walk chains page cursors and only admits a message after all of its
|
|
26
|
+
* contiguous frames have arrived. The Streams message limit bounds wire
|
|
27
|
+
* reassembly, while Inbox limits apply to the decoded batch.
|
|
39
28
|
*
|
|
40
29
|
* # Intake model: collect during the walk, receive forward at its end
|
|
41
30
|
*
|
|
@@ -98,7 +87,57 @@ const rethrow = (e) => {
|
|
|
98
87
|
throw e;
|
|
99
88
|
};
|
|
100
89
|
const HISTORY_SPACE = 'rsync_history';
|
|
101
|
-
const PREFIX_RECORD_VERSION =
|
|
90
|
+
const PREFIX_RECORD_VERSION = 2;
|
|
91
|
+
function messageBytes(message) {
|
|
92
|
+
if (message.fragments.length === 1)
|
|
93
|
+
return message.fragments[0];
|
|
94
|
+
const bytes = new Uint8Array(message.byteLength);
|
|
95
|
+
let offset = 0;
|
|
96
|
+
for (let i = message.fragments.length - 1; i >= 0; i--) {
|
|
97
|
+
const fragment = message.fragments[i];
|
|
98
|
+
bytes.set(fragment, offset);
|
|
99
|
+
offset += fragment.length;
|
|
100
|
+
}
|
|
101
|
+
return bytes;
|
|
102
|
+
}
|
|
103
|
+
async function collectBackwardPage(page, from, limit, partial, onMessage) {
|
|
104
|
+
if (from !== undefined && page.endOffset !== from)
|
|
105
|
+
throw invalid('provider page does not chain to the requested offset');
|
|
106
|
+
if ((page.frames.length === 0) !== (page.prevOffset === page.endOffset)
|
|
107
|
+
|| (page.frames.length === 0 && !page.reachedStart))
|
|
108
|
+
throw invalid('backward page made no progress');
|
|
109
|
+
if (page.frames.length !== 0 && page.frames[0].startOffset !== page.prevOffset)
|
|
110
|
+
throw invalid('provider frames do not start at the previous offset');
|
|
111
|
+
let bytesFetched = 0;
|
|
112
|
+
for (const [index, frame] of page.frames.entries()) {
|
|
113
|
+
if (frame.data.length === 0 || (frame.continuesBefore && index !== 0)
|
|
114
|
+
|| (frame.continuesAfter && index !== page.frames.length - 1))
|
|
115
|
+
throw invalid('invalid backward frame boundary');
|
|
116
|
+
bytesFetched += frame.data.length;
|
|
117
|
+
if (bytesFetched > limit)
|
|
118
|
+
throw invalid(`provider exceeded the page hard cap: ${bytesFetched} > ${limit}`);
|
|
119
|
+
}
|
|
120
|
+
for (let index = page.frames.length - 1; index >= 0; index--) {
|
|
121
|
+
const frame = page.frames[index];
|
|
122
|
+
if (frame.continuesAfter !== (partial !== undefined))
|
|
123
|
+
throw invalid('provider message fragments are not contiguous');
|
|
124
|
+
const message = partial ?? { fragments: [], byteLength: 0 };
|
|
125
|
+
if (frame.data.length > DEFAULT_BACKWARD_MAX_MESSAGE_BYTES - message.byteLength)
|
|
126
|
+
throw invalid('backward message exceeds the Streams message byte limit');
|
|
127
|
+
message.fragments.push(Uint8Array.from(frame.data));
|
|
128
|
+
message.byteLength += frame.data.length;
|
|
129
|
+
if (frame.continuesBefore) {
|
|
130
|
+
partial = message;
|
|
131
|
+
}
|
|
132
|
+
else {
|
|
133
|
+
await onMessage(frame.startOffset, messageBytes(message));
|
|
134
|
+
partial = undefined;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
if (page.reachedStart && partial !== undefined)
|
|
138
|
+
throw invalid('the log starts mid-message: provider boundaries contradict the bytes');
|
|
139
|
+
return { bytesFetched, partial };
|
|
140
|
+
}
|
|
102
141
|
const PREFIX_KEY_TAG = 0x01;
|
|
103
142
|
const utf8 = new TextEncoder();
|
|
104
143
|
const utf8d = new TextDecoder('utf-8', { fatal: true });
|
|
@@ -155,7 +194,9 @@ export class HistoryReader {
|
|
|
155
194
|
partial;
|
|
156
195
|
storage;
|
|
157
196
|
#crypto;
|
|
158
|
-
constructor(scope, stream, inbox, replay, coverage, policy,
|
|
197
|
+
constructor(scope, stream, inbox, replay, coverage, policy,
|
|
198
|
+
/** Maximum plaintext batch size accepted by Inbox. */
|
|
199
|
+
maxBatchBytes,
|
|
159
200
|
/** The intake is the partial-replica path (N3). Coverage marks use
|
|
160
201
|
* the exact local frames and bind a declared parent only where that
|
|
161
202
|
* parent's seal frame is local (N017 P1-C). A window turn whose
|
|
@@ -174,10 +215,8 @@ export class HistoryReader {
|
|
|
174
215
|
this.storage = storage;
|
|
175
216
|
}
|
|
176
217
|
/** Open the reader for one (stream, remote-generation) scope (the scope
|
|
177
|
-
* comes from `Executor.scope`). Reuses the link's
|
|
178
|
-
*
|
|
179
|
-
* boundary-discovery buffer (a missing chain past it is typed
|
|
180
|
-
* corruption). */
|
|
218
|
+
* comes from `Executor.scope`). Reuses the link's Inbox and replay limits
|
|
219
|
+
* for batches received after any configured decryption. */
|
|
181
220
|
static open(storage, stream, scope, limits) {
|
|
182
221
|
let fragment;
|
|
183
222
|
try {
|
|
@@ -282,14 +321,8 @@ export class HistoryReader {
|
|
|
282
321
|
// A crash between a committed receipt and its replay left durable
|
|
283
322
|
// work behind: drain before any new fetch (idle when caught up).
|
|
284
323
|
await this.#replayDrain(report, appliedSeen, pendingSeen);
|
|
285
|
-
//
|
|
286
|
-
|
|
287
|
-
// from the provider's verified spans; a fragment is transport
|
|
288
|
-
// state, never received.
|
|
289
|
-
let collected = [];
|
|
290
|
-
// The in-flight partial message: id, total length, the assembled
|
|
291
|
-
// bytes so far, and the message offset the NEXT (older) fragment
|
|
292
|
-
// must end at.
|
|
324
|
+
// Collect complete messages newest-first; import them in log order after the walk.
|
|
325
|
+
const collected = [];
|
|
293
326
|
let partial;
|
|
294
327
|
let from = options.before;
|
|
295
328
|
let tail;
|
|
@@ -329,82 +362,19 @@ export class HistoryReader {
|
|
|
329
362
|
? Math.min(pageLimitBytes, pageLimitBytes - extraFetched)
|
|
330
363
|
: Math.min(pageLimitBytes, budgetBytes - report.bytesFetched);
|
|
331
364
|
const page = await source.readBackward(from, limit);
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
// Verify the span list tiles the payload exactly, oldest first.
|
|
337
|
-
let cursor = 0;
|
|
338
|
-
for (const span of page.messages) {
|
|
339
|
-
if (!Number.isSafeInteger(span.relStart) || !Number.isSafeInteger(span.relEnd)
|
|
340
|
-
|| !Number.isSafeInteger(span.messageLen) || !Number.isSafeInteger(span.msgOffset)
|
|
341
|
-
|| span.relStart < 0 || span.relEnd < span.relStart || span.messageLen < 0 || span.msgOffset < 0)
|
|
342
|
-
throw invalid('provider message span is not a safe non-negative integer');
|
|
343
|
-
if (span.relStart !== cursor || span.relEnd > page.payload.length)
|
|
344
|
-
throw invalid('provider message spans do not tile the page payload');
|
|
345
|
-
cursor = span.relEnd;
|
|
346
|
-
const fragLen = span.relEnd - span.relStart;
|
|
347
|
-
if (fragLen === 0 || fragLen > span.messageLen)
|
|
348
|
-
throw invalid('provider message span exceeds its message length');
|
|
349
|
-
if (span.msgOffset > span.messageLen || fragLen > span.messageLen - span.msgOffset)
|
|
350
|
-
throw invalid('provider message fragment overruns the message');
|
|
351
|
-
}
|
|
352
|
-
if (cursor !== page.payload.length)
|
|
353
|
-
throw invalid('provider message spans do not cover the page payload');
|
|
365
|
+
const collectedPage = await collectBackwardPage(page, from, limit, partial, (start, bytes) => keepAssembled(this.#crypto, windowTurns, collected, (offset) => {
|
|
366
|
+
oldestBoundary = offset;
|
|
367
|
+
}, start, bytes));
|
|
368
|
+
partial = collectedPage.partial;
|
|
354
369
|
report.pages++;
|
|
355
|
-
report.bytesFetched +=
|
|
370
|
+
report.bytesFetched += collectedPage.bytesFetched;
|
|
356
371
|
if (overBudget)
|
|
357
|
-
extraFetched +=
|
|
372
|
+
extraFetched += collectedPage.bytesFetched;
|
|
358
373
|
tail ??= page.endOffset;
|
|
359
|
-
// Consume spans newest-first: complete-in-page messages
|
|
360
|
-
// collect directly, fragments extend the in-flight partial.
|
|
361
|
-
for (let spanIndex = page.messages.length - 1; spanIndex >= 0; spanIndex--) {
|
|
362
|
-
const span = page.messages[spanIndex];
|
|
363
|
-
const frag = page.payload.subarray(span.relStart, span.relEnd);
|
|
364
|
-
const fragLen = frag.length;
|
|
365
|
-
if (span.msgOffset === 0 && fragLen === span.messageLen) {
|
|
366
|
-
// A complete message in one page. An unrelated NEWER
|
|
367
|
-
// message's partial may legitimately be open (its
|
|
368
|
-
// older fragments arrive in older pages).
|
|
369
|
-
await keepAssembled(this.#crypto, windowTurns, collected, (start) => { oldestBoundary = start; }, span.messageStart, Uint8Array.from(frag));
|
|
370
|
-
continue;
|
|
371
|
-
}
|
|
372
|
-
if (partial === undefined) {
|
|
373
|
-
// The message's END fragment must be its last bytes
|
|
374
|
-
// (fragLen <= messageLen is already enforced, so the
|
|
375
|
-
// subtraction cannot go negative).
|
|
376
|
-
if (span.msgOffset !== span.messageLen - fragLen)
|
|
377
|
-
throw invalid('provider fragment is not contiguous with the message end');
|
|
378
|
-
partial = { id: span.messageStart, len: span.messageLen, bytes: Uint8Array.from(frag), nextOffset: span.msgOffset };
|
|
379
|
-
}
|
|
380
|
-
else {
|
|
381
|
-
if (partial.id !== span.messageStart || partial.len !== span.messageLen
|
|
382
|
-
|| fragLen > partial.nextOffset
|
|
383
|
-
|| span.msgOffset !== partial.nextOffset - fragLen)
|
|
384
|
-
throw invalid('provider message fragments are not contiguous');
|
|
385
|
-
// Fragments arrive newest-first: PREPEND this (older)
|
|
386
|
-
// fragment so the bytes stay in log order.
|
|
387
|
-
const assembled = new Uint8Array(partial.bytes.length + frag.length);
|
|
388
|
-
assembled.set(frag, 0);
|
|
389
|
-
assembled.set(partial.bytes, frag.length);
|
|
390
|
-
partial.bytes = assembled;
|
|
391
|
-
partial.nextOffset = span.msgOffset;
|
|
392
|
-
if (partial.nextOffset === 0) {
|
|
393
|
-
if (partial.bytes.length !== partial.len)
|
|
394
|
-
throw invalid('reassembled message length mismatch');
|
|
395
|
-
await keepAssembled(this.#crypto, windowTurns, collected, (start) => { oldestBoundary = start; }, partial.id, partial.bytes);
|
|
396
|
-
partial = undefined;
|
|
397
|
-
}
|
|
398
|
-
}
|
|
399
|
-
}
|
|
400
374
|
if (page.reachedStart) {
|
|
401
|
-
if (partial !== undefined)
|
|
402
|
-
throw invalid('the log starts mid-message: provider boundaries contradict the bytes');
|
|
403
375
|
report.reachedStart = true;
|
|
404
376
|
break;
|
|
405
377
|
}
|
|
406
|
-
if (page.prevOffset === page.endOffset && page.payload.length === 0)
|
|
407
|
-
throw invalid('backward page made no progress');
|
|
408
378
|
from = page.prevOffset;
|
|
409
379
|
}
|
|
410
380
|
// A partial left at the walk's edge is transport state: not
|
|
@@ -499,69 +469,17 @@ export class HistoryReader {
|
|
|
499
469
|
}
|
|
500
470
|
const limit = Math.min(pageLimitBytes, budgetBytes - report.bytesFetched);
|
|
501
471
|
const page = await source.readBackward(from, limit);
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
let cursor = 0;
|
|
507
|
-
for (const span of page.messages) {
|
|
508
|
-
if (!Number.isSafeInteger(span.relStart) || !Number.isSafeInteger(span.relEnd)
|
|
509
|
-
|| !Number.isSafeInteger(span.messageLen) || !Number.isSafeInteger(span.msgOffset)
|
|
510
|
-
|| span.relStart < 0 || span.relEnd < span.relStart || span.messageLen < 0 || span.msgOffset < 0)
|
|
511
|
-
throw invalid('provider message span is not a safe non-negative integer');
|
|
512
|
-
if (span.relStart !== cursor || span.relEnd > page.payload.length)
|
|
513
|
-
throw invalid('provider message spans do not tile the page payload');
|
|
514
|
-
cursor = span.relEnd;
|
|
515
|
-
const fragLen = span.relEnd - span.relStart;
|
|
516
|
-
if (fragLen === 0 || fragLen > span.messageLen)
|
|
517
|
-
throw invalid('provider message span exceeds its message length');
|
|
518
|
-
if (span.msgOffset > span.messageLen || fragLen > span.messageLen - span.msgOffset)
|
|
519
|
-
throw invalid('provider message fragment overruns the message');
|
|
520
|
-
}
|
|
521
|
-
if (cursor !== page.payload.length)
|
|
522
|
-
throw invalid('provider message spans do not cover the page payload');
|
|
472
|
+
const collectedPage = await collectBackwardPage(page, from, limit, partial, (start, bytes) => keepAssembled(this.#crypto, windowTurns, collected, (offset) => {
|
|
473
|
+
oldestBoundary = offset;
|
|
474
|
+
}, start, bytes));
|
|
475
|
+
partial = collectedPage.partial;
|
|
523
476
|
report.pages++;
|
|
524
|
-
report.bytesFetched +=
|
|
477
|
+
report.bytesFetched += collectedPage.bytesFetched;
|
|
525
478
|
tail ??= page.endOffset;
|
|
526
|
-
for (let spanIndex = page.messages.length - 1; spanIndex >= 0; spanIndex--) {
|
|
527
|
-
const span = page.messages[spanIndex];
|
|
528
|
-
const frag = page.payload.subarray(span.relStart, span.relEnd);
|
|
529
|
-
const fragLen = frag.length;
|
|
530
|
-
if (span.msgOffset === 0 && fragLen === span.messageLen) {
|
|
531
|
-
await keepAssembled(this.#crypto, windowTurns, collected, (start) => { oldestBoundary = start; }, span.messageStart, Uint8Array.from(frag));
|
|
532
|
-
continue;
|
|
533
|
-
}
|
|
534
|
-
if (partial === undefined) {
|
|
535
|
-
if (span.msgOffset !== span.messageLen - fragLen)
|
|
536
|
-
throw invalid('provider fragment is not contiguous with the message end');
|
|
537
|
-
partial = { id: span.messageStart, len: span.messageLen, bytes: Uint8Array.from(frag), nextOffset: span.msgOffset };
|
|
538
|
-
}
|
|
539
|
-
else {
|
|
540
|
-
if (partial.id !== span.messageStart || partial.len !== span.messageLen
|
|
541
|
-
|| fragLen > partial.nextOffset
|
|
542
|
-
|| span.msgOffset !== partial.nextOffset - fragLen)
|
|
543
|
-
throw invalid('provider message fragments are not contiguous');
|
|
544
|
-
const assembled = new Uint8Array(partial.bytes.length + frag.length);
|
|
545
|
-
assembled.set(frag, 0);
|
|
546
|
-
assembled.set(partial.bytes, frag.length);
|
|
547
|
-
partial.bytes = assembled;
|
|
548
|
-
partial.nextOffset = span.msgOffset;
|
|
549
|
-
if (partial.nextOffset === 0) {
|
|
550
|
-
if (partial.bytes.length !== partial.len)
|
|
551
|
-
throw invalid('reassembled message length mismatch');
|
|
552
|
-
await keepAssembled(this.#crypto, windowTurns, collected, (start) => { oldestBoundary = start; }, partial.id, partial.bytes);
|
|
553
|
-
partial = undefined;
|
|
554
|
-
}
|
|
555
|
-
}
|
|
556
|
-
}
|
|
557
479
|
if (page.reachedStart) {
|
|
558
|
-
if (partial !== undefined)
|
|
559
|
-
throw invalid('the log starts mid-message: provider boundaries contradict the bytes');
|
|
560
480
|
report.reachedStart = true;
|
|
561
481
|
break;
|
|
562
482
|
}
|
|
563
|
-
if (page.prevOffset === page.endOffset && page.payload.length === 0)
|
|
564
|
-
throw invalid('backward page made no progress');
|
|
565
483
|
from = page.prevOffset;
|
|
566
484
|
}
|
|
567
485
|
if (tail !== undefined)
|
|
@@ -671,10 +589,11 @@ export class HistoryReader {
|
|
|
671
589
|
return undefined;
|
|
672
590
|
if (raw.length === 0)
|
|
673
591
|
throw invalid('empty prefix-scan record');
|
|
674
|
-
|
|
675
|
-
|
|
592
|
+
const version = raw[0];
|
|
593
|
+
if (version !== 1 && version !== PREFIX_RECORD_VERSION)
|
|
594
|
+
throw invalid(`unsupported prefix-scan version ${version}`);
|
|
676
595
|
const dto = JSON.parse(utf8d.decode(raw.subarray(1)));
|
|
677
|
-
if (dto.v !==
|
|
596
|
+
if (dto.v !== version)
|
|
678
597
|
throw invalid(`unsupported prefix-scan version ${dto.v}`);
|
|
679
598
|
if (typeof dto.from !== 'string' || !Array.isArray(dto.wanted))
|
|
680
599
|
throw invalid('prefix-scan JSON');
|
|
@@ -683,22 +602,27 @@ export class HistoryReader {
|
|
|
683
602
|
throw invalid('prefix-scan turn id');
|
|
684
603
|
return parseUuid(id);
|
|
685
604
|
});
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
605
|
+
let partial;
|
|
606
|
+
if (dto.partial !== undefined) {
|
|
607
|
+
const fragment = dto.partial?.bytes;
|
|
608
|
+
if (typeof fragment !== 'string')
|
|
609
|
+
throw invalid('prefix-scan fragment');
|
|
610
|
+
// Both record formats store the contiguous wire suffix as hex.
|
|
611
|
+
if (fragment.length === 0 || fragment.length > DEFAULT_BACKWARD_MAX_MESSAGE_BYTES * 2)
|
|
612
|
+
throw invalid('prefix-scan fragment length');
|
|
613
|
+
const bytes = unhex(fragment);
|
|
614
|
+
partial = { fragments: [bytes], byteLength: bytes.length };
|
|
615
|
+
}
|
|
692
616
|
return { from: dto.from, wanted, partial };
|
|
693
617
|
}
|
|
694
618
|
async #storePrefixScan(scan) {
|
|
695
619
|
const key = this.#prefixKey();
|
|
696
|
-
const
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
620
|
+
const payload = utf8.encode(JSON.stringify({
|
|
621
|
+
v: PREFIX_RECORD_VERSION,
|
|
622
|
+
from: scan.from,
|
|
623
|
+
wanted: scan.wanted.map(uuidString),
|
|
624
|
+
partial: scan.partial === undefined ? undefined : { bytes: hex(messageBytes(scan.partial)) },
|
|
625
|
+
}));
|
|
702
626
|
const bytes = new Uint8Array(1 + payload.length);
|
|
703
627
|
bytes[0] = PREFIX_RECORD_VERSION;
|
|
704
628
|
bytes.set(payload, 1);
|
package/dist/sync/index.d.ts
CHANGED
|
@@ -8,7 +8,7 @@ export type { HeadInfo, ReadPage, ReadTransport } from './transport.js';
|
|
|
8
8
|
export { Link, LinkError, linkLimitsForSync } from './link.js';
|
|
9
9
|
export type { BridgeReport, DownloadReport, LinkLimits, StopToken } from './link.js';
|
|
10
10
|
export { HistoryReader, HistoryError } from './history.js';
|
|
11
|
-
export type { BackwardByteSource, BackwardPage, HistoryReport, PrefixScan } from './history.js';
|
|
11
|
+
export type { BackwardByteSource, BackwardFrame, BackwardPage, HistoryReport, PrefixScan } from './history.js';
|
|
12
12
|
export { PolicyStore, PolicyError, DEFAULT_MIRROR_POLICY } from './policy.js';
|
|
13
13
|
export type { MirrorDirection, MirrorPolicy } from './policy.js';
|
|
14
14
|
export { CryptoError } from './crypto.js';
|
package/dist/sync/mod.d.ts
CHANGED
|
@@ -20,5 +20,5 @@ export type { MirrorDirection, MirrorPolicy } from './policy.js';
|
|
|
20
20
|
export { Link, LinkError, linkLimitsForSync } from './link.js';
|
|
21
21
|
export type { BridgeReport, DownloadReport, LinkLimits, StopToken } from './link.js';
|
|
22
22
|
export { HistoryError, HistoryReader } from './history.js';
|
|
23
|
-
export type { BackwardByteSource, BackwardPage, HistoryReport, PrefixScan } from './history.js';
|
|
23
|
+
export type { BackwardByteSource, BackwardFrame, BackwardPage, HistoryReport, PrefixScan } from './history.js';
|
|
24
24
|
export { sealEnvelopeAsync, openEnvelopeAsync, openFirstEnvelopeAsync, openConcatenatedAsync, openConcatenatedPrefixAsync } from './crypto.js';
|
package/dist/sync/transport.d.ts
CHANGED
|
@@ -74,10 +74,7 @@ export declare class StreamsTransport implements SendTransport, ReadTransport, B
|
|
|
74
74
|
createStream(): Promise<void>;
|
|
75
75
|
/** Stream-tail metadata (opaque tail offset and the closed flag). */
|
|
76
76
|
head(): Promise<HeadInfo>;
|
|
77
|
-
/** One bounded
|
|
78
|
-
* before the current tail). The service supplies the message-span list;
|
|
79
|
-
* this adapter never infers boundaries from payload bytes. Requires a
|
|
80
|
-
* streams-client build that exports `readBackward` (sibling package). */
|
|
77
|
+
/** One bounded page decoded and validated by the Streams client. */
|
|
81
78
|
readBackward(from: string | undefined, limitBytes: number): Promise<BackwardPage>;
|
|
82
79
|
/** One catch-up page from `offset` (opaque; omitted reads from the
|
|
83
80
|
* beginning). No long-poll here: the caller's loop decides when to poll
|
package/dist/sync/transport.js
CHANGED
|
@@ -80,34 +80,24 @@ export class StreamsTransport {
|
|
|
80
80
|
const out = unwrap(await this.#client.head());
|
|
81
81
|
return { nextOffset: out.nextOffset, closed: out.closed };
|
|
82
82
|
}
|
|
83
|
-
/** One bounded
|
|
84
|
-
* before the current tail). The service supplies the message-span list;
|
|
85
|
-
* this adapter never infers boundaries from payload bytes. Requires a
|
|
86
|
-
* streams-client build that exports `readBackward` (sibling package). */
|
|
83
|
+
/** One bounded page decoded and validated by the Streams client. */
|
|
87
84
|
async readBackward(from, limitBytes) {
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
return {
|
|
98
|
-
relStart: span.relStart,
|
|
99
|
-
relEnd: span.relEnd,
|
|
100
|
-
messageStart: span.messageStart,
|
|
101
|
-
messageLen,
|
|
102
|
-
msgOffset,
|
|
103
|
-
};
|
|
85
|
+
const page = unwrap(await this.#client.readBackward({ before: from, limitBytes }));
|
|
86
|
+
if (page.frames.length === 0 && page.atRetainedStart && !page.atStart)
|
|
87
|
+
throw new TransportError('rejected', 'backward history starts at a retention floor');
|
|
88
|
+
// RR cursors are canonical 20-digit byte offsets. Only the transport
|
|
89
|
+
// interprets them; the history reader chains opaque provider offsets.
|
|
90
|
+
let offset = BigInt(page.prevOffset);
|
|
91
|
+
const frames = page.frames.map((frame) => {
|
|
92
|
+
const startOffset = offset.toString().padStart(page.prevOffset.length, '0');
|
|
93
|
+
offset += BigInt(frame.data.length);
|
|
94
|
+
return { ...frame, startOffset };
|
|
104
95
|
});
|
|
105
96
|
return {
|
|
106
|
-
|
|
107
|
-
endOffset:
|
|
108
|
-
prevOffset:
|
|
109
|
-
reachedStart:
|
|
110
|
-
messages,
|
|
97
|
+
frames,
|
|
98
|
+
endOffset: page.endOffset,
|
|
99
|
+
prevOffset: page.prevOffset,
|
|
100
|
+
reachedStart: page.atStart,
|
|
111
101
|
};
|
|
112
102
|
}
|
|
113
103
|
/** One catch-up page from `offset` (opaque; omitted reads from the
|
package/node/client.d.mts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/** Private prototype API. Pair this client with the artifact's matching owner binary. */
|
|
2
2
|
export const MAX_MESSAGE_BYTES: number;
|
|
3
3
|
export class RoostHostError extends Error { readonly code: string; }
|
|
4
|
-
export type OwnerCapability = 'history-v1' | 'create-once-v1' | 'create-once-cas-v1' | 'sync-v1' | 'host-crypto-v1' | 'index-cas-v1' | 'index-events-v1' | 'index-cas-events-v1' | 'commit-metadata-v1' | 'derived-indexes-v1' | 'receipt-checks-v1' | 'commit-observation-v1';
|
|
4
|
+
export type OwnerCapability = 'history-v1' | 'create-once-v1' | 'create-once-cas-v1' | 'field-reads-v1' | 'exclusive-batch-v1' | 'sync-v1' | 'host-crypto-v1' | 'index-cas-v1' | 'index-events-v1' | 'index-cas-events-v1' | 'commit-metadata-v1' | 'derived-indexes-v1' | 'receipt-checks-v1' | 'commit-observation-v1';
|
|
5
5
|
export type ParentRef = { id: Uint8Array; hash: Uint8Array };
|
|
6
6
|
export type UpdateRef = { turnId: Uint8Array; seq: bigint };
|
|
7
7
|
export type Verification = 'notRetrieved' | 'provisional' | 'selfVerified' | 'ancestorsVerified';
|
|
@@ -9,6 +9,8 @@ export type Header = { turnId: Uint8Array; owner: Uint8Array; parents: ParentRef
|
|
|
9
9
|
export type Turn = Header & { contentJson: string };
|
|
10
10
|
export type ReadResult<T> = { kind: 'found'; turn: T } | { kind: 'notFound'; turnId: Uint8Array } | { kind: 'incomplete'; turnId: Uint8Array; prefix: T | null };
|
|
11
11
|
export type Path = ({ key: string } | { index: bigint })[];
|
|
12
|
+
export type FieldSelector = { path: Path; jsonPath?: Path; info?: boolean };
|
|
13
|
+
export type FieldReadResult = { state: "missing" } | { state: "ready"; contentJson: string };
|
|
12
14
|
export type ContentOp =
|
|
13
15
|
| { kind: 'set'; path: Path; contentJson: string }
|
|
14
16
|
| { kind: 'remove'; path: Path }
|
|
@@ -43,7 +45,7 @@ export interface RoostNodeStream {
|
|
|
43
45
|
createOnce(key: Uint8Array, parents: ParentRef[], contentJson: string, options?: RequestOptions & {expectedEventCursor?: bigint}): Promise<{ turnId: Uint8Array; created: boolean }>;
|
|
44
46
|
edit(turnId: Uint8Array, expectedNextSeq: bigint, ops: ContentOp[], options?: RequestOptions): Promise<{ updates: UpdateRef[] }>;
|
|
45
47
|
seal(turnId: Uint8Array, expectedNextSeq: bigint, options?: RequestOptions): Promise<{ updates: UpdateRef[] }>;
|
|
46
|
-
writeBatch(writes: Write[], options?: RequestOptions & {indexPuts?: IndexPut[]; expectedEventCursor?: bigint}): Promise<{ updates: UpdateRef[] }>;
|
|
48
|
+
writeBatch(writes: Write[], options?: RequestOptions & {requireLocalInterval?: boolean; indexPuts?: IndexPut[]; expectedEventCursor?: bigint}): Promise<{ updates: UpdateRef[]; before?: bigint; through?: bigint }>;
|
|
47
49
|
readIndex(keys: IndexKey[], options?: RequestOptions): Promise<(Uint8Array | null)[]>;
|
|
48
50
|
compareAndWriteIndex(expected: IndexEntry[], changes: IndexEntry[], options?: RequestOptions & {eventKeys?: IndexKey[]}): Promise<boolean>;
|
|
49
51
|
scanIndex(table: string, start: Uint8Array, limit: bigint, options?: RequestOptions): Promise<{key: Uint8Array; value: Uint8Array}[]>;
|
|
@@ -55,6 +57,10 @@ export interface RoostNodeStream {
|
|
|
55
57
|
turnHeadersBefore(before: Uint8Array, limit: bigint, options?: RequestOptions): Promise<Header[]>;
|
|
56
58
|
turnHeadersAfter(after: Uint8Array | null, limit: bigint, options?: RequestOptions): Promise<ReadResult<Header>[]>;
|
|
57
59
|
readValue(turnId: Uint8Array, path: Path, options?: RequestOptions): Promise<{ contentJson: string; nextSeq: bigint }>;
|
|
60
|
+
readonly fieldReads: boolean;
|
|
61
|
+
readonly exclusiveBatches: boolean;
|
|
62
|
+
readCreateFields(turnId: Uint8Array, selectors: FieldSelector[], omitDigestKeys?: string[], options?: RequestOptions): Promise<{fields: FieldReadResult[]; owner: Uint8Array; digest: Uint8Array; filteredDigest: Uint8Array}>;
|
|
63
|
+
readFields(turnId: Uint8Array, selectors: FieldSelector[], options?: RequestOptions): Promise<{ fields: FieldReadResult[]; nextSeq: bigint }>;
|
|
58
64
|
readText(turnId: Uint8Array, path: Path, start: bigint, end: bigint, options?: RequestOptions): Promise<{ text: string; nextSeq: bigint }>;
|
|
59
65
|
verification(turnId: Uint8Array, options?: RequestOptions): Promise<Verification>;
|
|
60
66
|
eventsAfter(after: bigint, limit: bigint, options?: RequestOptions): Promise<EventRecord[]>;
|
package/node/client.mjs
CHANGED
|
@@ -243,11 +243,32 @@ class RoostNodeStream {
|
|
|
243
243
|
async turnHeadersAfter(after, limit, options) { return this.client.request({method:'turnHeadersAfter',stream:this.id,after:after===null?null:hex(after,16),limit:decimal(limit)},v=>v.map(r=>read(r,header)),options); }
|
|
244
244
|
async readTurns(turnIds, options) { return this.client.request({method:'readTurns',stream:this.id,turnIds:turnIds.map(id=>hex(id,16))},v=>v.map(r=>read(r)),options); }
|
|
245
245
|
async readValue(turnId, p, options) { return this.client.request({method:'readValue',stream:this.id,turnId:hex(turnId,16),path:path(p)},v=>{if(typeof v.contentJson!=='string')throw error('protocol');return {contentJson:v.contentJson,nextSeq:fromDecimal(v.nextSeq)};},options); }
|
|
246
|
+
get exclusiveBatches() { return this.client.capabilities.includes("exclusive-batch-v1"); }
|
|
247
|
+
get fieldReads() { return this.client.capabilities.includes("field-reads-v1"); }
|
|
248
|
+
async readCreateFields(turnId, selectors, omitDigestKeys = [], options) {
|
|
249
|
+
if (!Array.isArray(selectors) || selectors.length > 1024 || !Array.isArray(omitDigestKeys) || omitDigestKeys.length > 64) throw error("invalid");
|
|
250
|
+
return this.client.request({method:"readCreateFields",stream:this.id,turnId:hex(turnId,16),
|
|
251
|
+
selectors:selectors.map(selector=>({path:path(selector.path),...(selector.jsonPath===undefined?{}:{jsonPath:path(selector.jsonPath)}),...(selector.info===undefined?{}:{info:selector.info})})),omitDigestKeys}, v=>{
|
|
252
|
+
if (!Array.isArray(v.fields) || v.fields.length !== selectors.length) throw error("protocol");
|
|
253
|
+
return {fields:v.fields.map(field=>{
|
|
254
|
+
if(field?.state==="missing")return {state:"missing"};
|
|
255
|
+
if(field?.state!=="ready"||typeof field.contentJson!=="string")throw error("protocol");
|
|
256
|
+
return {state:"ready",contentJson:field.contentJson};
|
|
257
|
+
}),owner:unhex(v.owner,32),digest:unhex(v.digest,32),filteredDigest:unhex(v.filteredDigest,32)};
|
|
258
|
+
},options);
|
|
259
|
+
}
|
|
260
|
+
async readFields(turnId, selectors, options) {
|
|
261
|
+
if (!Array.isArray(selectors) || selectors.length > 1024) throw error('invalid');
|
|
262
|
+
return this.client.request({method:'readFields',stream:this.id,turnId:hex(turnId,16),selectors:selectors.map(selector=>({path:path(selector.path),...(selector.jsonPath===undefined?{}:{jsonPath:path(selector.jsonPath)}),...(selector.info===undefined?{}:{info:selector.info})}))},v=>{
|
|
263
|
+
if(!Array.isArray(v.fields)||v.fields.length!==selectors.length)throw error('protocol');
|
|
264
|
+
return {fields:v.fields.map(field=>{if(field?.state==='missing')return {state:'missing'};if(field?.state!=='ready'||typeof field.contentJson!=='string')throw error('protocol');return {state:'ready',contentJson:field.contentJson};}),nextSeq:fromDecimal(v.nextSeq)};
|
|
265
|
+
},options);
|
|
266
|
+
}
|
|
246
267
|
async verification(turnId, options) { return this.client.request({method:'verification',stream:this.id,turnId:hex(turnId,16)},v=>{if(!['notRetrieved','provisional','selfVerified','ancestorsVerified'].includes(v))throw error('protocol');return v;},options); }
|
|
247
268
|
async writeBatch(writes, options) {
|
|
248
269
|
const indexPuts = options?.indexPuts;
|
|
249
270
|
const cursor = options?.expectedEventCursor;
|
|
250
|
-
return this.client.request({method:'writeBatch',stream:this.id,writes:writes.map(w=>{
|
|
271
|
+
return this.client.request({method:'writeBatch',stream:this.id,...(options?.requireLocalInterval===undefined?{}:{requireLocalInterval:bool(options.requireLocalInterval)}),writes:writes.map(w=>{
|
|
251
272
|
switch(w.kind){
|
|
252
273
|
case 'create':return {kind:w.kind,parents:w.parents.map(p=>({id:hex(p.id,16),hash:hex(p.hash,32)})),contentJson:string(w.contentJson)};
|
|
253
274
|
case 'createOnce':return {kind:w.kind,keyHex:hex(w.key),parents:w.parents.map(p=>({id:hex(p.id,16),hash:hex(p.hash,32)})),contentJson:string(w.contentJson)};
|
|
@@ -257,7 +278,7 @@ class RoostNodeStream {
|
|
|
257
278
|
case 'sealOnce':return {kind:w.kind,keyHex:hex(w.key),expectedNextSeq:decimal(w.expectedNextSeq)};
|
|
258
279
|
default:throw new TypeError('unknown write');
|
|
259
280
|
}
|
|
260
|
-
}),...(indexPuts===undefined?{}:{indexPuts:indexPuts.map(p=>({table:string(p.table),keyHex:hex(p.key),valueHex:hex(p.value),...(p.emitEvent===undefined?{}:{emitEvent:bool(p.emitEvent)}),...(p.onceKey===undefined?{}:{onceKeyHex:hex(p.onceKey)})}))}),...(cursor===undefined?{}:{expectedEventCursor:decimal(cursor)})},v=>({updates:refs(v.updates)}),options); }
|
|
281
|
+
}),...(indexPuts===undefined?{}:{indexPuts:indexPuts.map(p=>({table:string(p.table),keyHex:hex(p.key),valueHex:hex(p.value),...(p.emitEvent===undefined?{}:{emitEvent:bool(p.emitEvent)}),...(p.onceKey===undefined?{}:{onceKeyHex:hex(p.onceKey)})}))}),...(cursor===undefined?{}:{expectedEventCursor:decimal(cursor)})},v=>({updates:refs(v.updates),before:fromDecimal(v.before),through:fromDecimal(v.through)}),options); }
|
|
261
282
|
async scanIndex(table, start, limit, options) {
|
|
262
283
|
return this.client.request({method:'indexScan',stream:this.id,table:string(table),start:hex(start),limit:decimal(limit)},v=>v.map(r=>({key:unhex(r.keyHex),value:unhex(r.valueHex)})),options);
|
|
263
284
|
}
|