@loro-dev/roost 0.1.0 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +66 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/lody-history.d.ts +113 -8
- package/dist/lody-history.js +1001 -16
- package/dist/sync/history.d.ts +8 -2
- package/dist/sync/history.js +10 -5
- package/node/client.d.mts +102 -0
- package/node/client.mjs +316 -0
- package/package.json +8 -2
package/dist/lody-history.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
/**
|
|
1
|
+
/** Lody's durable logical-history adapter. */
|
|
2
2
|
import { blake3 } from '@noble/hashes/blake3.js';
|
|
3
3
|
import { decodeBatch, decodeFrame, encodeFrame } from './codec.js';
|
|
4
|
-
import { decodeUtf8, encodeUtf8, encodeJson, decodeJson, MAX_JSON_DEPTH } from './json.js';
|
|
4
|
+
import { decodeUtf8, encodeUtf8, encodeJson, decodeJson, MAX_JSON_DEPTH, U64_MAX } from './json.js';
|
|
5
5
|
import { StoreError } from './store.js';
|
|
6
6
|
import { catchUpPublications, PUBLICATION_OBJECTS, PUBLICATION_DONE, PUBLICATION_CURSOR, checkPublicationRefs, publicationValue } from './history-publication.js';
|
|
7
7
|
const equal = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
|
|
@@ -9,23 +9,201 @@ 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
|
+
}
|
|
25
|
+
const BRANCH_TABLE = 'lody_history_branches_v1';
|
|
26
|
+
const BRANCH_OPERATIONS = 'lody_history_branch_operations_v1';
|
|
27
|
+
function branchKey(viewId) { return encodeUtf8(text(viewId)); }
|
|
28
|
+
function branchOperationKey(viewId, operationId) {
|
|
29
|
+
return encodeUtf8(JSON.stringify([text(viewId), text(operationId)]));
|
|
30
|
+
}
|
|
31
|
+
function branchIdentity(value, label) {
|
|
32
|
+
if (value === null)
|
|
33
|
+
return null;
|
|
34
|
+
if (!(value instanceof Map))
|
|
35
|
+
throw invalid(label);
|
|
36
|
+
return decodeIdentity(value);
|
|
37
|
+
}
|
|
38
|
+
function branchMetadataValue(value) {
|
|
39
|
+
const metadata = new Map([
|
|
40
|
+
['version', '1'],
|
|
41
|
+
['viewId', value.viewId],
|
|
42
|
+
['revision', { kind: 'u64', value: value.revision }],
|
|
43
|
+
['operationId', value.operationId],
|
|
44
|
+
['previousHead', value.previousHead ? identityValue(value.previousHead) : null],
|
|
45
|
+
['head', value.head ? identityValue(value.head) : null],
|
|
46
|
+
['baseTurn', value.baseTurn],
|
|
47
|
+
['supersedes', value.supersedes.map(identityValue)],
|
|
48
|
+
['digest', value.digest],
|
|
49
|
+
]);
|
|
50
|
+
if (value.logicalCount !== undefined)
|
|
51
|
+
metadata.set('logicalCount', { kind: 'u64', value: value.logicalCount });
|
|
52
|
+
return metadata;
|
|
53
|
+
}
|
|
54
|
+
function parseBranchMetadata(value) {
|
|
55
|
+
if (value === undefined)
|
|
56
|
+
return;
|
|
57
|
+
if (!(value instanceof Map) || value.get('version') !== '1')
|
|
58
|
+
throw invalid('history branch metadata');
|
|
59
|
+
const viewId = value.get('viewId'), operationId = value.get('operationId'), revision = value.get('revision');
|
|
60
|
+
const baseTurn = value.get('baseTurn'), digest = value.get('digest'), supersedes = value.get('supersedes');
|
|
61
|
+
const logicalCount = value.get('logicalCount');
|
|
62
|
+
if (typeof viewId !== 'string' || typeof operationId !== 'string' || typeof baseTurn !== 'string' && baseTurn !== null ||
|
|
63
|
+
typeof digest !== 'string' || !revision || typeof revision !== 'object' || Array.isArray(revision) || revision instanceof Map || revision.kind !== 'u64' ||
|
|
64
|
+
!Array.isArray(supersedes))
|
|
65
|
+
throw invalid('history branch metadata');
|
|
66
|
+
const head = branchIdentity(value.get('head'), 'history branch head');
|
|
67
|
+
const previousHead = branchIdentity(value.get('previousHead'), 'history branch previous head');
|
|
68
|
+
const parsed = {
|
|
69
|
+
viewId: text(viewId), revision: revision.value, operationId: text(operationId),
|
|
70
|
+
previousHead, head, baseTurn,
|
|
71
|
+
...(logicalCount === undefined ? {} : { logicalCount: seqOf(logicalCount) }),
|
|
72
|
+
supersedes: supersedes.map(item => decodeIdentity(item)), digest,
|
|
73
|
+
};
|
|
74
|
+
if (parsed.revision < 1n || (parsed.head !== null && parsed.head.kind !== 'message') || (parsed.previousHead !== null && parsed.previousHead.kind !== 'message') || parsed.supersedes.some(item => item.kind !== 'message'))
|
|
75
|
+
throw invalid('history branch metadata');
|
|
76
|
+
if (!/^[0-9a-f]{64}$/.test(parsed.digest))
|
|
77
|
+
throw invalid('history branch digest');
|
|
78
|
+
if (parsed.baseTurn !== null && !/^[0-9a-f]{32}$/.test(parsed.baseTurn))
|
|
79
|
+
throw invalid('history branch base turn');
|
|
80
|
+
return parsed;
|
|
81
|
+
}
|
|
82
|
+
function branchStateValue(value, conflict = false) {
|
|
83
|
+
const state = branchMetadataValue(value);
|
|
84
|
+
if (conflict && state instanceof Map)
|
|
85
|
+
state.set('conflict', true);
|
|
86
|
+
return encodeJson(state);
|
|
87
|
+
}
|
|
88
|
+
function parseBranchState(raw) {
|
|
89
|
+
const value = decodeJson(raw);
|
|
90
|
+
let metadata;
|
|
91
|
+
try {
|
|
92
|
+
metadata = parseBranchMetadata(value);
|
|
93
|
+
}
|
|
94
|
+
catch (error) {
|
|
95
|
+
throw new StoreError('corrupt', 'invalid history branch state', { cause: error });
|
|
96
|
+
}
|
|
97
|
+
if (!metadata)
|
|
98
|
+
throw new StoreError('corrupt', 'invalid history branch state');
|
|
99
|
+
const previous = value instanceof Map ? value.get('conflict') : undefined;
|
|
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
|
+
}
|
|
102
|
+
function branchOperationValue(result, digest) {
|
|
103
|
+
return encodeJson(new Map([
|
|
104
|
+
['version', '1'], ['operationId', result.operationId], ['created', result.created],
|
|
105
|
+
['oldHead', result.oldHead ? identityValue(result.oldHead) : null], ['newHead', result.newHead ? identityValue(result.newHead) : null],
|
|
106
|
+
['revision', { kind: 'u64', value: result.revision }], ['turnId', result.turnId ? hexBytes(result.turnId) : null], ['digest', digest],
|
|
107
|
+
]));
|
|
108
|
+
}
|
|
109
|
+
function parseBranchOperation(raw) {
|
|
110
|
+
const value = decodeJson(raw);
|
|
111
|
+
if (!(value instanceof Map) || value.get('version') !== '1')
|
|
112
|
+
throw new StoreError('corrupt', 'invalid history branch operation');
|
|
113
|
+
const operationId = value.get('operationId'), created = value.get('created'), revision = value.get('revision'), turnId = value.get('turnId'), digest = value.get('digest');
|
|
114
|
+
if (typeof operationId !== 'string' || typeof created !== 'boolean' || (turnId !== null && typeof turnId !== 'string') || typeof digest !== 'string' || !revision || typeof revision !== 'object' || Array.isArray(revision) || revision instanceof Map || revision.kind !== 'u64')
|
|
115
|
+
throw new StoreError('corrupt', 'invalid history branch operation');
|
|
116
|
+
const oldHead = branchIdentity(value.get('oldHead'), 'history branch operation old head');
|
|
117
|
+
const newHead = branchIdentity(value.get('newHead'), 'history branch operation new head');
|
|
118
|
+
if ((newHead !== null && newHead.kind !== 'message') || (oldHead !== null && oldHead.kind !== 'message'))
|
|
119
|
+
throw new StoreError('corrupt', 'invalid history branch operation head');
|
|
120
|
+
if ((turnId !== null && !/^[0-9a-f]{32}$/.test(turnId)) || !/^[0-9a-f]{64}$/.test(digest))
|
|
121
|
+
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 };
|
|
123
|
+
}
|
|
124
|
+
function branchMetadataFromContent(content) {
|
|
125
|
+
if (!(content instanceof Map))
|
|
126
|
+
return;
|
|
127
|
+
return parseBranchMetadata(content.get('lodyBranch'));
|
|
128
|
+
}
|
|
129
|
+
function branchStateEqual(a, b) {
|
|
130
|
+
if (a === null || b === null)
|
|
131
|
+
return a === b;
|
|
132
|
+
return equal(keyOf(a), keyOf(b));
|
|
133
|
+
}
|
|
134
|
+
function branchParentMatches(baseTurn, parents) {
|
|
135
|
+
return baseTurn === null ? parents.length === 0 : parents.some(parent => equal(parent.id, baseTurn));
|
|
136
|
+
}
|
|
137
|
+
function mergeBranchStateRaw(previous, candidate) {
|
|
138
|
+
if (!previous)
|
|
139
|
+
return candidate;
|
|
140
|
+
const old = parseBranchState(previous), next = parseBranchState(candidate);
|
|
141
|
+
if (old.conflict)
|
|
142
|
+
return previous;
|
|
143
|
+
if (next.revision > old.revision)
|
|
144
|
+
return candidate;
|
|
145
|
+
if (next.revision < old.revision)
|
|
146
|
+
return previous;
|
|
147
|
+
if (old.operationId === next.operationId && branchStateEqual(old.head, next.head) && old.digest === next.digest)
|
|
148
|
+
return previous;
|
|
149
|
+
return branchStateValue({
|
|
150
|
+
viewId: old.viewId,
|
|
151
|
+
revision: old.revision,
|
|
152
|
+
operationId: old.operationId,
|
|
153
|
+
previousHead: null,
|
|
154
|
+
head: old.head,
|
|
155
|
+
baseTurn: null,
|
|
156
|
+
supersedes: [],
|
|
157
|
+
digest: old.digest,
|
|
158
|
+
}, true);
|
|
159
|
+
}
|
|
160
|
+
function branchStateRows(rows, prior) {
|
|
161
|
+
const merged = new Map();
|
|
162
|
+
for (const row of rows) {
|
|
163
|
+
const key = hexBytes(row.key);
|
|
164
|
+
const before = merged.has(key) ? merged.get(key) : prior.get(key);
|
|
165
|
+
merged.set(key, mergeBranchStateRaw(before, row.value));
|
|
166
|
+
}
|
|
167
|
+
return merged;
|
|
168
|
+
}
|
|
169
|
+
function branchMutationDigest(input, owner, baseTurn, supersedes) {
|
|
170
|
+
const body = new Map([
|
|
171
|
+
['viewId', input.viewId],
|
|
172
|
+
['revision', { kind: 'u64', value: input.expectedRevision }],
|
|
173
|
+
['operationId', input.operationId],
|
|
174
|
+
['expectedHead', input.expectedHead ? identityValue(input.expectedHead) : null],
|
|
175
|
+
['baseTurn', baseTurn ? hexBytes(baseTurn) : null],
|
|
176
|
+
['supersedes', supersedes.map(identityValue)],
|
|
177
|
+
['createDigest', hexBytes(createDigest(owner, input.input.parents, envelope(input.input)))],
|
|
178
|
+
]);
|
|
179
|
+
return hexBytes(blake3(encodeJson(body)));
|
|
180
|
+
}
|
|
181
|
+
function branchMetadataFor(input, owner, previousHead, baseTurn, supersedes, logicalCount) {
|
|
182
|
+
const digest = branchMutationDigest(input, owner, baseTurn, supersedes);
|
|
183
|
+
return {
|
|
184
|
+
viewId: text(input.viewId),
|
|
185
|
+
revision: input.expectedRevision + 1n,
|
|
186
|
+
operationId: text(input.operationId),
|
|
187
|
+
previousHead,
|
|
188
|
+
head: { kind: input.input.kind, businessId: input.input.businessId, segmentId: input.input.segmentId },
|
|
189
|
+
baseTurn: baseTurn ? hexBytes(baseTurn) : null,
|
|
190
|
+
...(logicalCount !== undefined ? { logicalCount } : {}),
|
|
191
|
+
supersedes: supersedes.map(value => ({ ...value })),
|
|
192
|
+
digest,
|
|
193
|
+
};
|
|
194
|
+
}
|
|
19
195
|
function attachment(a) {
|
|
20
196
|
if (!/^[0-9a-f]{64}$/.test(a.sha256) || typeof a.size !== 'bigint' || a.size < 0n)
|
|
21
197
|
throw invalid('attachment identity');
|
|
22
198
|
return new Map([['attachmentId', text(a.attachmentId)], ['sha256', a.sha256], ['name', text(a.name)], ['size', { kind: 'u64', value: a.size }]]);
|
|
23
199
|
}
|
|
24
|
-
function envelope(v, publish = false) {
|
|
200
|
+
function envelope(v, publish = false, branch) {
|
|
25
201
|
keyOf(v);
|
|
26
202
|
const body = new Map([['lodyHistory', new Map([['version', '1'], ['kind', v.kind], ['businessId', v.businessId], ['segmentId', v.segmentId]])], ['content', v.content], ['attachments', (v.attachments ?? []).map(attachment)]]);
|
|
27
203
|
if (v.kind === 'message')
|
|
28
204
|
body.set('lodyPublication', publish ? 'direct' : 'private');
|
|
205
|
+
if (branch)
|
|
206
|
+
body.set('lodyBranch', branchMetadataValue(branch));
|
|
29
207
|
return body;
|
|
30
208
|
}
|
|
31
209
|
function identityOf(content) {
|
|
@@ -54,9 +232,10 @@ function canonicalCreate(owner, parents, content) {
|
|
|
54
232
|
// of the original application input. Old envelopes have no marker and retain
|
|
55
233
|
// exactly their previous digest. This is an application retry digest, not a seal.
|
|
56
234
|
function createDigest(owner, parents, content) {
|
|
57
|
-
if (content instanceof Map && (content.get('lodyPublication') === 'direct' || content.get('lodyPublication') === 'private')) {
|
|
235
|
+
if (content instanceof Map && (content.get('lodyPublication') === 'direct' || content.get('lodyPublication') === 'private' || content.has('lodyBranch'))) {
|
|
58
236
|
content = new Map(content);
|
|
59
237
|
content.delete('lodyPublication');
|
|
238
|
+
content.delete('lodyBranch');
|
|
60
239
|
}
|
|
61
240
|
return blake3(canonicalCreate(owner, parents, content));
|
|
62
241
|
}
|
|
@@ -83,10 +262,18 @@ function binding(raw) {
|
|
|
83
262
|
* never replaces an older signature. Dispatch/Flock and locations are host-owned. */
|
|
84
263
|
export class LodyHistory {
|
|
85
264
|
stream;
|
|
86
|
-
|
|
87
|
-
constructor(stream,
|
|
265
|
+
signingIdentity;
|
|
266
|
+
constructor(stream, signingIdentity) {
|
|
88
267
|
this.stream = stream;
|
|
89
|
-
this.
|
|
268
|
+
this.signingIdentity = signingIdentity;
|
|
269
|
+
}
|
|
270
|
+
/** A replica can project admitted history without owning a signing key.
|
|
271
|
+
* Index maintenance is local; authoring through this instance is rejected. */
|
|
272
|
+
static readOnly(stream) { return new LodyHistory(stream); }
|
|
273
|
+
get identity() {
|
|
274
|
+
if (!this.signingIdentity)
|
|
275
|
+
throw invalid('read-only history cannot author Turns');
|
|
276
|
+
return this.signingIdentity;
|
|
90
277
|
}
|
|
91
278
|
get space() { return this.stream.space('lody_history_bindings_v1'); }
|
|
92
279
|
get cursorSpace() { return this.stream.space('lody_history_index_v1'); }
|
|
@@ -100,6 +287,7 @@ export class LodyHistory {
|
|
|
100
287
|
if (!events.length)
|
|
101
288
|
return false; // A read must not write a cursor and wake itself.
|
|
102
289
|
const rows = [];
|
|
290
|
+
const branchRows = [];
|
|
103
291
|
const objects = [];
|
|
104
292
|
const invalidTurns = [];
|
|
105
293
|
for (const record of events) {
|
|
@@ -121,6 +309,19 @@ export class LodyHistory {
|
|
|
121
309
|
objects.push({ key: u.turnId, value: encodeUtf8('null') });
|
|
122
310
|
continue;
|
|
123
311
|
}
|
|
312
|
+
let branch;
|
|
313
|
+
try {
|
|
314
|
+
branch = branchMetadataFromContent(u.operation.content);
|
|
315
|
+
}
|
|
316
|
+
catch (error) {
|
|
317
|
+
if (errorCode(error) !== 'invalid')
|
|
318
|
+
throw error;
|
|
319
|
+
invalidTurns.push(u.turnId);
|
|
320
|
+
objects.push({ key: u.turnId, value: encodeUtf8('null') });
|
|
321
|
+
continue;
|
|
322
|
+
}
|
|
323
|
+
if (branch)
|
|
324
|
+
branchRows.push({ key: branchKey(branch.viewId), value: branchStateValue(branch) });
|
|
124
325
|
rows.push({ key: keyOf(id), value: { version: 1, turnId: [...u.turnId], owner: [...u.owner], digest: [...createDigest(u.owner, u.operation.parents, u.operation.content)] } });
|
|
125
326
|
objects.push({ key: u.turnId, value: encodeUtf8(JSON.stringify(publicationObject(u.owner, u.operation.parents, u.operation.content))) });
|
|
126
327
|
}
|
|
@@ -140,6 +341,15 @@ export class LodyHistory {
|
|
|
140
341
|
row.value.conflict = true;
|
|
141
342
|
yield* tx.put(space, row.key, encodeUtf8(JSON.stringify(row.value)));
|
|
142
343
|
}
|
|
344
|
+
const branchStates = new Map();
|
|
345
|
+
for (const row of branchRows) {
|
|
346
|
+
const key = hexBytes(row.key);
|
|
347
|
+
if (!branchStates.has(key))
|
|
348
|
+
branchStates.set(key, yield* tx.get(stream.space(BRANCH_TABLE), row.key));
|
|
349
|
+
branchStates.set(key, mergeBranchStateRaw(branchStates.get(key), row.value));
|
|
350
|
+
}
|
|
351
|
+
for (const [key, value] of branchStates)
|
|
352
|
+
yield* tx.put(stream.space(BRANCH_TABLE), unhexBytes(key, key.length / 2), value);
|
|
143
353
|
yield* tx.put(cursorSpace, key, encodeUtf8(through.toString()));
|
|
144
354
|
return true;
|
|
145
355
|
});
|
|
@@ -167,6 +377,7 @@ export class LodyHistory {
|
|
|
167
377
|
async accept(input, options) {
|
|
168
378
|
// Own every input before the first await. The original Create fingerprint is
|
|
169
379
|
// stable even after edits; a retry must not compare against the current body.
|
|
380
|
+
assertWritableIdentity(input);
|
|
170
381
|
const key = keyOf(input), owner = this.identity.owner();
|
|
171
382
|
const rawInput = canonicalCreate(owner, input.parents, envelope(input, options?.publish !== false)), fingerprint = createDigest(owner, input.parents, envelope(input));
|
|
172
383
|
const copied = decodeFrame(rawInput);
|
|
@@ -199,6 +410,23 @@ export class LodyHistory {
|
|
|
199
410
|
}
|
|
200
411
|
throw new StoreError('stale', 'history discovery retry budget exhausted');
|
|
201
412
|
}
|
|
413
|
+
/** Append a message to an active view and advance that view atomically. */
|
|
414
|
+
acceptToView(input) {
|
|
415
|
+
return branchAccept(this, input);
|
|
416
|
+
}
|
|
417
|
+
/** Create a replacement Turn and switch the same logical view to it. */
|
|
418
|
+
forkAndActivate(input) {
|
|
419
|
+
return branchFork(this, input);
|
|
420
|
+
}
|
|
421
|
+
restoreActiveBranch(input) {
|
|
422
|
+
return branchRestore(this, input);
|
|
423
|
+
}
|
|
424
|
+
readActiveBranch(viewId) {
|
|
425
|
+
return readActiveBranch(this, viewId);
|
|
426
|
+
}
|
|
427
|
+
readActiveBranchPage(viewId, input = {}) {
|
|
428
|
+
return readActiveBranchPage(this, viewId, input);
|
|
429
|
+
}
|
|
202
430
|
append(id, expectedNextSeq, ops) {
|
|
203
431
|
return this.stream.writer(this.identity).edit(id, expectedNextSeq, ops.map(op => ({ ...op, path: [{ key: 'content' }, ...op.path] })));
|
|
204
432
|
}
|
|
@@ -324,6 +552,7 @@ export class NodeLodyHistory {
|
|
|
324
552
|
return false;
|
|
325
553
|
const changes = [];
|
|
326
554
|
const rows = [];
|
|
555
|
+
const branchRows = [];
|
|
327
556
|
const touched = new Map();
|
|
328
557
|
const receipts = new Map();
|
|
329
558
|
for (const record of events) {
|
|
@@ -349,6 +578,19 @@ export class NodeLodyHistory {
|
|
|
349
578
|
changes.push({ table: PUBLICATION_OBJECTS, key: u.turnId, value: encodeUtf8('null') });
|
|
350
579
|
continue;
|
|
351
580
|
}
|
|
581
|
+
let branch;
|
|
582
|
+
try {
|
|
583
|
+
branch = branchMetadataFromContent(u.operation.content);
|
|
584
|
+
}
|
|
585
|
+
catch (error) {
|
|
586
|
+
if (errorCode(error) !== 'invalid')
|
|
587
|
+
throw error;
|
|
588
|
+
changes.push({ table: NODE_INVALID, key: u.turnId, value: encodeUtf8('invalid_envelope') });
|
|
589
|
+
changes.push({ table: PUBLICATION_OBJECTS, key: u.turnId, value: encodeUtf8('null') });
|
|
590
|
+
continue;
|
|
591
|
+
}
|
|
592
|
+
if (branch)
|
|
593
|
+
branchRows.push({ key: branchKey(branch.viewId), value: branchStateValue(branch) });
|
|
352
594
|
const key = keyOf(id);
|
|
353
595
|
rows.push({ key, value: { version: 1, turnId: [...u.turnId], owner: [...u.owner], digest: [...createDigest(u.owner, u.operation.parents, u.operation.content)] } });
|
|
354
596
|
changes.push({ table: PUBLICATION_OBJECTS, key: u.turnId, value: encodeUtf8(JSON.stringify(publicationObject(u.owner, u.operation.parents, u.operation.content))) });
|
|
@@ -367,6 +609,13 @@ export class NodeLodyHistory {
|
|
|
367
609
|
merged.set(key, row.value);
|
|
368
610
|
changes.push({ table: NODE_BINDINGS, key: row.key, value: encodeUtf8(JSON.stringify(row.value)) });
|
|
369
611
|
}
|
|
612
|
+
const branchPriorRows = await this.stream.readIndex([...new Map(branchRows.map(row => [hexBytes(row.key), row])).values()].map(row => ({ table: BRANCH_TABLE, key: row.key })));
|
|
613
|
+
const branchPrior = new Map();
|
|
614
|
+
let branchPriorIndex = 0;
|
|
615
|
+
for (const row of [...new Map(branchRows.map(row => [hexBytes(row.key), row])).values()])
|
|
616
|
+
branchPrior.set(hexBytes(row.key), branchPriorRows[branchPriorIndex++] ?? undefined);
|
|
617
|
+
for (const [key, value] of branchStateRows(branchRows, branchPrior))
|
|
618
|
+
changes.push({ table: BRANCH_TABLE, key: unhexBytes(key, key.length / 2), value });
|
|
370
619
|
// Only touched receipts are inspected. The pending index lets normal
|
|
371
620
|
// startup avoid enumerating every completed receipt / business binding.
|
|
372
621
|
const ids = [...touched.values()];
|
|
@@ -433,6 +682,7 @@ export class NodeLodyHistory {
|
|
|
433
682
|
}
|
|
434
683
|
async finish(id, seq) { await this.stream.seal(id, seq); }
|
|
435
684
|
async accept(input, options) {
|
|
685
|
+
assertWritableIdentity(input);
|
|
436
686
|
const key = keyOf(input), raw = canonicalCreate(this.owner, input.parents, envelope(input, options?.publish !== false)), digest = createDigest(this.owner, input.parents, envelope(input));
|
|
437
687
|
const copied = decodeFrame(raw);
|
|
438
688
|
if (copied.operation.kind !== 'create')
|
|
@@ -461,6 +711,13 @@ export class NodeLodyHistory {
|
|
|
461
711
|
}
|
|
462
712
|
throw new StoreError('stale', 'history discovery retry budget exhausted');
|
|
463
713
|
}
|
|
714
|
+
acceptToView(input) { return branchAccept(this, input); }
|
|
715
|
+
forkAndActivate(input) { return branchFork(this, input); }
|
|
716
|
+
restoreActiveBranch(input) { return branchRestore(this, input); }
|
|
717
|
+
readActiveBranch(viewId) { return readActiveBranch(this, viewId); }
|
|
718
|
+
readActiveBranchPage(viewId, input = {}) {
|
|
719
|
+
return readActiveBranchPage(this, viewId, input);
|
|
720
|
+
}
|
|
464
721
|
async respondPermission(input) {
|
|
465
722
|
const result = await this.accept({ businessId: text(input.requestId), segmentId: 'response', kind: 'permission_response', parents: input.parents,
|
|
466
723
|
content: new Map([['assistantBusinessId', text(input.assistantBusinessId)], ['outcome', input.outcome]]) });
|
|
@@ -534,6 +791,708 @@ export class NodeLodyHistory {
|
|
|
534
791
|
}
|
|
535
792
|
}
|
|
536
793
|
}
|
|
794
|
+
async function readBranchIndex(host, viewId) {
|
|
795
|
+
const key = branchKey(viewId);
|
|
796
|
+
const raw = host instanceof LodyHistory
|
|
797
|
+
? await host.stream.store.run(false, host.stream.id, function* (tx) { return yield* tx.get(host.stream.space(BRANCH_TABLE), key); })
|
|
798
|
+
: (await host.stream.readIndex([{ table: BRANCH_TABLE, key }]))[0];
|
|
799
|
+
return raw ? parseBranchState(raw) : undefined;
|
|
800
|
+
}
|
|
801
|
+
async function readBranchOperation(host, viewId, operationId) {
|
|
802
|
+
const key = branchOperationKey(viewId, operationId);
|
|
803
|
+
const raw = host instanceof LodyHistory
|
|
804
|
+
? await host.stream.store.run(false, host.stream.id, function* (tx) { return yield* tx.get(host.stream.space(BRANCH_OPERATIONS), key); })
|
|
805
|
+
: (await host.stream.readIndex([{ table: BRANCH_OPERATIONS, key }]))[0];
|
|
806
|
+
if (!raw)
|
|
807
|
+
return;
|
|
808
|
+
return parseBranchOperation(raw);
|
|
809
|
+
}
|
|
810
|
+
async function branchCursor(host) {
|
|
811
|
+
return host instanceof LodyHistory ? host.observedEventCursor() : (await host.observedEventCursor());
|
|
812
|
+
}
|
|
813
|
+
async function branchOwner(host) {
|
|
814
|
+
return host instanceof LodyHistory ? host.identity.owner() : host.owner.slice();
|
|
815
|
+
}
|
|
816
|
+
async function branchTurnByIdentity(host, identity) {
|
|
817
|
+
const found = await host.lookup(identity);
|
|
818
|
+
if (!found || found.kind !== 'found')
|
|
819
|
+
return;
|
|
820
|
+
return found.turn.turnId.slice();
|
|
821
|
+
}
|
|
822
|
+
async function branchMetadataAt(host, turnId) {
|
|
823
|
+
try {
|
|
824
|
+
return parseBranchMetadata(await publicationField(host, turnId, [{ key: 'lodyBranch' }]));
|
|
825
|
+
}
|
|
826
|
+
catch (error) {
|
|
827
|
+
if (errorCode(error) === 'invalid' || errorCode(error) === 'pending')
|
|
828
|
+
return undefined;
|
|
829
|
+
throw error;
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
async function branchLogicalCountAt(host, viewId, turnId) {
|
|
833
|
+
if (!turnId)
|
|
834
|
+
return 0n;
|
|
835
|
+
const metadata = await branchMetadataAt(host, turnId);
|
|
836
|
+
if (metadata?.viewId === viewId && metadata.logicalCount !== undefined)
|
|
837
|
+
return metadata.logicalCount;
|
|
838
|
+
const directory = await readActiveBranchDirectory(host, viewId);
|
|
839
|
+
const id = hexBytes(turnId);
|
|
840
|
+
const position = directory.rows.findIndex(row => row.segments.some(segment => hexBytes(segment.turnId) === id));
|
|
841
|
+
if (position < 0)
|
|
842
|
+
throw new StoreError('stale', 'branch base is not in the active history');
|
|
843
|
+
return BigInt(position + 1);
|
|
844
|
+
}
|
|
845
|
+
async function readBranchTurn(host, turnId) {
|
|
846
|
+
if (host instanceof LodyHistory) {
|
|
847
|
+
const result = await host.stream.readTurn(turnId);
|
|
848
|
+
if (result.kind !== 'found')
|
|
849
|
+
return;
|
|
850
|
+
const body = result.turn.content;
|
|
851
|
+
return {
|
|
852
|
+
turnId: result.turn.turnId.slice(),
|
|
853
|
+
parents: result.turn.parents.map(parent => ({ id: parent.id.slice(), hash: parent.hash.slice() })),
|
|
854
|
+
identity: identityOf(body),
|
|
855
|
+
content: body instanceof Map ? body.get('content') : undefined,
|
|
856
|
+
nextSeq: result.turn.nextSeq,
|
|
857
|
+
sealed: result.turn.sealed?.slice() ?? null,
|
|
858
|
+
};
|
|
859
|
+
}
|
|
860
|
+
const result = await host.stream.readTurn(turnId);
|
|
861
|
+
if (result.kind !== 'found')
|
|
862
|
+
return;
|
|
863
|
+
const [create] = decodeBatch(await host.stream.exportUpdates(turnId, 0n, 1n));
|
|
864
|
+
if (!create || create.operation.kind !== 'create')
|
|
865
|
+
throw new StoreError('corrupt', 'branch head has no Create');
|
|
866
|
+
const body = decodeJson(encodeUtf8(result.turn.contentJson));
|
|
867
|
+
return {
|
|
868
|
+
turnId: result.turn.turnId.slice(),
|
|
869
|
+
parents: create.operation.parents.map(parent => ({ id: parent.id.slice(), hash: parent.hash.slice() })),
|
|
870
|
+
identity: identityOf(body),
|
|
871
|
+
content: body instanceof Map ? body.get('content') : undefined,
|
|
872
|
+
nextSeq: result.turn.nextSeq,
|
|
873
|
+
sealed: result.turn.sealed?.slice() ?? null,
|
|
874
|
+
};
|
|
875
|
+
}
|
|
876
|
+
async function branchMutation(host, input, baseTurn, supersedes) {
|
|
877
|
+
if (input.input.kind !== 'message')
|
|
878
|
+
throw invalid('active branch only accepts message Turns');
|
|
879
|
+
if (typeof input.expectedRevision !== 'bigint' || input.expectedRevision < 0n || input.expectedRevision >= U64_MAX)
|
|
880
|
+
throw invalid('branch revision');
|
|
881
|
+
const viewId = text(input.viewId), operationId = text(input.operationId), owner = await branchOwner(host);
|
|
882
|
+
const expectedHead = input.expectedHead ? { ...input.expectedHead } : null;
|
|
883
|
+
if (baseTurn !== null && baseTurn.length !== 16)
|
|
884
|
+
throw invalid('branch base Turn');
|
|
885
|
+
if (expectedHead) {
|
|
886
|
+
if (expectedHead.kind !== 'message')
|
|
887
|
+
throw invalid('branch head kind');
|
|
888
|
+
keyOf(expectedHead);
|
|
889
|
+
}
|
|
890
|
+
for (const superseded of supersedes) {
|
|
891
|
+
if (superseded.kind !== 'message')
|
|
892
|
+
throw invalid('branch superseded kind');
|
|
893
|
+
keyOf(superseded);
|
|
894
|
+
}
|
|
895
|
+
if (!branchParentMatches(baseTurn, input.input.parents))
|
|
896
|
+
throw invalid('branch base parent');
|
|
897
|
+
const baseCount = await branchLogicalCountAt(host, viewId, baseTurn);
|
|
898
|
+
const logicalCount = baseCount + (input.input.segmentId === 'primary' ? 1n : 0n);
|
|
899
|
+
const metadata = branchMetadataFor({ ...input, viewId, operationId, expectedHead }, owner, expectedHead, baseTurn, supersedes, logicalCount);
|
|
900
|
+
const createKey = keyOf(input.input);
|
|
901
|
+
const branchValue = branchStateValue(metadata);
|
|
902
|
+
const operationValue = branchOperationValue({ operationId, created: true, oldHead: expectedHead, newHead: metadata.head, revision: metadata.revision, turnId: null }, metadata.digest);
|
|
903
|
+
for (let attempt = 0; attempt < 4; attempt++) {
|
|
904
|
+
// Fence every state read below, not only the final write. A concurrent
|
|
905
|
+
// branch mutation after these checks must invalidate this attempt.
|
|
906
|
+
const cursor = await branchCursor(host);
|
|
907
|
+
const [state, priorOperation] = await Promise.all([
|
|
908
|
+
readBranchIndex(host, viewId),
|
|
909
|
+
readBranchOperation(host, viewId, operationId),
|
|
910
|
+
]);
|
|
911
|
+
if (priorOperation) {
|
|
912
|
+
if (priorOperation.digest !== metadata.digest || !branchStateEqual(priorOperation.oldHead, expectedHead) || !branchStateEqual(priorOperation.newHead, metadata.head))
|
|
913
|
+
throw new StoreError('conflict', 'branch operation input changed');
|
|
914
|
+
if (priorOperation.newHead === null)
|
|
915
|
+
throw new StoreError('corrupt', 'branch operation head missing');
|
|
916
|
+
const turnId = priorOperation.turnId ?? await branchTurnByIdentity(host, priorOperation.newHead);
|
|
917
|
+
if (!turnId)
|
|
918
|
+
throw new StoreError('corrupt', 'branch operation Turn missing');
|
|
919
|
+
return { operationId, created: false, oldHead: priorOperation.oldHead, newHead: priorOperation.newHead, revision: priorOperation.revision, turnId };
|
|
920
|
+
}
|
|
921
|
+
if (state?.conflict)
|
|
922
|
+
throw new StoreError('conflict', 'active branch has conflicting revisions');
|
|
923
|
+
if ((state?.revision ?? 0n) !== input.expectedRevision || !branchStateEqual(state?.head ?? null, expectedHead))
|
|
924
|
+
throw new StoreError('stale', 'active branch changed');
|
|
925
|
+
const existing = await host.lookup(input.input);
|
|
926
|
+
if (existing) {
|
|
927
|
+
const existingEnvelope = existing.kind === 'found'
|
|
928
|
+
? ('content' in existing.turn ? existing.turn.content : decodeJson(encodeUtf8(existing.turn.contentJson)))
|
|
929
|
+
: undefined;
|
|
930
|
+
const existingBranch = existingEnvelope === undefined ? undefined : branchMetadataFromContent(existingEnvelope);
|
|
931
|
+
if (!existingBranch || existingBranch.operationId !== operationId || existingBranch.digest !== metadata.digest)
|
|
932
|
+
throw new StoreError('conflict', 'branch message identity already exists');
|
|
933
|
+
}
|
|
934
|
+
try {
|
|
935
|
+
await writeIndexed(host, [{ kind: 'createOnce', key: createKey, parents: input.input.parents, content: envelope(input.input, true, metadata) }], [
|
|
936
|
+
{ table: BRANCH_TABLE, key: branchKey(viewId), value: branchValue, emitEvent: true },
|
|
937
|
+
{ table: BRANCH_OPERATIONS, key: branchOperationKey(viewId, operationId), value: operationValue },
|
|
938
|
+
], cursor);
|
|
939
|
+
}
|
|
940
|
+
catch (error) {
|
|
941
|
+
if (errorCode(error) !== 'stale')
|
|
942
|
+
throw error;
|
|
943
|
+
continue;
|
|
944
|
+
}
|
|
945
|
+
await host.catchUpIndex();
|
|
946
|
+
const turnId = await branchTurnByIdentity(host, metadata.head);
|
|
947
|
+
if (!turnId)
|
|
948
|
+
throw new StoreError('corrupt', 'active branch replacement missing');
|
|
949
|
+
await maybePublishAccept(host, input.input, { publish: true }, turnId);
|
|
950
|
+
return { operationId, created: true, oldHead: expectedHead, newHead: metadata.head, revision: metadata.revision, turnId };
|
|
951
|
+
}
|
|
952
|
+
throw new StoreError('stale', 'active branch retry budget exhausted');
|
|
953
|
+
}
|
|
954
|
+
async function branchAccept(host, input) {
|
|
955
|
+
const baseTurn = input.expectedHead ? await branchTurnByIdentity(host, input.expectedHead) ?? null : null;
|
|
956
|
+
return branchMutation(host, input, baseTurn, []);
|
|
957
|
+
}
|
|
958
|
+
async function branchFork(host, input) {
|
|
959
|
+
if (input.input.kind !== 'message')
|
|
960
|
+
throw invalid('active branch only accepts message replacements');
|
|
961
|
+
if (input.baseTurn && input.baseTurn.length !== 16)
|
|
962
|
+
throw invalid('branch base Turn');
|
|
963
|
+
return branchMutation(host, input, input.baseTurn, input.supersedes);
|
|
964
|
+
}
|
|
965
|
+
function branchRestoreDigest(input) {
|
|
966
|
+
return hexBytes(blake3(encodeJson(new Map([
|
|
967
|
+
['viewId', text(input.viewId)],
|
|
968
|
+
['revision', { kind: 'u64', value: input.expectedRevision }],
|
|
969
|
+
['operationId', text(input.operationId)],
|
|
970
|
+
['expectedHead', input.expectedHead ? identityValue(input.expectedHead) : null],
|
|
971
|
+
['restoreHead', input.restoreHead ? identityValue(input.restoreHead) : null],
|
|
972
|
+
]))));
|
|
973
|
+
}
|
|
974
|
+
async function branchRestore(host, input) {
|
|
975
|
+
await branchOwner(host);
|
|
976
|
+
if (typeof input.expectedRevision !== 'bigint' || input.expectedRevision < 0n || input.expectedRevision >= U64_MAX)
|
|
977
|
+
throw invalid('branch revision');
|
|
978
|
+
const viewId = text(input.viewId), operationId = text(input.operationId), digest = branchRestoreDigest(input);
|
|
979
|
+
if (input.expectedHead) {
|
|
980
|
+
if (input.expectedHead.kind !== 'message')
|
|
981
|
+
throw invalid('branch expected head kind');
|
|
982
|
+
keyOf(input.expectedHead);
|
|
983
|
+
}
|
|
984
|
+
if (input.restoreHead) {
|
|
985
|
+
if (input.restoreHead.kind !== 'message')
|
|
986
|
+
throw invalid('branch restore head kind');
|
|
987
|
+
keyOf(input.restoreHead);
|
|
988
|
+
}
|
|
989
|
+
for (let attempt = 0; attempt < 4; attempt++) {
|
|
990
|
+
const cursor = await branchCursor(host);
|
|
991
|
+
const [state, priorOperation] = await Promise.all([
|
|
992
|
+
readBranchIndex(host, viewId),
|
|
993
|
+
readBranchOperation(host, viewId, operationId),
|
|
994
|
+
]);
|
|
995
|
+
if (priorOperation) {
|
|
996
|
+
if (priorOperation.digest !== digest || !branchStateEqual(priorOperation.oldHead, input.expectedHead) || !branchStateEqual(priorOperation.newHead, input.restoreHead))
|
|
997
|
+
throw new StoreError('conflict', 'branch restore input changed');
|
|
998
|
+
return {
|
|
999
|
+
operationId,
|
|
1000
|
+
created: false,
|
|
1001
|
+
oldHead: priorOperation.oldHead,
|
|
1002
|
+
newHead: priorOperation.newHead,
|
|
1003
|
+
revision: priorOperation.revision,
|
|
1004
|
+
turnId: priorOperation.turnId,
|
|
1005
|
+
};
|
|
1006
|
+
}
|
|
1007
|
+
if (state?.conflict)
|
|
1008
|
+
throw new StoreError('conflict', 'active branch has conflicting revisions');
|
|
1009
|
+
if ((state?.revision ?? 0n) !== input.expectedRevision || !branchStateEqual(state?.head ?? null, input.expectedHead))
|
|
1010
|
+
throw new StoreError('stale', 'active branch changed');
|
|
1011
|
+
const restoreTurnId = input.restoreHead ? await branchTurnByIdentity(host, input.restoreHead) : undefined;
|
|
1012
|
+
if (input.restoreHead && !restoreTurnId)
|
|
1013
|
+
throw new StoreError('corrupt', 'restore branch head missing');
|
|
1014
|
+
const logicalCount = await branchLogicalCountAt(host, viewId, restoreTurnId ?? null);
|
|
1015
|
+
const metadata = {
|
|
1016
|
+
viewId,
|
|
1017
|
+
revision: input.expectedRevision + 1n,
|
|
1018
|
+
operationId,
|
|
1019
|
+
previousHead: input.expectedHead,
|
|
1020
|
+
head: input.restoreHead,
|
|
1021
|
+
baseTurn: null,
|
|
1022
|
+
logicalCount,
|
|
1023
|
+
supersedes: [],
|
|
1024
|
+
digest,
|
|
1025
|
+
};
|
|
1026
|
+
// The branch index is only a projection. A signed native record makes a
|
|
1027
|
+
// rollback visible to remote replicas, including an empty restored view.
|
|
1028
|
+
// It is not a message and is never included in the visible transcript.
|
|
1029
|
+
const record = {
|
|
1030
|
+
kind: 'branch_state', businessId: viewId, segmentId: operationId, parents: [],
|
|
1031
|
+
content: new Map([['operation', 'restore']]),
|
|
1032
|
+
};
|
|
1033
|
+
const recordKey = keyOf(record);
|
|
1034
|
+
try {
|
|
1035
|
+
await writeIndexed(host, [
|
|
1036
|
+
{ kind: 'createOnce', key: recordKey, parents: [], content: envelope(record, false, metadata) },
|
|
1037
|
+
{ kind: 'sealOnce', key: recordKey, expectedNextSeq: 1n },
|
|
1038
|
+
], [
|
|
1039
|
+
{ table: BRANCH_TABLE, key: branchKey(viewId), value: branchStateValue(metadata), emitEvent: true },
|
|
1040
|
+
{ 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) },
|
|
1041
|
+
], cursor);
|
|
1042
|
+
}
|
|
1043
|
+
catch (error) {
|
|
1044
|
+
if (errorCode(error) !== 'stale')
|
|
1045
|
+
throw error;
|
|
1046
|
+
continue;
|
|
1047
|
+
}
|
|
1048
|
+
return { operationId, created: true, oldHead: input.expectedHead, newHead: input.restoreHead, revision: metadata.revision, turnId: restoreTurnId ?? null };
|
|
1049
|
+
}
|
|
1050
|
+
throw new StoreError('stale', 'active branch restore retry budget exhausted');
|
|
1051
|
+
}
|
|
1052
|
+
async function readActiveBranch(host, viewId) {
|
|
1053
|
+
return (await stableRead(host, () => readActiveBranchSnapshot(host, viewId))).value;
|
|
1054
|
+
}
|
|
1055
|
+
async function readActiveBranchSnapshot(host, viewId) {
|
|
1056
|
+
const state = await readBranchIndex(host, viewId);
|
|
1057
|
+
if (!state)
|
|
1058
|
+
return { state: { viewId: text(viewId), revision: 0n, head: null, operationId: null }, messages: [], complete: true };
|
|
1059
|
+
if (state.conflict)
|
|
1060
|
+
throw new StoreError('conflict', 'active branch has conflicting revisions');
|
|
1061
|
+
if (state.head === null)
|
|
1062
|
+
return { state, messages: [], complete: true };
|
|
1063
|
+
const headId = await branchTurnByIdentity(host, state.head);
|
|
1064
|
+
if (!headId)
|
|
1065
|
+
return { state, messages: [], complete: false };
|
|
1066
|
+
const seen = new Set(), output = [];
|
|
1067
|
+
let complete = true;
|
|
1068
|
+
const visit = async (id) => {
|
|
1069
|
+
const key = hexBytes(id);
|
|
1070
|
+
if (seen.has(key))
|
|
1071
|
+
return;
|
|
1072
|
+
seen.add(key);
|
|
1073
|
+
const turn = await readBranchTurn(host, id);
|
|
1074
|
+
if (!turn) {
|
|
1075
|
+
complete = false;
|
|
1076
|
+
return;
|
|
1077
|
+
}
|
|
1078
|
+
for (const parent of turn.parents)
|
|
1079
|
+
await visit(parent.id);
|
|
1080
|
+
if (turn.identity?.kind !== 'message' || turn.content === undefined)
|
|
1081
|
+
return;
|
|
1082
|
+
output.push({ businessId: turn.identity.businessId, segmentId: turn.identity.segmentId, turnId: turn.turnId, content: turn.content, nextSeq: turn.nextSeq, sealed: turn.sealed !== null, parents: turn.parents, sealedHash: turn.sealed });
|
|
1083
|
+
};
|
|
1084
|
+
await visit(headId);
|
|
1085
|
+
return { state, messages: output, complete };
|
|
1086
|
+
}
|
|
1087
|
+
async function readBranchPageMessages(host, segments) {
|
|
1088
|
+
const messages = [];
|
|
1089
|
+
let complete = true;
|
|
1090
|
+
// Pages can contain up to 500 rows. Keep body requests below the Node
|
|
1091
|
+
// client's bounded queue instead of launching one request per segment.
|
|
1092
|
+
for (let offset = 0; offset < segments.length; offset += 8) {
|
|
1093
|
+
const batch = segments.slice(offset, offset + 8);
|
|
1094
|
+
const turns = await Promise.all(batch.map(segment => readBranchTurn(host, segment.turnId)));
|
|
1095
|
+
for (let i = 0; i < batch.length; i++) {
|
|
1096
|
+
const turn = turns[i], segment = batch[i];
|
|
1097
|
+
if (!turn || turn.identity?.kind !== 'message' || turn.content === undefined) {
|
|
1098
|
+
complete = false;
|
|
1099
|
+
continue;
|
|
1100
|
+
}
|
|
1101
|
+
messages.push({
|
|
1102
|
+
businessId: segment.businessId, segmentId: segment.segmentId, turnId: turn.turnId,
|
|
1103
|
+
content: turn.content, nextSeq: turn.nextSeq, sealed: turn.sealed !== null,
|
|
1104
|
+
parents: turn.parents, sealedHash: turn.sealed,
|
|
1105
|
+
});
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
1108
|
+
return { messages, complete };
|
|
1109
|
+
}
|
|
1110
|
+
const activeBranchDirectoryCache = new WeakMap();
|
|
1111
|
+
function branchDirectoryKey(state) {
|
|
1112
|
+
return `${state.revision}:${state.head ? decodeUtf8(keyOf(state.head)) : ''}`;
|
|
1113
|
+
}
|
|
1114
|
+
async function branchTurnIdByIdentity(host, identity) {
|
|
1115
|
+
const key = keyOf(identity);
|
|
1116
|
+
const raw = host instanceof LodyHistory
|
|
1117
|
+
? await host.stream.store.run(false, host.stream.id, function* (tx) {
|
|
1118
|
+
return yield* tx.get(host.stream.space('lody_history_bindings_v1'), key);
|
|
1119
|
+
})
|
|
1120
|
+
: (await host.stream.readIndex([{ table: NODE_BINDINGS, key }]))[0];
|
|
1121
|
+
if (!raw)
|
|
1122
|
+
return;
|
|
1123
|
+
const found = binding(raw);
|
|
1124
|
+
if (found.conflict)
|
|
1125
|
+
throw new StoreError('conflict', 'multiple Turns claim one branch identity');
|
|
1126
|
+
return Uint8Array.from(found.turnId);
|
|
1127
|
+
}
|
|
1128
|
+
async function branchHeader(host, turnId) {
|
|
1129
|
+
const result = await host.stream.readTurnHeader(turnId);
|
|
1130
|
+
if (result.kind !== 'found')
|
|
1131
|
+
return;
|
|
1132
|
+
return { parents: result.turn.parents.map(parent => ({ id: parent.id.slice(), hash: parent.hash.slice() })) };
|
|
1133
|
+
}
|
|
1134
|
+
async function branchIdentityAt(host, turnId) {
|
|
1135
|
+
try {
|
|
1136
|
+
const value = await publicationField(host, turnId, [{ key: 'lodyHistory' }]);
|
|
1137
|
+
return decodeIdentity(value);
|
|
1138
|
+
}
|
|
1139
|
+
catch (error) {
|
|
1140
|
+
if (errorCode(error) === 'invalid' || errorCode(error) === 'pending')
|
|
1141
|
+
return undefined;
|
|
1142
|
+
throw error;
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
async function readActiveBranchDirectory(host, viewId) {
|
|
1146
|
+
for (let attempt = 0; attempt < 4; attempt++) {
|
|
1147
|
+
await host.catchUpIndex();
|
|
1148
|
+
const state = await readBranchIndex(host, viewId);
|
|
1149
|
+
const publicState = state
|
|
1150
|
+
? { viewId: state.viewId, revision: state.revision, head: state.head, operationId: state.operationId, ...(state.conflict ? { conflict: true } : {}) }
|
|
1151
|
+
: { viewId: text(viewId), revision: 0n, head: null, operationId: null };
|
|
1152
|
+
const key = branchDirectoryKey(publicState);
|
|
1153
|
+
const cached = activeBranchDirectoryCache.get(host)?.get(viewId);
|
|
1154
|
+
if (cached?.key === key)
|
|
1155
|
+
return cached.value;
|
|
1156
|
+
try {
|
|
1157
|
+
const { value } = await stableRead(host, async () => {
|
|
1158
|
+
const current = await readBranchIndex(host, viewId);
|
|
1159
|
+
const currentState = current
|
|
1160
|
+
? { viewId: current.viewId, revision: current.revision, head: current.head, operationId: current.operationId, ...(current.conflict ? { conflict: true } : {}) }
|
|
1161
|
+
: { viewId: text(viewId), revision: 0n, head: null, operationId: null };
|
|
1162
|
+
if (branchDirectoryKey(currentState) !== key)
|
|
1163
|
+
throw new StoreError('stale', 'active branch changed during directory read');
|
|
1164
|
+
if (current?.conflict)
|
|
1165
|
+
throw new StoreError('conflict', 'active branch has conflicting revisions');
|
|
1166
|
+
if (!current?.head)
|
|
1167
|
+
return { state: currentState, rows: [], complete: true };
|
|
1168
|
+
const headId = await branchTurnIdByIdentity(host, current.head);
|
|
1169
|
+
if (!headId)
|
|
1170
|
+
return { state: currentState, rows: [], complete: false };
|
|
1171
|
+
const seen = new Set();
|
|
1172
|
+
const rows = [];
|
|
1173
|
+
const byBusinessId = new Map();
|
|
1174
|
+
let complete = true;
|
|
1175
|
+
const visit = async (id) => {
|
|
1176
|
+
const idKey = hexBytes(id);
|
|
1177
|
+
if (seen.has(idKey))
|
|
1178
|
+
return;
|
|
1179
|
+
seen.add(idKey);
|
|
1180
|
+
const header = await branchHeader(host, id);
|
|
1181
|
+
if (!header) {
|
|
1182
|
+
complete = false;
|
|
1183
|
+
return;
|
|
1184
|
+
}
|
|
1185
|
+
for (const parent of header.parents)
|
|
1186
|
+
await visit(parent.id);
|
|
1187
|
+
const identity = await branchIdentityAt(host, id);
|
|
1188
|
+
if (identity?.kind !== 'message')
|
|
1189
|
+
return;
|
|
1190
|
+
let row = byBusinessId.get(identity.businessId);
|
|
1191
|
+
if (!row) {
|
|
1192
|
+
row = { businessId: identity.businessId, segments: [] };
|
|
1193
|
+
byBusinessId.set(identity.businessId, row);
|
|
1194
|
+
rows.push(row);
|
|
1195
|
+
}
|
|
1196
|
+
row.segments.push({ businessId: identity.businessId, segmentId: identity.segmentId, turnId: id.slice() });
|
|
1197
|
+
};
|
|
1198
|
+
await visit(headId);
|
|
1199
|
+
return { state: currentState, rows, complete };
|
|
1200
|
+
});
|
|
1201
|
+
let byView = activeBranchDirectoryCache.get(host);
|
|
1202
|
+
if (!byView) {
|
|
1203
|
+
byView = new Map();
|
|
1204
|
+
activeBranchDirectoryCache.set(host, byView);
|
|
1205
|
+
}
|
|
1206
|
+
byView.set(viewId, { key, value });
|
|
1207
|
+
return value;
|
|
1208
|
+
}
|
|
1209
|
+
catch (error) {
|
|
1210
|
+
if (errorCode(error) === 'stale' && attempt < 3)
|
|
1211
|
+
continue;
|
|
1212
|
+
throw error;
|
|
1213
|
+
}
|
|
1214
|
+
}
|
|
1215
|
+
throw new StoreError('stale', 'active branch directory retry budget exhausted');
|
|
1216
|
+
}
|
|
1217
|
+
async function readActiveBranchPage(host, viewId, input) {
|
|
1218
|
+
const limit = input.limit ?? 40;
|
|
1219
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 500)
|
|
1220
|
+
throw invalid('active branch page limit');
|
|
1221
|
+
if (input.from !== undefined && (!Number.isSafeInteger(input.from) || input.from < 0))
|
|
1222
|
+
throw invalid('active branch page offset');
|
|
1223
|
+
if ((input.latest && input.from !== undefined) || (input.before && (input.latest || input.from !== undefined))) {
|
|
1224
|
+
throw invalid('active branch page has conflicting cursors');
|
|
1225
|
+
}
|
|
1226
|
+
await host.catchUpIndex();
|
|
1227
|
+
const indexed = await readBranchIndex(host, text(viewId));
|
|
1228
|
+
const state = indexed
|
|
1229
|
+
? {
|
|
1230
|
+
viewId: indexed.viewId,
|
|
1231
|
+
revision: indexed.revision,
|
|
1232
|
+
head: indexed.head,
|
|
1233
|
+
operationId: indexed.operationId,
|
|
1234
|
+
...(indexed.logicalCount !== undefined ? { logicalCount: indexed.logicalCount } : {}),
|
|
1235
|
+
...(indexed.conflict ? { conflict: true } : {}),
|
|
1236
|
+
}
|
|
1237
|
+
: { viewId: text(viewId), revision: 0n, head: null, operationId: null, logicalCount: 0n };
|
|
1238
|
+
if (state.conflict)
|
|
1239
|
+
throw new StoreError('conflict', 'active branch has conflicting revisions');
|
|
1240
|
+
if (state.logicalCount !== undefined && (input.latest || input.before)) {
|
|
1241
|
+
try {
|
|
1242
|
+
const stable = await stableRead(host, async () => {
|
|
1243
|
+
const current = await readBranchIndex(host, state.viewId);
|
|
1244
|
+
const currentState = current
|
|
1245
|
+
? {
|
|
1246
|
+
viewId: current.viewId,
|
|
1247
|
+
revision: current.revision,
|
|
1248
|
+
head: current.head,
|
|
1249
|
+
operationId: current.operationId,
|
|
1250
|
+
...(current.logicalCount !== undefined ? { logicalCount: current.logicalCount } : {}),
|
|
1251
|
+
...(current.conflict ? { conflict: true } : {}),
|
|
1252
|
+
}
|
|
1253
|
+
: { viewId: state.viewId, revision: 0n, head: null, operationId: null, logicalCount: 0n };
|
|
1254
|
+
if (branchDirectoryKey(currentState) !== branchDirectoryKey(state)) {
|
|
1255
|
+
throw new StoreError('stale', 'active branch changed before page read');
|
|
1256
|
+
}
|
|
1257
|
+
if (currentState.conflict)
|
|
1258
|
+
throw new StoreError('conflict', 'active branch has conflicting revisions');
|
|
1259
|
+
return await readLinearActiveBranchPage(host, currentState, input, limit);
|
|
1260
|
+
});
|
|
1261
|
+
if (stable.value)
|
|
1262
|
+
return stable.value;
|
|
1263
|
+
}
|
|
1264
|
+
catch (error) {
|
|
1265
|
+
if (errorCode(error) !== 'stale')
|
|
1266
|
+
throw error;
|
|
1267
|
+
throw error;
|
|
1268
|
+
}
|
|
1269
|
+
}
|
|
1270
|
+
const directory = await readActiveBranchDirectory(host, text(viewId));
|
|
1271
|
+
const totalCount = directory.rows.length;
|
|
1272
|
+
if (input.before) {
|
|
1273
|
+
const before = input.before;
|
|
1274
|
+
const cursorRow = Number.isSafeInteger(before.position) ? directory.rows[before.position] : undefined;
|
|
1275
|
+
if (before.viewId !== directory.state.viewId || before.revision > directory.state.revision ||
|
|
1276
|
+
before.position < 0 || before.turnId.length !== 16 || before.headTurnId.length !== 16 ||
|
|
1277
|
+
!cursorRow?.segments.some(segment => equal(segment.turnId, before.turnId)) ||
|
|
1278
|
+
!directory.rows.some(row => row.segments.some(segment => equal(segment.turnId, before.headTurnId))))
|
|
1279
|
+
throw new StoreError('stale', 'active branch changed before older page was read');
|
|
1280
|
+
}
|
|
1281
|
+
const startPosition = input.before
|
|
1282
|
+
? Math.max(0, input.before.position - limit + 1)
|
|
1283
|
+
: input.latest
|
|
1284
|
+
? Math.max(0, totalCount - limit)
|
|
1285
|
+
: Math.min(input.from ?? 0, totalCount);
|
|
1286
|
+
const endPosition = Math.min(totalCount, input.before ? input.before.position + 1 : totalCount, startPosition + limit);
|
|
1287
|
+
const selectedIds = new Set(directory.rows.slice(startPosition, endPosition).map(row => row.businessId));
|
|
1288
|
+
const segments = directory.rows.filter(row => selectedIds.has(row.businessId)).flatMap(row => row.segments);
|
|
1289
|
+
let complete = directory.complete;
|
|
1290
|
+
const page = await readBranchPageMessages(host, segments);
|
|
1291
|
+
const messages = page.messages;
|
|
1292
|
+
complete &&= page.complete;
|
|
1293
|
+
let cursor = null;
|
|
1294
|
+
if (startPosition > 0) {
|
|
1295
|
+
if (input.before) {
|
|
1296
|
+
const headId = directory.state.head ? await branchTurnIdByIdentity(host, directory.state.head) : undefined;
|
|
1297
|
+
const activeIds = new Set(directory.rows.flatMap(row => row.segments.map(segment => hexBytes(segment.turnId))));
|
|
1298
|
+
if (!headId || !activeIds.has(hexBytes(input.before.headTurnId))) {
|
|
1299
|
+
throw new StoreError('stale', 'active branch changed before older page was read');
|
|
1300
|
+
}
|
|
1301
|
+
const olderRow = directory.rows[startPosition - 1];
|
|
1302
|
+
const olderSegment = olderRow?.segments[0];
|
|
1303
|
+
if (olderSegment)
|
|
1304
|
+
cursor = {
|
|
1305
|
+
viewId: directory.state.viewId,
|
|
1306
|
+
turnId: olderSegment.turnId.slice(),
|
|
1307
|
+
position: startPosition - 1,
|
|
1308
|
+
revision: directory.state.revision,
|
|
1309
|
+
headTurnId: headId,
|
|
1310
|
+
pendingSegments: [],
|
|
1311
|
+
};
|
|
1312
|
+
}
|
|
1313
|
+
else if (input.latest || input.from !== undefined) {
|
|
1314
|
+
const headId = directory.state.head ? await branchTurnIdByIdentity(host, directory.state.head) : undefined;
|
|
1315
|
+
const olderSegment = directory.rows[startPosition - 1]?.segments[0];
|
|
1316
|
+
if (headId && olderSegment)
|
|
1317
|
+
cursor = {
|
|
1318
|
+
viewId: directory.state.viewId,
|
|
1319
|
+
turnId: olderSegment.turnId.slice(),
|
|
1320
|
+
position: startPosition - 1,
|
|
1321
|
+
revision: directory.state.revision,
|
|
1322
|
+
headTurnId: headId,
|
|
1323
|
+
pendingSegments: [],
|
|
1324
|
+
};
|
|
1325
|
+
}
|
|
1326
|
+
}
|
|
1327
|
+
return {
|
|
1328
|
+
state: directory.state,
|
|
1329
|
+
totalCount,
|
|
1330
|
+
startPosition,
|
|
1331
|
+
messages,
|
|
1332
|
+
hasMoreOlder: startPosition > 0,
|
|
1333
|
+
cursor,
|
|
1334
|
+
complete,
|
|
1335
|
+
};
|
|
1336
|
+
}
|
|
1337
|
+
async function readLinearActiveBranchPage(host, state, input, limit) {
|
|
1338
|
+
const totalBigInt = state.logicalCount ?? 0n;
|
|
1339
|
+
if (totalBigInt > BigInt(Number.MAX_SAFE_INTEGER))
|
|
1340
|
+
throw new StoreError('invalid', 'active branch is too large to index');
|
|
1341
|
+
const totalCount = Number(totalBigInt);
|
|
1342
|
+
const headId = state.head ? await branchTurnIdByIdentity(host, state.head) : undefined;
|
|
1343
|
+
if (state.head && !headId)
|
|
1344
|
+
return {
|
|
1345
|
+
state, totalCount, startPosition: Math.max(0, totalCount - limit), messages: [],
|
|
1346
|
+
hasMoreOlder: totalCount > limit, cursor: null, complete: false,
|
|
1347
|
+
};
|
|
1348
|
+
if (!headId)
|
|
1349
|
+
return { state, totalCount, startPosition: 0, messages: [], hasMoreOlder: false, cursor: null, complete: true };
|
|
1350
|
+
let startPosition = input.before
|
|
1351
|
+
? Math.max(0, input.before.position - limit + 1)
|
|
1352
|
+
: Math.max(0, totalCount - limit);
|
|
1353
|
+
let currentId = input.before?.turnId.slice() ?? headId.slice();
|
|
1354
|
+
let collected = input.before?.pendingSegments.map(segment => ({ ...segment, turnId: segment.turnId.slice() })) ?? [];
|
|
1355
|
+
if (input.before) {
|
|
1356
|
+
const cursor = input.before;
|
|
1357
|
+
if (cursor.viewId !== state.viewId ||
|
|
1358
|
+
cursor.revision > state.revision ||
|
|
1359
|
+
!Number.isSafeInteger(cursor.position) ||
|
|
1360
|
+
cursor.position < 0 ||
|
|
1361
|
+
cursor.turnId.length !== 16 ||
|
|
1362
|
+
cursor.headTurnId.length !== 16 ||
|
|
1363
|
+
!Array.isArray(cursor.pendingSegments)) {
|
|
1364
|
+
throw new StoreError('stale', 'active branch page cursor is invalid');
|
|
1365
|
+
}
|
|
1366
|
+
const cursorMetadata = await branchMetadataAt(host, cursor.turnId);
|
|
1367
|
+
if (!cursorMetadata ||
|
|
1368
|
+
cursorMetadata.viewId !== state.viewId ||
|
|
1369
|
+
cursorMetadata.logicalCount !== BigInt(cursor.position + 1) ||
|
|
1370
|
+
cursorMetadata.head?.kind !== 'message' ||
|
|
1371
|
+
cursorMetadata.head.segmentId !== 'primary') {
|
|
1372
|
+
throw new StoreError('stale', 'active branch page cursor no longer names a primary row');
|
|
1373
|
+
}
|
|
1374
|
+
for (const segment of cursor.pendingSegments) {
|
|
1375
|
+
if (!segment ||
|
|
1376
|
+
typeof segment.businessId !== 'string' ||
|
|
1377
|
+
typeof segment.segmentId !== 'string' ||
|
|
1378
|
+
!(segment.turnId instanceof Uint8Array) ||
|
|
1379
|
+
segment.turnId.length !== 16) {
|
|
1380
|
+
throw new StoreError('stale', 'active branch page cursor has invalid pending segments');
|
|
1381
|
+
}
|
|
1382
|
+
}
|
|
1383
|
+
let ancestor = headId.slice();
|
|
1384
|
+
const expectedHead = hexBytes(cursor.headTurnId);
|
|
1385
|
+
let foundHead = false;
|
|
1386
|
+
const seen = new Set();
|
|
1387
|
+
const newerSuccessors = [];
|
|
1388
|
+
while (!seen.has(hexBytes(ancestor))) {
|
|
1389
|
+
const key = hexBytes(ancestor);
|
|
1390
|
+
if (key === expectedHead) {
|
|
1391
|
+
foundHead = true;
|
|
1392
|
+
break;
|
|
1393
|
+
}
|
|
1394
|
+
seen.add(key);
|
|
1395
|
+
const metadata = await branchMetadataAt(host, ancestor);
|
|
1396
|
+
if (!metadata || metadata.viewId !== state.viewId || !metadata.baseTurn)
|
|
1397
|
+
break;
|
|
1398
|
+
if (metadata.head?.kind === 'message' && metadata.head.segmentId !== 'primary') {
|
|
1399
|
+
const primaryId = await branchTurnIdByIdentity(host, {
|
|
1400
|
+
kind: 'message', businessId: metadata.head.businessId, segmentId: 'primary',
|
|
1401
|
+
});
|
|
1402
|
+
const primary = primaryId ? await branchMetadataAt(host, primaryId) : undefined;
|
|
1403
|
+
if (primary?.viewId !== state.viewId || primary.logicalCount === undefined)
|
|
1404
|
+
return undefined;
|
|
1405
|
+
if (primary.logicalCount <= BigInt(cursor.position + 1)) {
|
|
1406
|
+
newerSuccessors.push({ businessId: metadata.head.businessId, segmentId: metadata.head.segmentId, turnId: ancestor.slice() });
|
|
1407
|
+
}
|
|
1408
|
+
}
|
|
1409
|
+
ancestor = unhexBytes(metadata.baseTurn, 16);
|
|
1410
|
+
}
|
|
1411
|
+
if (!foundHead)
|
|
1412
|
+
throw new StoreError('stale', 'active branch changed before older page was read');
|
|
1413
|
+
collected = [...newerSuccessors, ...collected];
|
|
1414
|
+
}
|
|
1415
|
+
const selected = new Map();
|
|
1416
|
+
let olderCursor = null;
|
|
1417
|
+
let complete = true;
|
|
1418
|
+
const seen = new Set();
|
|
1419
|
+
while (true) {
|
|
1420
|
+
const turnKey = hexBytes(currentId);
|
|
1421
|
+
if (seen.has(turnKey)) {
|
|
1422
|
+
complete = false;
|
|
1423
|
+
break;
|
|
1424
|
+
}
|
|
1425
|
+
seen.add(turnKey);
|
|
1426
|
+
const metadata = await branchMetadataAt(host, currentId);
|
|
1427
|
+
// A partial replica stops at its fetched boundary. Do not turn that into
|
|
1428
|
+
// a full-directory fallback (and a false, shorter logical count).
|
|
1429
|
+
if (!metadata) {
|
|
1430
|
+
complete = false;
|
|
1431
|
+
break;
|
|
1432
|
+
}
|
|
1433
|
+
if (metadata.viewId !== state.viewId || !metadata.head || metadata.head.kind !== 'message')
|
|
1434
|
+
return undefined;
|
|
1435
|
+
if (metadata.logicalCount === undefined)
|
|
1436
|
+
return undefined;
|
|
1437
|
+
const header = await branchHeader(host, currentId);
|
|
1438
|
+
if (!header) {
|
|
1439
|
+
complete = false;
|
|
1440
|
+
break;
|
|
1441
|
+
}
|
|
1442
|
+
const expectedParent = metadata.baseTurn ? unhexBytes(metadata.baseTurn, 16) : undefined;
|
|
1443
|
+
if (header.parents.length !== (expectedParent ? 1 : 0) || (expectedParent && !equal(header.parents[0].id, expectedParent)))
|
|
1444
|
+
return undefined;
|
|
1445
|
+
const position = Number(metadata.logicalCount - 1n);
|
|
1446
|
+
if (metadata.head.segmentId === 'primary') {
|
|
1447
|
+
if (position < startPosition) {
|
|
1448
|
+
olderCursor = {
|
|
1449
|
+
viewId: state.viewId,
|
|
1450
|
+
turnId: currentId.slice(),
|
|
1451
|
+
position,
|
|
1452
|
+
revision: state.revision,
|
|
1453
|
+
headTurnId: headId.slice(),
|
|
1454
|
+
pendingSegments: collected.filter(segment => !selected.has(segment.businessId))
|
|
1455
|
+
.map(segment => ({ ...segment, turnId: segment.turnId.slice() })),
|
|
1456
|
+
};
|
|
1457
|
+
break;
|
|
1458
|
+
}
|
|
1459
|
+
if (position < startPosition + limit)
|
|
1460
|
+
selected.set(metadata.head.businessId, position);
|
|
1461
|
+
}
|
|
1462
|
+
collected.push({ businessId: metadata.head.businessId, segmentId: metadata.head.segmentId, turnId: currentId.slice() });
|
|
1463
|
+
if (!metadata.baseTurn)
|
|
1464
|
+
break;
|
|
1465
|
+
currentId = unhexBytes(metadata.baseTurn, 16);
|
|
1466
|
+
}
|
|
1467
|
+
const endPosition = Math.min(totalCount, input.before ? input.before.position + 1 : totalCount);
|
|
1468
|
+
const expectedRows = Math.max(0, Math.min(limit, endPosition - startPosition));
|
|
1469
|
+
if (selected.size !== expectedRows)
|
|
1470
|
+
complete = false;
|
|
1471
|
+
const selectedIds = new Set(selected.keys());
|
|
1472
|
+
const segmentGroups = new Map();
|
|
1473
|
+
for (const segment of [...collected].reverse()) {
|
|
1474
|
+
if (!selectedIds.has(segment.businessId))
|
|
1475
|
+
continue;
|
|
1476
|
+
const group = segmentGroups.get(segment.businessId) ?? [];
|
|
1477
|
+
group.push(segment);
|
|
1478
|
+
segmentGroups.set(segment.businessId, group);
|
|
1479
|
+
}
|
|
1480
|
+
const orderedSegments = [...selected].sort((a, b) => a[1] - b[1]).flatMap(([businessId]) => segmentGroups.get(businessId) ?? []);
|
|
1481
|
+
const page = await readBranchPageMessages(host, orderedSegments);
|
|
1482
|
+
const messages = page.messages;
|
|
1483
|
+
complete &&= page.complete;
|
|
1484
|
+
const actualStart = selected.size ? Math.min(...selected.values()) : startPosition;
|
|
1485
|
+
const cursor = olderCursor && actualStart > 0 ? olderCursor : null;
|
|
1486
|
+
return {
|
|
1487
|
+
state,
|
|
1488
|
+
totalCount,
|
|
1489
|
+
startPosition: actualStart,
|
|
1490
|
+
messages,
|
|
1491
|
+
hasMoreOlder: cursor !== null || (!complete && actualStart > 0),
|
|
1492
|
+
cursor,
|
|
1493
|
+
complete,
|
|
1494
|
+
};
|
|
1495
|
+
}
|
|
537
1496
|
async function publicationField(host, id, path) {
|
|
538
1497
|
if (host instanceof LodyHistory)
|
|
539
1498
|
return (await host.stream.readValue(id, path)).value;
|
|
@@ -728,6 +1687,7 @@ function decodeIdentity(value) {
|
|
|
728
1687
|
if (typeof kind !== 'string' || !knownKind(kind) || typeof businessId !== 'string' || typeof segmentId !== 'string')
|
|
729
1688
|
throw invalid('command identity');
|
|
730
1689
|
const identity = { kind, businessId, segmentId };
|
|
1690
|
+
assertWritableIdentity(identity);
|
|
731
1691
|
keyOf(identity);
|
|
732
1692
|
return identity;
|
|
733
1693
|
}
|
|
@@ -836,7 +1796,7 @@ async function readFound(host, id) {
|
|
|
836
1796
|
return { turnId: result.turn.turnId.slice(), nextSeq: result.turn.nextSeq, sealed: !!result.turn.sealed, inner: envelope.get('content') };
|
|
837
1797
|
}
|
|
838
1798
|
function encodeProjected(row) {
|
|
839
|
-
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]]);
|
|
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]]);
|
|
840
1800
|
}
|
|
841
1801
|
// Membership is durable; content and revision belong to the Turn. Legacy v1
|
|
842
1802
|
// rows containing full snapshots remain readable, without a migration scan.
|
|
@@ -1026,7 +1986,27 @@ async function hydratePublished(host, members) {
|
|
|
1026
1986
|
const body = 'contentJson' in turn ? decodeJson(encodeUtf8(turn.contentJson)) : turn.content;
|
|
1027
1987
|
if (!(body instanceof Map) || !body.has('content'))
|
|
1028
1988
|
throw invalid('history envelope');
|
|
1029
|
-
|
|
1989
|
+
let parents = [];
|
|
1990
|
+
if ('parents' in turn) {
|
|
1991
|
+
parents = turn.parents.map(parent => ({ id: parent.id.slice(), hash: parent.hash.slice() }));
|
|
1992
|
+
}
|
|
1993
|
+
else {
|
|
1994
|
+
const raw = host instanceof LodyHistory
|
|
1995
|
+
? await host.stream.exportUpdates(turn.turnId, 0n, 1)
|
|
1996
|
+
: await host.stream.exportUpdates(turn.turnId, 0n, 1n);
|
|
1997
|
+
const [create] = decodeBatch(raw);
|
|
1998
|
+
if (create?.operation.kind === 'create') {
|
|
1999
|
+
parents = create.operation.parents.map(parent => ({ id: parent.id.slice(), hash: parent.hash.slice() }));
|
|
2000
|
+
}
|
|
2001
|
+
}
|
|
2002
|
+
rows.push({
|
|
2003
|
+
...page[i],
|
|
2004
|
+
content: body.get('content'),
|
|
2005
|
+
nextSeq: turn.nextSeq,
|
|
2006
|
+
sealed: !!turn.sealed,
|
|
2007
|
+
parents,
|
|
2008
|
+
sealedHash: turn.sealed?.slice() ?? null,
|
|
2009
|
+
});
|
|
1030
2010
|
}
|
|
1031
2011
|
}
|
|
1032
2012
|
return rows;
|
|
@@ -1071,7 +2051,7 @@ async function captureBases(host, commands) {
|
|
|
1071
2051
|
}
|
|
1072
2052
|
const found = await readFound(host, command.identity);
|
|
1073
2053
|
if (found?.inner !== undefined)
|
|
1074
|
-
bases.push({ businessId: command.identity.businessId, segmentId: command.identity.segmentId, turnId: found.turnId, content: found.inner, nextSeq: found.nextSeq, sealed: found.sealed });
|
|
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 });
|
|
1075
2055
|
}
|
|
1076
2056
|
return bases;
|
|
1077
2057
|
}
|
|
@@ -1086,7 +2066,7 @@ async function messageEndStates(host, commands) {
|
|
|
1086
2066
|
seen.add(key);
|
|
1087
2067
|
const found = await readFound(host, command.identity);
|
|
1088
2068
|
if (found?.inner !== undefined)
|
|
1089
|
-
rows.push({ businessId: command.identity.businessId, segmentId: command.identity.segmentId, turnId: found.turnId, content: found.inner, nextSeq: found.nextSeq, sealed: found.sealed });
|
|
2069
|
+
rows.push({ businessId: command.identity.businessId, segmentId: command.identity.segmentId, turnId: found.turnId, content: found.inner, nextSeq: found.nextSeq, sealed: found.sealed, parents: [], sealedHash: null });
|
|
1090
2070
|
}
|
|
1091
2071
|
return rows;
|
|
1092
2072
|
}
|
|
@@ -1149,7 +2129,7 @@ function plannedMessage(id, found, planned) {
|
|
|
1149
2129
|
return prior;
|
|
1150
2130
|
if (found?.inner === undefined)
|
|
1151
2131
|
return;
|
|
1152
|
-
return { businessId: id.businessId, segmentId: id.segmentId, turnId: found.turnId, content: found.inner, nextSeq: found.nextSeq, sealed: found.sealed };
|
|
2132
|
+
return { businessId: id.businessId, segmentId: id.segmentId, turnId: found.turnId, content: found.inner, nextSeq: found.nextSeq, sealed: found.sealed, parents: [], sealedHash: null };
|
|
1153
2133
|
}
|
|
1154
2134
|
async function collectBatchWrites(host, identity, commands, applied) {
|
|
1155
2135
|
const writes = [];
|
|
@@ -1161,7 +2141,7 @@ async function collectBatchWrites(host, identity, commands, applied) {
|
|
|
1161
2141
|
if (command.type === 'accept' && command.identity.kind === 'message') {
|
|
1162
2142
|
const found = await readFound(host, command.identity);
|
|
1163
2143
|
if (found?.inner !== undefined)
|
|
1164
|
-
remember({ businessId: command.identity.businessId, segmentId: command.identity.segmentId, turnId: found.turnId, content: found.inner, nextSeq: found.nextSeq, sealed: found.sealed });
|
|
2144
|
+
remember({ businessId: command.identity.businessId, segmentId: command.identity.segmentId, turnId: found.turnId, content: found.inner, nextSeq: found.nextSeq, sealed: found.sealed, parents: [], sealedHash: null });
|
|
1165
2145
|
}
|
|
1166
2146
|
continue;
|
|
1167
2147
|
}
|
|
@@ -1174,8 +2154,8 @@ async function collectBatchWrites(host, identity, commands, applied) {
|
|
|
1174
2154
|
writes.push({ kind: 'createOnce', key: keyOf(command.identity), parents: command.parents, content: envelope(input) });
|
|
1175
2155
|
if (command.identity.kind === 'message') {
|
|
1176
2156
|
remember(found?.inner !== undefined
|
|
1177
|
-
? { businessId: command.identity.businessId, segmentId: command.identity.segmentId, turnId: found.turnId, content: found.inner, nextSeq: found.nextSeq, sealed: found.sealed }
|
|
1178
|
-
: { businessId: command.identity.businessId, segmentId: command.identity.segmentId, turnId: new Uint8Array(16), content: command.content, nextSeq: 1n, sealed: false, onceKey: keyOf(command.identity) });
|
|
2157
|
+
? { businessId: command.identity.businessId, segmentId: command.identity.segmentId, turnId: found.turnId, content: found.inner, nextSeq: found.nextSeq, sealed: found.sealed, parents: [], sealedHash: null }
|
|
2158
|
+
: { businessId: command.identity.businessId, segmentId: command.identity.segmentId, turnId: new Uint8Array(16), content: command.content, nextSeq: 1n, sealed: false, parents: [], sealedHash: null, onceKey: keyOf(command.identity) });
|
|
1179
2159
|
}
|
|
1180
2160
|
continue;
|
|
1181
2161
|
}
|
|
@@ -1274,6 +2254,11 @@ async function commitBatch(host, batchId, commands) {
|
|
|
1274
2254
|
throw invalid('batch id');
|
|
1275
2255
|
if (!commands.length || commands.length > 64)
|
|
1276
2256
|
throw invalid('batch size');
|
|
2257
|
+
for (const command of commands) {
|
|
2258
|
+
if (command.type === 'accept' || command.type === 'setContent' || command.type === 'finish') {
|
|
2259
|
+
assertWritableIdentity(command.identity);
|
|
2260
|
+
}
|
|
2261
|
+
}
|
|
1277
2262
|
await host.catchUpIndex();
|
|
1278
2263
|
const digest = commandDigest(batchId, commands);
|
|
1279
2264
|
const identity = { kind: 'batch_receipt', businessId: batchId, segmentId: 'v1' };
|