@loro-dev/roost 0.3.2 → 0.4.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/dist/sync/work.js CHANGED
@@ -1,5 +1,6 @@
1
+ import { MAX_FRAME, MAX_UPDATES, splitBatch } from '../codec.js';
1
2
  import { decodeUtf8, encodeUtf8 } from '../json.js';
2
- import { generationIn, generationKeyFragment } from './registry.js';
3
+ import { GenerationSource, generationIn, generationKeyFragment } from './registry.js';
3
4
  import { CoverageError, CoverageStore } from './coverage.js';
4
5
  /**
5
6
  * Durable send tasks and discovery progress for remote sync (RS2-02), the
@@ -88,13 +89,21 @@ export const STATUS_INDEX_MARKER_TAG = 0x07;
88
89
  /** Open-turn record keys (G009). */
89
90
  export const OPEN_TURN_KEY_TAG = 0x08;
90
91
  export const OPEN_INDEX_MARKER_TAG = 0x09;
91
- /** Maximum frozen bytes of one task's package. */
92
- export const MAX_TASK_BYTES = 1 << 20;
92
+ /** Maximum frozen bytes of one task's package (accommodates MAX_FRAME plus single-frame RST1 header). */
93
+ export const MAX_TASK_BYTES = MAX_FRAME + 16;
93
94
  /** Maximum direct dependencies recorded on one task (cross-turn parent refs
94
95
  * plus one same-turn predecessor — never the turn's length, L010). */
95
96
  export const MAX_TASK_DEPS = 4096;
96
97
  /** Maximum waiters tracked per dependency. */
97
98
  export const MAX_WAITERS_PER_DEP = 1 << 20;
99
+ /** Build a logical host-carried sync scope with empty app-marker generation. */
100
+ export function logicalWorkScope(remote, stream) {
101
+ return {
102
+ remote: remote.slice(),
103
+ generation: { bytes: new Uint8Array(), source: GenerationSource.AppMarker },
104
+ stream,
105
+ };
106
+ }
98
107
  /** Errors returned by WorkStore. `code` mirrors the Rust WorkError variants;
99
108
  * `cause` carries structured fields where the Rust variant has them. Native
100
109
  * IDB failures propagate as DOMExceptions, as in the registry. */
@@ -1017,6 +1026,246 @@ export class WorkStore {
1017
1026
  }
1018
1027
  return true;
1019
1028
  }
1029
+ *depsSatisfiedWithBatchIn(tx, scope, dto, inBatchOps, inBatchPrefix, inBatchCompleteSeals) {
1030
+ const turn = Uint8Array.from(dto.turn);
1031
+ const turnHex = hex(turn);
1032
+ const persistedUpto = yield* prefixSatisfiedIn(tx, scope, turn);
1033
+ const batchUpto = inBatchPrefix.get(turnHex);
1034
+ const effectiveUpto = persistedUpto === undefined
1035
+ ? batchUpto
1036
+ : batchUpto === undefined
1037
+ ? persistedUpto
1038
+ : Math.max(persistedUpto, batchUpto);
1039
+ if (dto.seq > 0 && (effectiveUpto === undefined || effectiveUpto < dto.seq - 1))
1040
+ return { ok: false };
1041
+ for (const dep of dto.deps) {
1042
+ const depTurn = Uint8Array.from(dep.turn);
1043
+ const depTurnHex = hex(depTurn);
1044
+ const depFp = Uint8Array.from(dep.fp);
1045
+ const depFpHex = hex(depFp);
1046
+ const ok = depTurnHex === turnHex
1047
+ ? inBatchOps.has(`${depTurnHex}:${dep.seq}:${depFpHex}`)
1048
+ || (yield* this.coverage.presentExactIn(tx, scope, depTurn, dep.seq, depFp))
1049
+ : inBatchCompleteSeals.get(depTurnHex) === depFpHex
1050
+ || (yield* this.coverage.parentAdmissibleIn(tx, scope, depTurn, depFp));
1051
+ if (!ok)
1052
+ return { ok: false };
1053
+ }
1054
+ for (const parent of dto.parents) {
1055
+ const parentTurn = Uint8Array.from(parent.turn);
1056
+ const parentTurnHex = hex(parentTurn);
1057
+ const sealFp = Uint8Array.from(parent.seal_fp);
1058
+ const sealFpHex = hex(sealFp);
1059
+ const ok = inBatchCompleteSeals.get(parentTurnHex) === sealFpHex
1060
+ || (yield* this.coverage.parentAdmissibleIn(tx, scope, parentTurn, sealFp));
1061
+ if (!ok)
1062
+ return { ok: false };
1063
+ }
1064
+ return { ok: true, effectiveUpto };
1065
+ }
1066
+ /** Freeze a topologically ordered batch of runnable tasks for one atomic
1067
+ * host-carried append (`encodeItems` budget: `Σ(4 + rawFrame.length) <= maxBytes`). */
1068
+ async acquireBatch(scope, maxBytes, maxItems) {
1069
+ if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0)
1070
+ throw invalid('maxBytes must be positive');
1071
+ if (!Number.isSafeInteger(maxItems) || maxItems <= 0)
1072
+ throw invalid('maxItems must be positive');
1073
+ const clampedItems = Math.min(maxItems, MAX_UPDATES);
1074
+ const self = this;
1075
+ const coverage = this.coverage;
1076
+ return this.storage.transact(true, function* (tx) {
1077
+ if (!(yield* orderedCandidatesReady(tx, scope))) {
1078
+ if (!(yield* statusIndexReady(tx, scope)))
1079
+ yield* buildStatusIndex(tx, scope);
1080
+ for (const status of ['ready', 'inflight']) {
1081
+ const pfx = statusIndexPrefix(scope, statusTag(status));
1082
+ let s = pfx;
1083
+ for (;;) {
1084
+ const rows = yield* tx.scan(WORK_SPACE, s, successor(pfx), 1000);
1085
+ if (!rows.length)
1086
+ break;
1087
+ for (const [, value] of rows) {
1088
+ if (value.length !== 20)
1089
+ throw corrupt('invalid status index value');
1090
+ yield* tx.put(WORK_SPACE, cat(orderedCandidatePrefix(scope), value), new Uint8Array());
1091
+ }
1092
+ s = cat(rows[rows.length - 1][0], Uint8Array.of(0));
1093
+ }
1094
+ }
1095
+ yield* tx.put(WORK_SPACE, orderedCandidateMarker(scope), Uint8Array.of(RECORD_VERSION));
1096
+ }
1097
+ const prefix = orderedCandidatePrefix(scope);
1098
+ const end = successor(prefix);
1099
+ let start = prefix;
1100
+ const selected = [];
1101
+ let usedBytes = 0;
1102
+ const inBatchOps = new Set();
1103
+ const inBatchPrefix = new Map();
1104
+ const inBatchCompleteSeals = new Map();
1105
+ scanLoop: for (;;) {
1106
+ const rows = yield* tx.scan(WORK_SPACE, start, end, 512);
1107
+ if (!rows.length)
1108
+ break;
1109
+ const lastKey = rows[rows.length - 1][0];
1110
+ for (const [key, value] of rows) {
1111
+ if (key.length !== prefix.length + 20 || value.length !== 0)
1112
+ throw corrupt('invalid ordered candidate row');
1113
+ const task = refFromIndexRow(key.slice(prefix.length));
1114
+ const dto = yield* self.loadTask(tx, scope, task);
1115
+ if (dto === undefined)
1116
+ throw corrupt('ordered candidate without task');
1117
+ if (dto.status !== 'ready' && dto.status !== 'inflight')
1118
+ throw corrupt('ordered candidate status mismatch');
1119
+ const fp = Uint8Array.from(dto.fingerprint);
1120
+ if (yield* coverage.presentExactIn(tx, scope, task.turn, task.seq, fp)) {
1121
+ const previous = dto.status;
1122
+ yield* advancePrefixIn(tx, scope, coverage, task.turn);
1123
+ if (dto.attempts === 0)
1124
+ dto.adopted = true;
1125
+ dto.status = 'done';
1126
+ yield* tx.put(WORK_SPACE, taskKey(scope, task), encode(dto));
1127
+ yield* statusIndexUpdate(tx, scope, dto.task_seq, task, previous, 'done');
1128
+ for (const dep of dto.deps)
1129
+ yield* waitRemove(tx, scope, { turn: Uint8Array.from(dep.turn), seq: dep.seq }, task);
1130
+ continue;
1131
+ }
1132
+ const check = yield* self.depsSatisfiedWithBatchIn(tx, scope, dto, inBatchOps, inBatchPrefix, inBatchCompleteSeals);
1133
+ if (!check.ok)
1134
+ continue;
1135
+ if (dto.bytes === null)
1136
+ throw corrupt('invariant: non-pending tasks carry frozen bytes');
1137
+ const batchBytes = Uint8Array.from(dto.bytes);
1138
+ let frames;
1139
+ try {
1140
+ frames = splitBatch(batchBytes);
1141
+ }
1142
+ catch (e) {
1143
+ throw corrupt(`task frozen batch invalid: ${e instanceof Error ? e.message : e}`);
1144
+ }
1145
+ if (frames.length !== 1)
1146
+ throw corrupt('task frozen batch must contain one frame');
1147
+ const itemBytes = 4 + frames[0].length;
1148
+ if (usedBytes + itemBytes > maxBytes) {
1149
+ if (selected.length === 0)
1150
+ throw invalid('next frame exceeds batch byte limit');
1151
+ break scanLoop;
1152
+ }
1153
+ const previous = dto.status;
1154
+ dto.attempts += 1;
1155
+ dto.status = 'inflight';
1156
+ const attempt = dto.attempts;
1157
+ yield* tx.put(WORK_SPACE, taskKey(scope, task), encode(dto));
1158
+ yield* statusIndexUpdate(tx, scope, dto.task_seq, task, previous, 'inflight');
1159
+ usedBytes += itemBytes;
1160
+ const turnHex = hex(task.turn);
1161
+ const fpHex = hex(fp);
1162
+ inBatchOps.add(`${turnHex}:${task.seq}:${fpHex}`);
1163
+ const nextUpto = check.effectiveUpto === undefined ? task.seq : Math.max(check.effectiveUpto, task.seq);
1164
+ inBatchPrefix.set(turnHex, nextUpto);
1165
+ if (dto.is_seal)
1166
+ inBatchCompleteSeals.set(turnHex, fpHex);
1167
+ selected.push({
1168
+ token: { scope, task: { turn: task.turn.slice(), seq: task.seq }, attempt },
1169
+ fingerprint: fp,
1170
+ deps: dto.deps.map(dep => ({ turn: Uint8Array.from(dep.turn), seq: dep.seq, fingerprint: Uint8Array.from(dep.fp) })),
1171
+ bytes: batchBytes,
1172
+ wire: dto.wire === undefined ? undefined : Uint8Array.from(dto.wire),
1173
+ });
1174
+ if (selected.length >= clampedItems)
1175
+ break scanLoop;
1176
+ }
1177
+ if (rows.length < 512)
1178
+ break;
1179
+ start = cat(lastKey, Uint8Array.of(0));
1180
+ }
1181
+ return selected;
1182
+ });
1183
+ }
1184
+ /** Atomically confirm a batch of acquired tasks in one write transaction. */
1185
+ async confirmBatch(tokens, checkRegistryGeneration) {
1186
+ if (tokens.length === 0)
1187
+ return [];
1188
+ const scope = tokens[0].scope;
1189
+ const scopeRaw = scopeBytes(scope);
1190
+ const seen = new Set();
1191
+ for (const token of tokens) {
1192
+ if (!equalBytes(scopeBytes(token.scope), scopeRaw))
1193
+ throw invalid('confirmBatch tokens must share one scope');
1194
+ const id = `${hex(token.task.turn)}:${token.task.seq}`;
1195
+ if (seen.has(id))
1196
+ throw invalid('confirmBatch contains duplicate task');
1197
+ seen.add(id);
1198
+ }
1199
+ const self = this;
1200
+ const coverage = this.coverage;
1201
+ return this.storage.transact(true, function* (tx) {
1202
+ if (checkRegistryGeneration) {
1203
+ const current = yield* generationIn(tx, scope.remote);
1204
+ if (current === undefined)
1205
+ throw new WorkError('registry', 'registry failure during confirm: remote not found', { cause: { code: 'notFound', remote: scope.remote } });
1206
+ if (!sameGeneration(current, scope.generation))
1207
+ throw new WorkError('generationConflict', 'generation changed', { cause: { current } });
1208
+ }
1209
+ const results = [];
1210
+ for (const token of tokens) {
1211
+ const task = token.task;
1212
+ const dto = yield* self.loadTask(tx, scope, task);
1213
+ if (dto === undefined)
1214
+ throw new WorkError('notFound', 'task not found', { cause: { task } });
1215
+ if (dto.attempts !== token.attempt)
1216
+ throw new WorkError('attemptMismatch', 'attempt mismatch', { cause: { task, expected: dto.attempts, got: token.attempt } });
1217
+ if (dto.status === 'done') {
1218
+ results.push({ task, woke: [], coverage: { kind: 'duplicate' } });
1219
+ continue;
1220
+ }
1221
+ if (dto.status !== 'inflight' && dto.status !== 'acked_local')
1222
+ throw new WorkError('invalidTransition', 'status inflight or acked_local to confirmBatch', { cause: { task, from: dto.status } });
1223
+ const previous = dto.status;
1224
+ let coverageResult;
1225
+ try {
1226
+ coverageResult = yield* coverage.markPresentIn(tx, scope, task.turn, task.seq, Uint8Array.from(dto.fingerprint), dto.is_seal, dto.parents.map(parent => ({ turn: parent.turn, seal_fp: parent.seal_fp })));
1227
+ }
1228
+ catch (e) {
1229
+ if (e instanceof CoverageError)
1230
+ throw new WorkError('coverage', `coverage failure during confirm: ${e.message}`, { cause: { code: e.code, message: e.message } });
1231
+ throw e;
1232
+ }
1233
+ yield* advancePrefixIn(tx, scope, coverage, task.turn);
1234
+ dto.status = 'done';
1235
+ yield* tx.put(WORK_SPACE, taskKey(scope, task), encode(dto));
1236
+ yield* statusIndexUpdate(tx, scope, dto.task_seq, task, previous, 'done');
1237
+ for (const dep of dto.deps)
1238
+ yield* waitRemove(tx, scope, { turn: Uint8Array.from(dep.turn), seq: dep.seq }, task);
1239
+ const woke = yield* waiters(tx, scope, task);
1240
+ results.push({ task, woke, coverage: coverageResult });
1241
+ }
1242
+ return results;
1243
+ });
1244
+ }
1245
+ /** Delete every work-store record belonging to `scope` inside the caller's
1246
+ * write transaction, preserving stream content and other scopes. */
1247
+ static *clearScopeIn(tx, scope) {
1248
+ const scopePart = scopeBytes(scope);
1249
+ let deleted = 0;
1250
+ for (const tag of [
1251
+ TASK_KEY_TAG,
1252
+ WAIT_KEY_TAG,
1253
+ CURSOR_KEY_TAG,
1254
+ TASKSEQ_KEY_TAG,
1255
+ PREFIX_KEY_TAG,
1256
+ STATUS_INDEX_KEY_TAG,
1257
+ STATUS_INDEX_MARKER_TAG,
1258
+ OPEN_TURN_KEY_TAG,
1259
+ OPEN_INDEX_MARKER_TAG,
1260
+ EVENT_CURSOR_KEY_TAG,
1261
+ ORDERED_CANDIDATE_TAG,
1262
+ ORDERED_CANDIDATE_MARKER_TAG,
1263
+ ]) {
1264
+ const prefix = cat(Uint8Array.of(tag), scopePart);
1265
+ deleted += yield* tx.deleteRange(WORK_SPACE, prefix, successor(prefix));
1266
+ }
1267
+ return deleted;
1268
+ }
1020
1269
  }
1021
1270
  // ---------------------------------------------------------------------------
1022
1271
  // Transaction-internal helpers (composed by the public methods above).
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' | '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';
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' | 'any-owner-v1' | 'purge-stream-v1' | 'explicit-sync-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';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@loro-dev/roost",
3
- "version": "0.3.2",
3
+ "version": "0.4.0",
4
4
  "description": "Browser conversation history and sync for Loro Roost",
5
5
  "license": "MIT",
6
6
  "publishConfig": { "access": "public" },
@@ -21,7 +21,7 @@
21
21
  "dependencies": {
22
22
  "@noble/curves": "2.4.0",
23
23
  "@noble/hashes": "2.4.0",
24
- "@loro-dev/streams-client": "0.16.0"
24
+ "@loro-dev/streams-client": "0.17.0"
25
25
  },
26
26
  "main": "./dist/index.js",
27
27
  "types": "./dist/index.d.ts",