@loro-dev/roost 0.1.2 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +39 -1
- package/dist/lody-history.d.ts +19 -2
- package/dist/lody-history.js +143 -37
- package/package.json +13 -13
package/README.md
CHANGED
|
@@ -12,9 +12,14 @@ 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.
|
|
15
|
+
npm install @loro-dev/roost@0.2.0
|
|
16
16
|
```
|
|
17
17
|
|
|
18
|
+
This source targets the coordinated Rust/TypeScript/Native 0.2.0 release;
|
|
19
|
+
the registry determines npm availability. Native SQLite storage in
|
|
20
|
+
this release accepts fresh/v4 containers only. Preserve older databases with
|
|
21
|
+
their compatible runtime; there is no automatic migration or deletion.
|
|
22
|
+
|
|
18
23
|
For source development and browser tests:
|
|
19
24
|
|
|
20
25
|
```sh
|
|
@@ -307,6 +312,24 @@ Concurrent plans retain their original processed cursor, retrying when interveni
|
|
|
307
312
|
events invalidate their absence/revision reads. Neither this entry nor the generic
|
|
308
313
|
package automatically replaces Lody runtime storage.
|
|
309
314
|
|
|
315
|
+
`commitHistoryBatch(batchId, commands, {recovery: 'local'})` explicitly keeps
|
|
316
|
+
pending command bodies in the authoritative `lody_history_local_batch_plans_v1`
|
|
317
|
+
journal of that owner database. Preparation creates the compact pending receipt
|
|
318
|
+
and journal together. Apply commits all effects, publication references, receipt
|
|
319
|
+
seal and an empty journal tombstone together. A lost reply therefore preserves
|
|
320
|
+
either recoverable pending commands or the original committed outcome. Committed
|
|
321
|
+
receipts and their retained updates contain no command bodies. New batches also
|
|
322
|
+
omit unused baseline snapshots in both modes. No historical signed data is pruned.
|
|
323
|
+
|
|
324
|
+
The default remains `recovery: 'replicated'`, preserving recovery commands in the
|
|
325
|
+
receipt. Retries keep the first preparation's recovery mode. Local mode requires backing up the whole owner database to move unfinished
|
|
326
|
+
work; exporting Turns does not export its journal. A same-owner imported pending
|
|
327
|
+
local receipt is observed without executing or failing it, and an explicit retry
|
|
328
|
+
of that unfinished batch requires its originating database. Committed publication
|
|
329
|
+
still rebuilds from the verified seal and target references on other replicas.
|
|
330
|
+
Stop older SDKs before writing local-mode pending work; use matching browser/Node
|
|
331
|
+
revisions. This option changes the business adapter, not core wire framing or seals.
|
|
332
|
+
|
|
310
333
|
Imported messages now rebuild local publication membership during read-side
|
|
311
334
|
catch-up or `recoverPendingBatches()` (which returns `Promise<void>`). New direct
|
|
312
335
|
messages carry original Create intent; batch members and explicitly promoted
|
|
@@ -392,6 +415,21 @@ different input under that ID is a conflict. `LodyHistory` and `NodeLodyHistory`
|
|
|
392
415
|
expose the same contract. The caller still owns queue, steer and ACP lifecycle
|
|
393
416
|
decisions.
|
|
394
417
|
|
|
418
|
+
For immutable input delivery, use `acceptInputToView` with the same
|
|
419
|
+
`BranchAcceptInput` shape, then query `readInputAcceptance({ viewId, operationId,
|
|
420
|
+
input })`. Both browser and Node adapters bind an immutable input fingerprint
|
|
421
|
+
and operation receipt in the same transaction as the branch mutation. Input is
|
|
422
|
+
copied before asynchronous work begins. The fingerprint includes owner, business/segment identity, content and attachment
|
|
423
|
+
identity; the receipt key binds view and operation identity. Mutable parents,
|
|
424
|
+
expected head and revision are excluded.
|
|
425
|
+
|
|
426
|
+
Repeating an identical accept returns its original receipt even after edits,
|
|
427
|
+
later appends or active-branch removal. Changed input conflicts. Read-only lookup
|
|
428
|
+
returns `undefined` when unobserved, never inserts history, and does not prove a
|
|
429
|
+
pending accept cannot later commit. A host may retry the identical operation
|
|
430
|
+
without inventing a new input. Receipts remain owner-local derived indexes;
|
|
431
|
+
hosts own access checks, retained-generation lookup, execution and guide recovery.
|
|
432
|
+
|
|
395
433
|
`LodyHistory.readOnly(stream)` indexes and projects admitted native history without
|
|
396
434
|
a signing identity; authoring through that instance rejects. The host still owns
|
|
397
435
|
stream authorization and seal verification. `restoreActiveBranch` is available in
|
package/dist/lody-history.d.ts
CHANGED
|
@@ -50,6 +50,11 @@ export type HistoryBatchResult = {
|
|
|
50
50
|
created: boolean;
|
|
51
51
|
revision: bigint;
|
|
52
52
|
};
|
|
53
|
+
export type HistoryBatchOptions = {
|
|
54
|
+
/** Keep pending commands in this owner database instead of replicated Turns.
|
|
55
|
+
* Move unfinished work with a whole-database backup, not a Turn export. */
|
|
56
|
+
recovery?: 'replicated' | 'local';
|
|
57
|
+
};
|
|
53
58
|
export type HistoryProjectedMessage = {
|
|
54
59
|
businessId: string;
|
|
55
60
|
segmentId: string;
|
|
@@ -105,6 +110,12 @@ export type BranchAcceptInput = {
|
|
|
105
110
|
operationId: string;
|
|
106
111
|
input: AcceptHistory;
|
|
107
112
|
};
|
|
113
|
+
/** Immutable application input; branch placement is chosen by its owner. */
|
|
114
|
+
export type HistoryInputIdentity = {
|
|
115
|
+
viewId: string;
|
|
116
|
+
operationId: string;
|
|
117
|
+
input: Omit<AcceptHistory, 'parents'>;
|
|
118
|
+
};
|
|
108
119
|
export type ForkAndActivateInput = BranchAcceptInput & {
|
|
109
120
|
/** Last retained Turn. The replacement must name it as a parent when present. */
|
|
110
121
|
baseTurn: Uint8Array | null;
|
|
@@ -183,6 +194,10 @@ export declare class LodyHistory {
|
|
|
183
194
|
}>;
|
|
184
195
|
/** Append a message to an active view and advance that view atomically. */
|
|
185
196
|
acceptToView(input: BranchAcceptInput): Promise<BranchMutationResult>;
|
|
197
|
+
/** Atomically bind immutable input to its first accepted branch placement. */
|
|
198
|
+
acceptInputToView(input: BranchAcceptInput): Promise<BranchMutationResult>;
|
|
199
|
+
/** Missing means unobserved, not that an in-flight acceptance cannot commit. */
|
|
200
|
+
readInputAcceptance(input: HistoryInputIdentity): Promise<BranchMutationResult | undefined>;
|
|
186
201
|
/** Create a replacement Turn and switch the same logical view to it. */
|
|
187
202
|
forkAndActivate(input: ForkAndActivateInput): Promise<BranchMutationResult>;
|
|
188
203
|
restoreActiveBranch(input: RestoreActiveBranchInput): Promise<RestoreActiveBranchResult>;
|
|
@@ -213,7 +228,7 @@ export declare class LodyHistory {
|
|
|
213
228
|
};
|
|
214
229
|
location: string | undefined;
|
|
215
230
|
}[]>;
|
|
216
|
-
commitHistoryBatch(batchId: string, commands: HistoryBatchCommand[]): Promise<HistoryBatchResult>;
|
|
231
|
+
commitHistoryBatch(batchId: string, commands: HistoryBatchCommand[], options?: HistoryBatchOptions): Promise<HistoryBatchResult>;
|
|
217
232
|
recoverPendingBatches(): Promise<void>;
|
|
218
233
|
/** A consumer-owned cache. Call refresh on change hints (or host polling). */
|
|
219
234
|
createMessageView(limit?: number): HistoryMessageView;
|
|
@@ -418,6 +433,8 @@ export declare class NodeLodyHistory {
|
|
|
418
433
|
created: boolean;
|
|
419
434
|
}>;
|
|
420
435
|
acceptToView(input: BranchAcceptInput): Promise<BranchMutationResult>;
|
|
436
|
+
acceptInputToView(input: BranchAcceptInput): Promise<BranchMutationResult>;
|
|
437
|
+
readInputAcceptance(input: HistoryInputIdentity): Promise<BranchMutationResult | undefined>;
|
|
421
438
|
forkAndActivate(input: ForkAndActivateInput): Promise<BranchMutationResult>;
|
|
422
439
|
restoreActiveBranch(input: RestoreActiveBranchInput): Promise<RestoreActiveBranchResult>;
|
|
423
440
|
readActiveBranch(viewId: string): Promise<ActiveBranchRead>;
|
|
@@ -436,7 +453,7 @@ export declare class NodeLodyHistory {
|
|
|
436
453
|
turnId: Uint8Array;
|
|
437
454
|
created: boolean;
|
|
438
455
|
}>;
|
|
439
|
-
commitHistoryBatch(batchId: string, commands: HistoryBatchCommand[]): Promise<HistoryBatchResult>;
|
|
456
|
+
commitHistoryBatch(batchId: string, commands: HistoryBatchCommand[], options?: HistoryBatchOptions): Promise<HistoryBatchResult>;
|
|
440
457
|
recoverPendingBatches(): Promise<void>;
|
|
441
458
|
/** A consumer-owned cache. Call refresh on change hints (or host polling). */
|
|
442
459
|
createMessageView(limit?: number): HistoryMessageView;
|
package/dist/lody-history.js
CHANGED
|
@@ -99,11 +99,12 @@ function parseBranchState(raw) {
|
|
|
99
99
|
const previous = value instanceof Map ? value.get('conflict') : undefined;
|
|
100
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 } : {}) };
|
|
101
101
|
}
|
|
102
|
-
function branchOperationValue(result, digest) {
|
|
102
|
+
function branchOperationValue(result, digest, inputDigest) {
|
|
103
103
|
return encodeJson(new Map([
|
|
104
104
|
['version', '1'], ['operationId', result.operationId], ['created', result.created],
|
|
105
105
|
['oldHead', result.oldHead ? identityValue(result.oldHead) : null], ['newHead', result.newHead ? identityValue(result.newHead) : null],
|
|
106
106
|
['revision', { kind: 'u64', value: result.revision }], ['turnId', result.turnId ? hexBytes(result.turnId) : null], ['digest', digest],
|
|
107
|
+
...(inputDigest === undefined ? [] : [['inputDigest', inputDigest]]),
|
|
107
108
|
]));
|
|
108
109
|
}
|
|
109
110
|
function parseBranchOperation(raw) {
|
|
@@ -115,11 +116,14 @@ function parseBranchOperation(raw) {
|
|
|
115
116
|
throw new StoreError('corrupt', 'invalid history branch operation');
|
|
116
117
|
const oldHead = branchIdentity(value.get('oldHead'), 'history branch operation old head');
|
|
117
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');
|
|
118
122
|
if ((newHead !== null && newHead.kind !== 'message') || (oldHead !== null && oldHead.kind !== 'message'))
|
|
119
123
|
throw new StoreError('corrupt', 'invalid history branch operation head');
|
|
120
124
|
if ((turnId !== null && !/^[0-9a-f]{32}$/.test(turnId)) || !/^[0-9a-f]{64}$/.test(digest))
|
|
121
125
|
throw new StoreError('corrupt', 'invalid history branch operation encoding');
|
|
122
|
-
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 }) };
|
|
123
127
|
}
|
|
124
128
|
function branchMetadataFromContent(content) {
|
|
125
129
|
if (!(content instanceof Map))
|
|
@@ -414,6 +418,14 @@ export class LodyHistory {
|
|
|
414
418
|
acceptToView(input) {
|
|
415
419
|
return branchAccept(this, input);
|
|
416
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
|
+
}
|
|
417
429
|
/** Create a replacement Turn and switch the same logical view to it. */
|
|
418
430
|
forkAndActivate(input) {
|
|
419
431
|
return branchFork(this, input);
|
|
@@ -469,8 +481,8 @@ export class LodyHistory {
|
|
|
469
481
|
// readTurn has completed its transaction before any host Promise is invoked.
|
|
470
482
|
return Promise.all(identities.map(async (value) => ({ identity: value, location: await resolve(value) })));
|
|
471
483
|
}
|
|
472
|
-
async commitHistoryBatch(batchId, commands) {
|
|
473
|
-
return commitBatch(this, batchId, commands);
|
|
484
|
+
async commitHistoryBatch(batchId, commands, options) {
|
|
485
|
+
return commitBatch(this, batchId, commands, options);
|
|
474
486
|
}
|
|
475
487
|
recoverPendingBatches() { return recoverBatches(this); }
|
|
476
488
|
/** A consumer-owned cache. Call refresh on change hints (or host polling). */
|
|
@@ -712,6 +724,8 @@ export class NodeLodyHistory {
|
|
|
712
724
|
throw new StoreError('stale', 'history discovery retry budget exhausted');
|
|
713
725
|
}
|
|
714
726
|
acceptToView(input) { return branchAccept(this, input); }
|
|
727
|
+
acceptInputToView(input) { return acceptInputToView(this, ownBranchInput(input)); }
|
|
728
|
+
readInputAcceptance(input) { return readInputAcceptance(this, ownInputIdentity(input)); }
|
|
715
729
|
forkAndActivate(input) { return branchFork(this, input); }
|
|
716
730
|
restoreActiveBranch(input) { return branchRestore(this, input); }
|
|
717
731
|
readActiveBranch(viewId) { return readActiveBranch(this, viewId); }
|
|
@@ -736,8 +750,8 @@ export class NodeLodyHistory {
|
|
|
736
750
|
}
|
|
737
751
|
return result;
|
|
738
752
|
}
|
|
739
|
-
async commitHistoryBatch(batchId, commands) {
|
|
740
|
-
return commitBatch(this, batchId, commands);
|
|
753
|
+
async commitHistoryBatch(batchId, commands, options) {
|
|
754
|
+
return commitBatch(this, batchId, commands, options);
|
|
741
755
|
}
|
|
742
756
|
recoverPendingBatches() { return recoverBatches(this); }
|
|
743
757
|
/** A consumer-owned cache. Call refresh on change hints (or host polling). */
|
|
@@ -873,7 +887,53 @@ async function readBranchTurn(host, turnId) {
|
|
|
873
887
|
sealed: result.turn.sealed?.slice() ?? null,
|
|
874
888
|
};
|
|
875
889
|
}
|
|
876
|
-
|
|
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) {
|
|
877
937
|
if (input.input.kind !== 'message')
|
|
878
938
|
throw invalid('active branch only accepts message Turns');
|
|
879
939
|
if (typeof input.expectedRevision !== 'bigint' || input.expectedRevision < 0n || input.expectedRevision >= U64_MAX)
|
|
@@ -899,7 +959,7 @@ async function branchMutation(host, input, baseTurn, supersedes) {
|
|
|
899
959
|
const metadata = branchMetadataFor({ ...input, viewId, operationId, expectedHead }, owner, expectedHead, baseTurn, supersedes, logicalCount);
|
|
900
960
|
const createKey = keyOf(input.input);
|
|
901
961
|
const branchValue = branchStateValue(metadata);
|
|
902
|
-
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);
|
|
903
963
|
for (let attempt = 0; attempt < 4; attempt++) {
|
|
904
964
|
// Fence every state read below, not only the final write. A concurrent
|
|
905
965
|
// branch mutation after these checks must invalidate this attempt.
|
|
@@ -909,6 +969,11 @@ async function branchMutation(host, input, baseTurn, supersedes) {
|
|
|
909
969
|
readBranchOperation(host, viewId, operationId),
|
|
910
970
|
]);
|
|
911
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
|
+
}
|
|
912
977
|
if (priorOperation.digest !== metadata.digest || !branchStateEqual(priorOperation.oldHead, expectedHead) || !branchStateEqual(priorOperation.newHead, metadata.head))
|
|
913
978
|
throw new StoreError('conflict', 'branch operation input changed');
|
|
914
979
|
if (priorOperation.newHead === null)
|
|
@@ -1795,9 +1860,6 @@ async function readFound(host, id) {
|
|
|
1795
1860
|
return;
|
|
1796
1861
|
return { turnId: result.turn.turnId.slice(), nextSeq: result.turn.nextSeq, sealed: !!result.turn.sealed, inner: envelope.get('content') };
|
|
1797
1862
|
}
|
|
1798
|
-
function encodeProjected(row) {
|
|
1799
|
-
return new Map([['businessId', row.businessId], ['segmentId', row.segmentId], ['turnId', hexBytes(row.turnId)], ['nextSeq', { kind: 'u64', value: row.nextSeq }], ['sealed', row.sealed], ['content', row.content], ['parents', row.parents.map(parentValue)], ['sealedHash', row.sealedHash ? hexBytes(row.sealedHash) : null]]);
|
|
1800
|
-
}
|
|
1801
1863
|
// Membership is durable; content and revision belong to the Turn. Legacy v1
|
|
1802
1864
|
// rows containing full snapshots remain readable, without a migration scan.
|
|
1803
1865
|
function projectedValue(row) {
|
|
@@ -2035,26 +2097,6 @@ async function stableRead(host, read) {
|
|
|
2035
2097
|
}
|
|
2036
2098
|
throw new StoreError('stale', 'history read retry budget exhausted');
|
|
2037
2099
|
}
|
|
2038
|
-
async function captureBases(host, commands) {
|
|
2039
|
-
const seen = new Set(), bases = [];
|
|
2040
|
-
for (const command of commands) {
|
|
2041
|
-
if ((command.type !== 'setContent' && command.type !== 'finish') || command.identity.kind !== 'message')
|
|
2042
|
-
continue;
|
|
2043
|
-
const key = messageKey(command.identity.businessId, command.identity.segmentId);
|
|
2044
|
-
if (seen.has(key))
|
|
2045
|
-
continue;
|
|
2046
|
-
seen.add(key);
|
|
2047
|
-
const published = await lookupPublished(host, command.identity);
|
|
2048
|
-
if (published) {
|
|
2049
|
-
bases.push(published);
|
|
2050
|
-
continue;
|
|
2051
|
-
}
|
|
2052
|
-
const found = await readFound(host, command.identity);
|
|
2053
|
-
if (found?.inner !== undefined)
|
|
2054
|
-
bases.push({ businessId: command.identity.businessId, segmentId: command.identity.segmentId, turnId: found.turnId, content: found.inner, nextSeq: found.nextSeq, sealed: found.sealed, parents: [], sealedHash: null });
|
|
2055
|
-
}
|
|
2056
|
-
return bases;
|
|
2057
|
-
}
|
|
2058
2100
|
async function messageEndStates(host, commands) {
|
|
2059
2101
|
const seen = new Set(), rows = [];
|
|
2060
2102
|
for (const command of commands) {
|
|
@@ -2084,6 +2126,14 @@ async function markFailed(host, identity, code) {
|
|
|
2084
2126
|
if (!found || found.sealed)
|
|
2085
2127
|
return;
|
|
2086
2128
|
try {
|
|
2129
|
+
if (found.inner instanceof Map && found.inner.get('recovery') === 'local-v1') {
|
|
2130
|
+
await writeIndexed(host, [
|
|
2131
|
+
{ kind: 'editPath', turnId: found.turnId, expectedNextSeq: found.nextSeq, path: [{ key: 'content' }, { key: 'status' }], value: 'failed' },
|
|
2132
|
+
{ kind: 'editPath', turnId: found.turnId, expectedNextSeq: found.nextSeq + 1n, path: [{ key: 'content' }, { key: 'error' }], value: code },
|
|
2133
|
+
{ kind: 'seal', turnId: found.turnId, expectedNextSeq: found.nextSeq + 2n },
|
|
2134
|
+
], [{ table: LOCAL_BATCH_PLANS, key: keyOf(identity), value: new Uint8Array() }]);
|
|
2135
|
+
return;
|
|
2136
|
+
}
|
|
2087
2137
|
await patchReceipt(host, identity, [{ key: 'status' }], 'failed');
|
|
2088
2138
|
await patchReceipt(host, identity, [{ key: 'error' }], code);
|
|
2089
2139
|
const next = await readFound(host, identity);
|
|
@@ -2222,6 +2272,9 @@ async function collectBatchWrites(host, identity, commands, applied) {
|
|
|
2222
2272
|
refs.push({ businessId: row.businessId, segmentId: row.segmentId, digest, nextSeq: row.nextSeq.toString(), sealed: row.sealed, ...(row.onceKey ? {} : { turnId: hexBytes(row.turnId) }) });
|
|
2223
2273
|
}
|
|
2224
2274
|
puts.push({ table: PUBLICATION_DONE, key: receipt.turnId, value: encodeUtf8('1') });
|
|
2275
|
+
if (receipt.inner instanceof Map && receipt.inner.get('recovery') === 'local-v1') {
|
|
2276
|
+
puts.push({ table: LOCAL_BATCH_PLANS, key: keyOf(identity), value: new Uint8Array() });
|
|
2277
|
+
}
|
|
2225
2278
|
writes.push({ kind: 'editPath', turnId: receipt.turnId, expectedNextSeq: receipt.nextSeq, path: [{ key: 'content' }, { key: 'applied' }], value: { kind: 'u64', value: BigInt(commands.length) } });
|
|
2226
2279
|
writes.push({ kind: 'editPath', turnId: receipt.turnId, expectedNextSeq: receipt.nextSeq + 1n, path: [{ key: 'content' }, { key: 'published' }], value: publicationValue(refs) });
|
|
2227
2280
|
writes.push({ kind: 'editPath', turnId: receipt.turnId, expectedNextSeq: receipt.nextSeq + 2n, path: [{ key: 'content' }, { key: 'status' }], value: 'committed' });
|
|
@@ -2249,11 +2302,32 @@ async function runBatchCommands(host, identity, commands, applied) {
|
|
|
2249
2302
|
}
|
|
2250
2303
|
throw lastStale ?? new StoreError('stale', 'batch apply retry budget exhausted');
|
|
2251
2304
|
}
|
|
2252
|
-
|
|
2305
|
+
const LOCAL_BATCH_PLANS = 'lody_history_local_batch_plans_v1';
|
|
2306
|
+
async function prepareLocalBatch(host, identity, digest, commands) {
|
|
2307
|
+
const content = new Map([['status', 'pending'], ['digest', hexBytes(digest)], ['recovery', 'local-v1'], ['applied', { kind: 'u64', value: 0n }]]);
|
|
2308
|
+
const plan = encodeJson(new Map([['version', '1'], ['digest', hexBytes(digest)], ['commands', encodeCommands(commands)]]));
|
|
2309
|
+
for (let attempt = 0; attempt < 4; attempt++) {
|
|
2310
|
+
const cursor = await host.observedEventCursor();
|
|
2311
|
+
if (await readFound(host, identity))
|
|
2312
|
+
return false;
|
|
2313
|
+
try {
|
|
2314
|
+
await writeIndexed(host, [{ kind: 'createOnce', key: keyOf(identity), parents: [], content: envelope({ ...identity, parents: [], content }) }], [{ table: LOCAL_BATCH_PLANS, key: keyOf(identity), value: plan }], cursor);
|
|
2315
|
+
return true;
|
|
2316
|
+
}
|
|
2317
|
+
catch (error) {
|
|
2318
|
+
if (errorCode(error) !== 'stale')
|
|
2319
|
+
throw error;
|
|
2320
|
+
}
|
|
2321
|
+
}
|
|
2322
|
+
throw new StoreError('stale', 'batch prepare retry budget exhausted');
|
|
2323
|
+
}
|
|
2324
|
+
async function commitBatch(host, batchId, commands, options) {
|
|
2253
2325
|
if (!batchId.length || encodeUtf8(batchId).length > 1024)
|
|
2254
2326
|
throw invalid('batch id');
|
|
2255
2327
|
if (!commands.length || commands.length > 64)
|
|
2256
2328
|
throw invalid('batch size');
|
|
2329
|
+
if (options?.recovery !== undefined && options.recovery !== 'replicated' && options.recovery !== 'local')
|
|
2330
|
+
throw invalid('batch recovery mode');
|
|
2257
2331
|
for (const command of commands) {
|
|
2258
2332
|
if (command.type === 'accept' || command.type === 'setContent' || command.type === 'finish') {
|
|
2259
2333
|
assertWritableIdentity(command.identity);
|
|
@@ -2265,10 +2339,13 @@ async function commitBatch(host, batchId, commands) {
|
|
|
2265
2339
|
let existing = await readFound(host, identity);
|
|
2266
2340
|
let created = false;
|
|
2267
2341
|
if (!existing) {
|
|
2268
|
-
|
|
2269
|
-
|
|
2270
|
-
|
|
2271
|
-
|
|
2342
|
+
if (options?.recovery === 'local')
|
|
2343
|
+
created = await prepareLocalBatch(host, identity, digest, commands);
|
|
2344
|
+
else {
|
|
2345
|
+
const receiptContent = new Map([['status', 'pending'], ['digest', hexBytes(digest)], ['commands', encodeCommands(commands)], ['applied', { kind: 'u64', value: 0n }]]);
|
|
2346
|
+
const receipt = await host.accept({ ...identity, parents: [], content: receiptContent }, { publish: false });
|
|
2347
|
+
created = receipt.created;
|
|
2348
|
+
}
|
|
2272
2349
|
existing = await readFound(host, identity);
|
|
2273
2350
|
}
|
|
2274
2351
|
if (!existing)
|
|
@@ -2281,6 +2358,11 @@ async function commitBatch(host, batchId, commands) {
|
|
|
2281
2358
|
return { batchId, created: false, revision: existing.nextSeq };
|
|
2282
2359
|
if (status === 'failed')
|
|
2283
2360
|
throw new StoreError('invalid', 'batch previously failed');
|
|
2361
|
+
if (existing.inner instanceof Map && existing.inner.get('recovery') === 'local-v1') {
|
|
2362
|
+
const [plan] = await indexValues(host, [{ table: LOCAL_BATCH_PLANS, key: keyOf(identity) }]);
|
|
2363
|
+
if (plan === null)
|
|
2364
|
+
throw invalid('unfinished local batch belongs to its originating owner database');
|
|
2365
|
+
}
|
|
2284
2366
|
const applied = existing.inner instanceof Map && existing.inner.get('applied') !== undefined ? Number(seqOf(existing.inner.get('applied'))) : 0;
|
|
2285
2367
|
try {
|
|
2286
2368
|
await runBatchCommands(host, identity, commands, applied);
|
|
@@ -2310,7 +2392,31 @@ async function recoverBatches(host) {
|
|
|
2310
2392
|
const status = found.inner.get('status');
|
|
2311
2393
|
if (status === 'failed' || status === 'committed')
|
|
2312
2394
|
continue;
|
|
2313
|
-
const digest = found.inner.get('digest')
|
|
2395
|
+
const digest = found.inner.get('digest');
|
|
2396
|
+
let encoded = found.inner.get('commands');
|
|
2397
|
+
if (found.inner.get('recovery') === 'local-v1') {
|
|
2398
|
+
const [raw] = await indexValues(host, [{ table: LOCAL_BATCH_PLANS, key: keyOf(row.identity) }]);
|
|
2399
|
+
// Same-owner imports have no authority to execute this database's work.
|
|
2400
|
+
// Only a preparation transaction in this database creates a local plan.
|
|
2401
|
+
if (raw === null)
|
|
2402
|
+
continue;
|
|
2403
|
+
if (raw.length === 0) {
|
|
2404
|
+
// Another caller may have retired the plan after our pending read.
|
|
2405
|
+
// Only this exceptional path rereads the compact receipt; ordinary
|
|
2406
|
+
// recovery and sends retain their existing reads and writes.
|
|
2407
|
+
const current = await readFound(host, row.identity), inner = current?.inner;
|
|
2408
|
+
if (!current?.sealed || !equal(current.turnId, found.turnId) ||
|
|
2409
|
+
!(inner instanceof Map) || typeof digest !== 'string' || inner.get('digest') !== digest ||
|
|
2410
|
+
inner.get('recovery') !== 'local-v1' || (inner.get('status') !== 'committed' && inner.get('status') !== 'failed')) {
|
|
2411
|
+
throw new StoreError('corrupt', 'retired local batch has no matching terminal receipt');
|
|
2412
|
+
}
|
|
2413
|
+
continue;
|
|
2414
|
+
}
|
|
2415
|
+
const plan = asMap(decodeJson(raw), 'local batch plan');
|
|
2416
|
+
if (plan.get('version') !== '1' || plan.get('digest') !== digest)
|
|
2417
|
+
throw new StoreError('corrupt', 'local batch recovery plan mismatch');
|
|
2418
|
+
encoded = plan.get('commands');
|
|
2419
|
+
}
|
|
2314
2420
|
if (typeof digest !== 'string' || encoded === undefined) {
|
|
2315
2421
|
await markFailed(host, row.identity, 'invalid');
|
|
2316
2422
|
continue;
|
package/package.json
CHANGED
|
@@ -1,19 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@loro-dev/roost",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
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
|
+
}
|