@loro-dev/roost 0.1.0 → 0.1.1
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 +42 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/lody-history.d.ts +98 -1
- package/dist/lody-history.js +952 -12
- 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]);
|
|
@@ -16,16 +16,188 @@ function keyOf(v) {
|
|
|
16
16
|
throw invalid('history kind');
|
|
17
17
|
return encodeUtf8(JSON.stringify([v.kind, text(v.businessId), text(v.segmentId)]));
|
|
18
18
|
}
|
|
19
|
+
const BRANCH_TABLE = 'lody_history_branches_v1';
|
|
20
|
+
const BRANCH_OPERATIONS = 'lody_history_branch_operations_v1';
|
|
21
|
+
function branchKey(viewId) { return encodeUtf8(text(viewId)); }
|
|
22
|
+
function branchOperationKey(viewId, operationId) {
|
|
23
|
+
return encodeUtf8(JSON.stringify([text(viewId), text(operationId)]));
|
|
24
|
+
}
|
|
25
|
+
function branchIdentity(value, label) {
|
|
26
|
+
if (value === null)
|
|
27
|
+
return null;
|
|
28
|
+
if (!(value instanceof Map))
|
|
29
|
+
throw invalid(label);
|
|
30
|
+
return decodeIdentity(value);
|
|
31
|
+
}
|
|
32
|
+
function branchMetadataValue(value) {
|
|
33
|
+
const metadata = new Map([
|
|
34
|
+
['version', '1'],
|
|
35
|
+
['viewId', value.viewId],
|
|
36
|
+
['revision', { kind: 'u64', value: value.revision }],
|
|
37
|
+
['operationId', value.operationId],
|
|
38
|
+
['previousHead', value.previousHead ? identityValue(value.previousHead) : null],
|
|
39
|
+
['head', value.head ? identityValue(value.head) : null],
|
|
40
|
+
['baseTurn', value.baseTurn],
|
|
41
|
+
['supersedes', value.supersedes.map(identityValue)],
|
|
42
|
+
['digest', value.digest],
|
|
43
|
+
]);
|
|
44
|
+
if (value.logicalCount !== undefined)
|
|
45
|
+
metadata.set('logicalCount', { kind: 'u64', value: value.logicalCount });
|
|
46
|
+
return metadata;
|
|
47
|
+
}
|
|
48
|
+
function parseBranchMetadata(value) {
|
|
49
|
+
if (value === undefined)
|
|
50
|
+
return;
|
|
51
|
+
if (!(value instanceof Map) || value.get('version') !== '1')
|
|
52
|
+
throw invalid('history branch metadata');
|
|
53
|
+
const viewId = value.get('viewId'), operationId = value.get('operationId'), revision = value.get('revision');
|
|
54
|
+
const baseTurn = value.get('baseTurn'), digest = value.get('digest'), supersedes = value.get('supersedes');
|
|
55
|
+
const logicalCount = value.get('logicalCount');
|
|
56
|
+
if (typeof viewId !== 'string' || typeof operationId !== 'string' || typeof baseTurn !== 'string' && baseTurn !== null ||
|
|
57
|
+
typeof digest !== 'string' || !revision || typeof revision !== 'object' || Array.isArray(revision) || revision instanceof Map || revision.kind !== 'u64' ||
|
|
58
|
+
!Array.isArray(supersedes))
|
|
59
|
+
throw invalid('history branch metadata');
|
|
60
|
+
const head = branchIdentity(value.get('head'), 'history branch head');
|
|
61
|
+
const previousHead = branchIdentity(value.get('previousHead'), 'history branch previous head');
|
|
62
|
+
const parsed = {
|
|
63
|
+
viewId: text(viewId), revision: revision.value, operationId: text(operationId),
|
|
64
|
+
previousHead, head, baseTurn,
|
|
65
|
+
...(logicalCount === undefined ? {} : { logicalCount: seqOf(logicalCount) }),
|
|
66
|
+
supersedes: supersedes.map(item => decodeIdentity(item)), digest,
|
|
67
|
+
};
|
|
68
|
+
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'))
|
|
69
|
+
throw invalid('history branch metadata');
|
|
70
|
+
if (!/^[0-9a-f]{64}$/.test(parsed.digest))
|
|
71
|
+
throw invalid('history branch digest');
|
|
72
|
+
if (parsed.baseTurn !== null && !/^[0-9a-f]{32}$/.test(parsed.baseTurn))
|
|
73
|
+
throw invalid('history branch base turn');
|
|
74
|
+
return parsed;
|
|
75
|
+
}
|
|
76
|
+
function branchStateValue(value, conflict = false) {
|
|
77
|
+
const state = branchMetadataValue(value);
|
|
78
|
+
if (conflict && state instanceof Map)
|
|
79
|
+
state.set('conflict', true);
|
|
80
|
+
return encodeJson(state);
|
|
81
|
+
}
|
|
82
|
+
function parseBranchState(raw) {
|
|
83
|
+
const value = decodeJson(raw);
|
|
84
|
+
let metadata;
|
|
85
|
+
try {
|
|
86
|
+
metadata = parseBranchMetadata(value);
|
|
87
|
+
}
|
|
88
|
+
catch (error) {
|
|
89
|
+
throw new StoreError('corrupt', 'invalid history branch state', { cause: error });
|
|
90
|
+
}
|
|
91
|
+
if (!metadata)
|
|
92
|
+
throw new StoreError('corrupt', 'invalid history branch state');
|
|
93
|
+
const previous = value instanceof Map ? value.get('conflict') : undefined;
|
|
94
|
+
return { viewId: metadata.viewId, revision: metadata.revision, head: metadata.head, operationId: metadata.operationId, digest: metadata.digest, ...(metadata.logicalCount !== undefined ? { logicalCount: metadata.logicalCount } : {}), ...(previous === true ? { conflict: true } : {}) };
|
|
95
|
+
}
|
|
96
|
+
function branchOperationValue(result, digest) {
|
|
97
|
+
return encodeJson(new Map([
|
|
98
|
+
['version', '1'], ['operationId', result.operationId], ['created', result.created],
|
|
99
|
+
['oldHead', result.oldHead ? identityValue(result.oldHead) : null], ['newHead', result.newHead ? identityValue(result.newHead) : null],
|
|
100
|
+
['revision', { kind: 'u64', value: result.revision }], ['turnId', result.turnId ? hexBytes(result.turnId) : null], ['digest', digest],
|
|
101
|
+
]));
|
|
102
|
+
}
|
|
103
|
+
function parseBranchOperation(raw) {
|
|
104
|
+
const value = decodeJson(raw);
|
|
105
|
+
if (!(value instanceof Map) || value.get('version') !== '1')
|
|
106
|
+
throw new StoreError('corrupt', 'invalid history branch operation');
|
|
107
|
+
const operationId = value.get('operationId'), created = value.get('created'), revision = value.get('revision'), turnId = value.get('turnId'), digest = value.get('digest');
|
|
108
|
+
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')
|
|
109
|
+
throw new StoreError('corrupt', 'invalid history branch operation');
|
|
110
|
+
const oldHead = branchIdentity(value.get('oldHead'), 'history branch operation old head');
|
|
111
|
+
const newHead = branchIdentity(value.get('newHead'), 'history branch operation new head');
|
|
112
|
+
if ((newHead !== null && newHead.kind !== 'message') || (oldHead !== null && oldHead.kind !== 'message'))
|
|
113
|
+
throw new StoreError('corrupt', 'invalid history branch operation head');
|
|
114
|
+
if ((turnId !== null && !/^[0-9a-f]{32}$/.test(turnId)) || !/^[0-9a-f]{64}$/.test(digest))
|
|
115
|
+
throw new StoreError('corrupt', 'invalid history branch operation encoding');
|
|
116
|
+
return { operationId: text(operationId), created, oldHead, newHead, revision: revision.value, turnId: turnId === null ? null : unhexBytes(turnId, 16), digest };
|
|
117
|
+
}
|
|
118
|
+
function branchMetadataFromContent(content) {
|
|
119
|
+
if (!(content instanceof Map))
|
|
120
|
+
return;
|
|
121
|
+
return parseBranchMetadata(content.get('lodyBranch'));
|
|
122
|
+
}
|
|
123
|
+
function branchStateEqual(a, b) {
|
|
124
|
+
if (a === null || b === null)
|
|
125
|
+
return a === b;
|
|
126
|
+
return equal(keyOf(a), keyOf(b));
|
|
127
|
+
}
|
|
128
|
+
function branchParentMatches(baseTurn, parents) {
|
|
129
|
+
return baseTurn === null ? parents.length === 0 : parents.some(parent => equal(parent.id, baseTurn));
|
|
130
|
+
}
|
|
131
|
+
function mergeBranchStateRaw(previous, candidate) {
|
|
132
|
+
if (!previous)
|
|
133
|
+
return candidate;
|
|
134
|
+
const old = parseBranchState(previous), next = parseBranchState(candidate);
|
|
135
|
+
if (old.conflict)
|
|
136
|
+
return previous;
|
|
137
|
+
if (next.revision > old.revision)
|
|
138
|
+
return candidate;
|
|
139
|
+
if (next.revision < old.revision)
|
|
140
|
+
return previous;
|
|
141
|
+
if (old.operationId === next.operationId && branchStateEqual(old.head, next.head) && old.digest === next.digest)
|
|
142
|
+
return previous;
|
|
143
|
+
return branchStateValue({
|
|
144
|
+
viewId: old.viewId,
|
|
145
|
+
revision: old.revision,
|
|
146
|
+
operationId: old.operationId,
|
|
147
|
+
previousHead: null,
|
|
148
|
+
head: old.head,
|
|
149
|
+
baseTurn: null,
|
|
150
|
+
supersedes: [],
|
|
151
|
+
digest: old.digest,
|
|
152
|
+
}, true);
|
|
153
|
+
}
|
|
154
|
+
function branchStateRows(rows, prior) {
|
|
155
|
+
const merged = new Map();
|
|
156
|
+
for (const row of rows) {
|
|
157
|
+
const key = hexBytes(row.key);
|
|
158
|
+
const before = merged.has(key) ? merged.get(key) : prior.get(key);
|
|
159
|
+
merged.set(key, mergeBranchStateRaw(before, row.value));
|
|
160
|
+
}
|
|
161
|
+
return merged;
|
|
162
|
+
}
|
|
163
|
+
function branchMutationDigest(input, owner, baseTurn, supersedes) {
|
|
164
|
+
const body = new Map([
|
|
165
|
+
['viewId', input.viewId],
|
|
166
|
+
['revision', { kind: 'u64', value: input.expectedRevision }],
|
|
167
|
+
['operationId', input.operationId],
|
|
168
|
+
['expectedHead', input.expectedHead ? identityValue(input.expectedHead) : null],
|
|
169
|
+
['baseTurn', baseTurn ? hexBytes(baseTurn) : null],
|
|
170
|
+
['supersedes', supersedes.map(identityValue)],
|
|
171
|
+
['createDigest', hexBytes(createDigest(owner, input.input.parents, envelope(input.input)))],
|
|
172
|
+
]);
|
|
173
|
+
return hexBytes(blake3(encodeJson(body)));
|
|
174
|
+
}
|
|
175
|
+
function branchMetadataFor(input, owner, previousHead, baseTurn, supersedes, logicalCount) {
|
|
176
|
+
const digest = branchMutationDigest(input, owner, baseTurn, supersedes);
|
|
177
|
+
return {
|
|
178
|
+
viewId: text(input.viewId),
|
|
179
|
+
revision: input.expectedRevision + 1n,
|
|
180
|
+
operationId: text(input.operationId),
|
|
181
|
+
previousHead,
|
|
182
|
+
head: { kind: input.input.kind, businessId: input.input.businessId, segmentId: input.input.segmentId },
|
|
183
|
+
baseTurn: baseTurn ? hexBytes(baseTurn) : null,
|
|
184
|
+
...(logicalCount !== undefined ? { logicalCount } : {}),
|
|
185
|
+
supersedes: supersedes.map(value => ({ ...value })),
|
|
186
|
+
digest,
|
|
187
|
+
};
|
|
188
|
+
}
|
|
19
189
|
function attachment(a) {
|
|
20
190
|
if (!/^[0-9a-f]{64}$/.test(a.sha256) || typeof a.size !== 'bigint' || a.size < 0n)
|
|
21
191
|
throw invalid('attachment identity');
|
|
22
192
|
return new Map([['attachmentId', text(a.attachmentId)], ['sha256', a.sha256], ['name', text(a.name)], ['size', { kind: 'u64', value: a.size }]]);
|
|
23
193
|
}
|
|
24
|
-
function envelope(v, publish = false) {
|
|
194
|
+
function envelope(v, publish = false, branch) {
|
|
25
195
|
keyOf(v);
|
|
26
196
|
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
197
|
if (v.kind === 'message')
|
|
28
198
|
body.set('lodyPublication', publish ? 'direct' : 'private');
|
|
199
|
+
if (branch)
|
|
200
|
+
body.set('lodyBranch', branchMetadataValue(branch));
|
|
29
201
|
return body;
|
|
30
202
|
}
|
|
31
203
|
function identityOf(content) {
|
|
@@ -54,9 +226,10 @@ function canonicalCreate(owner, parents, content) {
|
|
|
54
226
|
// of the original application input. Old envelopes have no marker and retain
|
|
55
227
|
// exactly their previous digest. This is an application retry digest, not a seal.
|
|
56
228
|
function createDigest(owner, parents, content) {
|
|
57
|
-
if (content instanceof Map && (content.get('lodyPublication') === 'direct' || content.get('lodyPublication') === 'private')) {
|
|
229
|
+
if (content instanceof Map && (content.get('lodyPublication') === 'direct' || content.get('lodyPublication') === 'private' || content.has('lodyBranch'))) {
|
|
58
230
|
content = new Map(content);
|
|
59
231
|
content.delete('lodyPublication');
|
|
232
|
+
content.delete('lodyBranch');
|
|
60
233
|
}
|
|
61
234
|
return blake3(canonicalCreate(owner, parents, content));
|
|
62
235
|
}
|
|
@@ -100,6 +273,7 @@ export class LodyHistory {
|
|
|
100
273
|
if (!events.length)
|
|
101
274
|
return false; // A read must not write a cursor and wake itself.
|
|
102
275
|
const rows = [];
|
|
276
|
+
const branchRows = [];
|
|
103
277
|
const objects = [];
|
|
104
278
|
const invalidTurns = [];
|
|
105
279
|
for (const record of events) {
|
|
@@ -121,6 +295,19 @@ export class LodyHistory {
|
|
|
121
295
|
objects.push({ key: u.turnId, value: encodeUtf8('null') });
|
|
122
296
|
continue;
|
|
123
297
|
}
|
|
298
|
+
let branch;
|
|
299
|
+
try {
|
|
300
|
+
branch = branchMetadataFromContent(u.operation.content);
|
|
301
|
+
}
|
|
302
|
+
catch (error) {
|
|
303
|
+
if (errorCode(error) !== 'invalid')
|
|
304
|
+
throw error;
|
|
305
|
+
invalidTurns.push(u.turnId);
|
|
306
|
+
objects.push({ key: u.turnId, value: encodeUtf8('null') });
|
|
307
|
+
continue;
|
|
308
|
+
}
|
|
309
|
+
if (branch)
|
|
310
|
+
branchRows.push({ key: branchKey(branch.viewId), value: branchStateValue(branch) });
|
|
124
311
|
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
312
|
objects.push({ key: u.turnId, value: encodeUtf8(JSON.stringify(publicationObject(u.owner, u.operation.parents, u.operation.content))) });
|
|
126
313
|
}
|
|
@@ -140,6 +327,15 @@ export class LodyHistory {
|
|
|
140
327
|
row.value.conflict = true;
|
|
141
328
|
yield* tx.put(space, row.key, encodeUtf8(JSON.stringify(row.value)));
|
|
142
329
|
}
|
|
330
|
+
const branchStates = new Map();
|
|
331
|
+
for (const row of branchRows) {
|
|
332
|
+
const key = hexBytes(row.key);
|
|
333
|
+
if (!branchStates.has(key))
|
|
334
|
+
branchStates.set(key, yield* tx.get(stream.space(BRANCH_TABLE), row.key));
|
|
335
|
+
branchStates.set(key, mergeBranchStateRaw(branchStates.get(key), row.value));
|
|
336
|
+
}
|
|
337
|
+
for (const [key, value] of branchStates)
|
|
338
|
+
yield* tx.put(stream.space(BRANCH_TABLE), unhexBytes(key, key.length / 2), value);
|
|
143
339
|
yield* tx.put(cursorSpace, key, encodeUtf8(through.toString()));
|
|
144
340
|
return true;
|
|
145
341
|
});
|
|
@@ -199,6 +395,20 @@ export class LodyHistory {
|
|
|
199
395
|
}
|
|
200
396
|
throw new StoreError('stale', 'history discovery retry budget exhausted');
|
|
201
397
|
}
|
|
398
|
+
/** Append a message to an active view and advance that view atomically. */
|
|
399
|
+
acceptToView(input) {
|
|
400
|
+
return branchAccept(this, input);
|
|
401
|
+
}
|
|
402
|
+
/** Create a replacement Turn and switch the same logical view to it. */
|
|
403
|
+
forkAndActivate(input) {
|
|
404
|
+
return branchFork(this, input);
|
|
405
|
+
}
|
|
406
|
+
readActiveBranch(viewId) {
|
|
407
|
+
return readActiveBranch(this, viewId);
|
|
408
|
+
}
|
|
409
|
+
readActiveBranchPage(viewId, input = {}) {
|
|
410
|
+
return readActiveBranchPage(this, viewId, input);
|
|
411
|
+
}
|
|
202
412
|
append(id, expectedNextSeq, ops) {
|
|
203
413
|
return this.stream.writer(this.identity).edit(id, expectedNextSeq, ops.map(op => ({ ...op, path: [{ key: 'content' }, ...op.path] })));
|
|
204
414
|
}
|
|
@@ -324,6 +534,7 @@ export class NodeLodyHistory {
|
|
|
324
534
|
return false;
|
|
325
535
|
const changes = [];
|
|
326
536
|
const rows = [];
|
|
537
|
+
const branchRows = [];
|
|
327
538
|
const touched = new Map();
|
|
328
539
|
const receipts = new Map();
|
|
329
540
|
for (const record of events) {
|
|
@@ -349,6 +560,19 @@ export class NodeLodyHistory {
|
|
|
349
560
|
changes.push({ table: PUBLICATION_OBJECTS, key: u.turnId, value: encodeUtf8('null') });
|
|
350
561
|
continue;
|
|
351
562
|
}
|
|
563
|
+
let branch;
|
|
564
|
+
try {
|
|
565
|
+
branch = branchMetadataFromContent(u.operation.content);
|
|
566
|
+
}
|
|
567
|
+
catch (error) {
|
|
568
|
+
if (errorCode(error) !== 'invalid')
|
|
569
|
+
throw error;
|
|
570
|
+
changes.push({ table: NODE_INVALID, key: u.turnId, value: encodeUtf8('invalid_envelope') });
|
|
571
|
+
changes.push({ table: PUBLICATION_OBJECTS, key: u.turnId, value: encodeUtf8('null') });
|
|
572
|
+
continue;
|
|
573
|
+
}
|
|
574
|
+
if (branch)
|
|
575
|
+
branchRows.push({ key: branchKey(branch.viewId), value: branchStateValue(branch) });
|
|
352
576
|
const key = keyOf(id);
|
|
353
577
|
rows.push({ key, value: { version: 1, turnId: [...u.turnId], owner: [...u.owner], digest: [...createDigest(u.owner, u.operation.parents, u.operation.content)] } });
|
|
354
578
|
changes.push({ table: PUBLICATION_OBJECTS, key: u.turnId, value: encodeUtf8(JSON.stringify(publicationObject(u.owner, u.operation.parents, u.operation.content))) });
|
|
@@ -367,6 +591,13 @@ export class NodeLodyHistory {
|
|
|
367
591
|
merged.set(key, row.value);
|
|
368
592
|
changes.push({ table: NODE_BINDINGS, key: row.key, value: encodeUtf8(JSON.stringify(row.value)) });
|
|
369
593
|
}
|
|
594
|
+
const branchPriorRows = await this.stream.readIndex([...new Map(branchRows.map(row => [hexBytes(row.key), row])).values()].map(row => ({ table: BRANCH_TABLE, key: row.key })));
|
|
595
|
+
const branchPrior = new Map();
|
|
596
|
+
let branchPriorIndex = 0;
|
|
597
|
+
for (const row of [...new Map(branchRows.map(row => [hexBytes(row.key), row])).values()])
|
|
598
|
+
branchPrior.set(hexBytes(row.key), branchPriorRows[branchPriorIndex++] ?? undefined);
|
|
599
|
+
for (const [key, value] of branchStateRows(branchRows, branchPrior))
|
|
600
|
+
changes.push({ table: BRANCH_TABLE, key: unhexBytes(key, key.length / 2), value });
|
|
370
601
|
// Only touched receipts are inspected. The pending index lets normal
|
|
371
602
|
// startup avoid enumerating every completed receipt / business binding.
|
|
372
603
|
const ids = [...touched.values()];
|
|
@@ -461,6 +692,13 @@ export class NodeLodyHistory {
|
|
|
461
692
|
}
|
|
462
693
|
throw new StoreError('stale', 'history discovery retry budget exhausted');
|
|
463
694
|
}
|
|
695
|
+
acceptToView(input) { return branchAccept(this, input); }
|
|
696
|
+
forkAndActivate(input) { return branchFork(this, input); }
|
|
697
|
+
restoreActiveBranch(input) { return branchRestore(this, input); }
|
|
698
|
+
readActiveBranch(viewId) { return readActiveBranch(this, viewId); }
|
|
699
|
+
readActiveBranchPage(viewId, input = {}) {
|
|
700
|
+
return readActiveBranchPage(this, viewId, input);
|
|
701
|
+
}
|
|
464
702
|
async respondPermission(input) {
|
|
465
703
|
const result = await this.accept({ businessId: text(input.requestId), segmentId: 'response', kind: 'permission_response', parents: input.parents,
|
|
466
704
|
content: new Map([['assistantBusinessId', text(input.assistantBusinessId)], ['outcome', input.outcome]]) });
|
|
@@ -534,6 +772,688 @@ export class NodeLodyHistory {
|
|
|
534
772
|
}
|
|
535
773
|
}
|
|
536
774
|
}
|
|
775
|
+
async function readBranchIndex(host, viewId) {
|
|
776
|
+
const key = branchKey(viewId);
|
|
777
|
+
const raw = host instanceof LodyHistory
|
|
778
|
+
? await host.stream.store.run(false, host.stream.id, function* (tx) { return yield* tx.get(host.stream.space(BRANCH_TABLE), key); })
|
|
779
|
+
: (await host.stream.readIndex([{ table: BRANCH_TABLE, key }]))[0];
|
|
780
|
+
return raw ? parseBranchState(raw) : undefined;
|
|
781
|
+
}
|
|
782
|
+
async function readBranchOperation(host, viewId, operationId) {
|
|
783
|
+
const key = branchOperationKey(viewId, operationId);
|
|
784
|
+
const raw = host instanceof LodyHistory
|
|
785
|
+
? await host.stream.store.run(false, host.stream.id, function* (tx) { return yield* tx.get(host.stream.space(BRANCH_OPERATIONS), key); })
|
|
786
|
+
: (await host.stream.readIndex([{ table: BRANCH_OPERATIONS, key }]))[0];
|
|
787
|
+
if (!raw)
|
|
788
|
+
return;
|
|
789
|
+
return parseBranchOperation(raw);
|
|
790
|
+
}
|
|
791
|
+
async function branchCursor(host) {
|
|
792
|
+
return host instanceof LodyHistory ? host.observedEventCursor() : (await host.observedEventCursor());
|
|
793
|
+
}
|
|
794
|
+
async function branchOwner(host) {
|
|
795
|
+
return host instanceof LodyHistory ? host.identity.owner() : host.owner.slice();
|
|
796
|
+
}
|
|
797
|
+
async function branchTurnByIdentity(host, identity) {
|
|
798
|
+
const found = await host.lookup(identity);
|
|
799
|
+
if (!found || found.kind !== 'found')
|
|
800
|
+
return;
|
|
801
|
+
return found.turn.turnId.slice();
|
|
802
|
+
}
|
|
803
|
+
async function branchMetadataAt(host, turnId) {
|
|
804
|
+
try {
|
|
805
|
+
return parseBranchMetadata(await publicationField(host, turnId, [{ key: 'lodyBranch' }]));
|
|
806
|
+
}
|
|
807
|
+
catch (error) {
|
|
808
|
+
if (errorCode(error) === 'invalid')
|
|
809
|
+
return undefined;
|
|
810
|
+
throw error;
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
async function branchLogicalCountAt(host, viewId, turnId) {
|
|
814
|
+
if (!turnId)
|
|
815
|
+
return 0n;
|
|
816
|
+
const metadata = await branchMetadataAt(host, turnId);
|
|
817
|
+
if (metadata?.viewId === viewId && metadata.logicalCount !== undefined)
|
|
818
|
+
return metadata.logicalCount;
|
|
819
|
+
const directory = await readActiveBranchDirectory(host, viewId);
|
|
820
|
+
const id = hexBytes(turnId);
|
|
821
|
+
const position = directory.rows.findIndex(row => row.segments.some(segment => hexBytes(segment.turnId) === id));
|
|
822
|
+
if (position < 0)
|
|
823
|
+
throw new StoreError('stale', 'branch base is not in the active history');
|
|
824
|
+
return BigInt(position + 1);
|
|
825
|
+
}
|
|
826
|
+
async function readBranchTurn(host, turnId) {
|
|
827
|
+
if (host instanceof LodyHistory) {
|
|
828
|
+
const result = await host.stream.readTurn(turnId);
|
|
829
|
+
if (result.kind !== 'found')
|
|
830
|
+
return;
|
|
831
|
+
const body = result.turn.content;
|
|
832
|
+
return {
|
|
833
|
+
turnId: result.turn.turnId.slice(),
|
|
834
|
+
parents: result.turn.parents.map(parent => ({ id: parent.id.slice(), hash: parent.hash.slice() })),
|
|
835
|
+
identity: identityOf(body),
|
|
836
|
+
content: body instanceof Map ? body.get('content') : undefined,
|
|
837
|
+
nextSeq: result.turn.nextSeq,
|
|
838
|
+
sealed: result.turn.sealed?.slice() ?? null,
|
|
839
|
+
};
|
|
840
|
+
}
|
|
841
|
+
const result = await host.stream.readTurn(turnId);
|
|
842
|
+
if (result.kind !== 'found')
|
|
843
|
+
return;
|
|
844
|
+
const [create] = decodeBatch(await host.stream.exportUpdates(turnId, 0n, 1n));
|
|
845
|
+
if (!create || create.operation.kind !== 'create')
|
|
846
|
+
throw new StoreError('corrupt', 'branch head has no Create');
|
|
847
|
+
const body = decodeJson(encodeUtf8(result.turn.contentJson));
|
|
848
|
+
return {
|
|
849
|
+
turnId: result.turn.turnId.slice(),
|
|
850
|
+
parents: create.operation.parents.map(parent => ({ id: parent.id.slice(), hash: parent.hash.slice() })),
|
|
851
|
+
identity: identityOf(body),
|
|
852
|
+
content: body instanceof Map ? body.get('content') : undefined,
|
|
853
|
+
nextSeq: result.turn.nextSeq,
|
|
854
|
+
sealed: result.turn.sealed?.slice() ?? null,
|
|
855
|
+
};
|
|
856
|
+
}
|
|
857
|
+
async function branchMutation(host, input, baseTurn, supersedes) {
|
|
858
|
+
if (input.input.kind !== 'message')
|
|
859
|
+
throw invalid('active branch only accepts message Turns');
|
|
860
|
+
if (typeof input.expectedRevision !== 'bigint' || input.expectedRevision < 0n || input.expectedRevision >= U64_MAX)
|
|
861
|
+
throw invalid('branch revision');
|
|
862
|
+
const viewId = text(input.viewId), operationId = text(input.operationId), owner = await branchOwner(host);
|
|
863
|
+
const expectedHead = input.expectedHead ? { ...input.expectedHead } : null;
|
|
864
|
+
if (baseTurn !== null && baseTurn.length !== 16)
|
|
865
|
+
throw invalid('branch base Turn');
|
|
866
|
+
if (expectedHead) {
|
|
867
|
+
if (expectedHead.kind !== 'message')
|
|
868
|
+
throw invalid('branch head kind');
|
|
869
|
+
keyOf(expectedHead);
|
|
870
|
+
}
|
|
871
|
+
for (const superseded of supersedes) {
|
|
872
|
+
if (superseded.kind !== 'message')
|
|
873
|
+
throw invalid('branch superseded kind');
|
|
874
|
+
keyOf(superseded);
|
|
875
|
+
}
|
|
876
|
+
if (!branchParentMatches(baseTurn, input.input.parents))
|
|
877
|
+
throw invalid('branch base parent');
|
|
878
|
+
const baseCount = await branchLogicalCountAt(host, viewId, baseTurn);
|
|
879
|
+
const logicalCount = baseCount + (input.input.segmentId === 'primary' ? 1n : 0n);
|
|
880
|
+
const metadata = branchMetadataFor({ ...input, viewId, operationId, expectedHead }, owner, expectedHead, baseTurn, supersedes, logicalCount);
|
|
881
|
+
const createKey = keyOf(input.input);
|
|
882
|
+
const branchValue = branchStateValue(metadata);
|
|
883
|
+
const operationValue = branchOperationValue({ operationId, created: true, oldHead: expectedHead, newHead: metadata.head, revision: metadata.revision, turnId: null }, metadata.digest);
|
|
884
|
+
for (let attempt = 0; attempt < 4; attempt++) {
|
|
885
|
+
await host.catchUpIndex();
|
|
886
|
+
const [state, priorOperation] = await Promise.all([
|
|
887
|
+
readBranchIndex(host, viewId),
|
|
888
|
+
readBranchOperation(host, viewId, operationId),
|
|
889
|
+
]);
|
|
890
|
+
if (priorOperation) {
|
|
891
|
+
if (priorOperation.digest !== metadata.digest || !branchStateEqual(priorOperation.oldHead, expectedHead) || !branchStateEqual(priorOperation.newHead, metadata.head))
|
|
892
|
+
throw new StoreError('conflict', 'branch operation input changed');
|
|
893
|
+
if (priorOperation.newHead === null)
|
|
894
|
+
throw new StoreError('corrupt', 'branch operation head missing');
|
|
895
|
+
const turnId = priorOperation.turnId ?? await branchTurnByIdentity(host, priorOperation.newHead);
|
|
896
|
+
if (!turnId)
|
|
897
|
+
throw new StoreError('corrupt', 'branch operation Turn missing');
|
|
898
|
+
return { operationId, created: false, oldHead: priorOperation.oldHead, newHead: priorOperation.newHead, revision: priorOperation.revision, turnId };
|
|
899
|
+
}
|
|
900
|
+
if (state?.conflict)
|
|
901
|
+
throw new StoreError('conflict', 'active branch has conflicting revisions');
|
|
902
|
+
if ((state?.revision ?? 0n) !== input.expectedRevision || !branchStateEqual(state?.head ?? null, expectedHead))
|
|
903
|
+
throw new StoreError('stale', 'active branch changed');
|
|
904
|
+
const existing = await host.lookup(input.input);
|
|
905
|
+
if (existing) {
|
|
906
|
+
const existingEnvelope = existing.kind === 'found'
|
|
907
|
+
? ('content' in existing.turn ? existing.turn.content : decodeJson(encodeUtf8(existing.turn.contentJson)))
|
|
908
|
+
: undefined;
|
|
909
|
+
const existingBranch = existingEnvelope === undefined ? undefined : branchMetadataFromContent(existingEnvelope);
|
|
910
|
+
if (!existingBranch || existingBranch.operationId !== operationId || existingBranch.digest !== metadata.digest)
|
|
911
|
+
throw new StoreError('conflict', 'branch message identity already exists');
|
|
912
|
+
}
|
|
913
|
+
const cursor = await branchCursor(host);
|
|
914
|
+
try {
|
|
915
|
+
await writeIndexed(host, [{ kind: 'createOnce', key: createKey, parents: input.input.parents, content: envelope(input.input, true, metadata) }], [
|
|
916
|
+
{ table: BRANCH_TABLE, key: branchKey(viewId), value: branchValue, emitEvent: true },
|
|
917
|
+
{ table: BRANCH_OPERATIONS, key: branchOperationKey(viewId, operationId), value: operationValue },
|
|
918
|
+
], cursor);
|
|
919
|
+
}
|
|
920
|
+
catch (error) {
|
|
921
|
+
if (errorCode(error) !== 'stale')
|
|
922
|
+
throw error;
|
|
923
|
+
continue;
|
|
924
|
+
}
|
|
925
|
+
await host.catchUpIndex();
|
|
926
|
+
const turnId = await branchTurnByIdentity(host, metadata.head);
|
|
927
|
+
if (!turnId)
|
|
928
|
+
throw new StoreError('corrupt', 'active branch replacement missing');
|
|
929
|
+
await maybePublishAccept(host, input.input, { publish: true }, turnId);
|
|
930
|
+
return { operationId, created: true, oldHead: expectedHead, newHead: metadata.head, revision: metadata.revision, turnId };
|
|
931
|
+
}
|
|
932
|
+
throw new StoreError('stale', 'active branch retry budget exhausted');
|
|
933
|
+
}
|
|
934
|
+
async function branchAccept(host, input) {
|
|
935
|
+
const baseTurn = input.expectedHead ? await branchTurnByIdentity(host, input.expectedHead) ?? null : null;
|
|
936
|
+
return branchMutation(host, input, baseTurn, []);
|
|
937
|
+
}
|
|
938
|
+
async function branchFork(host, input) {
|
|
939
|
+
if (input.input.kind !== 'message')
|
|
940
|
+
throw invalid('active branch only accepts message replacements');
|
|
941
|
+
if (input.baseTurn && input.baseTurn.length !== 16)
|
|
942
|
+
throw invalid('branch base Turn');
|
|
943
|
+
return branchMutation(host, input, input.baseTurn, input.supersedes);
|
|
944
|
+
}
|
|
945
|
+
function branchRestoreDigest(input) {
|
|
946
|
+
return hexBytes(blake3(encodeJson(new Map([
|
|
947
|
+
['viewId', text(input.viewId)],
|
|
948
|
+
['revision', { kind: 'u64', value: input.expectedRevision }],
|
|
949
|
+
['operationId', text(input.operationId)],
|
|
950
|
+
['expectedHead', input.expectedHead ? identityValue(input.expectedHead) : null],
|
|
951
|
+
['restoreHead', input.restoreHead ? identityValue(input.restoreHead) : null],
|
|
952
|
+
]))));
|
|
953
|
+
}
|
|
954
|
+
async function branchRestore(host, input) {
|
|
955
|
+
if (typeof input.expectedRevision !== 'bigint' || input.expectedRevision < 0n || input.expectedRevision >= U64_MAX)
|
|
956
|
+
throw invalid('branch revision');
|
|
957
|
+
const viewId = text(input.viewId), operationId = text(input.operationId), digest = branchRestoreDigest(input);
|
|
958
|
+
if (input.expectedHead) {
|
|
959
|
+
if (input.expectedHead.kind !== 'message')
|
|
960
|
+
throw invalid('branch expected head kind');
|
|
961
|
+
keyOf(input.expectedHead);
|
|
962
|
+
}
|
|
963
|
+
if (input.restoreHead) {
|
|
964
|
+
if (input.restoreHead.kind !== 'message')
|
|
965
|
+
throw invalid('branch restore head kind');
|
|
966
|
+
keyOf(input.restoreHead);
|
|
967
|
+
}
|
|
968
|
+
for (let attempt = 0; attempt < 4; attempt++) {
|
|
969
|
+
await host.catchUpIndex();
|
|
970
|
+
const [state, priorOperation] = await Promise.all([
|
|
971
|
+
readBranchIndex(host, viewId),
|
|
972
|
+
readBranchOperation(host, viewId, operationId),
|
|
973
|
+
]);
|
|
974
|
+
if (priorOperation) {
|
|
975
|
+
if (priorOperation.digest !== digest || !branchStateEqual(priorOperation.oldHead, input.expectedHead) || !branchStateEqual(priorOperation.newHead, input.restoreHead))
|
|
976
|
+
throw new StoreError('conflict', 'branch restore input changed');
|
|
977
|
+
return {
|
|
978
|
+
operationId,
|
|
979
|
+
created: false,
|
|
980
|
+
oldHead: priorOperation.oldHead,
|
|
981
|
+
newHead: priorOperation.newHead,
|
|
982
|
+
revision: priorOperation.revision,
|
|
983
|
+
turnId: priorOperation.turnId,
|
|
984
|
+
};
|
|
985
|
+
}
|
|
986
|
+
if (state?.conflict)
|
|
987
|
+
throw new StoreError('conflict', 'active branch has conflicting revisions');
|
|
988
|
+
if ((state?.revision ?? 0n) !== input.expectedRevision || !branchStateEqual(state?.head ?? null, input.expectedHead))
|
|
989
|
+
throw new StoreError('stale', 'active branch changed');
|
|
990
|
+
const restoreTurnId = input.restoreHead ? await branchTurnByIdentity(host, input.restoreHead) : undefined;
|
|
991
|
+
if (input.restoreHead && !restoreTurnId)
|
|
992
|
+
throw new StoreError('corrupt', 'restore branch head missing');
|
|
993
|
+
const logicalCount = await branchLogicalCountAt(host, viewId, restoreTurnId ?? null);
|
|
994
|
+
const metadata = {
|
|
995
|
+
viewId,
|
|
996
|
+
revision: input.expectedRevision + 1n,
|
|
997
|
+
operationId,
|
|
998
|
+
previousHead: input.expectedHead,
|
|
999
|
+
head: input.restoreHead,
|
|
1000
|
+
baseTurn: null,
|
|
1001
|
+
logicalCount,
|
|
1002
|
+
supersedes: [],
|
|
1003
|
+
digest,
|
|
1004
|
+
};
|
|
1005
|
+
const cursor = await branchCursor(host);
|
|
1006
|
+
try {
|
|
1007
|
+
await writeIndexed(host, [], [
|
|
1008
|
+
{ table: BRANCH_TABLE, key: branchKey(viewId), value: branchStateValue(metadata), emitEvent: true },
|
|
1009
|
+
{ table: BRANCH_OPERATIONS, key: branchOperationKey(viewId, operationId), value: branchOperationValue({ operationId, created: true, oldHead: input.expectedHead, newHead: input.restoreHead, revision: metadata.revision, turnId: restoreTurnId ?? null }, digest) },
|
|
1010
|
+
], cursor);
|
|
1011
|
+
}
|
|
1012
|
+
catch (error) {
|
|
1013
|
+
if (errorCode(error) !== 'stale')
|
|
1014
|
+
throw error;
|
|
1015
|
+
continue;
|
|
1016
|
+
}
|
|
1017
|
+
return { operationId, created: true, oldHead: input.expectedHead, newHead: input.restoreHead, revision: metadata.revision, turnId: restoreTurnId ?? null };
|
|
1018
|
+
}
|
|
1019
|
+
throw new StoreError('stale', 'active branch restore retry budget exhausted');
|
|
1020
|
+
}
|
|
1021
|
+
async function readActiveBranch(host, viewId) {
|
|
1022
|
+
await host.catchUpIndex();
|
|
1023
|
+
const state = await readBranchIndex(host, viewId);
|
|
1024
|
+
if (!state)
|
|
1025
|
+
return { state: { viewId: text(viewId), revision: 0n, head: null, operationId: null }, messages: [], complete: true };
|
|
1026
|
+
if (state.conflict)
|
|
1027
|
+
throw new StoreError('conflict', 'active branch has conflicting revisions');
|
|
1028
|
+
if (state.head === null)
|
|
1029
|
+
return { state, messages: [], complete: true };
|
|
1030
|
+
const headId = await branchTurnByIdentity(host, state.head);
|
|
1031
|
+
if (!headId)
|
|
1032
|
+
return { state, messages: [], complete: false };
|
|
1033
|
+
const seen = new Set(), output = [];
|
|
1034
|
+
let complete = true;
|
|
1035
|
+
const visit = async (id) => {
|
|
1036
|
+
const key = hexBytes(id);
|
|
1037
|
+
if (seen.has(key))
|
|
1038
|
+
return;
|
|
1039
|
+
seen.add(key);
|
|
1040
|
+
const turn = await readBranchTurn(host, id);
|
|
1041
|
+
if (!turn) {
|
|
1042
|
+
complete = false;
|
|
1043
|
+
return;
|
|
1044
|
+
}
|
|
1045
|
+
for (const parent of turn.parents)
|
|
1046
|
+
await visit(parent.id);
|
|
1047
|
+
if (turn.identity?.kind !== 'message' || turn.content === undefined)
|
|
1048
|
+
return;
|
|
1049
|
+
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 });
|
|
1050
|
+
};
|
|
1051
|
+
await visit(headId);
|
|
1052
|
+
return { state, messages: output, complete };
|
|
1053
|
+
}
|
|
1054
|
+
async function readBranchPageMessages(host, segments) {
|
|
1055
|
+
const messages = [];
|
|
1056
|
+
let complete = true;
|
|
1057
|
+
// Pages can contain up to 500 rows. Keep body requests below the Node
|
|
1058
|
+
// client's bounded queue instead of launching one request per segment.
|
|
1059
|
+
for (let offset = 0; offset < segments.length; offset += 8) {
|
|
1060
|
+
const batch = segments.slice(offset, offset + 8);
|
|
1061
|
+
const turns = await Promise.all(batch.map(segment => readBranchTurn(host, segment.turnId)));
|
|
1062
|
+
for (let i = 0; i < batch.length; i++) {
|
|
1063
|
+
const turn = turns[i], segment = batch[i];
|
|
1064
|
+
if (!turn || turn.identity?.kind !== 'message' || turn.content === undefined) {
|
|
1065
|
+
complete = false;
|
|
1066
|
+
continue;
|
|
1067
|
+
}
|
|
1068
|
+
messages.push({
|
|
1069
|
+
businessId: segment.businessId, segmentId: segment.segmentId, turnId: turn.turnId,
|
|
1070
|
+
content: turn.content, nextSeq: turn.nextSeq, sealed: turn.sealed !== null,
|
|
1071
|
+
parents: turn.parents, sealedHash: turn.sealed,
|
|
1072
|
+
});
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
1075
|
+
return { messages, complete };
|
|
1076
|
+
}
|
|
1077
|
+
const activeBranchDirectoryCache = new WeakMap();
|
|
1078
|
+
function branchDirectoryKey(state) {
|
|
1079
|
+
return `${state.revision}:${state.head ? decodeUtf8(keyOf(state.head)) : ''}`;
|
|
1080
|
+
}
|
|
1081
|
+
async function branchTurnIdByIdentity(host, identity) {
|
|
1082
|
+
const key = keyOf(identity);
|
|
1083
|
+
const raw = host instanceof LodyHistory
|
|
1084
|
+
? await host.stream.store.run(false, host.stream.id, function* (tx) {
|
|
1085
|
+
return yield* tx.get(host.stream.space('lody_history_bindings_v1'), key);
|
|
1086
|
+
})
|
|
1087
|
+
: (await host.stream.readIndex([{ table: NODE_BINDINGS, key }]))[0];
|
|
1088
|
+
if (!raw)
|
|
1089
|
+
return;
|
|
1090
|
+
const found = binding(raw);
|
|
1091
|
+
if (found.conflict)
|
|
1092
|
+
throw new StoreError('conflict', 'multiple Turns claim one branch identity');
|
|
1093
|
+
return Uint8Array.from(found.turnId);
|
|
1094
|
+
}
|
|
1095
|
+
async function branchHeader(host, turnId) {
|
|
1096
|
+
const result = await host.stream.readTurnHeader(turnId);
|
|
1097
|
+
if (result.kind !== 'found')
|
|
1098
|
+
return;
|
|
1099
|
+
return { parents: result.turn.parents.map(parent => ({ id: parent.id.slice(), hash: parent.hash.slice() })) };
|
|
1100
|
+
}
|
|
1101
|
+
async function branchIdentityAt(host, turnId) {
|
|
1102
|
+
try {
|
|
1103
|
+
const value = await publicationField(host, turnId, [{ key: 'lodyHistory' }]);
|
|
1104
|
+
return decodeIdentity(value);
|
|
1105
|
+
}
|
|
1106
|
+
catch (error) {
|
|
1107
|
+
if (errorCode(error) === 'invalid')
|
|
1108
|
+
return undefined;
|
|
1109
|
+
throw error;
|
|
1110
|
+
}
|
|
1111
|
+
}
|
|
1112
|
+
async function readActiveBranchDirectory(host, viewId) {
|
|
1113
|
+
for (let attempt = 0; attempt < 4; attempt++) {
|
|
1114
|
+
await host.catchUpIndex();
|
|
1115
|
+
const state = await readBranchIndex(host, viewId);
|
|
1116
|
+
const publicState = state
|
|
1117
|
+
? { viewId: state.viewId, revision: state.revision, head: state.head, operationId: state.operationId, ...(state.conflict ? { conflict: true } : {}) }
|
|
1118
|
+
: { viewId: text(viewId), revision: 0n, head: null, operationId: null };
|
|
1119
|
+
const key = branchDirectoryKey(publicState);
|
|
1120
|
+
const cached = activeBranchDirectoryCache.get(host)?.get(viewId);
|
|
1121
|
+
if (cached?.key === key)
|
|
1122
|
+
return cached.value;
|
|
1123
|
+
try {
|
|
1124
|
+
const { value } = await stableRead(host, async () => {
|
|
1125
|
+
const current = await readBranchIndex(host, viewId);
|
|
1126
|
+
const currentState = current
|
|
1127
|
+
? { viewId: current.viewId, revision: current.revision, head: current.head, operationId: current.operationId, ...(current.conflict ? { conflict: true } : {}) }
|
|
1128
|
+
: { viewId: text(viewId), revision: 0n, head: null, operationId: null };
|
|
1129
|
+
if (branchDirectoryKey(currentState) !== key)
|
|
1130
|
+
throw new StoreError('stale', 'active branch changed during directory read');
|
|
1131
|
+
if (current?.conflict)
|
|
1132
|
+
throw new StoreError('conflict', 'active branch has conflicting revisions');
|
|
1133
|
+
if (!current?.head)
|
|
1134
|
+
return { state: currentState, rows: [], complete: true };
|
|
1135
|
+
const headId = await branchTurnIdByIdentity(host, current.head);
|
|
1136
|
+
if (!headId)
|
|
1137
|
+
return { state: currentState, rows: [], complete: false };
|
|
1138
|
+
const seen = new Set();
|
|
1139
|
+
const rows = [];
|
|
1140
|
+
const byBusinessId = new Map();
|
|
1141
|
+
let complete = true;
|
|
1142
|
+
const visit = async (id) => {
|
|
1143
|
+
const idKey = hexBytes(id);
|
|
1144
|
+
if (seen.has(idKey))
|
|
1145
|
+
return;
|
|
1146
|
+
seen.add(idKey);
|
|
1147
|
+
const header = await branchHeader(host, id);
|
|
1148
|
+
if (!header) {
|
|
1149
|
+
complete = false;
|
|
1150
|
+
return;
|
|
1151
|
+
}
|
|
1152
|
+
for (const parent of header.parents)
|
|
1153
|
+
await visit(parent.id);
|
|
1154
|
+
const identity = await branchIdentityAt(host, id);
|
|
1155
|
+
if (identity?.kind !== 'message')
|
|
1156
|
+
return;
|
|
1157
|
+
let row = byBusinessId.get(identity.businessId);
|
|
1158
|
+
if (!row) {
|
|
1159
|
+
row = { businessId: identity.businessId, segments: [] };
|
|
1160
|
+
byBusinessId.set(identity.businessId, row);
|
|
1161
|
+
rows.push(row);
|
|
1162
|
+
}
|
|
1163
|
+
row.segments.push({ businessId: identity.businessId, segmentId: identity.segmentId, turnId: id.slice() });
|
|
1164
|
+
};
|
|
1165
|
+
await visit(headId);
|
|
1166
|
+
return { state: currentState, rows, complete };
|
|
1167
|
+
});
|
|
1168
|
+
let byView = activeBranchDirectoryCache.get(host);
|
|
1169
|
+
if (!byView) {
|
|
1170
|
+
byView = new Map();
|
|
1171
|
+
activeBranchDirectoryCache.set(host, byView);
|
|
1172
|
+
}
|
|
1173
|
+
byView.set(viewId, { key, value });
|
|
1174
|
+
return value;
|
|
1175
|
+
}
|
|
1176
|
+
catch (error) {
|
|
1177
|
+
if (errorCode(error) === 'stale' && attempt < 3)
|
|
1178
|
+
continue;
|
|
1179
|
+
throw error;
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
throw new StoreError('stale', 'active branch directory retry budget exhausted');
|
|
1183
|
+
}
|
|
1184
|
+
async function readActiveBranchPage(host, viewId, input) {
|
|
1185
|
+
const limit = input.limit ?? 40;
|
|
1186
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 500)
|
|
1187
|
+
throw invalid('active branch page limit');
|
|
1188
|
+
if (input.from !== undefined && (!Number.isSafeInteger(input.from) || input.from < 0))
|
|
1189
|
+
throw invalid('active branch page offset');
|
|
1190
|
+
if ((input.latest && input.from !== undefined) || (input.before && (input.latest || input.from !== undefined))) {
|
|
1191
|
+
throw invalid('active branch page has conflicting cursors');
|
|
1192
|
+
}
|
|
1193
|
+
await host.catchUpIndex();
|
|
1194
|
+
const indexed = await readBranchIndex(host, text(viewId));
|
|
1195
|
+
const state = indexed
|
|
1196
|
+
? {
|
|
1197
|
+
viewId: indexed.viewId,
|
|
1198
|
+
revision: indexed.revision,
|
|
1199
|
+
head: indexed.head,
|
|
1200
|
+
operationId: indexed.operationId,
|
|
1201
|
+
...(indexed.logicalCount !== undefined ? { logicalCount: indexed.logicalCount } : {}),
|
|
1202
|
+
...(indexed.conflict ? { conflict: true } : {}),
|
|
1203
|
+
}
|
|
1204
|
+
: { viewId: text(viewId), revision: 0n, head: null, operationId: null, logicalCount: 0n };
|
|
1205
|
+
if (state.conflict)
|
|
1206
|
+
throw new StoreError('conflict', 'active branch has conflicting revisions');
|
|
1207
|
+
if (state.logicalCount !== undefined && (input.latest || input.before)) {
|
|
1208
|
+
try {
|
|
1209
|
+
const stable = await stableRead(host, async () => {
|
|
1210
|
+
const current = await readBranchIndex(host, state.viewId);
|
|
1211
|
+
const currentState = current
|
|
1212
|
+
? {
|
|
1213
|
+
viewId: current.viewId,
|
|
1214
|
+
revision: current.revision,
|
|
1215
|
+
head: current.head,
|
|
1216
|
+
operationId: current.operationId,
|
|
1217
|
+
...(current.logicalCount !== undefined ? { logicalCount: current.logicalCount } : {}),
|
|
1218
|
+
...(current.conflict ? { conflict: true } : {}),
|
|
1219
|
+
}
|
|
1220
|
+
: { viewId: state.viewId, revision: 0n, head: null, operationId: null, logicalCount: 0n };
|
|
1221
|
+
if (branchDirectoryKey(currentState) !== branchDirectoryKey(state)) {
|
|
1222
|
+
throw new StoreError('stale', 'active branch changed before page read');
|
|
1223
|
+
}
|
|
1224
|
+
if (currentState.conflict)
|
|
1225
|
+
throw new StoreError('conflict', 'active branch has conflicting revisions');
|
|
1226
|
+
return await readLinearActiveBranchPage(host, currentState, input, limit);
|
|
1227
|
+
});
|
|
1228
|
+
if (stable.value)
|
|
1229
|
+
return stable.value;
|
|
1230
|
+
}
|
|
1231
|
+
catch (error) {
|
|
1232
|
+
if (errorCode(error) !== 'stale')
|
|
1233
|
+
throw error;
|
|
1234
|
+
throw error;
|
|
1235
|
+
}
|
|
1236
|
+
}
|
|
1237
|
+
const directory = await readActiveBranchDirectory(host, text(viewId));
|
|
1238
|
+
const totalCount = directory.rows.length;
|
|
1239
|
+
if (input.before) {
|
|
1240
|
+
const before = input.before;
|
|
1241
|
+
const cursorRow = Number.isSafeInteger(before.position) ? directory.rows[before.position] : undefined;
|
|
1242
|
+
if (before.viewId !== directory.state.viewId || before.revision > directory.state.revision ||
|
|
1243
|
+
before.position < 0 || before.turnId.length !== 16 || before.headTurnId.length !== 16 ||
|
|
1244
|
+
!cursorRow?.segments.some(segment => equal(segment.turnId, before.turnId)) ||
|
|
1245
|
+
!directory.rows.some(row => row.segments.some(segment => equal(segment.turnId, before.headTurnId))))
|
|
1246
|
+
throw new StoreError('stale', 'active branch changed before older page was read');
|
|
1247
|
+
}
|
|
1248
|
+
const startPosition = input.before
|
|
1249
|
+
? Math.max(0, input.before.position - limit + 1)
|
|
1250
|
+
: input.latest
|
|
1251
|
+
? Math.max(0, totalCount - limit)
|
|
1252
|
+
: Math.min(input.from ?? 0, totalCount);
|
|
1253
|
+
const endPosition = Math.min(totalCount, input.before ? input.before.position + 1 : totalCount, startPosition + limit);
|
|
1254
|
+
const selectedIds = new Set(directory.rows.slice(startPosition, endPosition).map(row => row.businessId));
|
|
1255
|
+
const segments = directory.rows.filter(row => selectedIds.has(row.businessId)).flatMap(row => row.segments);
|
|
1256
|
+
let complete = directory.complete;
|
|
1257
|
+
const page = await readBranchPageMessages(host, segments);
|
|
1258
|
+
const messages = page.messages;
|
|
1259
|
+
complete &&= page.complete;
|
|
1260
|
+
let cursor = null;
|
|
1261
|
+
if (startPosition > 0) {
|
|
1262
|
+
if (input.before) {
|
|
1263
|
+
const headId = directory.state.head ? await branchTurnIdByIdentity(host, directory.state.head) : undefined;
|
|
1264
|
+
const activeIds = new Set(directory.rows.flatMap(row => row.segments.map(segment => hexBytes(segment.turnId))));
|
|
1265
|
+
if (!headId || !activeIds.has(hexBytes(input.before.headTurnId))) {
|
|
1266
|
+
throw new StoreError('stale', 'active branch changed before older page was read');
|
|
1267
|
+
}
|
|
1268
|
+
const olderRow = directory.rows[startPosition - 1];
|
|
1269
|
+
const olderSegment = olderRow?.segments[0];
|
|
1270
|
+
if (olderSegment)
|
|
1271
|
+
cursor = {
|
|
1272
|
+
viewId: directory.state.viewId,
|
|
1273
|
+
turnId: olderSegment.turnId.slice(),
|
|
1274
|
+
position: startPosition - 1,
|
|
1275
|
+
revision: directory.state.revision,
|
|
1276
|
+
headTurnId: headId,
|
|
1277
|
+
pendingSegments: [],
|
|
1278
|
+
};
|
|
1279
|
+
}
|
|
1280
|
+
else if (input.latest || input.from !== undefined) {
|
|
1281
|
+
const headId = directory.state.head ? await branchTurnIdByIdentity(host, directory.state.head) : undefined;
|
|
1282
|
+
const olderSegment = directory.rows[startPosition - 1]?.segments[0];
|
|
1283
|
+
if (headId && olderSegment)
|
|
1284
|
+
cursor = {
|
|
1285
|
+
viewId: directory.state.viewId,
|
|
1286
|
+
turnId: olderSegment.turnId.slice(),
|
|
1287
|
+
position: startPosition - 1,
|
|
1288
|
+
revision: directory.state.revision,
|
|
1289
|
+
headTurnId: headId,
|
|
1290
|
+
pendingSegments: [],
|
|
1291
|
+
};
|
|
1292
|
+
}
|
|
1293
|
+
}
|
|
1294
|
+
return {
|
|
1295
|
+
state: directory.state,
|
|
1296
|
+
totalCount,
|
|
1297
|
+
startPosition,
|
|
1298
|
+
messages,
|
|
1299
|
+
hasMoreOlder: startPosition > 0,
|
|
1300
|
+
cursor,
|
|
1301
|
+
complete,
|
|
1302
|
+
};
|
|
1303
|
+
}
|
|
1304
|
+
async function readLinearActiveBranchPage(host, state, input, limit) {
|
|
1305
|
+
const totalBigInt = state.logicalCount ?? 0n;
|
|
1306
|
+
if (totalBigInt > BigInt(Number.MAX_SAFE_INTEGER))
|
|
1307
|
+
throw new StoreError('invalid', 'active branch is too large to index');
|
|
1308
|
+
const totalCount = Number(totalBigInt);
|
|
1309
|
+
const headId = state.head ? await branchTurnIdByIdentity(host, state.head) : undefined;
|
|
1310
|
+
if (state.head && !headId)
|
|
1311
|
+
return {
|
|
1312
|
+
state, totalCount, startPosition: Math.max(0, totalCount - limit), messages: [],
|
|
1313
|
+
hasMoreOlder: totalCount > limit, cursor: null, complete: false,
|
|
1314
|
+
};
|
|
1315
|
+
if (!headId)
|
|
1316
|
+
return { state, totalCount, startPosition: 0, messages: [], hasMoreOlder: false, cursor: null, complete: true };
|
|
1317
|
+
let startPosition = input.before
|
|
1318
|
+
? Math.max(0, input.before.position - limit + 1)
|
|
1319
|
+
: Math.max(0, totalCount - limit);
|
|
1320
|
+
let currentId = input.before?.turnId.slice() ?? headId.slice();
|
|
1321
|
+
let collected = input.before?.pendingSegments.map(segment => ({ ...segment, turnId: segment.turnId.slice() })) ?? [];
|
|
1322
|
+
if (input.before) {
|
|
1323
|
+
const cursor = input.before;
|
|
1324
|
+
if (cursor.viewId !== state.viewId ||
|
|
1325
|
+
cursor.revision > state.revision ||
|
|
1326
|
+
!Number.isSafeInteger(cursor.position) ||
|
|
1327
|
+
cursor.position < 0 ||
|
|
1328
|
+
cursor.turnId.length !== 16 ||
|
|
1329
|
+
cursor.headTurnId.length !== 16 ||
|
|
1330
|
+
!Array.isArray(cursor.pendingSegments)) {
|
|
1331
|
+
throw new StoreError('stale', 'active branch page cursor is invalid');
|
|
1332
|
+
}
|
|
1333
|
+
const cursorMetadata = await branchMetadataAt(host, cursor.turnId);
|
|
1334
|
+
if (!cursorMetadata ||
|
|
1335
|
+
cursorMetadata.viewId !== state.viewId ||
|
|
1336
|
+
cursorMetadata.logicalCount !== BigInt(cursor.position + 1) ||
|
|
1337
|
+
cursorMetadata.head?.kind !== 'message' ||
|
|
1338
|
+
cursorMetadata.head.segmentId !== 'primary') {
|
|
1339
|
+
throw new StoreError('stale', 'active branch page cursor no longer names a primary row');
|
|
1340
|
+
}
|
|
1341
|
+
for (const segment of cursor.pendingSegments) {
|
|
1342
|
+
if (!segment ||
|
|
1343
|
+
typeof segment.businessId !== 'string' ||
|
|
1344
|
+
typeof segment.segmentId !== 'string' ||
|
|
1345
|
+
!(segment.turnId instanceof Uint8Array) ||
|
|
1346
|
+
segment.turnId.length !== 16) {
|
|
1347
|
+
throw new StoreError('stale', 'active branch page cursor has invalid pending segments');
|
|
1348
|
+
}
|
|
1349
|
+
}
|
|
1350
|
+
let ancestor = headId.slice();
|
|
1351
|
+
const expectedHead = hexBytes(cursor.headTurnId);
|
|
1352
|
+
let foundHead = false;
|
|
1353
|
+
const seen = new Set();
|
|
1354
|
+
const newerSuccessors = [];
|
|
1355
|
+
while (!seen.has(hexBytes(ancestor))) {
|
|
1356
|
+
const key = hexBytes(ancestor);
|
|
1357
|
+
if (key === expectedHead) {
|
|
1358
|
+
foundHead = true;
|
|
1359
|
+
break;
|
|
1360
|
+
}
|
|
1361
|
+
seen.add(key);
|
|
1362
|
+
const metadata = await branchMetadataAt(host, ancestor);
|
|
1363
|
+
if (!metadata || metadata.viewId !== state.viewId || !metadata.baseTurn)
|
|
1364
|
+
break;
|
|
1365
|
+
if (metadata.head?.kind === 'message' && metadata.head.segmentId !== 'primary') {
|
|
1366
|
+
const primaryId = await branchTurnIdByIdentity(host, {
|
|
1367
|
+
kind: 'message', businessId: metadata.head.businessId, segmentId: 'primary',
|
|
1368
|
+
});
|
|
1369
|
+
const primary = primaryId ? await branchMetadataAt(host, primaryId) : undefined;
|
|
1370
|
+
if (primary?.viewId !== state.viewId || primary.logicalCount === undefined)
|
|
1371
|
+
return undefined;
|
|
1372
|
+
if (primary.logicalCount <= BigInt(cursor.position + 1)) {
|
|
1373
|
+
newerSuccessors.push({ businessId: metadata.head.businessId, segmentId: metadata.head.segmentId, turnId: ancestor.slice() });
|
|
1374
|
+
}
|
|
1375
|
+
}
|
|
1376
|
+
ancestor = unhexBytes(metadata.baseTurn, 16);
|
|
1377
|
+
}
|
|
1378
|
+
if (!foundHead)
|
|
1379
|
+
throw new StoreError('stale', 'active branch changed before older page was read');
|
|
1380
|
+
collected = [...newerSuccessors, ...collected];
|
|
1381
|
+
}
|
|
1382
|
+
const selected = new Map();
|
|
1383
|
+
let olderCursor = null;
|
|
1384
|
+
let complete = true;
|
|
1385
|
+
const seen = new Set();
|
|
1386
|
+
while (true) {
|
|
1387
|
+
const turnKey = hexBytes(currentId);
|
|
1388
|
+
if (seen.has(turnKey)) {
|
|
1389
|
+
complete = false;
|
|
1390
|
+
break;
|
|
1391
|
+
}
|
|
1392
|
+
seen.add(turnKey);
|
|
1393
|
+
const metadata = await branchMetadataAt(host, currentId);
|
|
1394
|
+
if (!metadata || metadata.viewId !== state.viewId || !metadata.head || metadata.head.kind !== 'message')
|
|
1395
|
+
return undefined;
|
|
1396
|
+
if (metadata.logicalCount === undefined)
|
|
1397
|
+
return undefined;
|
|
1398
|
+
const header = await branchHeader(host, currentId);
|
|
1399
|
+
if (!header) {
|
|
1400
|
+
complete = false;
|
|
1401
|
+
break;
|
|
1402
|
+
}
|
|
1403
|
+
const expectedParent = metadata.baseTurn ? unhexBytes(metadata.baseTurn, 16) : undefined;
|
|
1404
|
+
if (header.parents.length !== (expectedParent ? 1 : 0) || (expectedParent && !equal(header.parents[0].id, expectedParent)))
|
|
1405
|
+
return undefined;
|
|
1406
|
+
const position = Number(metadata.logicalCount - 1n);
|
|
1407
|
+
if (metadata.head.segmentId === 'primary') {
|
|
1408
|
+
if (position < startPosition) {
|
|
1409
|
+
olderCursor = {
|
|
1410
|
+
viewId: state.viewId,
|
|
1411
|
+
turnId: currentId.slice(),
|
|
1412
|
+
position,
|
|
1413
|
+
revision: state.revision,
|
|
1414
|
+
headTurnId: headId.slice(),
|
|
1415
|
+
pendingSegments: collected.filter(segment => !selected.has(segment.businessId))
|
|
1416
|
+
.map(segment => ({ ...segment, turnId: segment.turnId.slice() })),
|
|
1417
|
+
};
|
|
1418
|
+
break;
|
|
1419
|
+
}
|
|
1420
|
+
if (position < startPosition + limit)
|
|
1421
|
+
selected.set(metadata.head.businessId, position);
|
|
1422
|
+
}
|
|
1423
|
+
collected.push({ businessId: metadata.head.businessId, segmentId: metadata.head.segmentId, turnId: currentId.slice() });
|
|
1424
|
+
if (!metadata.baseTurn)
|
|
1425
|
+
break;
|
|
1426
|
+
currentId = unhexBytes(metadata.baseTurn, 16);
|
|
1427
|
+
}
|
|
1428
|
+
const endPosition = Math.min(totalCount, input.before ? input.before.position + 1 : totalCount);
|
|
1429
|
+
const expectedRows = Math.max(0, Math.min(limit, endPosition - startPosition));
|
|
1430
|
+
if (selected.size !== expectedRows)
|
|
1431
|
+
return undefined;
|
|
1432
|
+
const selectedIds = new Set(selected.keys());
|
|
1433
|
+
const segmentGroups = new Map();
|
|
1434
|
+
for (const segment of [...collected].reverse()) {
|
|
1435
|
+
if (!selectedIds.has(segment.businessId))
|
|
1436
|
+
continue;
|
|
1437
|
+
const group = segmentGroups.get(segment.businessId) ?? [];
|
|
1438
|
+
group.push(segment);
|
|
1439
|
+
segmentGroups.set(segment.businessId, group);
|
|
1440
|
+
}
|
|
1441
|
+
const orderedSegments = [...selected].sort((a, b) => a[1] - b[1]).flatMap(([businessId]) => segmentGroups.get(businessId) ?? []);
|
|
1442
|
+
const page = await readBranchPageMessages(host, orderedSegments);
|
|
1443
|
+
const messages = page.messages;
|
|
1444
|
+
complete &&= page.complete;
|
|
1445
|
+
const actualStart = selected.size ? Math.min(...selected.values()) : startPosition;
|
|
1446
|
+
const cursor = olderCursor && actualStart > 0 ? olderCursor : null;
|
|
1447
|
+
return {
|
|
1448
|
+
state,
|
|
1449
|
+
totalCount,
|
|
1450
|
+
startPosition: actualStart,
|
|
1451
|
+
messages,
|
|
1452
|
+
hasMoreOlder: cursor !== null,
|
|
1453
|
+
cursor,
|
|
1454
|
+
complete,
|
|
1455
|
+
};
|
|
1456
|
+
}
|
|
537
1457
|
async function publicationField(host, id, path) {
|
|
538
1458
|
if (host instanceof LodyHistory)
|
|
539
1459
|
return (await host.stream.readValue(id, path)).value;
|
|
@@ -836,7 +1756,7 @@ async function readFound(host, id) {
|
|
|
836
1756
|
return { turnId: result.turn.turnId.slice(), nextSeq: result.turn.nextSeq, sealed: !!result.turn.sealed, inner: envelope.get('content') };
|
|
837
1757
|
}
|
|
838
1758
|
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]]);
|
|
1759
|
+
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
1760
|
}
|
|
841
1761
|
// Membership is durable; content and revision belong to the Turn. Legacy v1
|
|
842
1762
|
// rows containing full snapshots remain readable, without a migration scan.
|
|
@@ -1026,7 +1946,27 @@ async function hydratePublished(host, members) {
|
|
|
1026
1946
|
const body = 'contentJson' in turn ? decodeJson(encodeUtf8(turn.contentJson)) : turn.content;
|
|
1027
1947
|
if (!(body instanceof Map) || !body.has('content'))
|
|
1028
1948
|
throw invalid('history envelope');
|
|
1029
|
-
|
|
1949
|
+
let parents = [];
|
|
1950
|
+
if ('parents' in turn) {
|
|
1951
|
+
parents = turn.parents.map(parent => ({ id: parent.id.slice(), hash: parent.hash.slice() }));
|
|
1952
|
+
}
|
|
1953
|
+
else {
|
|
1954
|
+
const raw = host instanceof LodyHistory
|
|
1955
|
+
? await host.stream.exportUpdates(turn.turnId, 0n, 1)
|
|
1956
|
+
: await host.stream.exportUpdates(turn.turnId, 0n, 1n);
|
|
1957
|
+
const [create] = decodeBatch(raw);
|
|
1958
|
+
if (create?.operation.kind === 'create') {
|
|
1959
|
+
parents = create.operation.parents.map(parent => ({ id: parent.id.slice(), hash: parent.hash.slice() }));
|
|
1960
|
+
}
|
|
1961
|
+
}
|
|
1962
|
+
rows.push({
|
|
1963
|
+
...page[i],
|
|
1964
|
+
content: body.get('content'),
|
|
1965
|
+
nextSeq: turn.nextSeq,
|
|
1966
|
+
sealed: !!turn.sealed,
|
|
1967
|
+
parents,
|
|
1968
|
+
sealedHash: turn.sealed?.slice() ?? null,
|
|
1969
|
+
});
|
|
1030
1970
|
}
|
|
1031
1971
|
}
|
|
1032
1972
|
return rows;
|
|
@@ -1071,7 +2011,7 @@ async function captureBases(host, commands) {
|
|
|
1071
2011
|
}
|
|
1072
2012
|
const found = await readFound(host, command.identity);
|
|
1073
2013
|
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 });
|
|
2014
|
+
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
2015
|
}
|
|
1076
2016
|
return bases;
|
|
1077
2017
|
}
|
|
@@ -1086,7 +2026,7 @@ async function messageEndStates(host, commands) {
|
|
|
1086
2026
|
seen.add(key);
|
|
1087
2027
|
const found = await readFound(host, command.identity);
|
|
1088
2028
|
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 });
|
|
2029
|
+
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
2030
|
}
|
|
1091
2031
|
return rows;
|
|
1092
2032
|
}
|
|
@@ -1149,7 +2089,7 @@ function plannedMessage(id, found, planned) {
|
|
|
1149
2089
|
return prior;
|
|
1150
2090
|
if (found?.inner === undefined)
|
|
1151
2091
|
return;
|
|
1152
|
-
return { businessId: id.businessId, segmentId: id.segmentId, turnId: found.turnId, content: found.inner, nextSeq: found.nextSeq, sealed: found.sealed };
|
|
2092
|
+
return { businessId: id.businessId, segmentId: id.segmentId, turnId: found.turnId, content: found.inner, nextSeq: found.nextSeq, sealed: found.sealed, parents: [], sealedHash: null };
|
|
1153
2093
|
}
|
|
1154
2094
|
async function collectBatchWrites(host, identity, commands, applied) {
|
|
1155
2095
|
const writes = [];
|
|
@@ -1161,7 +2101,7 @@ async function collectBatchWrites(host, identity, commands, applied) {
|
|
|
1161
2101
|
if (command.type === 'accept' && command.identity.kind === 'message') {
|
|
1162
2102
|
const found = await readFound(host, command.identity);
|
|
1163
2103
|
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 });
|
|
2104
|
+
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
2105
|
}
|
|
1166
2106
|
continue;
|
|
1167
2107
|
}
|
|
@@ -1174,8 +2114,8 @@ async function collectBatchWrites(host, identity, commands, applied) {
|
|
|
1174
2114
|
writes.push({ kind: 'createOnce', key: keyOf(command.identity), parents: command.parents, content: envelope(input) });
|
|
1175
2115
|
if (command.identity.kind === 'message') {
|
|
1176
2116
|
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) });
|
|
2117
|
+
? { businessId: command.identity.businessId, segmentId: command.identity.segmentId, turnId: found.turnId, content: found.inner, nextSeq: found.nextSeq, sealed: found.sealed, parents: [], sealedHash: null }
|
|
2118
|
+
: { 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
2119
|
}
|
|
1180
2120
|
continue;
|
|
1181
2121
|
}
|