@loro-dev/roost 0.1.1 → 0.1.3
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 +43 -5
- package/dist/lody-history.d.ts +27 -7
- package/dist/lody-history.js +129 -19
- package/dist/sync/history.d.ts +8 -2
- package/dist/sync/history.js +10 -5
- package/package.json +13 -13
package/README.md
CHANGED
|
@@ -12,7 +12,7 @@ The `Inbox` module adds atomic raw receipt/cursor storage, without authenticatin
|
|
|
12
12
|
or applying those bytes.
|
|
13
13
|
|
|
14
14
|
```sh
|
|
15
|
-
npm install @loro-dev/roost@0.1.
|
|
15
|
+
npm install @loro-dev/roost@0.1.3
|
|
16
16
|
```
|
|
17
17
|
|
|
18
18
|
For source development and browser tests:
|
|
@@ -271,6 +271,14 @@ the core outbox. Discovery page size bounds each page, while `maxSend` bounds on
|
|
|
271
271
|
sends. Partial replicas keep directed `Link.bridgeTurns` and its `waitingParent`
|
|
272
272
|
result for missing dependencies. See the discovery and upgrade contract.
|
|
273
273
|
|
|
274
|
+
Browser `HistoryReader.fetchWindow(source, budgetBytes, pageLimitBytes, stop,
|
|
275
|
+
{ before, completePrefixes: false })` resumes at the previous window's complete
|
|
276
|
+
message boundary. This option stops at the byte budget without filtering extra
|
|
277
|
+
prefix-repair pages into the window range. Use explicit `completePrefixes` to
|
|
278
|
+
repair pending window turns. Persist the oldest contiguous boundary only after
|
|
279
|
+
intake commits, and initialize `Link.catchUpAt` from the original window tail,
|
|
280
|
+
never a later `head()` result. The Node window API is unchanged.
|
|
281
|
+
|
|
274
282
|
`pnpm pack:consumer -- /absolute/output/directory` builds the npm tarball and
|
|
275
283
|
checks its public entries. It depends on the exact registry release
|
|
276
284
|
`@loro-dev/streams-client@0.8.0`, with no bundled SDK. `pnpm check:consumer`
|
|
@@ -384,21 +392,51 @@ different input under that ID is a conflict. `LodyHistory` and `NodeLodyHistory`
|
|
|
384
392
|
expose the same contract. The caller still owns queue, steer and ACP lifecycle
|
|
385
393
|
decisions.
|
|
386
394
|
|
|
395
|
+
For immutable input delivery, use `acceptInputToView` with the same
|
|
396
|
+
`BranchAcceptInput` shape, then query `readInputAcceptance({ viewId, operationId,
|
|
397
|
+
input })`. Both browser and Node adapters bind an immutable input fingerprint
|
|
398
|
+
and operation receipt in the same transaction as the branch mutation. Input is
|
|
399
|
+
copied before asynchronous work begins. The fingerprint includes owner, business/segment identity, content and attachment
|
|
400
|
+
identity; the receipt key binds view and operation identity. Mutable parents,
|
|
401
|
+
expected head and revision are excluded.
|
|
402
|
+
|
|
403
|
+
Repeating an identical accept returns its original receipt even after edits,
|
|
404
|
+
later appends or active-branch removal. Changed input conflicts. Read-only lookup
|
|
405
|
+
returns `undefined` when unobserved, never inserts history, and does not prove a
|
|
406
|
+
pending accept cannot later commit. A host may retry the identical operation
|
|
407
|
+
without inventing a new input. Receipts remain owner-local derived indexes;
|
|
408
|
+
hosts own access checks, retained-generation lookup, execution and guide recovery.
|
|
409
|
+
|
|
410
|
+
`LodyHistory.readOnly(stream)` indexes and projects admitted native history without
|
|
411
|
+
a signing identity; authoring through that instance rejects. The host still owns
|
|
412
|
+
stream authorization and seal verification. `restoreActiveBranch` is available in
|
|
413
|
+
both browser and Node adapters: it atomically creates and seals a non-message
|
|
414
|
+
`branch_state` record with its local branch/operation indexes. Remote indexers
|
|
415
|
+
reconstruct the rollback, including an empty restored view, from that native
|
|
416
|
+
record. `branch_state` is readable as an internal history identity but is excluded
|
|
417
|
+
from `HistoryWriteIdentity`, `AcceptHistory` and batch commands; generic authoring
|
|
418
|
+
rejects it at runtime as well. Use `restoreActiveBranch` as the only write path. It
|
|
419
|
+
does not edit sealed Turns or change the Rust state machine/wire.
|
|
420
|
+
|
|
387
421
|
Active-branch pages return `startPosition`, `totalCount`, `hasMoreOlder`, and an
|
|
388
422
|
opaque ancestry cursor alongside the selected messages. Positions/counts refer
|
|
389
423
|
to logical `businessId` rows: use `primary` for the initial segment and distinct
|
|
390
424
|
successor IDs for late output. Project all returned segments of a business ID
|
|
391
425
|
into one row. Linear branches written with this metadata read a bounded page;
|
|
392
426
|
legacy/nonlinear ancestry may rebuild a complete directory. `readActiveBranch`
|
|
393
|
-
remains available for explicit full snapshots
|
|
427
|
+
remains available for explicit full snapshots, fenced by the durable event cursor
|
|
428
|
+
so a concurrent import cannot mix branch membership and bodies. A partial replica
|
|
429
|
+
missing an older boundary reports incomplete and preserves the logical count;
|
|
430
|
+
the host fetches or repairs that boundary instead of declaring shorter history.
|
|
431
|
+
Generic published-message reverse
|
|
394
432
|
pages include superseded messages and cannot substitute for active-branch pages.
|
|
395
433
|
|
|
396
434
|
An append preserves older cursors while adding any intervening late successors.
|
|
397
435
|
A fork that removes the cursor's ancestry rejects it as `stale`; refresh the
|
|
398
436
|
loaded window and obtain a new cursor. The last reverse page can contain fewer
|
|
399
|
-
than `limit` rows and never extends past the cursor.
|
|
400
|
-
|
|
401
|
-
|
|
437
|
+
than `limit` rows and never extends past the cursor. Lody uses these APIs in its
|
|
438
|
+
Node owner and read-only browser replica. Static checks of that composition do
|
|
439
|
+
not establish live-service synchronization or product performance acceptance.
|
|
402
440
|
|
|
403
441
|
New records in the private `lody_history_published_v1` table have a `version: "2"`
|
|
404
442
|
membership-only value. Current readers also accept legacy full-snapshot values;
|
package/dist/lody-history.d.ts
CHANGED
|
@@ -10,26 +10,29 @@ import { type ContentOp, type ParentRef } from './codec.js';
|
|
|
10
10
|
import { type JsonValue } from './json.js';
|
|
11
11
|
import { Identity } from './identity.js';
|
|
12
12
|
import { Stream, type TurnReadResult } from './store.js';
|
|
13
|
-
type Kind = 'message' | 'permission_response' | 'dispatch_intent' | 'batch_receipt' | 'publication';
|
|
13
|
+
type Kind = 'message' | 'permission_response' | 'dispatch_intent' | 'batch_receipt' | 'publication' | 'branch_state';
|
|
14
14
|
export type HistoryIdentity = {
|
|
15
15
|
businessId: string;
|
|
16
16
|
segmentId: string;
|
|
17
17
|
kind: Kind;
|
|
18
18
|
};
|
|
19
|
+
export type HistoryWriteIdentity = Omit<HistoryIdentity, 'kind'> & {
|
|
20
|
+
kind: Exclude<Kind, 'branch_state'>;
|
|
21
|
+
};
|
|
19
22
|
export type HistoryBatchCommand = {
|
|
20
23
|
type: 'accept';
|
|
21
|
-
identity:
|
|
24
|
+
identity: HistoryWriteIdentity;
|
|
22
25
|
parents: ParentRef[];
|
|
23
26
|
content: JsonValue;
|
|
24
27
|
attachments?: AttachmentIdentity[];
|
|
25
28
|
} | {
|
|
26
29
|
type: 'setContent';
|
|
27
|
-
identity:
|
|
30
|
+
identity: HistoryWriteIdentity;
|
|
28
31
|
expectedNextSeq: bigint;
|
|
29
32
|
content: JsonValue;
|
|
30
33
|
} | {
|
|
31
34
|
type: 'finish';
|
|
32
|
-
identity:
|
|
35
|
+
identity: HistoryWriteIdentity;
|
|
33
36
|
expectedNextSeq: bigint;
|
|
34
37
|
} | {
|
|
35
38
|
type: 'permission';
|
|
@@ -70,7 +73,7 @@ export type AttachmentIdentity = {
|
|
|
70
73
|
name: string;
|
|
71
74
|
size: bigint;
|
|
72
75
|
};
|
|
73
|
-
export type AcceptHistory =
|
|
76
|
+
export type AcceptHistory = HistoryWriteIdentity & {
|
|
74
77
|
parents: ParentRef[];
|
|
75
78
|
content: JsonValue;
|
|
76
79
|
attachments?: AttachmentIdentity[];
|
|
@@ -102,6 +105,12 @@ export type BranchAcceptInput = {
|
|
|
102
105
|
operationId: string;
|
|
103
106
|
input: AcceptHistory;
|
|
104
107
|
};
|
|
108
|
+
/** Immutable application input; branch placement is chosen by its owner. */
|
|
109
|
+
export type HistoryInputIdentity = {
|
|
110
|
+
viewId: string;
|
|
111
|
+
operationId: string;
|
|
112
|
+
input: Omit<AcceptHistory, 'parents'>;
|
|
113
|
+
};
|
|
105
114
|
export type ForkAndActivateInput = BranchAcceptInput & {
|
|
106
115
|
/** Last retained Turn. The replacement must name it as a parent when present. */
|
|
107
116
|
baseTurn: Uint8Array | null;
|
|
@@ -160,8 +169,12 @@ type Binding = {
|
|
|
160
169
|
* never replaces an older signature. Dispatch/Flock and locations are host-owned. */
|
|
161
170
|
export declare class LodyHistory {
|
|
162
171
|
readonly stream: Stream;
|
|
163
|
-
readonly
|
|
164
|
-
constructor(stream: Stream,
|
|
172
|
+
private readonly signingIdentity?;
|
|
173
|
+
constructor(stream: Stream, signingIdentity?: Identity | undefined);
|
|
174
|
+
/** A replica can project admitted history without owning a signing key.
|
|
175
|
+
* Index maintenance is local; authoring through this instance is rejected. */
|
|
176
|
+
static readOnly(stream: Stream): LodyHistory;
|
|
177
|
+
get identity(): Identity;
|
|
165
178
|
private get space();
|
|
166
179
|
private get cursorSpace();
|
|
167
180
|
indexPage(limit?: number): Promise<boolean>;
|
|
@@ -176,8 +189,13 @@ export declare class LodyHistory {
|
|
|
176
189
|
}>;
|
|
177
190
|
/** Append a message to an active view and advance that view atomically. */
|
|
178
191
|
acceptToView(input: BranchAcceptInput): Promise<BranchMutationResult>;
|
|
192
|
+
/** Atomically bind immutable input to its first accepted branch placement. */
|
|
193
|
+
acceptInputToView(input: BranchAcceptInput): Promise<BranchMutationResult>;
|
|
194
|
+
/** Missing means unobserved, not that an in-flight acceptance cannot commit. */
|
|
195
|
+
readInputAcceptance(input: HistoryInputIdentity): Promise<BranchMutationResult | undefined>;
|
|
179
196
|
/** Create a replacement Turn and switch the same logical view to it. */
|
|
180
197
|
forkAndActivate(input: ForkAndActivateInput): Promise<BranchMutationResult>;
|
|
198
|
+
restoreActiveBranch(input: RestoreActiveBranchInput): Promise<RestoreActiveBranchResult>;
|
|
181
199
|
readActiveBranch(viewId: string): Promise<ActiveBranchRead>;
|
|
182
200
|
readActiveBranchPage(viewId: string, input?: {
|
|
183
201
|
before?: ActiveBranchPageCursor;
|
|
@@ -410,6 +428,8 @@ export declare class NodeLodyHistory {
|
|
|
410
428
|
created: boolean;
|
|
411
429
|
}>;
|
|
412
430
|
acceptToView(input: BranchAcceptInput): Promise<BranchMutationResult>;
|
|
431
|
+
acceptInputToView(input: BranchAcceptInput): Promise<BranchMutationResult>;
|
|
432
|
+
readInputAcceptance(input: HistoryInputIdentity): Promise<BranchMutationResult | undefined>;
|
|
413
433
|
forkAndActivate(input: ForkAndActivateInput): Promise<BranchMutationResult>;
|
|
414
434
|
restoreActiveBranch(input: RestoreActiveBranchInput): Promise<RestoreActiveBranchResult>;
|
|
415
435
|
readActiveBranch(viewId: string): Promise<ActiveBranchRead>;
|
package/dist/lody-history.js
CHANGED
|
@@ -9,13 +9,19 @@ const invalid = (message) => new StoreError('invalid', message);
|
|
|
9
9
|
function text(v) { if (typeof v !== 'string' || !v.length || encodeUtf8(v).length > 1024)
|
|
10
10
|
throw invalid('history identity size'); return v; }
|
|
11
11
|
function knownKind(kind) {
|
|
12
|
-
return kind === 'message' || kind === 'permission_response' || kind === 'dispatch_intent' || kind === 'batch_receipt' || kind === 'publication';
|
|
12
|
+
return kind === 'message' || kind === 'permission_response' || kind === 'dispatch_intent' || kind === 'batch_receipt' || kind === 'publication' || kind === 'branch_state';
|
|
13
13
|
}
|
|
14
14
|
function keyOf(v) {
|
|
15
15
|
if (!knownKind(v.kind))
|
|
16
16
|
throw invalid('history kind');
|
|
17
17
|
return encodeUtf8(JSON.stringify([v.kind, text(v.businessId), text(v.segmentId)]));
|
|
18
18
|
}
|
|
19
|
+
function assertWritableIdentity(value) {
|
|
20
|
+
if (!value || typeof value !== 'object' || !knownKind(value.kind))
|
|
21
|
+
throw invalid('history kind');
|
|
22
|
+
if (value.kind === 'branch_state')
|
|
23
|
+
throw invalid('branch_state is reserved for restoreActiveBranch');
|
|
24
|
+
}
|
|
19
25
|
const BRANCH_TABLE = 'lody_history_branches_v1';
|
|
20
26
|
const BRANCH_OPERATIONS = 'lody_history_branch_operations_v1';
|
|
21
27
|
function branchKey(viewId) { return encodeUtf8(text(viewId)); }
|
|
@@ -93,11 +99,12 @@ function parseBranchState(raw) {
|
|
|
93
99
|
const previous = value instanceof Map ? value.get('conflict') : undefined;
|
|
94
100
|
return { viewId: metadata.viewId, revision: metadata.revision, head: metadata.head, operationId: metadata.operationId, digest: metadata.digest, ...(metadata.logicalCount !== undefined ? { logicalCount: metadata.logicalCount } : {}), ...(previous === true ? { conflict: true } : {}) };
|
|
95
101
|
}
|
|
96
|
-
function branchOperationValue(result, digest) {
|
|
102
|
+
function branchOperationValue(result, digest, inputDigest) {
|
|
97
103
|
return encodeJson(new Map([
|
|
98
104
|
['version', '1'], ['operationId', result.operationId], ['created', result.created],
|
|
99
105
|
['oldHead', result.oldHead ? identityValue(result.oldHead) : null], ['newHead', result.newHead ? identityValue(result.newHead) : null],
|
|
100
106
|
['revision', { kind: 'u64', value: result.revision }], ['turnId', result.turnId ? hexBytes(result.turnId) : null], ['digest', digest],
|
|
107
|
+
...(inputDigest === undefined ? [] : [['inputDigest', inputDigest]]),
|
|
101
108
|
]));
|
|
102
109
|
}
|
|
103
110
|
function parseBranchOperation(raw) {
|
|
@@ -109,11 +116,14 @@ function parseBranchOperation(raw) {
|
|
|
109
116
|
throw new StoreError('corrupt', 'invalid history branch operation');
|
|
110
117
|
const oldHead = branchIdentity(value.get('oldHead'), 'history branch operation old head');
|
|
111
118
|
const newHead = branchIdentity(value.get('newHead'), 'history branch operation new head');
|
|
119
|
+
const inputDigest = value.get('inputDigest');
|
|
120
|
+
if (inputDigest !== undefined && (typeof inputDigest !== 'string' || !/^[0-9a-f]{64}$/.test(inputDigest)))
|
|
121
|
+
throw new StoreError('corrupt', 'invalid input acceptance digest');
|
|
112
122
|
if ((newHead !== null && newHead.kind !== 'message') || (oldHead !== null && oldHead.kind !== 'message'))
|
|
113
123
|
throw new StoreError('corrupt', 'invalid history branch operation head');
|
|
114
124
|
if ((turnId !== null && !/^[0-9a-f]{32}$/.test(turnId)) || !/^[0-9a-f]{64}$/.test(digest))
|
|
115
125
|
throw new StoreError('corrupt', 'invalid history branch operation encoding');
|
|
116
|
-
return { operationId: text(operationId), created, oldHead, newHead, revision: revision.value, turnId: turnId === null ? null : unhexBytes(turnId, 16), digest };
|
|
126
|
+
return { operationId: text(operationId), created, oldHead, newHead, revision: revision.value, turnId: turnId === null ? null : unhexBytes(turnId, 16), digest, ...(inputDigest === undefined ? {} : { inputDigest }) };
|
|
117
127
|
}
|
|
118
128
|
function branchMetadataFromContent(content) {
|
|
119
129
|
if (!(content instanceof Map))
|
|
@@ -256,10 +266,18 @@ function binding(raw) {
|
|
|
256
266
|
* never replaces an older signature. Dispatch/Flock and locations are host-owned. */
|
|
257
267
|
export class LodyHistory {
|
|
258
268
|
stream;
|
|
259
|
-
|
|
260
|
-
constructor(stream,
|
|
269
|
+
signingIdentity;
|
|
270
|
+
constructor(stream, signingIdentity) {
|
|
261
271
|
this.stream = stream;
|
|
262
|
-
this.
|
|
272
|
+
this.signingIdentity = signingIdentity;
|
|
273
|
+
}
|
|
274
|
+
/** A replica can project admitted history without owning a signing key.
|
|
275
|
+
* Index maintenance is local; authoring through this instance is rejected. */
|
|
276
|
+
static readOnly(stream) { return new LodyHistory(stream); }
|
|
277
|
+
get identity() {
|
|
278
|
+
if (!this.signingIdentity)
|
|
279
|
+
throw invalid('read-only history cannot author Turns');
|
|
280
|
+
return this.signingIdentity;
|
|
263
281
|
}
|
|
264
282
|
get space() { return this.stream.space('lody_history_bindings_v1'); }
|
|
265
283
|
get cursorSpace() { return this.stream.space('lody_history_index_v1'); }
|
|
@@ -363,6 +381,7 @@ export class LodyHistory {
|
|
|
363
381
|
async accept(input, options) {
|
|
364
382
|
// Own every input before the first await. The original Create fingerprint is
|
|
365
383
|
// stable even after edits; a retry must not compare against the current body.
|
|
384
|
+
assertWritableIdentity(input);
|
|
366
385
|
const key = keyOf(input), owner = this.identity.owner();
|
|
367
386
|
const rawInput = canonicalCreate(owner, input.parents, envelope(input, options?.publish !== false)), fingerprint = createDigest(owner, input.parents, envelope(input));
|
|
368
387
|
const copied = decodeFrame(rawInput);
|
|
@@ -399,10 +418,21 @@ export class LodyHistory {
|
|
|
399
418
|
acceptToView(input) {
|
|
400
419
|
return branchAccept(this, input);
|
|
401
420
|
}
|
|
421
|
+
/** Atomically bind immutable input to its first accepted branch placement. */
|
|
422
|
+
acceptInputToView(input) {
|
|
423
|
+
return acceptInputToView(this, ownBranchInput(input));
|
|
424
|
+
}
|
|
425
|
+
/** Missing means unobserved, not that an in-flight acceptance cannot commit. */
|
|
426
|
+
readInputAcceptance(input) {
|
|
427
|
+
return readInputAcceptance(this, ownInputIdentity(input));
|
|
428
|
+
}
|
|
402
429
|
/** Create a replacement Turn and switch the same logical view to it. */
|
|
403
430
|
forkAndActivate(input) {
|
|
404
431
|
return branchFork(this, input);
|
|
405
432
|
}
|
|
433
|
+
restoreActiveBranch(input) {
|
|
434
|
+
return branchRestore(this, input);
|
|
435
|
+
}
|
|
406
436
|
readActiveBranch(viewId) {
|
|
407
437
|
return readActiveBranch(this, viewId);
|
|
408
438
|
}
|
|
@@ -664,6 +694,7 @@ export class NodeLodyHistory {
|
|
|
664
694
|
}
|
|
665
695
|
async finish(id, seq) { await this.stream.seal(id, seq); }
|
|
666
696
|
async accept(input, options) {
|
|
697
|
+
assertWritableIdentity(input);
|
|
667
698
|
const key = keyOf(input), raw = canonicalCreate(this.owner, input.parents, envelope(input, options?.publish !== false)), digest = createDigest(this.owner, input.parents, envelope(input));
|
|
668
699
|
const copied = decodeFrame(raw);
|
|
669
700
|
if (copied.operation.kind !== 'create')
|
|
@@ -693,6 +724,8 @@ export class NodeLodyHistory {
|
|
|
693
724
|
throw new StoreError('stale', 'history discovery retry budget exhausted');
|
|
694
725
|
}
|
|
695
726
|
acceptToView(input) { return branchAccept(this, input); }
|
|
727
|
+
acceptInputToView(input) { return acceptInputToView(this, ownBranchInput(input)); }
|
|
728
|
+
readInputAcceptance(input) { return readInputAcceptance(this, ownInputIdentity(input)); }
|
|
696
729
|
forkAndActivate(input) { return branchFork(this, input); }
|
|
697
730
|
restoreActiveBranch(input) { return branchRestore(this, input); }
|
|
698
731
|
readActiveBranch(viewId) { return readActiveBranch(this, viewId); }
|
|
@@ -805,7 +838,7 @@ async function branchMetadataAt(host, turnId) {
|
|
|
805
838
|
return parseBranchMetadata(await publicationField(host, turnId, [{ key: 'lodyBranch' }]));
|
|
806
839
|
}
|
|
807
840
|
catch (error) {
|
|
808
|
-
if (errorCode(error) === 'invalid')
|
|
841
|
+
if (errorCode(error) === 'invalid' || errorCode(error) === 'pending')
|
|
809
842
|
return undefined;
|
|
810
843
|
throw error;
|
|
811
844
|
}
|
|
@@ -854,7 +887,53 @@ async function readBranchTurn(host, turnId) {
|
|
|
854
887
|
sealed: result.turn.sealed?.slice() ?? null,
|
|
855
888
|
};
|
|
856
889
|
}
|
|
857
|
-
|
|
890
|
+
function ownInputIdentity(input) {
|
|
891
|
+
return { viewId: text(input.viewId), operationId: text(input.operationId), input: {
|
|
892
|
+
kind: input.input.kind, businessId: text(input.input.businessId), segmentId: text(input.input.segmentId),
|
|
893
|
+
content: decodeJson(encodeJson(input.input.content)),
|
|
894
|
+
...(input.input.attachments === undefined ? {} : { attachments: input.input.attachments.map(item => ({ ...item })) }),
|
|
895
|
+
} };
|
|
896
|
+
}
|
|
897
|
+
function ownBranchInput(input) {
|
|
898
|
+
const owned = ownInputIdentity(input);
|
|
899
|
+
return { ...owned, expectedRevision: input.expectedRevision, expectedHead: input.expectedHead ? { ...input.expectedHead } : null,
|
|
900
|
+
input: { ...owned.input, parents: input.input.parents.map(parent => ({ id: parent.id.slice(), hash: parent.hash.slice() })) } };
|
|
901
|
+
}
|
|
902
|
+
async function branchOperationResult(host, operation) {
|
|
903
|
+
if (operation.newHead === null)
|
|
904
|
+
throw new StoreError('corrupt', 'branch operation head missing');
|
|
905
|
+
const turnId = operation.turnId ?? await branchTurnByIdentity(host, operation.newHead);
|
|
906
|
+
if (!turnId)
|
|
907
|
+
throw new StoreError('corrupt', 'branch operation Turn missing');
|
|
908
|
+
return { operationId: operation.operationId, created: false, oldHead: operation.oldHead, newHead: operation.newHead, revision: operation.revision, turnId };
|
|
909
|
+
}
|
|
910
|
+
async function immutableInputDigest(host, input) {
|
|
911
|
+
text(input.viewId);
|
|
912
|
+
text(input.operationId);
|
|
913
|
+
if (input.input.kind !== 'message')
|
|
914
|
+
throw invalid('input acceptance only accepts message Turns');
|
|
915
|
+
assertWritableIdentity(input.input);
|
|
916
|
+
return hexBytes(createDigest(await branchOwner(host), [], envelope({ ...input.input, parents: [] })));
|
|
917
|
+
}
|
|
918
|
+
async function readInputAcceptance(host, input) {
|
|
919
|
+
const digest = await immutableInputDigest(host, input);
|
|
920
|
+
await branchCursor(host);
|
|
921
|
+
const prior = await readBranchOperation(host, input.viewId, input.operationId);
|
|
922
|
+
if (!prior)
|
|
923
|
+
return;
|
|
924
|
+
if (prior.inputDigest !== digest)
|
|
925
|
+
throw new StoreError('conflict', 'accepted input changed');
|
|
926
|
+
return branchOperationResult(host, prior);
|
|
927
|
+
}
|
|
928
|
+
async function acceptInputToView(host, input) {
|
|
929
|
+
const digest = await immutableInputDigest(host, input);
|
|
930
|
+
const prior = await readInputAcceptance(host, input);
|
|
931
|
+
if (prior)
|
|
932
|
+
return prior;
|
|
933
|
+
const baseTurn = input.expectedHead ? await branchTurnByIdentity(host, input.expectedHead) ?? null : null;
|
|
934
|
+
return branchMutation(host, input, baseTurn, [], digest);
|
|
935
|
+
}
|
|
936
|
+
async function branchMutation(host, input, baseTurn, supersedes, inputDigest) {
|
|
858
937
|
if (input.input.kind !== 'message')
|
|
859
938
|
throw invalid('active branch only accepts message Turns');
|
|
860
939
|
if (typeof input.expectedRevision !== 'bigint' || input.expectedRevision < 0n || input.expectedRevision >= U64_MAX)
|
|
@@ -880,14 +959,21 @@ async function branchMutation(host, input, baseTurn, supersedes) {
|
|
|
880
959
|
const metadata = branchMetadataFor({ ...input, viewId, operationId, expectedHead }, owner, expectedHead, baseTurn, supersedes, logicalCount);
|
|
881
960
|
const createKey = keyOf(input.input);
|
|
882
961
|
const branchValue = branchStateValue(metadata);
|
|
883
|
-
const operationValue = branchOperationValue({ operationId, created: true, oldHead: expectedHead, newHead: metadata.head, revision: metadata.revision, turnId: null }, metadata.digest);
|
|
962
|
+
const operationValue = branchOperationValue({ operationId, created: true, oldHead: expectedHead, newHead: metadata.head, revision: metadata.revision, turnId: null }, metadata.digest, inputDigest);
|
|
884
963
|
for (let attempt = 0; attempt < 4; attempt++) {
|
|
885
|
-
|
|
964
|
+
// Fence every state read below, not only the final write. A concurrent
|
|
965
|
+
// branch mutation after these checks must invalidate this attempt.
|
|
966
|
+
const cursor = await branchCursor(host);
|
|
886
967
|
const [state, priorOperation] = await Promise.all([
|
|
887
968
|
readBranchIndex(host, viewId),
|
|
888
969
|
readBranchOperation(host, viewId, operationId),
|
|
889
970
|
]);
|
|
890
971
|
if (priorOperation) {
|
|
972
|
+
if (inputDigest !== undefined) {
|
|
973
|
+
if (priorOperation.inputDigest !== inputDigest)
|
|
974
|
+
throw new StoreError('conflict', 'accepted input changed');
|
|
975
|
+
return branchOperationResult(host, priorOperation);
|
|
976
|
+
}
|
|
891
977
|
if (priorOperation.digest !== metadata.digest || !branchStateEqual(priorOperation.oldHead, expectedHead) || !branchStateEqual(priorOperation.newHead, metadata.head))
|
|
892
978
|
throw new StoreError('conflict', 'branch operation input changed');
|
|
893
979
|
if (priorOperation.newHead === null)
|
|
@@ -910,7 +996,6 @@ async function branchMutation(host, input, baseTurn, supersedes) {
|
|
|
910
996
|
if (!existingBranch || existingBranch.operationId !== operationId || existingBranch.digest !== metadata.digest)
|
|
911
997
|
throw new StoreError('conflict', 'branch message identity already exists');
|
|
912
998
|
}
|
|
913
|
-
const cursor = await branchCursor(host);
|
|
914
999
|
try {
|
|
915
1000
|
await writeIndexed(host, [{ kind: 'createOnce', key: createKey, parents: input.input.parents, content: envelope(input.input, true, metadata) }], [
|
|
916
1001
|
{ table: BRANCH_TABLE, key: branchKey(viewId), value: branchValue, emitEvent: true },
|
|
@@ -952,6 +1037,7 @@ function branchRestoreDigest(input) {
|
|
|
952
1037
|
]))));
|
|
953
1038
|
}
|
|
954
1039
|
async function branchRestore(host, input) {
|
|
1040
|
+
await branchOwner(host);
|
|
955
1041
|
if (typeof input.expectedRevision !== 'bigint' || input.expectedRevision < 0n || input.expectedRevision >= U64_MAX)
|
|
956
1042
|
throw invalid('branch revision');
|
|
957
1043
|
const viewId = text(input.viewId), operationId = text(input.operationId), digest = branchRestoreDigest(input);
|
|
@@ -966,7 +1052,7 @@ async function branchRestore(host, input) {
|
|
|
966
1052
|
keyOf(input.restoreHead);
|
|
967
1053
|
}
|
|
968
1054
|
for (let attempt = 0; attempt < 4; attempt++) {
|
|
969
|
-
await host
|
|
1055
|
+
const cursor = await branchCursor(host);
|
|
970
1056
|
const [state, priorOperation] = await Promise.all([
|
|
971
1057
|
readBranchIndex(host, viewId),
|
|
972
1058
|
readBranchOperation(host, viewId, operationId),
|
|
@@ -1002,9 +1088,19 @@ async function branchRestore(host, input) {
|
|
|
1002
1088
|
supersedes: [],
|
|
1003
1089
|
digest,
|
|
1004
1090
|
};
|
|
1005
|
-
|
|
1091
|
+
// The branch index is only a projection. A signed native record makes a
|
|
1092
|
+
// rollback visible to remote replicas, including an empty restored view.
|
|
1093
|
+
// It is not a message and is never included in the visible transcript.
|
|
1094
|
+
const record = {
|
|
1095
|
+
kind: 'branch_state', businessId: viewId, segmentId: operationId, parents: [],
|
|
1096
|
+
content: new Map([['operation', 'restore']]),
|
|
1097
|
+
};
|
|
1098
|
+
const recordKey = keyOf(record);
|
|
1006
1099
|
try {
|
|
1007
|
-
await writeIndexed(host, [
|
|
1100
|
+
await writeIndexed(host, [
|
|
1101
|
+
{ kind: 'createOnce', key: recordKey, parents: [], content: envelope(record, false, metadata) },
|
|
1102
|
+
{ kind: 'sealOnce', key: recordKey, expectedNextSeq: 1n },
|
|
1103
|
+
], [
|
|
1008
1104
|
{ table: BRANCH_TABLE, key: branchKey(viewId), value: branchStateValue(metadata), emitEvent: true },
|
|
1009
1105
|
{ table: BRANCH_OPERATIONS, key: branchOperationKey(viewId, operationId), value: branchOperationValue({ operationId, created: true, oldHead: input.expectedHead, newHead: input.restoreHead, revision: metadata.revision, turnId: restoreTurnId ?? null }, digest) },
|
|
1010
1106
|
], cursor);
|
|
@@ -1019,7 +1115,9 @@ async function branchRestore(host, input) {
|
|
|
1019
1115
|
throw new StoreError('stale', 'active branch restore retry budget exhausted');
|
|
1020
1116
|
}
|
|
1021
1117
|
async function readActiveBranch(host, viewId) {
|
|
1022
|
-
await host
|
|
1118
|
+
return (await stableRead(host, () => readActiveBranchSnapshot(host, viewId))).value;
|
|
1119
|
+
}
|
|
1120
|
+
async function readActiveBranchSnapshot(host, viewId) {
|
|
1023
1121
|
const state = await readBranchIndex(host, viewId);
|
|
1024
1122
|
if (!state)
|
|
1025
1123
|
return { state: { viewId: text(viewId), revision: 0n, head: null, operationId: null }, messages: [], complete: true };
|
|
@@ -1104,7 +1202,7 @@ async function branchIdentityAt(host, turnId) {
|
|
|
1104
1202
|
return decodeIdentity(value);
|
|
1105
1203
|
}
|
|
1106
1204
|
catch (error) {
|
|
1107
|
-
if (errorCode(error) === 'invalid')
|
|
1205
|
+
if (errorCode(error) === 'invalid' || errorCode(error) === 'pending')
|
|
1108
1206
|
return undefined;
|
|
1109
1207
|
throw error;
|
|
1110
1208
|
}
|
|
@@ -1391,7 +1489,13 @@ async function readLinearActiveBranchPage(host, state, input, limit) {
|
|
|
1391
1489
|
}
|
|
1392
1490
|
seen.add(turnKey);
|
|
1393
1491
|
const metadata = await branchMetadataAt(host, currentId);
|
|
1394
|
-
|
|
1492
|
+
// A partial replica stops at its fetched boundary. Do not turn that into
|
|
1493
|
+
// a full-directory fallback (and a false, shorter logical count).
|
|
1494
|
+
if (!metadata) {
|
|
1495
|
+
complete = false;
|
|
1496
|
+
break;
|
|
1497
|
+
}
|
|
1498
|
+
if (metadata.viewId !== state.viewId || !metadata.head || metadata.head.kind !== 'message')
|
|
1395
1499
|
return undefined;
|
|
1396
1500
|
if (metadata.logicalCount === undefined)
|
|
1397
1501
|
return undefined;
|
|
@@ -1428,7 +1532,7 @@ async function readLinearActiveBranchPage(host, state, input, limit) {
|
|
|
1428
1532
|
const endPosition = Math.min(totalCount, input.before ? input.before.position + 1 : totalCount);
|
|
1429
1533
|
const expectedRows = Math.max(0, Math.min(limit, endPosition - startPosition));
|
|
1430
1534
|
if (selected.size !== expectedRows)
|
|
1431
|
-
|
|
1535
|
+
complete = false;
|
|
1432
1536
|
const selectedIds = new Set(selected.keys());
|
|
1433
1537
|
const segmentGroups = new Map();
|
|
1434
1538
|
for (const segment of [...collected].reverse()) {
|
|
@@ -1449,7 +1553,7 @@ async function readLinearActiveBranchPage(host, state, input, limit) {
|
|
|
1449
1553
|
totalCount,
|
|
1450
1554
|
startPosition: actualStart,
|
|
1451
1555
|
messages,
|
|
1452
|
-
hasMoreOlder: cursor !== null,
|
|
1556
|
+
hasMoreOlder: cursor !== null || (!complete && actualStart > 0),
|
|
1453
1557
|
cursor,
|
|
1454
1558
|
complete,
|
|
1455
1559
|
};
|
|
@@ -1648,6 +1752,7 @@ function decodeIdentity(value) {
|
|
|
1648
1752
|
if (typeof kind !== 'string' || !knownKind(kind) || typeof businessId !== 'string' || typeof segmentId !== 'string')
|
|
1649
1753
|
throw invalid('command identity');
|
|
1650
1754
|
const identity = { kind, businessId, segmentId };
|
|
1755
|
+
assertWritableIdentity(identity);
|
|
1651
1756
|
keyOf(identity);
|
|
1652
1757
|
return identity;
|
|
1653
1758
|
}
|
|
@@ -2214,6 +2319,11 @@ async function commitBatch(host, batchId, commands) {
|
|
|
2214
2319
|
throw invalid('batch id');
|
|
2215
2320
|
if (!commands.length || commands.length > 64)
|
|
2216
2321
|
throw invalid('batch size');
|
|
2322
|
+
for (const command of commands) {
|
|
2323
|
+
if (command.type === 'accept' || command.type === 'setContent' || command.type === 'finish') {
|
|
2324
|
+
assertWritableIdentity(command.identity);
|
|
2325
|
+
}
|
|
2326
|
+
}
|
|
2217
2327
|
await host.catchUpIndex();
|
|
2218
2328
|
const digest = commandDigest(batchId, commands);
|
|
2219
2329
|
const identity = { kind: 'batch_receipt', businessId: batchId, segmentId: 'v1' };
|
package/dist/sync/history.d.ts
CHANGED
|
@@ -201,8 +201,14 @@ export declare class HistoryReader {
|
|
|
201
201
|
* Network, receipt persistence, import and coverage marks are atomic
|
|
202
202
|
* per batch; the walk's buffer is never persisted (a crash re-walks:
|
|
203
203
|
* the fetch cost is visible in `bytesFetched`, the ledger absorbs every
|
|
204
|
-
* re-receipt).
|
|
205
|
-
|
|
204
|
+
* re-receipt). `before` continues an older window at a previously returned
|
|
205
|
+
* complete-message boundary. With `completePrefixes: false`, the report's
|
|
206
|
+
* range is a contiguous imported suffix: prefix repair is deferred to
|
|
207
|
+
* `completePrefixes`, so a pagination cursor never skips filtered messages. */
|
|
208
|
+
fetchWindow(source: BackwardByteSource, budgetBytes: number, pageLimitBytes: number, stop: StopToken, options?: {
|
|
209
|
+
before?: string;
|
|
210
|
+
completePrefixes?: boolean;
|
|
211
|
+
}): Promise<HistoryReport>;
|
|
206
212
|
/** The durable reverse-scan position for incomplete window-turn prefixes. */
|
|
207
213
|
prefixScan(): Promise<PrefixScan | undefined>;
|
|
208
214
|
/** Resume the reverse scan for pending window-turn prefixes. Each call
|
package/dist/sync/history.js
CHANGED
|
@@ -257,16 +257,19 @@ export class HistoryReader {
|
|
|
257
257
|
* Network, receipt persistence, import and coverage marks are atomic
|
|
258
258
|
* per batch; the walk's buffer is never persisted (a crash re-walks:
|
|
259
259
|
* the fetch cost is visible in `bytesFetched`, the ledger absorbs every
|
|
260
|
-
* re-receipt).
|
|
261
|
-
|
|
260
|
+
* re-receipt). `before` continues an older window at a previously returned
|
|
261
|
+
* complete-message boundary. With `completePrefixes: false`, the report's
|
|
262
|
+
* range is a contiguous imported suffix: prefix repair is deferred to
|
|
263
|
+
* `completePrefixes`, so a pagination cursor never skips filtered messages. */
|
|
264
|
+
async fetchWindow(source, budgetBytes, pageLimitBytes, stop, options = {}) {
|
|
262
265
|
try {
|
|
263
|
-
return await this.#fetchWindow(source, budgetBytes, pageLimitBytes, stop);
|
|
266
|
+
return await this.#fetchWindow(source, budgetBytes, pageLimitBytes, stop, options);
|
|
264
267
|
}
|
|
265
268
|
catch (e) {
|
|
266
269
|
return rethrow(e);
|
|
267
270
|
}
|
|
268
271
|
}
|
|
269
|
-
async #fetchWindow(source, budgetBytes, pageLimitBytes, stop) {
|
|
272
|
+
async #fetchWindow(source, budgetBytes, pageLimitBytes, stop, options) {
|
|
270
273
|
if (!await this.policy.allowsDownload(this.scope))
|
|
271
274
|
throw new HistoryError('policyDenied', 'mirror policy denies download for this scope');
|
|
272
275
|
if (pageLimitBytes === 0 || budgetBytes === 0)
|
|
@@ -288,7 +291,7 @@ export class HistoryReader {
|
|
|
288
291
|
// bytes so far, and the message offset the NEXT (older) fragment
|
|
289
292
|
// must end at.
|
|
290
293
|
let partial;
|
|
291
|
-
let from;
|
|
294
|
+
let from = options.before;
|
|
292
295
|
let tail;
|
|
293
296
|
let oldestBoundary;
|
|
294
297
|
// Turns that appeared in the budget-bounded window. After the
|
|
@@ -308,6 +311,8 @@ export class HistoryReader {
|
|
|
308
311
|
windowTurns = await turnsInWindow(this.#crypto, collected);
|
|
309
312
|
await this.#includePriorWanted(windowTurns);
|
|
310
313
|
}
|
|
314
|
+
if (options.completePrefixes === false)
|
|
315
|
+
break;
|
|
311
316
|
if (windowTurns.size === 0 || await prefixesComplete(this.#crypto, collected, windowTurns)
|
|
312
317
|
|| extraFetched >= pageLimitBytes)
|
|
313
318
|
break;
|
package/package.json
CHANGED
|
@@ -1,19 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@loro-dev/roost",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.3",
|
|
4
4
|
"description": "Browser conversation history and sync for Loro Roost",
|
|
5
5
|
"license": "MIT",
|
|
6
|
-
"publishConfig": {
|
|
7
|
-
|
|
8
|
-
"packageManager": "pnpm@12.3.4",
|
|
9
|
-
"scripts": {
|
|
10
|
-
"check": "tsc --noEmit",
|
|
11
|
-
"build": "tsc",
|
|
12
|
-
"prepack": "pnpm build",
|
|
13
|
-
"test": "pnpm build && node --test tests/*.test.mjs",
|
|
14
|
-
"pack:consumer": "pnpm build && node scripts/pack-consumer.mjs",
|
|
15
|
-
"check:consumer": "pnpm build && node scripts/check-consumer.mjs"
|
|
6
|
+
"publishConfig": {
|
|
7
|
+
"access": "public"
|
|
16
8
|
},
|
|
9
|
+
"type": "module",
|
|
17
10
|
"devDependencies": {
|
|
18
11
|
"playwright": "1.58.2",
|
|
19
12
|
"typescript": "5.9.3"
|
|
@@ -49,5 +42,12 @@
|
|
|
49
42
|
"node/client.d.mts",
|
|
50
43
|
"README.md",
|
|
51
44
|
"LICENSE"
|
|
52
|
-
]
|
|
53
|
-
|
|
45
|
+
],
|
|
46
|
+
"scripts": {
|
|
47
|
+
"check": "tsc --noEmit",
|
|
48
|
+
"build": "tsc",
|
|
49
|
+
"test": "pnpm build && node --test tests/*.test.mjs",
|
|
50
|
+
"pack:consumer": "pnpm build && node scripts/pack-consumer.mjs",
|
|
51
|
+
"check:consumer": "pnpm build && node scripts/check-consumer.mjs"
|
|
52
|
+
}
|
|
53
|
+
}
|