@loro-dev/roost 0.3.0 → 0.3.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 +24 -3
- package/dist/lody-history.d.ts +65 -0
- package/dist/lody-history.js +415 -49
- package/node/client.d.mts +8 -2
- package/node/client.mjs +23 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -12,10 +12,10 @@ The `Inbox` module adds atomic raw receipt/cursor storage, without authenticatin
|
|
|
12
12
|
or applying those bytes.
|
|
13
13
|
|
|
14
14
|
```sh
|
|
15
|
-
npm install @loro-dev/roost@0.3.
|
|
15
|
+
npm install @loro-dev/roost@0.3.1
|
|
16
16
|
```
|
|
17
17
|
|
|
18
|
-
This source targets the coordinated Rust/TypeScript/Native 0.3.
|
|
18
|
+
This source targets the coordinated Rust/TypeScript/Native 0.3.1 release;
|
|
19
19
|
the registry determines npm availability. Native SQLite storage in
|
|
20
20
|
this release accepts fresh/v10 containers only. Preserve older databases with
|
|
21
21
|
their compatible runtime; there is no automatic migration or deletion.
|
|
@@ -477,7 +477,7 @@ both browser and Node adapters: it atomically creates and seals a non-message
|
|
|
477
477
|
reconstruct the rollback, including an empty restored view, from that native
|
|
478
478
|
record. `branch_state` is readable as an internal history identity but is excluded
|
|
479
479
|
from `HistoryWriteIdentity`, `AcceptHistory` and batch commands; generic authoring
|
|
480
|
-
rejects it at runtime as well. Use
|
|
480
|
+
rejects it at runtime as well. Use the dedicated branch APIs for this reserved identity. It
|
|
481
481
|
does not edit sealed Turns or change the Rust state machine/wire.
|
|
482
482
|
|
|
483
483
|
Active-branch pages return `startPosition`, `totalCount`, `hasMoreOlder`, and an
|
|
@@ -548,3 +548,24 @@ Recorded example: 2026-09-17 results and measurement limits.
|
|
|
548
548
|
Host payload crypto may return a Promise (`AsyncPayloadCrypto`), including
|
|
549
549
|
WebCrypto. Encryption and decryption are awaited outside storage transactions;
|
|
550
550
|
failed transforms never fall back to plaintext. See RSE1.
|
|
551
|
+
|
|
552
|
+
### Selected membership and sparse branch changes (0.3.1)
|
|
553
|
+
|
|
554
|
+
`readActiveBranchMembers(viewId, options)` returns logical positions, member references and ancestry
|
|
555
|
+
cursors. `lookupMember(identity)` returns header information;
|
|
556
|
+
`readActiveBranchMessages(viewId, businessIds)` hydrates selected active bodies.
|
|
557
|
+
|
|
558
|
+
`NodeLodyHistory.replaceActiveBranchMembers` accepts an ordered list of logical segment references
|
|
559
|
+
and optional new messages. Each logical row has one primary. Existing physical Turns are reused;
|
|
560
|
+
a fresh `primary:<id>` physical segment can represent a reinserted business ID's logical `primary`.
|
|
561
|
+
A signed `branch_state` with v2 metadata holds the membership root, which subsequent appends reference.
|
|
562
|
+
New messages are sealed by default; `sealed: false` creates an unsealed replacement.
|
|
563
|
+
|
|
564
|
+
The manifest uses bounded private array appends. Its Create binds the intent digest, retries compare
|
|
565
|
+
the stored prefix, and the completed root is sealed. A small activation claim commits branch state
|
|
566
|
+
and operation/application receipts in one exclusive Native transaction. Operation-ID retries return
|
|
567
|
+
the original receipt. Incomplete membership is reported until referenced records arrive.
|
|
568
|
+
|
|
569
|
+
The SDK reads existing v1 branches in place and v2 membership views. V1 SDKs read v1 views. This API
|
|
570
|
+
requires matching `field-reads-v1` and `exclusive-batch-v1` Native capabilities; consumers update their
|
|
571
|
+
version pins after the paired SDK/Native release.
|
package/dist/lody-history.d.ts
CHANGED
|
@@ -58,6 +58,7 @@ export type HistoryBatchOptions = {
|
|
|
58
58
|
export type HistoryProjectedMessage = {
|
|
59
59
|
businessId: string;
|
|
60
60
|
segmentId: string;
|
|
61
|
+
physicalSegmentId?: string;
|
|
61
62
|
turnId: Uint8Array;
|
|
62
63
|
content: JsonValue;
|
|
63
64
|
nextSeq: bigint;
|
|
@@ -93,6 +94,7 @@ export type BranchViewState = {
|
|
|
93
94
|
head: HistoryIdentity | null;
|
|
94
95
|
operationId: string | null;
|
|
95
96
|
logicalCount?: bigint;
|
|
97
|
+
membershipBase?: HistoryIdentity;
|
|
96
98
|
conflict?: boolean;
|
|
97
99
|
};
|
|
98
100
|
export type BranchMutationResult = {
|
|
@@ -136,6 +138,10 @@ export type ActiveBranchPageRead = {
|
|
|
136
138
|
cursor: ActiveBranchPageCursor | null;
|
|
137
139
|
complete: boolean;
|
|
138
140
|
};
|
|
141
|
+
/** Read active member references and headers. */
|
|
142
|
+
export type ActiveBranchMembersRead = Omit<ActiveBranchPageRead, 'messages'> & {
|
|
143
|
+
members: ActiveBranchSegmentRef[];
|
|
144
|
+
};
|
|
139
145
|
export type ActiveBranchPageCursor = {
|
|
140
146
|
viewId: string;
|
|
141
147
|
turnId: Uint8Array;
|
|
@@ -154,6 +160,29 @@ export type ActiveBranchPageAdvance = Omit<ActiveBranchPageRead, 'messages'> & {
|
|
|
154
160
|
message: HistoryProjectedMessage;
|
|
155
161
|
through: bigint;
|
|
156
162
|
};
|
|
163
|
+
export type ActiveBranchMemberIdentity = {
|
|
164
|
+
identity: HistoryIdentity;
|
|
165
|
+
segmentId: string;
|
|
166
|
+
};
|
|
167
|
+
export type ReplaceActiveBranchMembersInput = {
|
|
168
|
+
viewId: string;
|
|
169
|
+
expectedRevision: bigint;
|
|
170
|
+
expectedHead: HistoryIdentity | null;
|
|
171
|
+
operationId: string;
|
|
172
|
+
members: ActiveBranchMemberIdentity[];
|
|
173
|
+
messages?: {
|
|
174
|
+
identity: HistoryWriteIdentity;
|
|
175
|
+
content: JsonValue;
|
|
176
|
+
parents?: ParentRef[];
|
|
177
|
+
attachments?: AcceptHistory['attachments'];
|
|
178
|
+
sealed?: boolean;
|
|
179
|
+
}[];
|
|
180
|
+
supersedes?: HistoryIdentity[];
|
|
181
|
+
receipts?: Extract<HistoryBatchCommand, {
|
|
182
|
+
type: 'accept';
|
|
183
|
+
}>[];
|
|
184
|
+
expectedEventCursor: bigint;
|
|
185
|
+
};
|
|
157
186
|
export type RestoreActiveBranchInput = {
|
|
158
187
|
viewId: string;
|
|
159
188
|
expectedRevision: bigint;
|
|
@@ -316,6 +345,7 @@ export type NodeHistoryIndexPut = NodeIndexKey & {
|
|
|
316
345
|
emitEvent?: boolean;
|
|
317
346
|
};
|
|
318
347
|
export type NodeHistoryBatchOptions = {
|
|
348
|
+
requireLocalInterval?: boolean;
|
|
319
349
|
indexPuts?: NodeHistoryIndexPut[];
|
|
320
350
|
expectedEventCursor?: bigint;
|
|
321
351
|
expectedIndexes?: NodeIndexEntry[];
|
|
@@ -355,6 +385,21 @@ export interface LodyNodeHost {
|
|
|
355
385
|
key?: Uint8Array;
|
|
356
386
|
};
|
|
357
387
|
}[]>;
|
|
388
|
+
readonly fieldReads?: boolean;
|
|
389
|
+
readonly exclusiveBatches?: boolean;
|
|
390
|
+
readCreateFields?(id: Uint8Array, selectors: {
|
|
391
|
+
path: NodeHistoryPath;
|
|
392
|
+
}[], omitDigestKeys: string[]): Promise<{
|
|
393
|
+
fields: ({
|
|
394
|
+
state: 'missing';
|
|
395
|
+
} | {
|
|
396
|
+
state: 'ready';
|
|
397
|
+
contentJson: string;
|
|
398
|
+
})[];
|
|
399
|
+
owner: Uint8Array;
|
|
400
|
+
digest: Uint8Array;
|
|
401
|
+
filteredDigest: Uint8Array;
|
|
402
|
+
}>;
|
|
358
403
|
exportUpdates(id: Uint8Array, from: bigint, limit: bigint): Promise<Uint8Array>;
|
|
359
404
|
createOnce(key: Uint8Array, parents: ParentRef[], contentJson: string, options?: {
|
|
360
405
|
expectedEventCursor?: bigint;
|
|
@@ -495,6 +540,20 @@ export declare class NodeLodyHistory {
|
|
|
495
540
|
latest?: boolean;
|
|
496
541
|
limit?: number;
|
|
497
542
|
}): Promise<ActiveBranchPageRead>;
|
|
543
|
+
readActiveBranchMembers(viewId: string, input?: {
|
|
544
|
+
before?: ActiveBranchPageCursor;
|
|
545
|
+
from?: number;
|
|
546
|
+
latest?: boolean;
|
|
547
|
+
limit?: number;
|
|
548
|
+
}): Promise<ActiveBranchMembersRead>;
|
|
549
|
+
/** Resolve an identity to its Turn header. */
|
|
550
|
+
lookupMember(identity: HistoryIdentity): Promise<{
|
|
551
|
+
turnId: Uint8Array;
|
|
552
|
+
nextSeq: bigint;
|
|
553
|
+
sealed: boolean;
|
|
554
|
+
} | undefined>;
|
|
555
|
+
replaceActiveBranchMembers(input: ReplaceActiveBranchMembersInput): Promise<RestoreActiveBranchResult>;
|
|
556
|
+
readActiveBranchMessages(viewId: string, businessIds: readonly string[]): Promise<HistoryProjectedMessage[]>;
|
|
498
557
|
advanceActiveBranchDirectory(page: ActiveBranchPageRead, result: BranchMutationResult, limit?: number): ActiveBranchPageAdvance | undefined;
|
|
499
558
|
respondPermission(input: {
|
|
500
559
|
requestId: string;
|
|
@@ -536,6 +595,12 @@ export declare class NodeLodyHistory {
|
|
|
536
595
|
}>;
|
|
537
596
|
}
|
|
538
597
|
type HistoryHost = LodyHistory | NodeLodyHistory;
|
|
598
|
+
type ActiveBranchSegmentRef = {
|
|
599
|
+
businessId: string;
|
|
600
|
+
segmentId: string;
|
|
601
|
+
turnId: Uint8Array;
|
|
602
|
+
physicalSegmentId?: string;
|
|
603
|
+
};
|
|
539
604
|
export type HistoryMessageViewUpdate = {
|
|
540
605
|
/** Treat rows and their nested content as read-only. Unchanged rows retain identity. */
|
|
541
606
|
messages: readonly HistoryProjectedMessage[];
|
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
|
}
|
|
@@ -1060,7 +1121,7 @@ async function branchMutation(host, input, baseTurn, supersedes, inputDigest, li
|
|
|
1060
1121
|
if (baseTurn !== null && baseTurn.length !== 16)
|
|
1061
1122
|
throw invalid('branch base Turn');
|
|
1062
1123
|
if (expectedHead) {
|
|
1063
|
-
if (expectedHead.kind !== 'message')
|
|
1124
|
+
if (expectedHead.kind !== 'message' && expectedHead.kind !== 'branch_state')
|
|
1064
1125
|
throw invalid('branch head kind');
|
|
1065
1126
|
keyOf(expectedHead);
|
|
1066
1127
|
}
|
|
@@ -1071,9 +1132,13 @@ async function branchMutation(host, input, baseTurn, supersedes, inputDigest, li
|
|
|
1071
1132
|
}
|
|
1072
1133
|
if (!branchParentMatches(baseTurn, input.input.parents))
|
|
1073
1134
|
throw invalid('branch base parent');
|
|
1074
|
-
const
|
|
1135
|
+
const inherited = await readBranchIndex(host, viewId);
|
|
1136
|
+
const rooted = inherited?.membershipBase && inherited.revision === input.expectedRevision && branchStateEqual(inherited.head, expectedHead) && linearAppend;
|
|
1137
|
+
const baseCount = rooted ? inherited.logicalCount : await branchLogicalCountAt(host, viewId, baseTurn);
|
|
1075
1138
|
const logicalCount = baseCount + (input.input.segmentId === 'primary' ? 1n : 0n);
|
|
1076
1139
|
const metadata = branchMetadataFor({ ...input, viewId, operationId, expectedHead }, owner, expectedHead, baseTurn, supersedes, logicalCount);
|
|
1140
|
+
if (rooted)
|
|
1141
|
+
metadata.membershipBase = inherited.membershipBase;
|
|
1077
1142
|
const createKey = keyOf(input.input);
|
|
1078
1143
|
const branchValue = branchStateValue(metadata);
|
|
1079
1144
|
const operationValue = branchOperationValue({ operationId, created: true, oldHead: expectedHead, newHead: metadata.head, revision: metadata.revision, turnId: null }, metadata.digest, inputDigest);
|
|
@@ -1136,7 +1201,7 @@ async function branchMutation(host, input, baseTurn, supersedes, inputDigest, li
|
|
|
1136
1201
|
equal(committed.updates[0].turnId, turnId) && committed.through - committed.before === 2n) {
|
|
1137
1202
|
branchTransitions.set(result, {
|
|
1138
1203
|
ownerToken: branchHandleToken(host), beforeRevision: input.expectedRevision, beforeHead: structuredClone(expectedHead),
|
|
1139
|
-
state: { viewId, revision: metadata.revision, head: structuredClone(metadata.head), operationId, logicalCount },
|
|
1204
|
+
state: { viewId, revision: metadata.revision, head: structuredClone(metadata.head), operationId, logicalCount, ...(metadata.membershipBase ? { membershipBase: metadata.membershipBase } : {}) },
|
|
1140
1205
|
message: { businessId: input.input.businessId, segmentId: 'primary', turnId: turnId.slice(),
|
|
1141
1206
|
content: structuredClone(input.input.content), nextSeq: 1n, sealed: false,
|
|
1142
1207
|
parents: structuredClone(input.input.parents), sealedHash: null },
|
|
@@ -1157,6 +1222,35 @@ async function branchFork(host, input) {
|
|
|
1157
1222
|
throw invalid('active branch only accepts message replacements');
|
|
1158
1223
|
if (input.baseTurn && input.baseTurn.length !== 16)
|
|
1159
1224
|
throw invalid('branch base Turn');
|
|
1225
|
+
input = structuredClone(input);
|
|
1226
|
+
const expectedId = input.expectedHead ? await branchTurnIdByIdentity(host, input.expectedHead) : undefined;
|
|
1227
|
+
const expected = expectedId ? await branchMetadataAt(host, expectedId) : undefined;
|
|
1228
|
+
if (expected?.membershipBase && expected.viewId === input.viewId) {
|
|
1229
|
+
if (!(host instanceof NodeLodyHistory))
|
|
1230
|
+
throw invalid('membership forks require a Native author');
|
|
1231
|
+
if (!branchParentMatches(input.baseTurn, input.input.parents))
|
|
1232
|
+
throw invalid('branch base parent');
|
|
1233
|
+
const cursor = await host.observedEventCursor();
|
|
1234
|
+
const directory = await readRootedBranchDirectory(host, { viewId: input.viewId, revision: input.expectedRevision, head: input.expectedHead,
|
|
1235
|
+
operationId: expected.operationId, membershipBase: expected.membershipBase, ...(expected.logicalCount === undefined ? {} : { logicalCount: expected.logicalCount }) });
|
|
1236
|
+
if (!directory.complete)
|
|
1237
|
+
throw new StoreError('pending', 'fork membership is incomplete');
|
|
1238
|
+
const members = directory.rows.flatMap(row => row.segments);
|
|
1239
|
+
const boundary = input.baseTurn ? members.findIndex(row => equal(row.turnId, input.baseTurn)) : -1;
|
|
1240
|
+
if (input.baseTurn && boundary < 0)
|
|
1241
|
+
throw new StoreError('stale', 'fork base is not active');
|
|
1242
|
+
const prefix = members.slice(0, boundary + 1).map(row => ({ identity: { kind: 'message', businessId: row.businessId, segmentId: row.physicalSegmentId ?? row.segmentId }, segmentId: row.segmentId }));
|
|
1243
|
+
const result = await host.replaceActiveBranchMembers({ viewId: input.viewId, expectedRevision: input.expectedRevision,
|
|
1244
|
+
expectedHead: input.expectedHead, operationId: input.operationId, expectedEventCursor: cursor,
|
|
1245
|
+
members: [...prefix, { identity: input.input, segmentId: input.input.segmentId }],
|
|
1246
|
+
messages: [{ identity: input.input, content: input.input.content, parents: input.input.parents, attachments: input.input.attachments, sealed: false }], supersedes: input.supersedes });
|
|
1247
|
+
if (!result.newHead)
|
|
1248
|
+
throw invalid('fork root missing');
|
|
1249
|
+
const physical = await host.lookupMember(input.input);
|
|
1250
|
+
if (!physical)
|
|
1251
|
+
throw new StoreError('pending', 'fork replacement missing');
|
|
1252
|
+
return { ...result, newHead: result.newHead, turnId: physical.turnId };
|
|
1253
|
+
}
|
|
1160
1254
|
return branchMutation(host, input, input.baseTurn, input.supersedes);
|
|
1161
1255
|
}
|
|
1162
1256
|
function branchRestoreDigest(input) {
|
|
@@ -1174,12 +1268,12 @@ async function branchRestore(host, input) {
|
|
|
1174
1268
|
throw invalid('branch revision');
|
|
1175
1269
|
const viewId = text(input.viewId), operationId = text(input.operationId), digest = branchRestoreDigest(input);
|
|
1176
1270
|
if (input.expectedHead) {
|
|
1177
|
-
if (input.expectedHead.kind !== 'message')
|
|
1271
|
+
if (input.expectedHead.kind !== 'message' && input.expectedHead.kind !== 'branch_state')
|
|
1178
1272
|
throw invalid('branch expected head kind');
|
|
1179
1273
|
keyOf(input.expectedHead);
|
|
1180
1274
|
}
|
|
1181
1275
|
if (input.restoreHead) {
|
|
1182
|
-
if (input.restoreHead.kind !== 'message')
|
|
1276
|
+
if (input.restoreHead.kind !== 'message' && input.restoreHead.kind !== 'branch_state')
|
|
1183
1277
|
throw invalid('branch restore head kind');
|
|
1184
1278
|
keyOf(input.restoreHead);
|
|
1185
1279
|
}
|
|
@@ -1209,12 +1303,14 @@ async function branchRestore(host, input) {
|
|
|
1209
1303
|
if (input.restoreHead && !restoreTurnId)
|
|
1210
1304
|
throw new StoreError('corrupt', 'restore branch head missing');
|
|
1211
1305
|
const logicalCount = await branchLogicalCountAt(host, viewId, restoreTurnId ?? null);
|
|
1306
|
+
const restoredMetadata = restoreTurnId ? await branchMetadataAt(host, restoreTurnId) : undefined;
|
|
1212
1307
|
const metadata = {
|
|
1213
1308
|
viewId,
|
|
1214
1309
|
revision: input.expectedRevision + 1n,
|
|
1215
1310
|
operationId,
|
|
1216
1311
|
previousHead: input.expectedHead,
|
|
1217
1312
|
head: input.restoreHead,
|
|
1313
|
+
...(restoredMetadata?.membershipBase ? { membershipBase: restoredMetadata.membershipBase } : {}),
|
|
1218
1314
|
baseTurn: null,
|
|
1219
1315
|
logicalCount,
|
|
1220
1316
|
supersedes: [],
|
|
@@ -1255,6 +1351,11 @@ async function readActiveBranchSnapshot(host, viewId) {
|
|
|
1255
1351
|
return { state: { viewId: text(viewId), revision: 0n, head: null, operationId: null }, messages: [], complete: true };
|
|
1256
1352
|
if (state.conflict)
|
|
1257
1353
|
throw new StoreError('conflict', 'active branch has conflicting revisions');
|
|
1354
|
+
if (state.membershipBase) {
|
|
1355
|
+
const directory = await readActiveBranchDirectory(host, viewId);
|
|
1356
|
+
const page = await readBranchPageMessages(host, directory.rows.flatMap(row => row.segments));
|
|
1357
|
+
return { state, messages: page.messages, complete: directory.complete && page.complete };
|
|
1358
|
+
}
|
|
1258
1359
|
if (state.head === null)
|
|
1259
1360
|
return { state, messages: [], complete: true };
|
|
1260
1361
|
const headId = await branchTurnByIdentity(host, state.head);
|
|
@@ -1294,12 +1395,13 @@ async function readBranchPageMessages(host, segments, headers) {
|
|
|
1294
1395
|
const turns = await Promise.all(batch.map(segment => readBranchPageTurn(host, segment.turnId, headers?.get(hexBytes(segment.turnId)), retained?.get(hexBytes(segment.turnId)))));
|
|
1295
1396
|
for (let i = 0; i < batch.length; i++) {
|
|
1296
1397
|
const turn = turns[i], segment = batch[i];
|
|
1297
|
-
if (!turn || turn.identity?.kind !== 'message' || turn.content === undefined) {
|
|
1398
|
+
if (!turn || turn.identity?.kind !== 'message' || turn.identity.businessId !== segment.businessId || turn.identity.segmentId !== (segment.physicalSegmentId ?? segment.segmentId) || turn.content === undefined) {
|
|
1298
1399
|
complete = false;
|
|
1299
1400
|
continue;
|
|
1300
1401
|
}
|
|
1301
1402
|
messages.push({
|
|
1302
|
-
businessId: segment.businessId, segmentId: segment.segmentId,
|
|
1403
|
+
businessId: segment.businessId, segmentId: segment.segmentId,
|
|
1404
|
+
...(segment.physicalSegmentId ? { physicalSegmentId: segment.physicalSegmentId } : {}), turnId: turn.turnId,
|
|
1303
1405
|
content: turn.content, nextSeq: turn.nextSeq, sealed: turn.sealed !== null,
|
|
1304
1406
|
parents: turn.parents, sealedHash: turn.sealed,
|
|
1305
1407
|
});
|
|
@@ -1307,9 +1409,239 @@ async function readBranchPageMessages(host, segments, headers) {
|
|
|
1307
1409
|
}
|
|
1308
1410
|
return { messages, complete };
|
|
1309
1411
|
}
|
|
1412
|
+
async function readRootedBranchDirectory(host, state) {
|
|
1413
|
+
const root = state.membershipBase;
|
|
1414
|
+
const rootId = await branchTurnIdByIdentity(host, root);
|
|
1415
|
+
if (!rootId)
|
|
1416
|
+
return { state, rows: [], complete: false };
|
|
1417
|
+
const header = await branchHeader(host, rootId);
|
|
1418
|
+
if (!header?.sealed)
|
|
1419
|
+
return { state, rows: [], complete: false };
|
|
1420
|
+
const rootMeta = await branchMetadataAt(host, rootId);
|
|
1421
|
+
if (!rootMeta || rootMeta.viewId !== state.viewId || !branchStateEqual(rootMeta.membershipBase ?? null, root))
|
|
1422
|
+
throw invalid('membership root metadata');
|
|
1423
|
+
const content = asMap(await publicationField(host, rootId, [{ key: 'content' }]), 'membership root');
|
|
1424
|
+
const raw = content.get('members');
|
|
1425
|
+
if (content.get('version') !== '1' || !Array.isArray(raw))
|
|
1426
|
+
throw invalid('membership root members');
|
|
1427
|
+
const refs = raw.map(value => {
|
|
1428
|
+
const row = asMap(value, 'membership member');
|
|
1429
|
+
const identity = decodeIdentity(row.get('identity'));
|
|
1430
|
+
const segmentId = row.get('segmentId');
|
|
1431
|
+
if (identity.kind !== 'message' || typeof segmentId !== 'string')
|
|
1432
|
+
throw invalid('membership member identity');
|
|
1433
|
+
if (segmentId !== identity.segmentId && (segmentId !== 'primary' || !identity.segmentId.startsWith('primary:')))
|
|
1434
|
+
throw invalid('membership segment alias');
|
|
1435
|
+
return { identity, segmentId: text(segmentId) };
|
|
1436
|
+
});
|
|
1437
|
+
const rows = [], byId = new Map();
|
|
1438
|
+
let complete = true;
|
|
1439
|
+
const seen = new Set();
|
|
1440
|
+
const add = (ref, turnId) => {
|
|
1441
|
+
const key = hexBytes(turnId);
|
|
1442
|
+
if (seen.has(key))
|
|
1443
|
+
throw invalid('duplicate membership member');
|
|
1444
|
+
seen.add(key);
|
|
1445
|
+
let row = byId.get(ref.identity.businessId);
|
|
1446
|
+
if (!row) {
|
|
1447
|
+
row = { businessId: ref.identity.businessId, segments: [] };
|
|
1448
|
+
byId.set(row.businessId, row);
|
|
1449
|
+
rows.push(row);
|
|
1450
|
+
}
|
|
1451
|
+
row.segments.push({ businessId: row.businessId, segmentId: ref.segmentId, turnId: turnId.slice(),
|
|
1452
|
+
...(ref.identity.segmentId === ref.segmentId ? {} : { physicalSegmentId: ref.identity.segmentId }) });
|
|
1453
|
+
};
|
|
1454
|
+
for (const ref of refs) {
|
|
1455
|
+
const turnId = await branchTurnIdByIdentity(host, ref.identity);
|
|
1456
|
+
if (!turnId || !await branchHeader(host, turnId)) {
|
|
1457
|
+
complete = false;
|
|
1458
|
+
continue;
|
|
1459
|
+
}
|
|
1460
|
+
add(ref, turnId);
|
|
1461
|
+
}
|
|
1462
|
+
const boundary = rootMeta.head ? await branchTurnIdByIdentity(host, rootMeta.head) : undefined;
|
|
1463
|
+
let current = state.head ? await branchTurnIdByIdentity(host, state.head) : undefined;
|
|
1464
|
+
const suffix = [], walked = new Set();
|
|
1465
|
+
while (current && (!boundary || !equal(current, boundary))) {
|
|
1466
|
+
const id = hexBytes(current);
|
|
1467
|
+
if (walked.has(id))
|
|
1468
|
+
throw invalid('membership suffix cycle');
|
|
1469
|
+
walked.add(id);
|
|
1470
|
+
const metadata = await branchMetadataAt(host, current);
|
|
1471
|
+
if (!metadata) {
|
|
1472
|
+
complete = false;
|
|
1473
|
+
break;
|
|
1474
|
+
}
|
|
1475
|
+
if (metadata.viewId !== state.viewId || !branchStateEqual(metadata.membershipBase ?? null, root) || !metadata.head)
|
|
1476
|
+
throw invalid('membership suffix metadata');
|
|
1477
|
+
suffix.push({ identity: metadata.head, turnId: current });
|
|
1478
|
+
current = metadata.baseTurn ? unhexBytes(metadata.baseTurn, 16) : undefined;
|
|
1479
|
+
}
|
|
1480
|
+
if (boundary && (!current || !equal(current, boundary)))
|
|
1481
|
+
complete = false;
|
|
1482
|
+
for (const ref of suffix.reverse())
|
|
1483
|
+
add({ identity: ref.identity, segmentId: ref.identity.segmentId }, ref.turnId);
|
|
1484
|
+
if (state.logicalCount !== undefined && BigInt(rows.length) !== state.logicalCount)
|
|
1485
|
+
complete = false;
|
|
1486
|
+
return { state, rows, complete };
|
|
1487
|
+
}
|
|
1488
|
+
async function replaceBranchMembers(host, input) {
|
|
1489
|
+
if (!host.stream.exclusiveBatches)
|
|
1490
|
+
throw invalid('membership requires exclusive-batch-v1');
|
|
1491
|
+
input = structuredClone(input);
|
|
1492
|
+
const { viewId, operationId } = input;
|
|
1493
|
+
text(viewId);
|
|
1494
|
+
text(operationId);
|
|
1495
|
+
if (typeof input.expectedRevision !== 'bigint' || input.expectedRevision < 0n || input.expectedRevision >= U64_MAX)
|
|
1496
|
+
throw invalid('branch revision');
|
|
1497
|
+
if (typeof input.expectedEventCursor !== 'bigint' || input.expectedEventCursor < 0n || input.expectedEventCursor > U64_MAX)
|
|
1498
|
+
throw invalid('membership event cursor');
|
|
1499
|
+
for (const superseded of input.supersedes ?? []) {
|
|
1500
|
+
if (superseded.kind !== 'message')
|
|
1501
|
+
throw invalid('branch superseded kind');
|
|
1502
|
+
keyOf(superseded);
|
|
1503
|
+
}
|
|
1504
|
+
const owner = host.owner;
|
|
1505
|
+
const identity = { kind: 'branch_state', businessId: viewId, segmentId: operationId };
|
|
1506
|
+
const newHead = identity;
|
|
1507
|
+
const messageKeys = new Set((input.messages ?? []).map(row => decodeUtf8(keyOf(row.identity))));
|
|
1508
|
+
const memberKeys = new Set(), logicalIds = new Set(), primaryIds = new Set();
|
|
1509
|
+
for (const member of input.members) {
|
|
1510
|
+
if (member.identity.kind !== 'message' || typeof member.segmentId !== 'string')
|
|
1511
|
+
throw invalid('membership identity');
|
|
1512
|
+
text(member.segmentId);
|
|
1513
|
+
const key = decodeUtf8(keyOf(member.identity));
|
|
1514
|
+
if (memberKeys.has(key))
|
|
1515
|
+
throw invalid('duplicate membership identity');
|
|
1516
|
+
memberKeys.add(key);
|
|
1517
|
+
logicalIds.add(member.identity.businessId);
|
|
1518
|
+
if (member.segmentId === 'primary') {
|
|
1519
|
+
if (primaryIds.has(member.identity.businessId))
|
|
1520
|
+
throw invalid('duplicate membership primary');
|
|
1521
|
+
primaryIds.add(member.identity.businessId);
|
|
1522
|
+
}
|
|
1523
|
+
if (member.segmentId !== member.identity.segmentId && (member.segmentId !== 'primary' || !member.identity.segmentId.startsWith('primary:')))
|
|
1524
|
+
throw invalid('membership segment alias');
|
|
1525
|
+
}
|
|
1526
|
+
if (primaryIds.size !== logicalIds.size)
|
|
1527
|
+
throw invalid('membership primary missing');
|
|
1528
|
+
const members = input.members.map(row => new Map([['identity', identityValue(row.identity)], ['segmentId', row.segmentId]]));
|
|
1529
|
+
const messages = input.messages ?? [];
|
|
1530
|
+
if (messages.some(row => row.identity.kind !== 'message' || !memberKeys.has(decodeUtf8(keyOf(row.identity)))) || messageKeys.size !== messages.length)
|
|
1531
|
+
throw invalid('membership messages');
|
|
1532
|
+
if (messages.some(row => row.sealed !== undefined && typeof row.sealed !== 'boolean'))
|
|
1533
|
+
throw invalid('membership sealing flag');
|
|
1534
|
+
const receipts = input.receipts ?? [];
|
|
1535
|
+
const digest = hexBytes(blake3(encodeJson(new Map([
|
|
1536
|
+
['viewId', viewId], ['operationId', operationId], ['revision', { kind: 'u64', value: input.expectedRevision }],
|
|
1537
|
+
['expectedHead', input.expectedHead ? identityValue(input.expectedHead) : null], ['members', members],
|
|
1538
|
+
['messages', messages.map(row => [hexBytes(createDigest(owner, row.parents ?? [], envelope({ ...row.identity, parents: row.parents ?? [], content: row.content, attachments: row.attachments }))), row.sealed !== false])],
|
|
1539
|
+
['receipts', encodeCommands(receipts)], ['supersedes', (input.supersedes ?? []).map(identityValue)],
|
|
1540
|
+
]))));
|
|
1541
|
+
const prior = await readBranchOperation(host, viewId, operationId);
|
|
1542
|
+
if (prior) {
|
|
1543
|
+
if (prior.digest !== digest)
|
|
1544
|
+
throw new StoreError('conflict', 'membership operation changed');
|
|
1545
|
+
return { operationId, created: false, oldHead: prior.oldHead, newHead: prior.newHead, revision: prior.revision, turnId: prior.turnId };
|
|
1546
|
+
}
|
|
1547
|
+
let cursor = await branchCursor(host);
|
|
1548
|
+
if (cursor !== input.expectedEventCursor)
|
|
1549
|
+
throw new StoreError('stale', 'membership observation changed');
|
|
1550
|
+
const state = await readBranchIndex(host, viewId);
|
|
1551
|
+
if (state?.conflict)
|
|
1552
|
+
throw new StoreError('conflict', 'active branch has conflicting revisions');
|
|
1553
|
+
if ((state?.revision ?? 0n) !== input.expectedRevision || !branchStateEqual(state?.head ?? null, input.expectedHead))
|
|
1554
|
+
throw new StoreError('stale', 'active branch changed');
|
|
1555
|
+
for (const member of input.members)
|
|
1556
|
+
if (!messageKeys.has(decodeUtf8(keyOf(member.identity)))) {
|
|
1557
|
+
const turnId = await branchTurnIdByIdentity(host, member.identity);
|
|
1558
|
+
if (!turnId || !await branchHeader(host, turnId))
|
|
1559
|
+
throw new StoreError('pending', 'membership reference missing');
|
|
1560
|
+
}
|
|
1561
|
+
if (!host.stream.exclusiveBatches)
|
|
1562
|
+
throw invalid('membership requires exclusive-batch-v1');
|
|
1563
|
+
const writes = [];
|
|
1564
|
+
for (const row of messages) {
|
|
1565
|
+
const prior = await host.lookupMember(row.identity);
|
|
1566
|
+
if (prior && (prior.sealed ? prior.nextSeq !== 2n || row.sealed === false : prior.nextSeq !== 1n))
|
|
1567
|
+
throw new StoreError('conflict', 'prepared membership message changed');
|
|
1568
|
+
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) });
|
|
1569
|
+
if (row.sealed !== false && !prior?.sealed)
|
|
1570
|
+
writes.push({ kind: 'sealOnce', key: keyOf(row.identity), expectedNextSeq: 1n });
|
|
1571
|
+
}
|
|
1572
|
+
const receiptWrites = [];
|
|
1573
|
+
for (const receipt of receipts) {
|
|
1574
|
+
assertWritableIdentity(receipt.identity);
|
|
1575
|
+
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) });
|
|
1576
|
+
}
|
|
1577
|
+
if (receiptWrites.length > 4094)
|
|
1578
|
+
throw invalid('membership receipt limit');
|
|
1579
|
+
// Prepare messages in exclusive groups; author receipts during activation.
|
|
1580
|
+
for (let offset = 0; offset < writes.length; offset += 64) {
|
|
1581
|
+
const commit = await writeIndexed(host, writes.slice(offset, offset + 64), [], cursor, true);
|
|
1582
|
+
if (commit?.through === undefined)
|
|
1583
|
+
throw invalid('membership requires fenced Native writes');
|
|
1584
|
+
cursor = commit.through;
|
|
1585
|
+
}
|
|
1586
|
+
const metadata = { viewId, operationId, revision: input.expectedRevision + 1n,
|
|
1587
|
+
previousHead: input.expectedHead, head: newHead, baseTurn: null, membershipBase: identity,
|
|
1588
|
+
logicalCount: BigInt(logicalIds.size), supersedes: input.supersedes ?? [], digest };
|
|
1589
|
+
// Append manifest chunks under a fixed intent digest and resume an exact prefix.
|
|
1590
|
+
const root = { ...identity, parents: [], content: new Map([['version', '1'], ['intentDigest', digest], ['members', []]]) };
|
|
1591
|
+
const createdRoot = await writeIndexed(host, [
|
|
1592
|
+
{ kind: 'createOnce', key: keyOf(identity), parents: [], content: envelope(root, false, { ...metadata, prepared: true }) },
|
|
1593
|
+
], [], cursor, true);
|
|
1594
|
+
if (createdRoot?.through === undefined)
|
|
1595
|
+
throw invalid('membership requires fenced Native writes');
|
|
1596
|
+
cursor = createdRoot.through;
|
|
1597
|
+
await host.catchUpIndex();
|
|
1598
|
+
const rootId = await branchTurnIdByIdentity(host, identity);
|
|
1599
|
+
if (!rootId)
|
|
1600
|
+
throw new StoreError('corrupt', 'prepared membership root missing');
|
|
1601
|
+
let rootHeader = await branchHeader(host, rootId);
|
|
1602
|
+
if (!rootHeader)
|
|
1603
|
+
throw new StoreError('corrupt', 'prepared membership root header missing');
|
|
1604
|
+
const prepared = await publicationField(host, rootId, [{ key: 'content' }, { key: 'members' }]);
|
|
1605
|
+
if (!Array.isArray(prepared) || prepared.length > members.length || prepared.some((value, i) => !equal(encodeJson(value), encodeJson(members[i]))))
|
|
1606
|
+
throw new StoreError('conflict', 'prepared membership prefix changed');
|
|
1607
|
+
if (rootHeader.sealed && prepared.length !== members.length)
|
|
1608
|
+
throw new StoreError('conflict', 'prepared membership root incomplete');
|
|
1609
|
+
for (let offset = prepared.length; offset < members.length; offset += 128) {
|
|
1610
|
+
const commit = await host.stream.writeBatch([{
|
|
1611
|
+
kind: 'edit', turnId: rootId, expectedNextSeq: rootHeader.nextSeq,
|
|
1612
|
+
ops: [{ kind: 'spliceArray', path: [{ key: 'content' }, { key: 'members' }], index: BigInt(offset), delete: 0n,
|
|
1613
|
+
valuesJson: decodeUtf8(encodeJson(members.slice(offset, offset + 128))) }],
|
|
1614
|
+
}], { expectedEventCursor: cursor, requireLocalInterval: true });
|
|
1615
|
+
if (commit.through === undefined)
|
|
1616
|
+
throw invalid('membership requires fenced Native writes');
|
|
1617
|
+
cursor = commit.through;
|
|
1618
|
+
rootHeader = { ...rootHeader, nextSeq: rootHeader.nextSeq + 1n };
|
|
1619
|
+
}
|
|
1620
|
+
if (!rootHeader.sealed) {
|
|
1621
|
+
const commit = await writeIndexed(host, [{ kind: 'seal', turnId: rootId, expectedNextSeq: rootHeader.nextSeq }], [], cursor, true);
|
|
1622
|
+
if (commit?.through === undefined)
|
|
1623
|
+
throw invalid('membership requires fenced Native writes');
|
|
1624
|
+
cursor = commit.through;
|
|
1625
|
+
rootHeader = (await branchHeader(host, rootId));
|
|
1626
|
+
}
|
|
1627
|
+
if (!rootHeader.sealed)
|
|
1628
|
+
throw new StoreError('corrupt', 'prepared membership root not sealed');
|
|
1629
|
+
const activation = { kind: 'branch_state', businessId: viewId, segmentId: `activation:${digest}`,
|
|
1630
|
+
parents: [{ id: rootId, hash: rootHeader.sealed }], content: null };
|
|
1631
|
+
const result = { operationId, created: true, oldHead: input.expectedHead, newHead, revision: metadata.revision, turnId: null };
|
|
1632
|
+
await writeIndexed(host, [
|
|
1633
|
+
...receiptWrites,
|
|
1634
|
+
{ kind: 'createOnce', key: keyOf(activation), parents: activation.parents, content: envelope(activation, false, metadata) },
|
|
1635
|
+
{ kind: 'sealOnce', key: keyOf(activation), expectedNextSeq: 1n },
|
|
1636
|
+
], [
|
|
1637
|
+
{ table: BRANCH_TABLE, key: branchKey(viewId), value: branchStateValue(metadata), emitEvent: true },
|
|
1638
|
+
{ table: BRANCH_OPERATIONS, key: branchOperationKey(viewId, operationId), value: branchOperationValue(result, digest) },
|
|
1639
|
+
], cursor, true);
|
|
1640
|
+
return result;
|
|
1641
|
+
}
|
|
1310
1642
|
const activeBranchDirectoryCache = new WeakMap();
|
|
1311
1643
|
function branchDirectoryKey(state) {
|
|
1312
|
-
return `${state.revision}:${state.head ? decodeUtf8(keyOf(state.head)) : ''}`;
|
|
1644
|
+
return `${state.revision}:${state.head ? decodeUtf8(keyOf(state.head)) : ''}:${state.membershipBase ? decodeUtf8(keyOf(state.membershipBase)) : ''}`;
|
|
1313
1645
|
}
|
|
1314
1646
|
async function branchTurnIdByIdentity(host, identity) {
|
|
1315
1647
|
const key = keyOf(identity);
|
|
@@ -1350,7 +1682,7 @@ async function readActiveBranchDirectory(host, viewId) {
|
|
|
1350
1682
|
await host.catchUpIndex();
|
|
1351
1683
|
const state = await readBranchIndex(host, viewId);
|
|
1352
1684
|
const publicState = state
|
|
1353
|
-
? { viewId: state.viewId, revision: state.revision, head: state.head, operationId: state.operationId, ...(state.conflict ? { conflict: true } : {}) }
|
|
1685
|
+
? { 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
1686
|
: { viewId: text(viewId), revision: 0n, head: null, operationId: null };
|
|
1355
1687
|
const key = branchDirectoryKey(publicState);
|
|
1356
1688
|
const cached = activeBranchDirectoryCache.get(host)?.get(viewId);
|
|
@@ -1360,7 +1692,7 @@ async function readActiveBranchDirectory(host, viewId) {
|
|
|
1360
1692
|
const { value } = await stableRead(host, async () => {
|
|
1361
1693
|
const current = await readBranchIndex(host, viewId);
|
|
1362
1694
|
const currentState = current
|
|
1363
|
-
? { viewId: current.viewId, revision: current.revision, head: current.head, operationId: current.operationId, ...(current.conflict ? { conflict: true } : {}) }
|
|
1695
|
+
? { 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
1696
|
: { viewId: text(viewId), revision: 0n, head: null, operationId: null };
|
|
1365
1697
|
if (branchDirectoryKey(currentState) !== key)
|
|
1366
1698
|
throw new StoreError('stale', 'active branch changed during directory read');
|
|
@@ -1368,6 +1700,8 @@ async function readActiveBranchDirectory(host, viewId) {
|
|
|
1368
1700
|
throw new StoreError('conflict', 'active branch has conflicting revisions');
|
|
1369
1701
|
if (!current?.head)
|
|
1370
1702
|
return { state: currentState, rows: [], complete: true };
|
|
1703
|
+
if (current.membershipBase)
|
|
1704
|
+
return readRootedBranchDirectory(host, current);
|
|
1371
1705
|
const headId = await branchTurnIdByIdentity(host, current.head);
|
|
1372
1706
|
if (!headId)
|
|
1373
1707
|
return { state: currentState, rows: [], complete: false };
|
|
@@ -1406,7 +1740,8 @@ async function readActiveBranchDirectory(host, viewId) {
|
|
|
1406
1740
|
byView = new Map();
|
|
1407
1741
|
activeBranchDirectoryCache.set(host, byView);
|
|
1408
1742
|
}
|
|
1409
|
-
|
|
1743
|
+
if (value.complete)
|
|
1744
|
+
byView.set(viewId, { key, value });
|
|
1410
1745
|
return value;
|
|
1411
1746
|
}
|
|
1412
1747
|
catch (error) {
|
|
@@ -1418,6 +1753,38 @@ async function readActiveBranchDirectory(host, viewId) {
|
|
|
1418
1753
|
throw new StoreError('stale', 'active branch directory retry budget exhausted');
|
|
1419
1754
|
}
|
|
1420
1755
|
async function readActiveBranchPage(host, viewId, input) {
|
|
1756
|
+
return (await stableRead(host, async () => {
|
|
1757
|
+
const { segments, headers, ...selected } = await readActiveBranchSelection(host, viewId, input);
|
|
1758
|
+
const page = await readBranchPageMessages(host, segments, headers);
|
|
1759
|
+
return { ...selected, messages: page.messages, complete: selected.complete && page.complete };
|
|
1760
|
+
})).value;
|
|
1761
|
+
}
|
|
1762
|
+
async function readActiveBranchMembers(host, viewId, input) {
|
|
1763
|
+
return (await stableRead(host, async () => {
|
|
1764
|
+
const { segments, headers: _headers, ...selected } = await readActiveBranchSelection(host, viewId, input);
|
|
1765
|
+
return { ...selected, members: segments.map(segment => ({ ...segment, turnId: segment.turnId.slice() })) };
|
|
1766
|
+
})).value;
|
|
1767
|
+
}
|
|
1768
|
+
async function activeCursorHead(host, directory, head) {
|
|
1769
|
+
if (!directory.state.membershipBase)
|
|
1770
|
+
return directory.rows.some(row => row.segments.some(segment => equal(segment.turnId, head)));
|
|
1771
|
+
const root = await branchTurnIdByIdentity(host, directory.state.membershipBase);
|
|
1772
|
+
let current = directory.state.head ? await branchTurnIdByIdentity(host, directory.state.head) : undefined;
|
|
1773
|
+
const seen = new Set();
|
|
1774
|
+
while (current && !seen.has(hexBytes(current))) {
|
|
1775
|
+
if (equal(current, head))
|
|
1776
|
+
return true;
|
|
1777
|
+
if (root && equal(current, root))
|
|
1778
|
+
return false;
|
|
1779
|
+
seen.add(hexBytes(current));
|
|
1780
|
+
const metadata = await branchMetadataAt(host, current);
|
|
1781
|
+
if (!metadata || metadata.viewId !== directory.state.viewId || !branchStateEqual(metadata.membershipBase ?? null, directory.state.membershipBase))
|
|
1782
|
+
return false;
|
|
1783
|
+
current = metadata.baseTurn ? unhexBytes(metadata.baseTurn, 16) : undefined;
|
|
1784
|
+
}
|
|
1785
|
+
return false;
|
|
1786
|
+
}
|
|
1787
|
+
async function readActiveBranchSelection(host, viewId, input) {
|
|
1421
1788
|
const limit = input.limit ?? 40;
|
|
1422
1789
|
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 500)
|
|
1423
1790
|
throw invalid('active branch page limit');
|
|
@@ -1434,6 +1801,7 @@ async function readActiveBranchPage(host, viewId, input) {
|
|
|
1434
1801
|
revision: indexed.revision,
|
|
1435
1802
|
head: indexed.head,
|
|
1436
1803
|
operationId: indexed.operationId,
|
|
1804
|
+
...(indexed.membershipBase ? { membershipBase: indexed.membershipBase } : {}),
|
|
1437
1805
|
...(indexed.logicalCount !== undefined ? { logicalCount: indexed.logicalCount } : {}),
|
|
1438
1806
|
...(indexed.conflict ? { conflict: true } : {}),
|
|
1439
1807
|
}
|
|
@@ -1450,6 +1818,7 @@ async function readActiveBranchPage(host, viewId, input) {
|
|
|
1450
1818
|
revision: current.revision,
|
|
1451
1819
|
head: current.head,
|
|
1452
1820
|
operationId: current.operationId,
|
|
1821
|
+
...(current.membershipBase ? { membershipBase: current.membershipBase } : {}),
|
|
1453
1822
|
...(current.logicalCount !== undefined ? { logicalCount: current.logicalCount } : {}),
|
|
1454
1823
|
...(current.conflict ? { conflict: true } : {}),
|
|
1455
1824
|
}
|
|
@@ -1478,7 +1847,7 @@ async function readActiveBranchPage(host, viewId, input) {
|
|
|
1478
1847
|
if (before.viewId !== directory.state.viewId || before.revision > directory.state.revision ||
|
|
1479
1848
|
before.position < 0 || before.turnId.length !== 16 || before.headTurnId.length !== 16 ||
|
|
1480
1849
|
!cursorRow?.segments.some(segment => equal(segment.turnId, before.turnId)) ||
|
|
1481
|
-
!
|
|
1850
|
+
!await activeCursorHead(host, directory, before.headTurnId))
|
|
1482
1851
|
throw new StoreError('stale', 'active branch changed before older page was read');
|
|
1483
1852
|
}
|
|
1484
1853
|
const startPosition = input.before
|
|
@@ -1489,16 +1858,12 @@ async function readActiveBranchPage(host, viewId, input) {
|
|
|
1489
1858
|
const endPosition = Math.min(totalCount, input.before ? input.before.position + 1 : totalCount, startPosition + limit);
|
|
1490
1859
|
const selectedIds = new Set(directory.rows.slice(startPosition, endPosition).map(row => row.businessId));
|
|
1491
1860
|
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;
|
|
1861
|
+
const complete = directory.complete;
|
|
1496
1862
|
let cursor = null;
|
|
1497
1863
|
if (startPosition > 0) {
|
|
1498
1864
|
if (input.before) {
|
|
1499
1865
|
const headId = directory.state.head ? await branchTurnIdByIdentity(host, directory.state.head) : undefined;
|
|
1500
|
-
|
|
1501
|
-
if (!headId || !activeIds.has(hexBytes(input.before.headTurnId))) {
|
|
1866
|
+
if (!headId || !await activeCursorHead(host, directory, input.before.headTurnId)) {
|
|
1502
1867
|
throw new StoreError('stale', 'active branch changed before older page was read');
|
|
1503
1868
|
}
|
|
1504
1869
|
const olderRow = directory.rows[startPosition - 1];
|
|
@@ -1531,7 +1896,7 @@ async function readActiveBranchPage(host, viewId, input) {
|
|
|
1531
1896
|
state: directory.state,
|
|
1532
1897
|
totalCount,
|
|
1533
1898
|
startPosition,
|
|
1534
|
-
|
|
1899
|
+
segments,
|
|
1535
1900
|
hasMoreOlder: startPosition > 0,
|
|
1536
1901
|
cursor,
|
|
1537
1902
|
complete,
|
|
@@ -1612,6 +1977,8 @@ function advanceBranchDirectory(host, page, result, limit) {
|
|
|
1612
1977
|
retainedFrom, message: structuredClone(change.message), through: change.through };
|
|
1613
1978
|
}
|
|
1614
1979
|
async function readLinearActiveBranchPage(host, state, input, limit) {
|
|
1980
|
+
if (state.membershipBase)
|
|
1981
|
+
return undefined;
|
|
1615
1982
|
const totalBigInt = state.logicalCount ?? 0n;
|
|
1616
1983
|
if (totalBigInt > BigInt(Number.MAX_SAFE_INTEGER))
|
|
1617
1984
|
throw new StoreError('invalid', 'active branch is too large to index');
|
|
@@ -1619,11 +1986,11 @@ async function readLinearActiveBranchPage(host, state, input, limit) {
|
|
|
1619
1986
|
const headId = state.head ? await branchTurnIdByIdentity(host, state.head) : undefined;
|
|
1620
1987
|
if (state.head && !headId)
|
|
1621
1988
|
return {
|
|
1622
|
-
state, totalCount, startPosition: Math.max(0, totalCount - limit),
|
|
1989
|
+
state, totalCount, startPosition: Math.max(0, totalCount - limit), segments: [],
|
|
1623
1990
|
hasMoreOlder: totalCount > limit, cursor: null, complete: false,
|
|
1624
1991
|
};
|
|
1625
1992
|
if (!headId)
|
|
1626
|
-
return { state, totalCount, startPosition: 0,
|
|
1993
|
+
return { state, totalCount, startPosition: 0, segments: [], hasMoreOlder: false, cursor: null, complete: true };
|
|
1627
1994
|
let startPosition = input.before
|
|
1628
1995
|
? Math.max(0, input.before.position - limit + 1)
|
|
1629
1996
|
: Math.max(0, totalCount - limit);
|
|
@@ -1757,16 +2124,14 @@ async function readLinearActiveBranchPage(host, state, input, limit) {
|
|
|
1757
2124
|
segmentGroups.set(segment.businessId, group);
|
|
1758
2125
|
}
|
|
1759
2126
|
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
2127
|
const actualStart = selected.size ? Math.min(...selected.values()) : startPosition;
|
|
1764
2128
|
const cursor = olderCursor && actualStart > 0 ? olderCursor : null;
|
|
1765
2129
|
return {
|
|
1766
2130
|
state,
|
|
1767
2131
|
totalCount,
|
|
1768
2132
|
startPosition: actualStart,
|
|
1769
|
-
|
|
2133
|
+
segments: orderedSegments,
|
|
2134
|
+
headers,
|
|
1770
2135
|
hasMoreOlder: cursor !== null || (!complete && actualStart > 0),
|
|
1771
2136
|
cursor,
|
|
1772
2137
|
complete,
|
|
@@ -1968,13 +2333,14 @@ function identityValue(id) {
|
|
|
1968
2333
|
function parentValue(parent) {
|
|
1969
2334
|
return new Map([['id', hexBytes(parent.id)], ['hash', hexBytes(parent.hash)]]);
|
|
1970
2335
|
}
|
|
1971
|
-
function decodeIdentity(value) {
|
|
2336
|
+
function decodeIdentity(value, reserved = false) {
|
|
1972
2337
|
const row = asMap(value, 'command identity');
|
|
1973
2338
|
const kind = row.get('kind'), businessId = row.get('businessId'), segmentId = row.get('segmentId');
|
|
1974
2339
|
if (typeof kind !== 'string' || !knownKind(kind) || typeof businessId !== 'string' || typeof segmentId !== 'string')
|
|
1975
2340
|
throw invalid('command identity');
|
|
1976
2341
|
const identity = { kind, businessId, segmentId };
|
|
1977
|
-
|
|
2342
|
+
if (!reserved)
|
|
2343
|
+
assertWritableIdentity(identity);
|
|
1978
2344
|
keyOf(identity);
|
|
1979
2345
|
return identity;
|
|
1980
2346
|
}
|
|
@@ -2097,7 +2463,7 @@ function publishedIdentity(raw, id) {
|
|
|
2097
2463
|
return { businessId: text(businessId), segmentId: text(segmentId), turnId: id.slice() };
|
|
2098
2464
|
}
|
|
2099
2465
|
function messageKey(businessId, segmentId) { return decodeUtf8(keyOf({ kind: 'message', businessId, segmentId })); }
|
|
2100
|
-
async function writeIndexed(host, writes, puts, expectedEventCursor) {
|
|
2466
|
+
async function writeIndexed(host, writes, puts, expectedEventCursor, requireLocalInterval = false) {
|
|
2101
2467
|
if (!writes.length && !puts.length)
|
|
2102
2468
|
return;
|
|
2103
2469
|
if (host instanceof LodyHistory) {
|
|
@@ -2128,7 +2494,7 @@ async function writeIndexed(host, writes, puts, expectedEventCursor) {
|
|
|
2128
2494
|
if (w.kind === 'editPath')
|
|
2129
2495
|
return { kind: 'edit', turnId: w.turnId, expectedNextSeq: w.expectedNextSeq, ops: [{ kind: 'set', path: w.path, contentJson: decodeUtf8(encodeJson(w.value)) }] };
|
|
2130
2496
|
return { kind: 'edit', turnId: w.turnId, expectedNextSeq: w.expectedNextSeq, ops: [{ kind: 'set', path: [{ key: 'content' }], contentJson: decodeUtf8(encodeJson(w.value)) }] };
|
|
2131
|
-
}), { indexPuts: puts, expectedEventCursor });
|
|
2497
|
+
}), { indexPuts: puts, expectedEventCursor, ...(requireLocalInterval ? { requireLocalInterval: true } : {}) });
|
|
2132
2498
|
}
|
|
2133
2499
|
async function maybePublishAccept(host, input, options, turnId) {
|
|
2134
2500
|
if (options?.publish === false || input.kind !== 'message')
|
package/node/client.d.mts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/** Private prototype API. Pair this client with the artifact's matching owner binary. */
|
|
2
2
|
export const MAX_MESSAGE_BYTES: number;
|
|
3
3
|
export class RoostHostError extends Error { readonly code: string; }
|
|
4
|
-
export type OwnerCapability = 'history-v1' | 'create-once-v1' | 'create-once-cas-v1' | 'sync-v1' | 'host-crypto-v1' | 'index-cas-v1' | 'index-events-v1' | 'index-cas-events-v1' | 'commit-metadata-v1' | 'derived-indexes-v1' | 'receipt-checks-v1' | 'commit-observation-v1';
|
|
4
|
+
export type OwnerCapability = 'history-v1' | 'create-once-v1' | 'create-once-cas-v1' | 'field-reads-v1' | 'exclusive-batch-v1' | 'sync-v1' | 'host-crypto-v1' | 'index-cas-v1' | 'index-events-v1' | 'index-cas-events-v1' | 'commit-metadata-v1' | 'derived-indexes-v1' | 'receipt-checks-v1' | 'commit-observation-v1';
|
|
5
5
|
export type ParentRef = { id: Uint8Array; hash: Uint8Array };
|
|
6
6
|
export type UpdateRef = { turnId: Uint8Array; seq: bigint };
|
|
7
7
|
export type Verification = 'notRetrieved' | 'provisional' | 'selfVerified' | 'ancestorsVerified';
|
|
@@ -9,6 +9,8 @@ export type Header = { turnId: Uint8Array; owner: Uint8Array; parents: ParentRef
|
|
|
9
9
|
export type Turn = Header & { contentJson: string };
|
|
10
10
|
export type ReadResult<T> = { kind: 'found'; turn: T } | { kind: 'notFound'; turnId: Uint8Array } | { kind: 'incomplete'; turnId: Uint8Array; prefix: T | null };
|
|
11
11
|
export type Path = ({ key: string } | { index: bigint })[];
|
|
12
|
+
export type FieldSelector = { path: Path; jsonPath?: Path; info?: boolean };
|
|
13
|
+
export type FieldReadResult = { state: "missing" } | { state: "ready"; contentJson: string };
|
|
12
14
|
export type ContentOp =
|
|
13
15
|
| { kind: 'set'; path: Path; contentJson: string }
|
|
14
16
|
| { kind: 'remove'; path: Path }
|
|
@@ -43,7 +45,7 @@ export interface RoostNodeStream {
|
|
|
43
45
|
createOnce(key: Uint8Array, parents: ParentRef[], contentJson: string, options?: RequestOptions & {expectedEventCursor?: bigint}): Promise<{ turnId: Uint8Array; created: boolean }>;
|
|
44
46
|
edit(turnId: Uint8Array, expectedNextSeq: bigint, ops: ContentOp[], options?: RequestOptions): Promise<{ updates: UpdateRef[] }>;
|
|
45
47
|
seal(turnId: Uint8Array, expectedNextSeq: bigint, options?: RequestOptions): Promise<{ updates: UpdateRef[] }>;
|
|
46
|
-
writeBatch(writes: Write[], options?: RequestOptions & {indexPuts?: IndexPut[]; expectedEventCursor?: bigint}): Promise<{ updates: UpdateRef[] }>;
|
|
48
|
+
writeBatch(writes: Write[], options?: RequestOptions & {requireLocalInterval?: boolean; indexPuts?: IndexPut[]; expectedEventCursor?: bigint}): Promise<{ updates: UpdateRef[]; before?: bigint; through?: bigint }>;
|
|
47
49
|
readIndex(keys: IndexKey[], options?: RequestOptions): Promise<(Uint8Array | null)[]>;
|
|
48
50
|
compareAndWriteIndex(expected: IndexEntry[], changes: IndexEntry[], options?: RequestOptions & {eventKeys?: IndexKey[]}): Promise<boolean>;
|
|
49
51
|
scanIndex(table: string, start: Uint8Array, limit: bigint, options?: RequestOptions): Promise<{key: Uint8Array; value: Uint8Array}[]>;
|
|
@@ -55,6 +57,10 @@ export interface RoostNodeStream {
|
|
|
55
57
|
turnHeadersBefore(before: Uint8Array, limit: bigint, options?: RequestOptions): Promise<Header[]>;
|
|
56
58
|
turnHeadersAfter(after: Uint8Array | null, limit: bigint, options?: RequestOptions): Promise<ReadResult<Header>[]>;
|
|
57
59
|
readValue(turnId: Uint8Array, path: Path, options?: RequestOptions): Promise<{ contentJson: string; nextSeq: bigint }>;
|
|
60
|
+
readonly fieldReads: boolean;
|
|
61
|
+
readonly exclusiveBatches: boolean;
|
|
62
|
+
readCreateFields(turnId: Uint8Array, selectors: FieldSelector[], omitDigestKeys?: string[], options?: RequestOptions): Promise<{fields: FieldReadResult[]; owner: Uint8Array; digest: Uint8Array; filteredDigest: Uint8Array}>;
|
|
63
|
+
readFields(turnId: Uint8Array, selectors: FieldSelector[], options?: RequestOptions): Promise<{ fields: FieldReadResult[]; nextSeq: bigint }>;
|
|
58
64
|
readText(turnId: Uint8Array, path: Path, start: bigint, end: bigint, options?: RequestOptions): Promise<{ text: string; nextSeq: bigint }>;
|
|
59
65
|
verification(turnId: Uint8Array, options?: RequestOptions): Promise<Verification>;
|
|
60
66
|
eventsAfter(after: bigint, limit: bigint, options?: RequestOptions): Promise<EventRecord[]>;
|
package/node/client.mjs
CHANGED
|
@@ -243,11 +243,32 @@ class RoostNodeStream {
|
|
|
243
243
|
async turnHeadersAfter(after, limit, options) { return this.client.request({method:'turnHeadersAfter',stream:this.id,after:after===null?null:hex(after,16),limit:decimal(limit)},v=>v.map(r=>read(r,header)),options); }
|
|
244
244
|
async readTurns(turnIds, options) { return this.client.request({method:'readTurns',stream:this.id,turnIds:turnIds.map(id=>hex(id,16))},v=>v.map(r=>read(r)),options); }
|
|
245
245
|
async readValue(turnId, p, options) { return this.client.request({method:'readValue',stream:this.id,turnId:hex(turnId,16),path:path(p)},v=>{if(typeof v.contentJson!=='string')throw error('protocol');return {contentJson:v.contentJson,nextSeq:fromDecimal(v.nextSeq)};},options); }
|
|
246
|
+
get exclusiveBatches() { return this.client.capabilities.includes("exclusive-batch-v1"); }
|
|
247
|
+
get fieldReads() { return this.client.capabilities.includes("field-reads-v1"); }
|
|
248
|
+
async readCreateFields(turnId, selectors, omitDigestKeys = [], options) {
|
|
249
|
+
if (!Array.isArray(selectors) || selectors.length > 1024 || !Array.isArray(omitDigestKeys) || omitDigestKeys.length > 64) throw error("invalid");
|
|
250
|
+
return this.client.request({method:"readCreateFields",stream:this.id,turnId:hex(turnId,16),
|
|
251
|
+
selectors:selectors.map(selector=>({path:path(selector.path),...(selector.jsonPath===undefined?{}:{jsonPath:path(selector.jsonPath)}),...(selector.info===undefined?{}:{info:selector.info})})),omitDigestKeys}, v=>{
|
|
252
|
+
if (!Array.isArray(v.fields) || v.fields.length !== selectors.length) throw error("protocol");
|
|
253
|
+
return {fields:v.fields.map(field=>{
|
|
254
|
+
if(field?.state==="missing")return {state:"missing"};
|
|
255
|
+
if(field?.state!=="ready"||typeof field.contentJson!=="string")throw error("protocol");
|
|
256
|
+
return {state:"ready",contentJson:field.contentJson};
|
|
257
|
+
}),owner:unhex(v.owner,32),digest:unhex(v.digest,32),filteredDigest:unhex(v.filteredDigest,32)};
|
|
258
|
+
},options);
|
|
259
|
+
}
|
|
260
|
+
async readFields(turnId, selectors, options) {
|
|
261
|
+
if (!Array.isArray(selectors) || selectors.length > 1024) throw error('invalid');
|
|
262
|
+
return this.client.request({method:'readFields',stream:this.id,turnId:hex(turnId,16),selectors:selectors.map(selector=>({path:path(selector.path),...(selector.jsonPath===undefined?{}:{jsonPath:path(selector.jsonPath)}),...(selector.info===undefined?{}:{info:selector.info})}))},v=>{
|
|
263
|
+
if(!Array.isArray(v.fields)||v.fields.length!==selectors.length)throw error('protocol');
|
|
264
|
+
return {fields:v.fields.map(field=>{if(field?.state==='missing')return {state:'missing'};if(field?.state!=='ready'||typeof field.contentJson!=='string')throw error('protocol');return {state:'ready',contentJson:field.contentJson};}),nextSeq:fromDecimal(v.nextSeq)};
|
|
265
|
+
},options);
|
|
266
|
+
}
|
|
246
267
|
async verification(turnId, options) { return this.client.request({method:'verification',stream:this.id,turnId:hex(turnId,16)},v=>{if(!['notRetrieved','provisional','selfVerified','ancestorsVerified'].includes(v))throw error('protocol');return v;},options); }
|
|
247
268
|
async writeBatch(writes, options) {
|
|
248
269
|
const indexPuts = options?.indexPuts;
|
|
249
270
|
const cursor = options?.expectedEventCursor;
|
|
250
|
-
return this.client.request({method:'writeBatch',stream:this.id,writes:writes.map(w=>{
|
|
271
|
+
return this.client.request({method:'writeBatch',stream:this.id,...(options?.requireLocalInterval===undefined?{}:{requireLocalInterval:bool(options.requireLocalInterval)}),writes:writes.map(w=>{
|
|
251
272
|
switch(w.kind){
|
|
252
273
|
case 'create':return {kind:w.kind,parents:w.parents.map(p=>({id:hex(p.id,16),hash:hex(p.hash,32)})),contentJson:string(w.contentJson)};
|
|
253
274
|
case 'createOnce':return {kind:w.kind,keyHex:hex(w.key),parents:w.parents.map(p=>({id:hex(p.id,16),hash:hex(p.hash,32)})),contentJson:string(w.contentJson)};
|
|
@@ -257,7 +278,7 @@ class RoostNodeStream {
|
|
|
257
278
|
case 'sealOnce':return {kind:w.kind,keyHex:hex(w.key),expectedNextSeq:decimal(w.expectedNextSeq)};
|
|
258
279
|
default:throw new TypeError('unknown write');
|
|
259
280
|
}
|
|
260
|
-
}),...(indexPuts===undefined?{}:{indexPuts:indexPuts.map(p=>({table:string(p.table),keyHex:hex(p.key),valueHex:hex(p.value),...(p.emitEvent===undefined?{}:{emitEvent:bool(p.emitEvent)}),...(p.onceKey===undefined?{}:{onceKeyHex:hex(p.onceKey)})}))}),...(cursor===undefined?{}:{expectedEventCursor:decimal(cursor)})},v=>({updates:refs(v.updates)}),options); }
|
|
281
|
+
}),...(indexPuts===undefined?{}:{indexPuts:indexPuts.map(p=>({table:string(p.table),keyHex:hex(p.key),valueHex:hex(p.value),...(p.emitEvent===undefined?{}:{emitEvent:bool(p.emitEvent)}),...(p.onceKey===undefined?{}:{onceKeyHex:hex(p.onceKey)})}))}),...(cursor===undefined?{}:{expectedEventCursor:decimal(cursor)})},v=>({updates:refs(v.updates),before:fromDecimal(v.before),through:fromDecimal(v.through)}),options); }
|
|
261
282
|
async scanIndex(table, start, limit, options) {
|
|
262
283
|
return this.client.request({method:'indexScan',stream:this.id,table:string(table),start:hex(start),limit:decimal(limit)},v=>v.map(r=>({key:unhex(r.keyHex),value:unhex(r.valueHex)})),options);
|
|
263
284
|
}
|