@loro-dev/roost 0.1.3 → 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 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.1.3
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
@@ -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;
@@ -223,7 +228,7 @@ export declare class LodyHistory {
223
228
  };
224
229
  location: string | undefined;
225
230
  }[]>;
226
- commitHistoryBatch(batchId: string, commands: HistoryBatchCommand[]): Promise<HistoryBatchResult>;
231
+ commitHistoryBatch(batchId: string, commands: HistoryBatchCommand[], options?: HistoryBatchOptions): Promise<HistoryBatchResult>;
227
232
  recoverPendingBatches(): Promise<void>;
228
233
  /** A consumer-owned cache. Call refresh on change hints (or host polling). */
229
234
  createMessageView(limit?: number): HistoryMessageView;
@@ -448,7 +453,7 @@ export declare class NodeLodyHistory {
448
453
  turnId: Uint8Array;
449
454
  created: boolean;
450
455
  }>;
451
- commitHistoryBatch(batchId: string, commands: HistoryBatchCommand[]): Promise<HistoryBatchResult>;
456
+ commitHistoryBatch(batchId: string, commands: HistoryBatchCommand[], options?: HistoryBatchOptions): Promise<HistoryBatchResult>;
452
457
  recoverPendingBatches(): Promise<void>;
453
458
  /** A consumer-owned cache. Call refresh on change hints (or host polling). */
454
459
  createMessageView(limit?: number): HistoryMessageView;
@@ -481,8 +481,8 @@ export class LodyHistory {
481
481
  // readTurn has completed its transaction before any host Promise is invoked.
482
482
  return Promise.all(identities.map(async (value) => ({ identity: value, location: await resolve(value) })));
483
483
  }
484
- async commitHistoryBatch(batchId, commands) {
485
- return commitBatch(this, batchId, commands);
484
+ async commitHistoryBatch(batchId, commands, options) {
485
+ return commitBatch(this, batchId, commands, options);
486
486
  }
487
487
  recoverPendingBatches() { return recoverBatches(this); }
488
488
  /** A consumer-owned cache. Call refresh on change hints (or host polling). */
@@ -750,8 +750,8 @@ export class NodeLodyHistory {
750
750
  }
751
751
  return result;
752
752
  }
753
- async commitHistoryBatch(batchId, commands) {
754
- return commitBatch(this, batchId, commands);
753
+ async commitHistoryBatch(batchId, commands, options) {
754
+ return commitBatch(this, batchId, commands, options);
755
755
  }
756
756
  recoverPendingBatches() { return recoverBatches(this); }
757
757
  /** A consumer-owned cache. Call refresh on change hints (or host polling). */
@@ -1860,9 +1860,6 @@ async function readFound(host, id) {
1860
1860
  return;
1861
1861
  return { turnId: result.turn.turnId.slice(), nextSeq: result.turn.nextSeq, sealed: !!result.turn.sealed, inner: envelope.get('content') };
1862
1862
  }
1863
- function encodeProjected(row) {
1864
- 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]]);
1865
- }
1866
1863
  // Membership is durable; content and revision belong to the Turn. Legacy v1
1867
1864
  // rows containing full snapshots remain readable, without a migration scan.
1868
1865
  function projectedValue(row) {
@@ -2100,26 +2097,6 @@ async function stableRead(host, read) {
2100
2097
  }
2101
2098
  throw new StoreError('stale', 'history read retry budget exhausted');
2102
2099
  }
2103
- async function captureBases(host, commands) {
2104
- const seen = new Set(), bases = [];
2105
- for (const command of commands) {
2106
- if ((command.type !== 'setContent' && command.type !== 'finish') || command.identity.kind !== 'message')
2107
- continue;
2108
- const key = messageKey(command.identity.businessId, command.identity.segmentId);
2109
- if (seen.has(key))
2110
- continue;
2111
- seen.add(key);
2112
- const published = await lookupPublished(host, command.identity);
2113
- if (published) {
2114
- bases.push(published);
2115
- continue;
2116
- }
2117
- const found = await readFound(host, command.identity);
2118
- if (found?.inner !== undefined)
2119
- 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 });
2120
- }
2121
- return bases;
2122
- }
2123
2100
  async function messageEndStates(host, commands) {
2124
2101
  const seen = new Set(), rows = [];
2125
2102
  for (const command of commands) {
@@ -2149,6 +2126,14 @@ async function markFailed(host, identity, code) {
2149
2126
  if (!found || found.sealed)
2150
2127
  return;
2151
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
+ }
2152
2137
  await patchReceipt(host, identity, [{ key: 'status' }], 'failed');
2153
2138
  await patchReceipt(host, identity, [{ key: 'error' }], code);
2154
2139
  const next = await readFound(host, identity);
@@ -2287,6 +2272,9 @@ async function collectBatchWrites(host, identity, commands, applied) {
2287
2272
  refs.push({ businessId: row.businessId, segmentId: row.segmentId, digest, nextSeq: row.nextSeq.toString(), sealed: row.sealed, ...(row.onceKey ? {} : { turnId: hexBytes(row.turnId) }) });
2288
2273
  }
2289
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
+ }
2290
2278
  writes.push({ kind: 'editPath', turnId: receipt.turnId, expectedNextSeq: receipt.nextSeq, path: [{ key: 'content' }, { key: 'applied' }], value: { kind: 'u64', value: BigInt(commands.length) } });
2291
2279
  writes.push({ kind: 'editPath', turnId: receipt.turnId, expectedNextSeq: receipt.nextSeq + 1n, path: [{ key: 'content' }, { key: 'published' }], value: publicationValue(refs) });
2292
2280
  writes.push({ kind: 'editPath', turnId: receipt.turnId, expectedNextSeq: receipt.nextSeq + 2n, path: [{ key: 'content' }, { key: 'status' }], value: 'committed' });
@@ -2314,11 +2302,32 @@ async function runBatchCommands(host, identity, commands, applied) {
2314
2302
  }
2315
2303
  throw lastStale ?? new StoreError('stale', 'batch apply retry budget exhausted');
2316
2304
  }
2317
- async function commitBatch(host, batchId, commands) {
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) {
2318
2325
  if (!batchId.length || encodeUtf8(batchId).length > 1024)
2319
2326
  throw invalid('batch id');
2320
2327
  if (!commands.length || commands.length > 64)
2321
2328
  throw invalid('batch size');
2329
+ if (options?.recovery !== undefined && options.recovery !== 'replicated' && options.recovery !== 'local')
2330
+ throw invalid('batch recovery mode');
2322
2331
  for (const command of commands) {
2323
2332
  if (command.type === 'accept' || command.type === 'setContent' || command.type === 'finish') {
2324
2333
  assertWritableIdentity(command.identity);
@@ -2330,10 +2339,13 @@ async function commitBatch(host, batchId, commands) {
2330
2339
  let existing = await readFound(host, identity);
2331
2340
  let created = false;
2332
2341
  if (!existing) {
2333
- const bases = await captureBases(host, commands);
2334
- const receiptContent = new Map([['status', 'pending'], ['digest', hexBytes(digest)], ['commands', encodeCommands(commands)], ['bases', bases.map(encodeProjected)], ['applied', { kind: 'u64', value: 0n }]]);
2335
- const receipt = await host.accept({ ...identity, parents: [], content: receiptContent }, { publish: false });
2336
- created = receipt.created;
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
+ }
2337
2349
  existing = await readFound(host, identity);
2338
2350
  }
2339
2351
  if (!existing)
@@ -2346,6 +2358,11 @@ async function commitBatch(host, batchId, commands) {
2346
2358
  return { batchId, created: false, revision: existing.nextSeq };
2347
2359
  if (status === 'failed')
2348
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
+ }
2349
2366
  const applied = existing.inner instanceof Map && existing.inner.get('applied') !== undefined ? Number(seqOf(existing.inner.get('applied'))) : 0;
2350
2367
  try {
2351
2368
  await runBatchCommands(host, identity, commands, applied);
@@ -2375,7 +2392,31 @@ async function recoverBatches(host) {
2375
2392
  const status = found.inner.get('status');
2376
2393
  if (status === 'failed' || status === 'committed')
2377
2394
  continue;
2378
- const digest = found.inner.get('digest'), encoded = found.inner.get('commands');
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
+ }
2379
2420
  if (typeof digest !== 'string' || encoded === undefined) {
2380
2421
  await markFailed(host, row.identity, 'invalid');
2381
2422
  continue;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@loro-dev/roost",
3
- "version": "0.1.3",
3
+ "version": "0.2.0",
4
4
  "description": "Browser conversation history and sync for Loro Roost",
5
5
  "license": "MIT",
6
6
  "publishConfig": {