@loro-dev/roost 0.3.0 → 0.3.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 +36 -11
- package/dist/lody-history.d.ts +65 -0
- package/dist/lody-history.js +425 -55
- package/dist/sync/history.d.ts +16 -51
- package/dist/sync/history.js +96 -172
- package/dist/sync/index.d.ts +1 -1
- package/dist/sync/mod.d.ts +1 -1
- package/dist/sync/transport.d.ts +1 -4
- package/dist/sync/transport.js +15 -25
- package/node/client.d.mts +8 -2
- package/node/client.mjs +23 -2
- package/package.json +6 -6
package/dist/lody-history.js
CHANGED
|
@@ -33,11 +33,11 @@ function branchIdentity(value, label) {
|
|
|
33
33
|
return null;
|
|
34
34
|
if (!(value instanceof Map))
|
|
35
35
|
throw invalid(label);
|
|
36
|
-
return decodeIdentity(value);
|
|
36
|
+
return decodeIdentity(value, true);
|
|
37
37
|
}
|
|
38
38
|
function branchMetadataValue(value) {
|
|
39
39
|
const metadata = new Map([
|
|
40
|
-
['version', '1'],
|
|
40
|
+
['version', value.membershipBase || value.head?.kind === 'branch_state' || value.previousHead?.kind === 'branch_state' ? '2' : '1'],
|
|
41
41
|
['viewId', value.viewId],
|
|
42
42
|
['revision', { kind: 'u64', value: value.revision }],
|
|
43
43
|
['operationId', value.operationId],
|
|
@@ -49,16 +49,22 @@ function branchMetadataValue(value) {
|
|
|
49
49
|
]);
|
|
50
50
|
if (value.logicalCount !== undefined)
|
|
51
51
|
metadata.set('logicalCount', { kind: 'u64', value: value.logicalCount });
|
|
52
|
+
if (value.membershipBase)
|
|
53
|
+
metadata.set('membershipBase', identityValue(value.membershipBase));
|
|
54
|
+
if (value.prepared)
|
|
55
|
+
metadata.set('prepared', true);
|
|
52
56
|
return metadata;
|
|
53
57
|
}
|
|
54
58
|
function parseBranchMetadata(value) {
|
|
55
59
|
if (value === undefined)
|
|
56
60
|
return;
|
|
57
|
-
if (!(value instanceof Map) || value.get('version') !== '1')
|
|
61
|
+
if (!(value instanceof Map) || (value.get('version') !== '1' && value.get('version') !== '2'))
|
|
58
62
|
throw invalid('history branch metadata');
|
|
59
63
|
const viewId = value.get('viewId'), operationId = value.get('operationId'), revision = value.get('revision');
|
|
60
64
|
const baseTurn = value.get('baseTurn'), digest = value.get('digest'), supersedes = value.get('supersedes');
|
|
61
65
|
const logicalCount = value.get('logicalCount');
|
|
66
|
+
if (value.has('prepared') && value.get('prepared') !== true)
|
|
67
|
+
throw invalid('history prepared branch metadata');
|
|
62
68
|
if (typeof viewId !== 'string' || typeof operationId !== 'string' || typeof baseTurn !== 'string' && baseTurn !== null ||
|
|
63
69
|
typeof digest !== 'string' || !revision || typeof revision !== 'object' || Array.isArray(revision) || revision instanceof Map || revision.kind !== 'u64' ||
|
|
64
70
|
!Array.isArray(supersedes))
|
|
@@ -69,12 +75,16 @@ function parseBranchMetadata(value) {
|
|
|
69
75
|
viewId: text(viewId), revision: revision.value, operationId: text(operationId),
|
|
70
76
|
previousHead, head, baseTurn,
|
|
71
77
|
...(logicalCount === undefined ? {} : { logicalCount: seqOf(logicalCount) }),
|
|
78
|
+
...(value.has('membershipBase') ? { membershipBase: decodeIdentity(value.get('membershipBase'), true) } : {}),
|
|
79
|
+
...(value.get('prepared') === true ? { prepared: true } : {}),
|
|
72
80
|
supersedes: supersedes.map(item => decodeIdentity(item)), digest,
|
|
73
81
|
};
|
|
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'))
|
|
82
|
+
if (parsed.revision < 1n || (parsed.head !== null && parsed.head.kind !== 'message' && parsed.head.kind !== 'branch_state') || (parsed.previousHead !== null && parsed.previousHead.kind !== 'message' && parsed.previousHead.kind !== 'branch_state') || parsed.supersedes.some(item => item.kind !== 'message'))
|
|
75
83
|
throw invalid('history branch metadata');
|
|
76
84
|
if (!/^[0-9a-f]{64}$/.test(parsed.digest))
|
|
77
85
|
throw invalid('history branch digest');
|
|
86
|
+
if (parsed.membershipBase && parsed.membershipBase.kind !== 'branch_state')
|
|
87
|
+
throw invalid('history membership root');
|
|
78
88
|
if (parsed.baseTurn !== null && !/^[0-9a-f]{32}$/.test(parsed.baseTurn))
|
|
79
89
|
throw invalid('history branch base turn');
|
|
80
90
|
return parsed;
|
|
@@ -97,7 +107,7 @@ function parseBranchState(raw) {
|
|
|
97
107
|
if (!metadata)
|
|
98
108
|
throw new StoreError('corrupt', 'invalid history branch state');
|
|
99
109
|
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 } : {}) };
|
|
110
|
+
return { viewId: metadata.viewId, revision: metadata.revision, head: metadata.head, operationId: metadata.operationId, digest: metadata.digest, ...(metadata.membershipBase ? { membershipBase: metadata.membershipBase } : {}), ...(metadata.logicalCount !== undefined ? { logicalCount: metadata.logicalCount } : {}), ...(previous === true ? { conflict: true } : {}) };
|
|
101
111
|
}
|
|
102
112
|
function branchOperationValue(result, digest, inputDigest) {
|
|
103
113
|
return encodeJson(new Map([
|
|
@@ -119,7 +129,7 @@ function parseBranchOperation(raw) {
|
|
|
119
129
|
const inputDigest = value.get('inputDigest');
|
|
120
130
|
if (inputDigest !== undefined && (typeof inputDigest !== 'string' || !/^[0-9a-f]{64}$/.test(inputDigest)))
|
|
121
131
|
throw new StoreError('corrupt', 'invalid input acceptance digest');
|
|
122
|
-
if ((newHead !== null && newHead.kind !== 'message') || (oldHead !== null && oldHead.kind !== 'message'))
|
|
132
|
+
if ((newHead !== null && newHead.kind !== 'message' && newHead.kind !== 'branch_state') || (oldHead !== null && oldHead.kind !== 'message' && oldHead.kind !== 'branch_state'))
|
|
123
133
|
throw new StoreError('corrupt', 'invalid history branch operation head');
|
|
124
134
|
if ((turnId !== null && !/^[0-9a-f]{32}$/.test(turnId)) || !/^[0-9a-f]{64}$/.test(digest))
|
|
125
135
|
throw new StoreError('corrupt', 'invalid history branch operation encoding');
|
|
@@ -128,7 +138,8 @@ function parseBranchOperation(raw) {
|
|
|
128
138
|
function branchMetadataFromContent(content) {
|
|
129
139
|
if (!(content instanceof Map))
|
|
130
140
|
return;
|
|
131
|
-
|
|
141
|
+
const metadata = parseBranchMetadata(content.get('lodyBranch'));
|
|
142
|
+
return metadata?.prepared ? undefined : metadata;
|
|
132
143
|
}
|
|
133
144
|
function branchStateEqual(a, b) {
|
|
134
145
|
if (a === null || b === null)
|
|
@@ -574,41 +585,60 @@ export class NodeLodyHistory {
|
|
|
574
585
|
touched.set(hexBytes(update.turnId), update.turnId);
|
|
575
586
|
if (update.seq !== 0n)
|
|
576
587
|
continue;
|
|
577
|
-
|
|
578
|
-
if (
|
|
579
|
-
|
|
588
|
+
let turnId = update.turnId, owner, content, digest;
|
|
589
|
+
if (this.stream.fieldReads && this.stream.readCreateFields) {
|
|
590
|
+
const selected = await this.stream.readCreateFields(turnId, ['lodyHistory', 'lodyBranch', 'lodyPublication'].map(key => ({ path: [{ key }] })), ['lodyBranch', 'lodyPublication']);
|
|
591
|
+
const envelope = new Map();
|
|
592
|
+
for (const [index, field] of selected.fields.entries()) {
|
|
593
|
+
if (field.state === 'ready')
|
|
594
|
+
envelope.set(['lodyHistory', 'lodyBranch', 'lodyPublication'][index], decodeJson(encodeUtf8(field.contentJson)));
|
|
595
|
+
}
|
|
596
|
+
owner = selected.owner;
|
|
597
|
+
content = envelope;
|
|
598
|
+
digest = envelope.has('lodyBranch') || envelope.get('lodyPublication') === 'direct' || envelope.get('lodyPublication') === 'private'
|
|
599
|
+
? selected.filteredDigest : selected.digest;
|
|
600
|
+
}
|
|
601
|
+
else {
|
|
602
|
+
const [u] = decodeBatch(await this.stream.exportUpdates(turnId, 0n, 1n));
|
|
603
|
+
if (!u || u.operation.kind !== 'create')
|
|
604
|
+
throw new StoreError('corrupt', 'history create event has no operation');
|
|
605
|
+
turnId = u.turnId;
|
|
606
|
+
owner = u.owner;
|
|
607
|
+
content = u.operation.content;
|
|
608
|
+
digest = createDigest(owner, u.operation.parents, content);
|
|
609
|
+
}
|
|
580
610
|
let id;
|
|
581
611
|
try {
|
|
582
|
-
id = identityOf(
|
|
612
|
+
id = identityOf(content);
|
|
583
613
|
}
|
|
584
614
|
catch (error) {
|
|
585
615
|
if (!(error instanceof StoreError) || error.code !== 'invalid')
|
|
586
616
|
throw error;
|
|
587
|
-
changes.push({ table: NODE_INVALID, key:
|
|
617
|
+
changes.push({ table: NODE_INVALID, key: turnId, value: encodeUtf8('invalid_envelope') });
|
|
588
618
|
}
|
|
589
619
|
if (!id) {
|
|
590
|
-
changes.push({ table: PUBLICATION_OBJECTS, key:
|
|
620
|
+
changes.push({ table: PUBLICATION_OBJECTS, key: turnId, value: encodeUtf8('null') });
|
|
591
621
|
continue;
|
|
592
622
|
}
|
|
593
623
|
let branch;
|
|
594
624
|
try {
|
|
595
|
-
branch = branchMetadataFromContent(
|
|
625
|
+
branch = branchMetadataFromContent(content);
|
|
596
626
|
}
|
|
597
627
|
catch (error) {
|
|
598
628
|
if (errorCode(error) !== 'invalid')
|
|
599
629
|
throw error;
|
|
600
|
-
changes.push({ table: NODE_INVALID, key:
|
|
601
|
-
changes.push({ table: PUBLICATION_OBJECTS, key:
|
|
630
|
+
changes.push({ table: NODE_INVALID, key: turnId, value: encodeUtf8('invalid_envelope') });
|
|
631
|
+
changes.push({ table: PUBLICATION_OBJECTS, key: turnId, value: encodeUtf8('null') });
|
|
602
632
|
continue;
|
|
603
633
|
}
|
|
604
634
|
if (branch)
|
|
605
635
|
branchRows.push({ key: branchKey(branch.viewId), value: branchStateValue(branch) });
|
|
606
636
|
const key = keyOf(id);
|
|
607
|
-
rows.push({ key, value: { version: 1, turnId: [...
|
|
608
|
-
changes.push({ table: PUBLICATION_OBJECTS, key:
|
|
637
|
+
rows.push({ key, value: { version: 1, turnId: [...turnId], owner: [...owner], digest: [...digest] } });
|
|
638
|
+
changes.push({ table: PUBLICATION_OBJECTS, key: turnId, value: encodeUtf8(JSON.stringify({ key: decodeUtf8(key), owner: hexBytes(owner), digest: hexBytes(digest), kind: id.kind, direct: id.kind === 'message' && content instanceof Map && content.get('lodyPublication') === 'direct' })) });
|
|
609
639
|
if (id.kind === 'batch_receipt') {
|
|
610
|
-
receipts.set(hexBytes(
|
|
611
|
-
changes.push({ table: NODE_RECEIPTS, key:
|
|
640
|
+
receipts.set(hexBytes(turnId), { id: turnId, key });
|
|
641
|
+
changes.push({ table: NODE_RECEIPTS, key: turnId, value: key });
|
|
612
642
|
}
|
|
613
643
|
}
|
|
614
644
|
const previous = await this.stream.readIndex(rows.map(row => ({ table: NODE_BINDINGS, key: row.key })));
|
|
@@ -794,6 +824,37 @@ export class NodeLodyHistory {
|
|
|
794
824
|
rememberBranchDirectory(this, page);
|
|
795
825
|
return page;
|
|
796
826
|
}
|
|
827
|
+
readActiveBranchMembers(viewId, input = {}) {
|
|
828
|
+
return readActiveBranchMembers(this, viewId, input);
|
|
829
|
+
}
|
|
830
|
+
/** Resolve an identity to its Turn header. */
|
|
831
|
+
async lookupMember(identity) {
|
|
832
|
+
return (await stableRead(this, async () => {
|
|
833
|
+
const id = await branchTurnIdByIdentity(this, identity);
|
|
834
|
+
if (!id)
|
|
835
|
+
return;
|
|
836
|
+
const header = await branchHeader(this, id);
|
|
837
|
+
if (!header)
|
|
838
|
+
throw new StoreError('pending', 'history member is incomplete');
|
|
839
|
+
return { turnId: id.slice(), nextSeq: header.nextSeq, sealed: header.sealed !== null };
|
|
840
|
+
})).value;
|
|
841
|
+
}
|
|
842
|
+
replaceActiveBranchMembers(input) {
|
|
843
|
+
return replaceBranchMembers(this, input);
|
|
844
|
+
}
|
|
845
|
+
async readActiveBranchMessages(viewId, businessIds) {
|
|
846
|
+
const ids = new Set(businessIds);
|
|
847
|
+
return (await stableRead(this, async () => {
|
|
848
|
+
const directory = await readActiveBranchDirectory(this, viewId);
|
|
849
|
+
if (!directory.complete)
|
|
850
|
+
throw new StoreError('pending', 'active branch is incomplete');
|
|
851
|
+
const selected = directory.rows.filter(row => ids.has(row.businessId)).flatMap(row => row.segments);
|
|
852
|
+
const result = await readBranchPageMessages(this, selected);
|
|
853
|
+
if (!result.complete)
|
|
854
|
+
throw new StoreError('pending', 'active members are incomplete');
|
|
855
|
+
return result.messages;
|
|
856
|
+
})).value;
|
|
857
|
+
}
|
|
797
858
|
advanceActiveBranchDirectory(page, result, limit = 40) {
|
|
798
859
|
return advanceBranchDirectory(this, page, result, limit);
|
|
799
860
|
}
|
|
@@ -898,7 +959,7 @@ async function readBranchPageTurn(host, turnId, knownHeader, retained) {
|
|
|
898
959
|
}
|
|
899
960
|
return structuredClone(cached);
|
|
900
961
|
}
|
|
901
|
-
const turn = await readBranchTurn(host, turnId);
|
|
962
|
+
const turn = await readBranchTurn(host, turnId, header);
|
|
902
963
|
if (!turn || !sameBranchHeader(turn, header) || turn.sourceBytes === undefined || turn.sourceBytes > SEALED_PAGE_BYTES)
|
|
903
964
|
return turn;
|
|
904
965
|
cache = sealedPageBodies.get(host);
|
|
@@ -971,7 +1032,7 @@ async function branchLogicalCountAt(host, viewId, turnId) {
|
|
|
971
1032
|
throw new StoreError('stale', 'branch base is not in the active history');
|
|
972
1033
|
return BigInt(position + 1);
|
|
973
1034
|
}
|
|
974
|
-
async function readBranchTurn(host, turnId) {
|
|
1035
|
+
async function readBranchTurn(host, turnId, knownHeader) {
|
|
975
1036
|
if (host instanceof LodyHistory) {
|
|
976
1037
|
const result = await host.stream.readTurn(turnId);
|
|
977
1038
|
if (result.kind !== 'found')
|
|
@@ -989,13 +1050,17 @@ async function readBranchTurn(host, turnId) {
|
|
|
989
1050
|
const result = await host.stream.readTurn(turnId);
|
|
990
1051
|
if (result.kind !== 'found')
|
|
991
1052
|
return;
|
|
992
|
-
|
|
993
|
-
if (!
|
|
994
|
-
|
|
1053
|
+
let parents = knownHeader?.parents;
|
|
1054
|
+
if (!parents) {
|
|
1055
|
+
const [create] = decodeBatch(await host.stream.exportUpdates(turnId, 0n, 1n));
|
|
1056
|
+
if (!create || create.operation.kind !== 'create')
|
|
1057
|
+
throw new StoreError('corrupt', 'branch head has no Create');
|
|
1058
|
+
parents = create.operation.parents;
|
|
1059
|
+
}
|
|
995
1060
|
const body = decodeJson(encodeUtf8(result.turn.contentJson));
|
|
996
1061
|
return {
|
|
997
1062
|
turnId: result.turn.turnId.slice(),
|
|
998
|
-
parents:
|
|
1063
|
+
parents: parents.map(parent => ({ id: parent.id.slice(), hash: parent.hash.slice() })),
|
|
999
1064
|
identity: identityOf(body),
|
|
1000
1065
|
content: body instanceof Map ? body.get('content') : undefined,
|
|
1001
1066
|
nextSeq: result.turn.nextSeq,
|
|
@@ -1060,7 +1125,7 @@ async function branchMutation(host, input, baseTurn, supersedes, inputDigest, li
|
|
|
1060
1125
|
if (baseTurn !== null && baseTurn.length !== 16)
|
|
1061
1126
|
throw invalid('branch base Turn');
|
|
1062
1127
|
if (expectedHead) {
|
|
1063
|
-
if (expectedHead.kind !== 'message')
|
|
1128
|
+
if (expectedHead.kind !== 'message' && expectedHead.kind !== 'branch_state')
|
|
1064
1129
|
throw invalid('branch head kind');
|
|
1065
1130
|
keyOf(expectedHead);
|
|
1066
1131
|
}
|
|
@@ -1071,9 +1136,13 @@ async function branchMutation(host, input, baseTurn, supersedes, inputDigest, li
|
|
|
1071
1136
|
}
|
|
1072
1137
|
if (!branchParentMatches(baseTurn, input.input.parents))
|
|
1073
1138
|
throw invalid('branch base parent');
|
|
1074
|
-
const
|
|
1139
|
+
const inherited = await readBranchIndex(host, viewId);
|
|
1140
|
+
const rooted = inherited?.membershipBase && inherited.revision === input.expectedRevision && branchStateEqual(inherited.head, expectedHead) && linearAppend;
|
|
1141
|
+
const baseCount = rooted ? inherited.logicalCount : await branchLogicalCountAt(host, viewId, baseTurn);
|
|
1075
1142
|
const logicalCount = baseCount + (input.input.segmentId === 'primary' ? 1n : 0n);
|
|
1076
1143
|
const metadata = branchMetadataFor({ ...input, viewId, operationId, expectedHead }, owner, expectedHead, baseTurn, supersedes, logicalCount);
|
|
1144
|
+
if (rooted)
|
|
1145
|
+
metadata.membershipBase = inherited.membershipBase;
|
|
1077
1146
|
const createKey = keyOf(input.input);
|
|
1078
1147
|
const branchValue = branchStateValue(metadata);
|
|
1079
1148
|
const operationValue = branchOperationValue({ operationId, created: true, oldHead: expectedHead, newHead: metadata.head, revision: metadata.revision, turnId: null }, metadata.digest, inputDigest);
|
|
@@ -1136,7 +1205,7 @@ async function branchMutation(host, input, baseTurn, supersedes, inputDigest, li
|
|
|
1136
1205
|
equal(committed.updates[0].turnId, turnId) && committed.through - committed.before === 2n) {
|
|
1137
1206
|
branchTransitions.set(result, {
|
|
1138
1207
|
ownerToken: branchHandleToken(host), beforeRevision: input.expectedRevision, beforeHead: structuredClone(expectedHead),
|
|
1139
|
-
state: { viewId, revision: metadata.revision, head: structuredClone(metadata.head), operationId, logicalCount },
|
|
1208
|
+
state: { viewId, revision: metadata.revision, head: structuredClone(metadata.head), operationId, logicalCount, ...(metadata.membershipBase ? { membershipBase: metadata.membershipBase } : {}) },
|
|
1140
1209
|
message: { businessId: input.input.businessId, segmentId: 'primary', turnId: turnId.slice(),
|
|
1141
1210
|
content: structuredClone(input.input.content), nextSeq: 1n, sealed: false,
|
|
1142
1211
|
parents: structuredClone(input.input.parents), sealedHash: null },
|
|
@@ -1157,6 +1226,35 @@ async function branchFork(host, input) {
|
|
|
1157
1226
|
throw invalid('active branch only accepts message replacements');
|
|
1158
1227
|
if (input.baseTurn && input.baseTurn.length !== 16)
|
|
1159
1228
|
throw invalid('branch base Turn');
|
|
1229
|
+
input = structuredClone(input);
|
|
1230
|
+
const expectedId = input.expectedHead ? await branchTurnIdByIdentity(host, input.expectedHead) : undefined;
|
|
1231
|
+
const expected = expectedId ? await branchMetadataAt(host, expectedId) : undefined;
|
|
1232
|
+
if (expected?.membershipBase && expected.viewId === input.viewId) {
|
|
1233
|
+
if (!(host instanceof NodeLodyHistory))
|
|
1234
|
+
throw invalid('membership forks require a Native author');
|
|
1235
|
+
if (!branchParentMatches(input.baseTurn, input.input.parents))
|
|
1236
|
+
throw invalid('branch base parent');
|
|
1237
|
+
const cursor = await host.observedEventCursor();
|
|
1238
|
+
const directory = await readRootedBranchDirectory(host, { viewId: input.viewId, revision: input.expectedRevision, head: input.expectedHead,
|
|
1239
|
+
operationId: expected.operationId, membershipBase: expected.membershipBase, ...(expected.logicalCount === undefined ? {} : { logicalCount: expected.logicalCount }) });
|
|
1240
|
+
if (!directory.complete)
|
|
1241
|
+
throw new StoreError('pending', 'fork membership is incomplete');
|
|
1242
|
+
const members = directory.rows.flatMap(row => row.segments);
|
|
1243
|
+
const boundary = input.baseTurn ? members.findIndex(row => equal(row.turnId, input.baseTurn)) : -1;
|
|
1244
|
+
if (input.baseTurn && boundary < 0)
|
|
1245
|
+
throw new StoreError('stale', 'fork base is not active');
|
|
1246
|
+
const prefix = members.slice(0, boundary + 1).map(row => ({ identity: { kind: 'message', businessId: row.businessId, segmentId: row.physicalSegmentId ?? row.segmentId }, segmentId: row.segmentId }));
|
|
1247
|
+
const result = await host.replaceActiveBranchMembers({ viewId: input.viewId, expectedRevision: input.expectedRevision,
|
|
1248
|
+
expectedHead: input.expectedHead, operationId: input.operationId, expectedEventCursor: cursor,
|
|
1249
|
+
members: [...prefix, { identity: input.input, segmentId: input.input.segmentId }],
|
|
1250
|
+
messages: [{ identity: input.input, content: input.input.content, parents: input.input.parents, attachments: input.input.attachments, sealed: false }], supersedes: input.supersedes });
|
|
1251
|
+
if (!result.newHead)
|
|
1252
|
+
throw invalid('fork root missing');
|
|
1253
|
+
const physical = await host.lookupMember(input.input);
|
|
1254
|
+
if (!physical)
|
|
1255
|
+
throw new StoreError('pending', 'fork replacement missing');
|
|
1256
|
+
return { ...result, newHead: result.newHead, turnId: physical.turnId };
|
|
1257
|
+
}
|
|
1160
1258
|
return branchMutation(host, input, input.baseTurn, input.supersedes);
|
|
1161
1259
|
}
|
|
1162
1260
|
function branchRestoreDigest(input) {
|
|
@@ -1174,12 +1272,12 @@ async function branchRestore(host, input) {
|
|
|
1174
1272
|
throw invalid('branch revision');
|
|
1175
1273
|
const viewId = text(input.viewId), operationId = text(input.operationId), digest = branchRestoreDigest(input);
|
|
1176
1274
|
if (input.expectedHead) {
|
|
1177
|
-
if (input.expectedHead.kind !== 'message')
|
|
1275
|
+
if (input.expectedHead.kind !== 'message' && input.expectedHead.kind !== 'branch_state')
|
|
1178
1276
|
throw invalid('branch expected head kind');
|
|
1179
1277
|
keyOf(input.expectedHead);
|
|
1180
1278
|
}
|
|
1181
1279
|
if (input.restoreHead) {
|
|
1182
|
-
if (input.restoreHead.kind !== 'message')
|
|
1280
|
+
if (input.restoreHead.kind !== 'message' && input.restoreHead.kind !== 'branch_state')
|
|
1183
1281
|
throw invalid('branch restore head kind');
|
|
1184
1282
|
keyOf(input.restoreHead);
|
|
1185
1283
|
}
|
|
@@ -1209,12 +1307,14 @@ async function branchRestore(host, input) {
|
|
|
1209
1307
|
if (input.restoreHead && !restoreTurnId)
|
|
1210
1308
|
throw new StoreError('corrupt', 'restore branch head missing');
|
|
1211
1309
|
const logicalCount = await branchLogicalCountAt(host, viewId, restoreTurnId ?? null);
|
|
1310
|
+
const restoredMetadata = restoreTurnId ? await branchMetadataAt(host, restoreTurnId) : undefined;
|
|
1212
1311
|
const metadata = {
|
|
1213
1312
|
viewId,
|
|
1214
1313
|
revision: input.expectedRevision + 1n,
|
|
1215
1314
|
operationId,
|
|
1216
1315
|
previousHead: input.expectedHead,
|
|
1217
1316
|
head: input.restoreHead,
|
|
1317
|
+
...(restoredMetadata?.membershipBase ? { membershipBase: restoredMetadata.membershipBase } : {}),
|
|
1218
1318
|
baseTurn: null,
|
|
1219
1319
|
logicalCount,
|
|
1220
1320
|
supersedes: [],
|
|
@@ -1255,6 +1355,11 @@ async function readActiveBranchSnapshot(host, viewId) {
|
|
|
1255
1355
|
return { state: { viewId: text(viewId), revision: 0n, head: null, operationId: null }, messages: [], complete: true };
|
|
1256
1356
|
if (state.conflict)
|
|
1257
1357
|
throw new StoreError('conflict', 'active branch has conflicting revisions');
|
|
1358
|
+
if (state.membershipBase) {
|
|
1359
|
+
const directory = await readActiveBranchDirectory(host, viewId);
|
|
1360
|
+
const page = await readBranchPageMessages(host, directory.rows.flatMap(row => row.segments));
|
|
1361
|
+
return { state, messages: page.messages, complete: directory.complete && page.complete };
|
|
1362
|
+
}
|
|
1258
1363
|
if (state.head === null)
|
|
1259
1364
|
return { state, messages: [], complete: true };
|
|
1260
1365
|
const headId = await branchTurnByIdentity(host, state.head);
|
|
@@ -1294,12 +1399,13 @@ async function readBranchPageMessages(host, segments, headers) {
|
|
|
1294
1399
|
const turns = await Promise.all(batch.map(segment => readBranchPageTurn(host, segment.turnId, headers?.get(hexBytes(segment.turnId)), retained?.get(hexBytes(segment.turnId)))));
|
|
1295
1400
|
for (let i = 0; i < batch.length; i++) {
|
|
1296
1401
|
const turn = turns[i], segment = batch[i];
|
|
1297
|
-
if (!turn || turn.identity?.kind !== 'message' || turn.content === undefined) {
|
|
1402
|
+
if (!turn || turn.identity?.kind !== 'message' || turn.identity.businessId !== segment.businessId || turn.identity.segmentId !== (segment.physicalSegmentId ?? segment.segmentId) || turn.content === undefined) {
|
|
1298
1403
|
complete = false;
|
|
1299
1404
|
continue;
|
|
1300
1405
|
}
|
|
1301
1406
|
messages.push({
|
|
1302
|
-
businessId: segment.businessId, segmentId: segment.segmentId,
|
|
1407
|
+
businessId: segment.businessId, segmentId: segment.segmentId,
|
|
1408
|
+
...(segment.physicalSegmentId ? { physicalSegmentId: segment.physicalSegmentId } : {}), turnId: turn.turnId,
|
|
1303
1409
|
content: turn.content, nextSeq: turn.nextSeq, sealed: turn.sealed !== null,
|
|
1304
1410
|
parents: turn.parents, sealedHash: turn.sealed,
|
|
1305
1411
|
});
|
|
@@ -1307,9 +1413,239 @@ async function readBranchPageMessages(host, segments, headers) {
|
|
|
1307
1413
|
}
|
|
1308
1414
|
return { messages, complete };
|
|
1309
1415
|
}
|
|
1416
|
+
async function readRootedBranchDirectory(host, state) {
|
|
1417
|
+
const root = state.membershipBase;
|
|
1418
|
+
const rootId = await branchTurnIdByIdentity(host, root);
|
|
1419
|
+
if (!rootId)
|
|
1420
|
+
return { state, rows: [], complete: false };
|
|
1421
|
+
const header = await branchHeader(host, rootId);
|
|
1422
|
+
if (!header?.sealed)
|
|
1423
|
+
return { state, rows: [], complete: false };
|
|
1424
|
+
const rootMeta = await branchMetadataAt(host, rootId);
|
|
1425
|
+
if (!rootMeta || rootMeta.viewId !== state.viewId || !branchStateEqual(rootMeta.membershipBase ?? null, root))
|
|
1426
|
+
throw invalid('membership root metadata');
|
|
1427
|
+
const content = asMap(await publicationField(host, rootId, [{ key: 'content' }]), 'membership root');
|
|
1428
|
+
const raw = content.get('members');
|
|
1429
|
+
if (content.get('version') !== '1' || !Array.isArray(raw))
|
|
1430
|
+
throw invalid('membership root members');
|
|
1431
|
+
const refs = raw.map(value => {
|
|
1432
|
+
const row = asMap(value, 'membership member');
|
|
1433
|
+
const identity = decodeIdentity(row.get('identity'));
|
|
1434
|
+
const segmentId = row.get('segmentId');
|
|
1435
|
+
if (identity.kind !== 'message' || typeof segmentId !== 'string')
|
|
1436
|
+
throw invalid('membership member identity');
|
|
1437
|
+
if (segmentId !== identity.segmentId && (segmentId !== 'primary' || !identity.segmentId.startsWith('primary:')))
|
|
1438
|
+
throw invalid('membership segment alias');
|
|
1439
|
+
return { identity, segmentId: text(segmentId) };
|
|
1440
|
+
});
|
|
1441
|
+
const rows = [], byId = new Map();
|
|
1442
|
+
let complete = true;
|
|
1443
|
+
const seen = new Set();
|
|
1444
|
+
const add = (ref, turnId) => {
|
|
1445
|
+
const key = hexBytes(turnId);
|
|
1446
|
+
if (seen.has(key))
|
|
1447
|
+
throw invalid('duplicate membership member');
|
|
1448
|
+
seen.add(key);
|
|
1449
|
+
let row = byId.get(ref.identity.businessId);
|
|
1450
|
+
if (!row) {
|
|
1451
|
+
row = { businessId: ref.identity.businessId, segments: [] };
|
|
1452
|
+
byId.set(row.businessId, row);
|
|
1453
|
+
rows.push(row);
|
|
1454
|
+
}
|
|
1455
|
+
row.segments.push({ businessId: row.businessId, segmentId: ref.segmentId, turnId: turnId.slice(),
|
|
1456
|
+
...(ref.identity.segmentId === ref.segmentId ? {} : { physicalSegmentId: ref.identity.segmentId }) });
|
|
1457
|
+
};
|
|
1458
|
+
for (const ref of refs) {
|
|
1459
|
+
const turnId = await branchTurnIdByIdentity(host, ref.identity);
|
|
1460
|
+
if (!turnId || !await branchHeader(host, turnId)) {
|
|
1461
|
+
complete = false;
|
|
1462
|
+
continue;
|
|
1463
|
+
}
|
|
1464
|
+
add(ref, turnId);
|
|
1465
|
+
}
|
|
1466
|
+
const boundary = rootMeta.head ? await branchTurnIdByIdentity(host, rootMeta.head) : undefined;
|
|
1467
|
+
let current = state.head ? await branchTurnIdByIdentity(host, state.head) : undefined;
|
|
1468
|
+
const suffix = [], walked = new Set();
|
|
1469
|
+
while (current && (!boundary || !equal(current, boundary))) {
|
|
1470
|
+
const id = hexBytes(current);
|
|
1471
|
+
if (walked.has(id))
|
|
1472
|
+
throw invalid('membership suffix cycle');
|
|
1473
|
+
walked.add(id);
|
|
1474
|
+
const metadata = await branchMetadataAt(host, current);
|
|
1475
|
+
if (!metadata) {
|
|
1476
|
+
complete = false;
|
|
1477
|
+
break;
|
|
1478
|
+
}
|
|
1479
|
+
if (metadata.viewId !== state.viewId || !branchStateEqual(metadata.membershipBase ?? null, root) || !metadata.head)
|
|
1480
|
+
throw invalid('membership suffix metadata');
|
|
1481
|
+
suffix.push({ identity: metadata.head, turnId: current });
|
|
1482
|
+
current = metadata.baseTurn ? unhexBytes(metadata.baseTurn, 16) : undefined;
|
|
1483
|
+
}
|
|
1484
|
+
if (boundary && (!current || !equal(current, boundary)))
|
|
1485
|
+
complete = false;
|
|
1486
|
+
for (const ref of suffix.reverse())
|
|
1487
|
+
add({ identity: ref.identity, segmentId: ref.identity.segmentId }, ref.turnId);
|
|
1488
|
+
if (state.logicalCount !== undefined && BigInt(rows.length) !== state.logicalCount)
|
|
1489
|
+
complete = false;
|
|
1490
|
+
return { state, rows, complete };
|
|
1491
|
+
}
|
|
1492
|
+
async function replaceBranchMembers(host, input) {
|
|
1493
|
+
if (!host.stream.exclusiveBatches)
|
|
1494
|
+
throw invalid('membership requires exclusive-batch-v1');
|
|
1495
|
+
input = structuredClone(input);
|
|
1496
|
+
const { viewId, operationId } = input;
|
|
1497
|
+
text(viewId);
|
|
1498
|
+
text(operationId);
|
|
1499
|
+
if (typeof input.expectedRevision !== 'bigint' || input.expectedRevision < 0n || input.expectedRevision >= U64_MAX)
|
|
1500
|
+
throw invalid('branch revision');
|
|
1501
|
+
if (typeof input.expectedEventCursor !== 'bigint' || input.expectedEventCursor < 0n || input.expectedEventCursor > U64_MAX)
|
|
1502
|
+
throw invalid('membership event cursor');
|
|
1503
|
+
for (const superseded of input.supersedes ?? []) {
|
|
1504
|
+
if (superseded.kind !== 'message')
|
|
1505
|
+
throw invalid('branch superseded kind');
|
|
1506
|
+
keyOf(superseded);
|
|
1507
|
+
}
|
|
1508
|
+
const owner = host.owner;
|
|
1509
|
+
const identity = { kind: 'branch_state', businessId: viewId, segmentId: operationId };
|
|
1510
|
+
const newHead = identity;
|
|
1511
|
+
const messageKeys = new Set((input.messages ?? []).map(row => decodeUtf8(keyOf(row.identity))));
|
|
1512
|
+
const memberKeys = new Set(), logicalIds = new Set(), primaryIds = new Set();
|
|
1513
|
+
for (const member of input.members) {
|
|
1514
|
+
if (member.identity.kind !== 'message' || typeof member.segmentId !== 'string')
|
|
1515
|
+
throw invalid('membership identity');
|
|
1516
|
+
text(member.segmentId);
|
|
1517
|
+
const key = decodeUtf8(keyOf(member.identity));
|
|
1518
|
+
if (memberKeys.has(key))
|
|
1519
|
+
throw invalid('duplicate membership identity');
|
|
1520
|
+
memberKeys.add(key);
|
|
1521
|
+
logicalIds.add(member.identity.businessId);
|
|
1522
|
+
if (member.segmentId === 'primary') {
|
|
1523
|
+
if (primaryIds.has(member.identity.businessId))
|
|
1524
|
+
throw invalid('duplicate membership primary');
|
|
1525
|
+
primaryIds.add(member.identity.businessId);
|
|
1526
|
+
}
|
|
1527
|
+
if (member.segmentId !== member.identity.segmentId && (member.segmentId !== 'primary' || !member.identity.segmentId.startsWith('primary:')))
|
|
1528
|
+
throw invalid('membership segment alias');
|
|
1529
|
+
}
|
|
1530
|
+
if (primaryIds.size !== logicalIds.size)
|
|
1531
|
+
throw invalid('membership primary missing');
|
|
1532
|
+
const members = input.members.map(row => new Map([['identity', identityValue(row.identity)], ['segmentId', row.segmentId]]));
|
|
1533
|
+
const messages = input.messages ?? [];
|
|
1534
|
+
if (messages.some(row => row.identity.kind !== 'message' || !memberKeys.has(decodeUtf8(keyOf(row.identity)))) || messageKeys.size !== messages.length)
|
|
1535
|
+
throw invalid('membership messages');
|
|
1536
|
+
if (messages.some(row => row.sealed !== undefined && typeof row.sealed !== 'boolean'))
|
|
1537
|
+
throw invalid('membership sealing flag');
|
|
1538
|
+
const receipts = input.receipts ?? [];
|
|
1539
|
+
const digest = hexBytes(blake3(encodeJson(new Map([
|
|
1540
|
+
['viewId', viewId], ['operationId', operationId], ['revision', { kind: 'u64', value: input.expectedRevision }],
|
|
1541
|
+
['expectedHead', input.expectedHead ? identityValue(input.expectedHead) : null], ['members', members],
|
|
1542
|
+
['messages', messages.map(row => [hexBytes(createDigest(owner, row.parents ?? [], envelope({ ...row.identity, parents: row.parents ?? [], content: row.content, attachments: row.attachments }))), row.sealed !== false])],
|
|
1543
|
+
['receipts', encodeCommands(receipts)], ['supersedes', (input.supersedes ?? []).map(identityValue)],
|
|
1544
|
+
]))));
|
|
1545
|
+
const prior = await readBranchOperation(host, viewId, operationId);
|
|
1546
|
+
if (prior) {
|
|
1547
|
+
if (prior.digest !== digest)
|
|
1548
|
+
throw new StoreError('conflict', 'membership operation changed');
|
|
1549
|
+
return { operationId, created: false, oldHead: prior.oldHead, newHead: prior.newHead, revision: prior.revision, turnId: prior.turnId };
|
|
1550
|
+
}
|
|
1551
|
+
let cursor = await branchCursor(host);
|
|
1552
|
+
if (cursor !== input.expectedEventCursor)
|
|
1553
|
+
throw new StoreError('stale', 'membership observation changed');
|
|
1554
|
+
const state = await readBranchIndex(host, viewId);
|
|
1555
|
+
if (state?.conflict)
|
|
1556
|
+
throw new StoreError('conflict', 'active branch has conflicting revisions');
|
|
1557
|
+
if ((state?.revision ?? 0n) !== input.expectedRevision || !branchStateEqual(state?.head ?? null, input.expectedHead))
|
|
1558
|
+
throw new StoreError('stale', 'active branch changed');
|
|
1559
|
+
for (const member of input.members)
|
|
1560
|
+
if (!messageKeys.has(decodeUtf8(keyOf(member.identity)))) {
|
|
1561
|
+
const turnId = await branchTurnIdByIdentity(host, member.identity);
|
|
1562
|
+
if (!turnId || !await branchHeader(host, turnId))
|
|
1563
|
+
throw new StoreError('pending', 'membership reference missing');
|
|
1564
|
+
}
|
|
1565
|
+
if (!host.stream.exclusiveBatches)
|
|
1566
|
+
throw invalid('membership requires exclusive-batch-v1');
|
|
1567
|
+
const writes = [];
|
|
1568
|
+
for (const row of messages) {
|
|
1569
|
+
const prior = await host.lookupMember(row.identity);
|
|
1570
|
+
if (prior && (prior.sealed ? prior.nextSeq !== 2n || row.sealed === false : prior.nextSeq !== 1n))
|
|
1571
|
+
throw new StoreError('conflict', 'prepared membership message changed');
|
|
1572
|
+
writes.push({ kind: 'createOnce', key: keyOf(row.identity), parents: row.parents ?? [], content: envelope({ ...row.identity, parents: row.parents ?? [], content: row.content, attachments: row.attachments }, false) });
|
|
1573
|
+
if (row.sealed !== false && !prior?.sealed)
|
|
1574
|
+
writes.push({ kind: 'sealOnce', key: keyOf(row.identity), expectedNextSeq: 1n });
|
|
1575
|
+
}
|
|
1576
|
+
const receiptWrites = [];
|
|
1577
|
+
for (const receipt of receipts) {
|
|
1578
|
+
assertWritableIdentity(receipt.identity);
|
|
1579
|
+
receiptWrites.push({ kind: 'createOnce', key: keyOf(receipt.identity), parents: receipt.parents, content: envelope({ ...receipt.identity, parents: receipt.parents, content: receipt.content, attachments: receipt.attachments }, false) });
|
|
1580
|
+
}
|
|
1581
|
+
if (receiptWrites.length > 4094)
|
|
1582
|
+
throw invalid('membership receipt limit');
|
|
1583
|
+
// Prepare messages in exclusive groups; author receipts during activation.
|
|
1584
|
+
for (let offset = 0; offset < writes.length; offset += 64) {
|
|
1585
|
+
const commit = await writeIndexed(host, writes.slice(offset, offset + 64), [], cursor, true);
|
|
1586
|
+
if (commit?.through === undefined)
|
|
1587
|
+
throw invalid('membership requires fenced Native writes');
|
|
1588
|
+
cursor = commit.through;
|
|
1589
|
+
}
|
|
1590
|
+
const metadata = { viewId, operationId, revision: input.expectedRevision + 1n,
|
|
1591
|
+
previousHead: input.expectedHead, head: newHead, baseTurn: null, membershipBase: identity,
|
|
1592
|
+
logicalCount: BigInt(logicalIds.size), supersedes: input.supersedes ?? [], digest };
|
|
1593
|
+
// Append manifest chunks under a fixed intent digest and resume an exact prefix.
|
|
1594
|
+
const root = { ...identity, parents: [], content: new Map([['version', '1'], ['intentDigest', digest], ['members', []]]) };
|
|
1595
|
+
const createdRoot = await writeIndexed(host, [
|
|
1596
|
+
{ kind: 'createOnce', key: keyOf(identity), parents: [], content: envelope(root, false, { ...metadata, prepared: true }) },
|
|
1597
|
+
], [], cursor, true);
|
|
1598
|
+
if (createdRoot?.through === undefined)
|
|
1599
|
+
throw invalid('membership requires fenced Native writes');
|
|
1600
|
+
cursor = createdRoot.through;
|
|
1601
|
+
await host.catchUpIndex();
|
|
1602
|
+
const rootId = await branchTurnIdByIdentity(host, identity);
|
|
1603
|
+
if (!rootId)
|
|
1604
|
+
throw new StoreError('corrupt', 'prepared membership root missing');
|
|
1605
|
+
let rootHeader = await branchHeader(host, rootId);
|
|
1606
|
+
if (!rootHeader)
|
|
1607
|
+
throw new StoreError('corrupt', 'prepared membership root header missing');
|
|
1608
|
+
const prepared = await publicationField(host, rootId, [{ key: 'content' }, { key: 'members' }]);
|
|
1609
|
+
if (!Array.isArray(prepared) || prepared.length > members.length || prepared.some((value, i) => !equal(encodeJson(value), encodeJson(members[i]))))
|
|
1610
|
+
throw new StoreError('conflict', 'prepared membership prefix changed');
|
|
1611
|
+
if (rootHeader.sealed && prepared.length !== members.length)
|
|
1612
|
+
throw new StoreError('conflict', 'prepared membership root incomplete');
|
|
1613
|
+
for (let offset = prepared.length; offset < members.length; offset += 128) {
|
|
1614
|
+
const commit = await host.stream.writeBatch([{
|
|
1615
|
+
kind: 'edit', turnId: rootId, expectedNextSeq: rootHeader.nextSeq,
|
|
1616
|
+
ops: [{ kind: 'spliceArray', path: [{ key: 'content' }, { key: 'members' }], index: BigInt(offset), delete: 0n,
|
|
1617
|
+
valuesJson: decodeUtf8(encodeJson(members.slice(offset, offset + 128))) }],
|
|
1618
|
+
}], { expectedEventCursor: cursor, requireLocalInterval: true });
|
|
1619
|
+
if (commit.through === undefined)
|
|
1620
|
+
throw invalid('membership requires fenced Native writes');
|
|
1621
|
+
cursor = commit.through;
|
|
1622
|
+
rootHeader = { ...rootHeader, nextSeq: rootHeader.nextSeq + 1n };
|
|
1623
|
+
}
|
|
1624
|
+
if (!rootHeader.sealed) {
|
|
1625
|
+
const commit = await writeIndexed(host, [{ kind: 'seal', turnId: rootId, expectedNextSeq: rootHeader.nextSeq }], [], cursor, true);
|
|
1626
|
+
if (commit?.through === undefined)
|
|
1627
|
+
throw invalid('membership requires fenced Native writes');
|
|
1628
|
+
cursor = commit.through;
|
|
1629
|
+
rootHeader = (await branchHeader(host, rootId));
|
|
1630
|
+
}
|
|
1631
|
+
if (!rootHeader.sealed)
|
|
1632
|
+
throw new StoreError('corrupt', 'prepared membership root not sealed');
|
|
1633
|
+
const activation = { kind: 'branch_state', businessId: viewId, segmentId: `activation:${digest}`,
|
|
1634
|
+
parents: [{ id: rootId, hash: rootHeader.sealed }], content: null };
|
|
1635
|
+
const result = { operationId, created: true, oldHead: input.expectedHead, newHead, revision: metadata.revision, turnId: null };
|
|
1636
|
+
await writeIndexed(host, [
|
|
1637
|
+
...receiptWrites,
|
|
1638
|
+
{ kind: 'createOnce', key: keyOf(activation), parents: activation.parents, content: envelope(activation, false, metadata) },
|
|
1639
|
+
{ kind: 'sealOnce', key: keyOf(activation), expectedNextSeq: 1n },
|
|
1640
|
+
], [
|
|
1641
|
+
{ table: BRANCH_TABLE, key: branchKey(viewId), value: branchStateValue(metadata), emitEvent: true },
|
|
1642
|
+
{ table: BRANCH_OPERATIONS, key: branchOperationKey(viewId, operationId), value: branchOperationValue(result, digest) },
|
|
1643
|
+
], cursor, true);
|
|
1644
|
+
return result;
|
|
1645
|
+
}
|
|
1310
1646
|
const activeBranchDirectoryCache = new WeakMap();
|
|
1311
1647
|
function branchDirectoryKey(state) {
|
|
1312
|
-
return `${state.revision}:${state.head ? decodeUtf8(keyOf(state.head)) : ''}`;
|
|
1648
|
+
return `${state.revision}:${state.head ? decodeUtf8(keyOf(state.head)) : ''}:${state.membershipBase ? decodeUtf8(keyOf(state.membershipBase)) : ''}`;
|
|
1313
1649
|
}
|
|
1314
1650
|
async function branchTurnIdByIdentity(host, identity) {
|
|
1315
1651
|
const key = keyOf(identity);
|
|
@@ -1350,7 +1686,7 @@ async function readActiveBranchDirectory(host, viewId) {
|
|
|
1350
1686
|
await host.catchUpIndex();
|
|
1351
1687
|
const state = await readBranchIndex(host, viewId);
|
|
1352
1688
|
const publicState = state
|
|
1353
|
-
? { viewId: state.viewId, revision: state.revision, head: state.head, operationId: state.operationId, ...(state.conflict ? { conflict: true } : {}) }
|
|
1689
|
+
? { viewId: state.viewId, revision: state.revision, head: state.head, operationId: state.operationId, ...(state.logicalCount !== undefined ? { logicalCount: state.logicalCount } : {}), ...(state.membershipBase ? { membershipBase: state.membershipBase } : {}), ...(state.conflict ? { conflict: true } : {}) }
|
|
1354
1690
|
: { viewId: text(viewId), revision: 0n, head: null, operationId: null };
|
|
1355
1691
|
const key = branchDirectoryKey(publicState);
|
|
1356
1692
|
const cached = activeBranchDirectoryCache.get(host)?.get(viewId);
|
|
@@ -1360,7 +1696,7 @@ async function readActiveBranchDirectory(host, viewId) {
|
|
|
1360
1696
|
const { value } = await stableRead(host, async () => {
|
|
1361
1697
|
const current = await readBranchIndex(host, viewId);
|
|
1362
1698
|
const currentState = current
|
|
1363
|
-
? { viewId: current.viewId, revision: current.revision, head: current.head, operationId: current.operationId, ...(current.conflict ? { conflict: true } : {}) }
|
|
1699
|
+
? { viewId: current.viewId, revision: current.revision, head: current.head, operationId: current.operationId, ...(current.logicalCount !== undefined ? { logicalCount: current.logicalCount } : {}), ...(current.membershipBase ? { membershipBase: current.membershipBase } : {}), ...(current.conflict ? { conflict: true } : {}) }
|
|
1364
1700
|
: { viewId: text(viewId), revision: 0n, head: null, operationId: null };
|
|
1365
1701
|
if (branchDirectoryKey(currentState) !== key)
|
|
1366
1702
|
throw new StoreError('stale', 'active branch changed during directory read');
|
|
@@ -1368,6 +1704,8 @@ async function readActiveBranchDirectory(host, viewId) {
|
|
|
1368
1704
|
throw new StoreError('conflict', 'active branch has conflicting revisions');
|
|
1369
1705
|
if (!current?.head)
|
|
1370
1706
|
return { state: currentState, rows: [], complete: true };
|
|
1707
|
+
if (current.membershipBase)
|
|
1708
|
+
return readRootedBranchDirectory(host, current);
|
|
1371
1709
|
const headId = await branchTurnIdByIdentity(host, current.head);
|
|
1372
1710
|
if (!headId)
|
|
1373
1711
|
return { state: currentState, rows: [], complete: false };
|
|
@@ -1406,7 +1744,8 @@ async function readActiveBranchDirectory(host, viewId) {
|
|
|
1406
1744
|
byView = new Map();
|
|
1407
1745
|
activeBranchDirectoryCache.set(host, byView);
|
|
1408
1746
|
}
|
|
1409
|
-
|
|
1747
|
+
if (value.complete)
|
|
1748
|
+
byView.set(viewId, { key, value });
|
|
1410
1749
|
return value;
|
|
1411
1750
|
}
|
|
1412
1751
|
catch (error) {
|
|
@@ -1418,6 +1757,38 @@ async function readActiveBranchDirectory(host, viewId) {
|
|
|
1418
1757
|
throw new StoreError('stale', 'active branch directory retry budget exhausted');
|
|
1419
1758
|
}
|
|
1420
1759
|
async function readActiveBranchPage(host, viewId, input) {
|
|
1760
|
+
return (await stableRead(host, async () => {
|
|
1761
|
+
const { segments, headers, ...selected } = await readActiveBranchSelection(host, viewId, input);
|
|
1762
|
+
const page = await readBranchPageMessages(host, segments, headers);
|
|
1763
|
+
return { ...selected, messages: page.messages, complete: selected.complete && page.complete };
|
|
1764
|
+
})).value;
|
|
1765
|
+
}
|
|
1766
|
+
async function readActiveBranchMembers(host, viewId, input) {
|
|
1767
|
+
return (await stableRead(host, async () => {
|
|
1768
|
+
const { segments, headers: _headers, ...selected } = await readActiveBranchSelection(host, viewId, input);
|
|
1769
|
+
return { ...selected, members: segments.map(segment => ({ ...segment, turnId: segment.turnId.slice() })) };
|
|
1770
|
+
})).value;
|
|
1771
|
+
}
|
|
1772
|
+
async function activeCursorHead(host, directory, head) {
|
|
1773
|
+
if (!directory.state.membershipBase)
|
|
1774
|
+
return directory.rows.some(row => row.segments.some(segment => equal(segment.turnId, head)));
|
|
1775
|
+
const root = await branchTurnIdByIdentity(host, directory.state.membershipBase);
|
|
1776
|
+
let current = directory.state.head ? await branchTurnIdByIdentity(host, directory.state.head) : undefined;
|
|
1777
|
+
const seen = new Set();
|
|
1778
|
+
while (current && !seen.has(hexBytes(current))) {
|
|
1779
|
+
if (equal(current, head))
|
|
1780
|
+
return true;
|
|
1781
|
+
if (root && equal(current, root))
|
|
1782
|
+
return false;
|
|
1783
|
+
seen.add(hexBytes(current));
|
|
1784
|
+
const metadata = await branchMetadataAt(host, current);
|
|
1785
|
+
if (!metadata || metadata.viewId !== directory.state.viewId || !branchStateEqual(metadata.membershipBase ?? null, directory.state.membershipBase))
|
|
1786
|
+
return false;
|
|
1787
|
+
current = metadata.baseTurn ? unhexBytes(metadata.baseTurn, 16) : undefined;
|
|
1788
|
+
}
|
|
1789
|
+
return false;
|
|
1790
|
+
}
|
|
1791
|
+
async function readActiveBranchSelection(host, viewId, input) {
|
|
1421
1792
|
const limit = input.limit ?? 40;
|
|
1422
1793
|
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 500)
|
|
1423
1794
|
throw invalid('active branch page limit');
|
|
@@ -1434,6 +1805,7 @@ async function readActiveBranchPage(host, viewId, input) {
|
|
|
1434
1805
|
revision: indexed.revision,
|
|
1435
1806
|
head: indexed.head,
|
|
1436
1807
|
operationId: indexed.operationId,
|
|
1808
|
+
...(indexed.membershipBase ? { membershipBase: indexed.membershipBase } : {}),
|
|
1437
1809
|
...(indexed.logicalCount !== undefined ? { logicalCount: indexed.logicalCount } : {}),
|
|
1438
1810
|
...(indexed.conflict ? { conflict: true } : {}),
|
|
1439
1811
|
}
|
|
@@ -1450,6 +1822,7 @@ async function readActiveBranchPage(host, viewId, input) {
|
|
|
1450
1822
|
revision: current.revision,
|
|
1451
1823
|
head: current.head,
|
|
1452
1824
|
operationId: current.operationId,
|
|
1825
|
+
...(current.membershipBase ? { membershipBase: current.membershipBase } : {}),
|
|
1453
1826
|
...(current.logicalCount !== undefined ? { logicalCount: current.logicalCount } : {}),
|
|
1454
1827
|
...(current.conflict ? { conflict: true } : {}),
|
|
1455
1828
|
}
|
|
@@ -1478,7 +1851,7 @@ async function readActiveBranchPage(host, viewId, input) {
|
|
|
1478
1851
|
if (before.viewId !== directory.state.viewId || before.revision > directory.state.revision ||
|
|
1479
1852
|
before.position < 0 || before.turnId.length !== 16 || before.headTurnId.length !== 16 ||
|
|
1480
1853
|
!cursorRow?.segments.some(segment => equal(segment.turnId, before.turnId)) ||
|
|
1481
|
-
!
|
|
1854
|
+
!await activeCursorHead(host, directory, before.headTurnId))
|
|
1482
1855
|
throw new StoreError('stale', 'active branch changed before older page was read');
|
|
1483
1856
|
}
|
|
1484
1857
|
const startPosition = input.before
|
|
@@ -1489,16 +1862,12 @@ async function readActiveBranchPage(host, viewId, input) {
|
|
|
1489
1862
|
const endPosition = Math.min(totalCount, input.before ? input.before.position + 1 : totalCount, startPosition + limit);
|
|
1490
1863
|
const selectedIds = new Set(directory.rows.slice(startPosition, endPosition).map(row => row.businessId));
|
|
1491
1864
|
const segments = directory.rows.filter(row => selectedIds.has(row.businessId)).flatMap(row => row.segments);
|
|
1492
|
-
|
|
1493
|
-
const page = await readBranchPageMessages(host, segments);
|
|
1494
|
-
const messages = page.messages;
|
|
1495
|
-
complete &&= page.complete;
|
|
1865
|
+
const complete = directory.complete;
|
|
1496
1866
|
let cursor = null;
|
|
1497
1867
|
if (startPosition > 0) {
|
|
1498
1868
|
if (input.before) {
|
|
1499
1869
|
const headId = directory.state.head ? await branchTurnIdByIdentity(host, directory.state.head) : undefined;
|
|
1500
|
-
|
|
1501
|
-
if (!headId || !activeIds.has(hexBytes(input.before.headTurnId))) {
|
|
1870
|
+
if (!headId || !await activeCursorHead(host, directory, input.before.headTurnId)) {
|
|
1502
1871
|
throw new StoreError('stale', 'active branch changed before older page was read');
|
|
1503
1872
|
}
|
|
1504
1873
|
const olderRow = directory.rows[startPosition - 1];
|
|
@@ -1531,7 +1900,7 @@ async function readActiveBranchPage(host, viewId, input) {
|
|
|
1531
1900
|
state: directory.state,
|
|
1532
1901
|
totalCount,
|
|
1533
1902
|
startPosition,
|
|
1534
|
-
|
|
1903
|
+
segments,
|
|
1535
1904
|
hasMoreOlder: startPosition > 0,
|
|
1536
1905
|
cursor,
|
|
1537
1906
|
complete,
|
|
@@ -1612,6 +1981,8 @@ function advanceBranchDirectory(host, page, result, limit) {
|
|
|
1612
1981
|
retainedFrom, message: structuredClone(change.message), through: change.through };
|
|
1613
1982
|
}
|
|
1614
1983
|
async function readLinearActiveBranchPage(host, state, input, limit) {
|
|
1984
|
+
if (state.membershipBase)
|
|
1985
|
+
return undefined;
|
|
1615
1986
|
const totalBigInt = state.logicalCount ?? 0n;
|
|
1616
1987
|
if (totalBigInt > BigInt(Number.MAX_SAFE_INTEGER))
|
|
1617
1988
|
throw new StoreError('invalid', 'active branch is too large to index');
|
|
@@ -1619,11 +1990,11 @@ async function readLinearActiveBranchPage(host, state, input, limit) {
|
|
|
1619
1990
|
const headId = state.head ? await branchTurnIdByIdentity(host, state.head) : undefined;
|
|
1620
1991
|
if (state.head && !headId)
|
|
1621
1992
|
return {
|
|
1622
|
-
state, totalCount, startPosition: Math.max(0, totalCount - limit),
|
|
1993
|
+
state, totalCount, startPosition: Math.max(0, totalCount - limit), segments: [],
|
|
1623
1994
|
hasMoreOlder: totalCount > limit, cursor: null, complete: false,
|
|
1624
1995
|
};
|
|
1625
1996
|
if (!headId)
|
|
1626
|
-
return { state, totalCount, startPosition: 0,
|
|
1997
|
+
return { state, totalCount, startPosition: 0, segments: [], hasMoreOlder: false, cursor: null, complete: true };
|
|
1627
1998
|
let startPosition = input.before
|
|
1628
1999
|
? Math.max(0, input.before.position - limit + 1)
|
|
1629
2000
|
: Math.max(0, totalCount - limit);
|
|
@@ -1757,16 +2128,14 @@ async function readLinearActiveBranchPage(host, state, input, limit) {
|
|
|
1757
2128
|
segmentGroups.set(segment.businessId, group);
|
|
1758
2129
|
}
|
|
1759
2130
|
const orderedSegments = [...selected].sort((a, b) => a[1] - b[1]).flatMap(([businessId]) => segmentGroups.get(businessId) ?? []);
|
|
1760
|
-
const page = await readBranchPageMessages(host, orderedSegments, headers);
|
|
1761
|
-
const messages = page.messages;
|
|
1762
|
-
complete &&= page.complete;
|
|
1763
2131
|
const actualStart = selected.size ? Math.min(...selected.values()) : startPosition;
|
|
1764
2132
|
const cursor = olderCursor && actualStart > 0 ? olderCursor : null;
|
|
1765
2133
|
return {
|
|
1766
2134
|
state,
|
|
1767
2135
|
totalCount,
|
|
1768
2136
|
startPosition: actualStart,
|
|
1769
|
-
|
|
2137
|
+
segments: orderedSegments,
|
|
2138
|
+
headers,
|
|
1770
2139
|
hasMoreOlder: cursor !== null || (!complete && actualStart > 0),
|
|
1771
2140
|
cursor,
|
|
1772
2141
|
complete,
|
|
@@ -1968,13 +2337,14 @@ function identityValue(id) {
|
|
|
1968
2337
|
function parentValue(parent) {
|
|
1969
2338
|
return new Map([['id', hexBytes(parent.id)], ['hash', hexBytes(parent.hash)]]);
|
|
1970
2339
|
}
|
|
1971
|
-
function decodeIdentity(value) {
|
|
2340
|
+
function decodeIdentity(value, reserved = false) {
|
|
1972
2341
|
const row = asMap(value, 'command identity');
|
|
1973
2342
|
const kind = row.get('kind'), businessId = row.get('businessId'), segmentId = row.get('segmentId');
|
|
1974
2343
|
if (typeof kind !== 'string' || !knownKind(kind) || typeof businessId !== 'string' || typeof segmentId !== 'string')
|
|
1975
2344
|
throw invalid('command identity');
|
|
1976
2345
|
const identity = { kind, businessId, segmentId };
|
|
1977
|
-
|
|
2346
|
+
if (!reserved)
|
|
2347
|
+
assertWritableIdentity(identity);
|
|
1978
2348
|
keyOf(identity);
|
|
1979
2349
|
return identity;
|
|
1980
2350
|
}
|
|
@@ -2097,7 +2467,7 @@ function publishedIdentity(raw, id) {
|
|
|
2097
2467
|
return { businessId: text(businessId), segmentId: text(segmentId), turnId: id.slice() };
|
|
2098
2468
|
}
|
|
2099
2469
|
function messageKey(businessId, segmentId) { return decodeUtf8(keyOf({ kind: 'message', businessId, segmentId })); }
|
|
2100
|
-
async function writeIndexed(host, writes, puts, expectedEventCursor) {
|
|
2470
|
+
async function writeIndexed(host, writes, puts, expectedEventCursor, requireLocalInterval = false) {
|
|
2101
2471
|
if (!writes.length && !puts.length)
|
|
2102
2472
|
return;
|
|
2103
2473
|
if (host instanceof LodyHistory) {
|
|
@@ -2128,7 +2498,7 @@ async function writeIndexed(host, writes, puts, expectedEventCursor) {
|
|
|
2128
2498
|
if (w.kind === 'editPath')
|
|
2129
2499
|
return { kind: 'edit', turnId: w.turnId, expectedNextSeq: w.expectedNextSeq, ops: [{ kind: 'set', path: w.path, contentJson: decodeUtf8(encodeJson(w.value)) }] };
|
|
2130
2500
|
return { kind: 'edit', turnId: w.turnId, expectedNextSeq: w.expectedNextSeq, ops: [{ kind: 'set', path: [{ key: 'content' }], contentJson: decodeUtf8(encodeJson(w.value)) }] };
|
|
2131
|
-
}), { indexPuts: puts, expectedEventCursor });
|
|
2501
|
+
}), { indexPuts: puts, expectedEventCursor, ...(requireLocalInterval ? { requireLocalInterval: true } : {}) });
|
|
2132
2502
|
}
|
|
2133
2503
|
async function maybePublishAccept(host, input, options, turnId) {
|
|
2134
2504
|
if (options?.publish === false || input.kind !== 'message')
|