@loro-dev/roost 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +397 -0
- package/dist/codec.d.ts +66 -0
- package/dist/codec.js +275 -0
- package/dist/crypto.d.ts +21 -0
- package/dist/crypto.js +103 -0
- package/dist/durable-framing.d.ts +44 -0
- package/dist/durable-framing.js +207 -0
- package/dist/framing.d.ts +28 -0
- package/dist/framing.js +144 -0
- package/dist/history-publication.d.ts +58 -0
- package/dist/history-publication.js +234 -0
- package/dist/identity.d.ts +14 -0
- package/dist/identity.js +62 -0
- package/dist/inbox.d.ts +69 -0
- package/dist/inbox.js +262 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +6 -0
- package/dist/indexeddb.d.ts +38 -0
- package/dist/indexeddb.js +299 -0
- package/dist/json.d.ts +23 -0
- package/dist/json.js +221 -0
- package/dist/lody-history.d.ts +397 -0
- package/dist/lody-history.js +1559 -0
- package/dist/projection.d.ts +53 -0
- package/dist/projection.js +543 -0
- package/dist/replay.d.ts +63 -0
- package/dist/replay.js +201 -0
- package/dist/sender.d.ts +26 -0
- package/dist/sender.js +67 -0
- package/dist/store.d.ts +384 -0
- package/dist/store.js +1437 -0
- package/dist/sync/coverage.d.ts +276 -0
- package/dist/sync/coverage.js +1084 -0
- package/dist/sync/crypto.d.ts +64 -0
- package/dist/sync/crypto.js +155 -0
- package/dist/sync/execute.d.ts +142 -0
- package/dist/sync/execute.js +321 -0
- package/dist/sync/history.d.ts +214 -0
- package/dist/sync/history.js +786 -0
- package/dist/sync/index.d.ts +17 -0
- package/dist/sync/index.js +9 -0
- package/dist/sync/link.d.ts +192 -0
- package/dist/sync/link.js +663 -0
- package/dist/sync/mod.d.ts +24 -0
- package/dist/sync/mod.js +15 -0
- package/dist/sync/policy.d.ts +62 -0
- package/dist/sync/policy.js +128 -0
- package/dist/sync/registry.d.ts +129 -0
- package/dist/sync/registry.js +333 -0
- package/dist/sync/transport.d.ts +91 -0
- package/dist/sync/transport.js +162 -0
- package/dist/sync/work.d.ts +351 -0
- package/dist/sync/work.js +1344 -0
- package/package.json +47 -0
package/dist/framing.js
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { MAX_BATCH, MAX_UPDATES } from './codec.js';
|
|
2
|
+
export const FRAMING_WINDOW = 64 * 1024;
|
|
3
|
+
/** Outer RST1 framing only. Frame syntax, size, admission and seals belong to import. */
|
|
4
|
+
export class BatchFramer {
|
|
5
|
+
#phase = 'magic';
|
|
6
|
+
#total = 0;
|
|
7
|
+
#framesLeft = 0;
|
|
8
|
+
#payloadLeft = 0;
|
|
9
|
+
#varValue = 0n;
|
|
10
|
+
#varBytes = 0;
|
|
11
|
+
#pages = [];
|
|
12
|
+
#pageUsed = FRAMING_WINDOW;
|
|
13
|
+
#failure;
|
|
14
|
+
#ended = false;
|
|
15
|
+
/** Copies consumed input; returns at the first batch boundary and leaves its suffix untouched. */
|
|
16
|
+
push(input) {
|
|
17
|
+
if (!(input instanceof Uint8Array))
|
|
18
|
+
throw new TypeError('framing input must be Uint8Array');
|
|
19
|
+
if (input.length > FRAMING_WINDOW)
|
|
20
|
+
throw new RangeError('framing input exceeds 64 KiB');
|
|
21
|
+
if (this.#failure !== undefined)
|
|
22
|
+
return { kind: 'invalid', consumed: 0, reason: this.#failure };
|
|
23
|
+
if (this.#ended)
|
|
24
|
+
throw new Error('framer has ended');
|
|
25
|
+
let consumed = 0;
|
|
26
|
+
while (consumed < input.length) {
|
|
27
|
+
if (this.#phase === 'payload') {
|
|
28
|
+
const length = Math.min(this.#payloadLeft, input.length - consumed);
|
|
29
|
+
this.#append(input, consumed, length);
|
|
30
|
+
consumed += length;
|
|
31
|
+
this.#payloadLeft -= length;
|
|
32
|
+
if (this.#payloadLeft === 0 && this.#frameEnd())
|
|
33
|
+
return this.#batch(consumed);
|
|
34
|
+
continue;
|
|
35
|
+
}
|
|
36
|
+
// Future-header budget is checked when count/length arrives, before waiting for payload.
|
|
37
|
+
if (this.#total === MAX_BATCH)
|
|
38
|
+
return this.#invalid('batchLimit', consumed);
|
|
39
|
+
const byte = input[consumed++];
|
|
40
|
+
if (this.#phase === 'magic' && byte !== [82, 83, 84, 49][this.#total]) {
|
|
41
|
+
return this.#invalid('magic', consumed);
|
|
42
|
+
}
|
|
43
|
+
this.#append(input, consumed - 1, 1);
|
|
44
|
+
if (this.#phase === 'magic') {
|
|
45
|
+
if (this.#total === 4)
|
|
46
|
+
this.#phase = 'count';
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
this.#varBytes++;
|
|
50
|
+
if (this.#varBytes === 10 && byte > 1)
|
|
51
|
+
return this.#invalid('varint', consumed);
|
|
52
|
+
this.#varValue |= BigInt(byte & 127) << BigInt(7 * (this.#varBytes - 1));
|
|
53
|
+
const isCount = this.#phase === 'count';
|
|
54
|
+
const limitReason = isCount ? 'countLimit' : 'batchLimit';
|
|
55
|
+
const continuation = byte >= 128;
|
|
56
|
+
// Every remaining frame needs at least its one-byte length, even if empty.
|
|
57
|
+
const cap = isCount ? MAX_UPDATES : MAX_BATCH - this.#total - (this.#framesLeft - 1) - Number(continuation);
|
|
58
|
+
if (continuation) {
|
|
59
|
+
if (this.#varBytes === 10)
|
|
60
|
+
return this.#invalid('varint', consumed);
|
|
61
|
+
const minimum = this.#varValue + (1n << BigInt(7 * this.#varBytes));
|
|
62
|
+
if (minimum > BigInt(cap))
|
|
63
|
+
return this.#invalid(limitReason, consumed);
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
if (this.#varBytes > 1 && byte === 0)
|
|
67
|
+
return this.#invalid('varint', consumed);
|
|
68
|
+
if (this.#varValue > BigInt(cap))
|
|
69
|
+
return this.#invalid(limitReason, consumed);
|
|
70
|
+
// Conversion is safe only after applying the small count/remaining-batch limit.
|
|
71
|
+
const value = Number(this.#varValue);
|
|
72
|
+
this.#varValue = 0n;
|
|
73
|
+
this.#varBytes = 0;
|
|
74
|
+
if (isCount) {
|
|
75
|
+
this.#framesLeft = value;
|
|
76
|
+
if (value === 0)
|
|
77
|
+
return this.#batch(consumed);
|
|
78
|
+
if (this.#total + value > MAX_BATCH)
|
|
79
|
+
return this.#invalid('batchLimit', consumed);
|
|
80
|
+
this.#phase = 'length';
|
|
81
|
+
}
|
|
82
|
+
else {
|
|
83
|
+
this.#payloadLeft = value;
|
|
84
|
+
this.#phase = 'payload';
|
|
85
|
+
if (value === 0 && this.#frameEnd())
|
|
86
|
+
return this.#batch(consumed);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return { kind: 'needMore', consumed };
|
|
90
|
+
}
|
|
91
|
+
/** Only a confirmed final EOF closes the parser. A live pause must not call this. */
|
|
92
|
+
finish() {
|
|
93
|
+
if (this.#failure !== undefined)
|
|
94
|
+
return { kind: 'invalid', reason: this.#failure };
|
|
95
|
+
if (this.#total !== 0) {
|
|
96
|
+
this.#invalid('truncated', 0);
|
|
97
|
+
return { kind: 'invalid', reason: 'truncated' };
|
|
98
|
+
}
|
|
99
|
+
this.#ended = true;
|
|
100
|
+
return { kind: 'end' };
|
|
101
|
+
}
|
|
102
|
+
#append(input, offset, length) {
|
|
103
|
+
// Pages grow only with received bytes, never with advertised frame lengths.
|
|
104
|
+
while (length > 0) {
|
|
105
|
+
if (this.#pageUsed === FRAMING_WINDOW) {
|
|
106
|
+
this.#pages.push(new Uint8Array(FRAMING_WINDOW));
|
|
107
|
+
this.#pageUsed = 0;
|
|
108
|
+
}
|
|
109
|
+
const size = Math.min(length, FRAMING_WINDOW - this.#pageUsed);
|
|
110
|
+
this.#pages[this.#pages.length - 1].set(input.subarray(offset, offset + size), this.#pageUsed);
|
|
111
|
+
this.#pageUsed += size;
|
|
112
|
+
this.#total += size;
|
|
113
|
+
offset += size;
|
|
114
|
+
length -= size;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
#frameEnd() {
|
|
118
|
+
this.#framesLeft--;
|
|
119
|
+
this.#phase = 'length';
|
|
120
|
+
return this.#framesLeft === 0;
|
|
121
|
+
}
|
|
122
|
+
#batch(consumed) {
|
|
123
|
+
const bytes = new Uint8Array(this.#total);
|
|
124
|
+
let offset = 0;
|
|
125
|
+
for (const page of this.#pages) {
|
|
126
|
+
const length = Math.min(page.length, bytes.length - offset);
|
|
127
|
+
bytes.set(page.subarray(0, length), offset);
|
|
128
|
+
offset += length;
|
|
129
|
+
}
|
|
130
|
+
this.#clear();
|
|
131
|
+
this.#phase = 'magic';
|
|
132
|
+
this.#total = 0;
|
|
133
|
+
return { kind: 'batch', consumed, bytes };
|
|
134
|
+
}
|
|
135
|
+
#invalid(reason, consumed) {
|
|
136
|
+
this.#failure = reason;
|
|
137
|
+
this.#clear();
|
|
138
|
+
return { kind: 'invalid', reason, consumed };
|
|
139
|
+
}
|
|
140
|
+
#clear() {
|
|
141
|
+
this.#pages = [];
|
|
142
|
+
this.#pageUsed = FRAMING_WINDOW;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { type JsonValue } from './json.js';
|
|
2
|
+
export type IndexKey = {
|
|
3
|
+
table: string;
|
|
4
|
+
key: Uint8Array;
|
|
5
|
+
};
|
|
6
|
+
export type IndexEntry = IndexKey & {
|
|
7
|
+
value: Uint8Array | null;
|
|
8
|
+
};
|
|
9
|
+
export type PublicationObject = {
|
|
10
|
+
key: string;
|
|
11
|
+
owner: string;
|
|
12
|
+
digest: string;
|
|
13
|
+
kind: string;
|
|
14
|
+
direct: boolean;
|
|
15
|
+
};
|
|
16
|
+
export type PublicationRef = {
|
|
17
|
+
businessId: string;
|
|
18
|
+
segmentId: string;
|
|
19
|
+
nextSeq: string;
|
|
20
|
+
sealed: boolean;
|
|
21
|
+
digest?: string;
|
|
22
|
+
turnId?: string;
|
|
23
|
+
};
|
|
24
|
+
export type PublicationHeader = {
|
|
25
|
+
nextSeq: bigint;
|
|
26
|
+
sealed: Uint8Array | null;
|
|
27
|
+
bodyVerified: boolean;
|
|
28
|
+
};
|
|
29
|
+
export interface PublicationPort {
|
|
30
|
+
readIndex(keys: IndexKey[]): Promise<(Uint8Array | null)[]>;
|
|
31
|
+
scanIndex(table: string, start: Uint8Array, limit: number): Promise<{
|
|
32
|
+
key: Uint8Array;
|
|
33
|
+
value: Uint8Array;
|
|
34
|
+
}[]>;
|
|
35
|
+
commit(expected: IndexEntry[], changes: IndexEntry[], eventKeys?: IndexKey[]): Promise<boolean>;
|
|
36
|
+
events(after: bigint, limit: number): Promise<{
|
|
37
|
+
cursor: bigint;
|
|
38
|
+
event: {
|
|
39
|
+
kind: string;
|
|
40
|
+
update?: {
|
|
41
|
+
turnId: Uint8Array;
|
|
42
|
+
seq: bigint;
|
|
43
|
+
};
|
|
44
|
+
};
|
|
45
|
+
}[]>;
|
|
46
|
+
discover(id: Uint8Array): Promise<PublicationObject | undefined>;
|
|
47
|
+
header(id: Uint8Array): Promise<PublicationHeader | undefined>;
|
|
48
|
+
status(id: Uint8Array): Promise<JsonValue | undefined>;
|
|
49
|
+
manifest(id: Uint8Array, object: PublicationObject): Promise<PublicationRef[] | undefined>;
|
|
50
|
+
}
|
|
51
|
+
export declare const PUBLICATION_OBJECTS = "lody_history_publication_objects_v1";
|
|
52
|
+
export declare const PUBLICATION_DONE = "lody_history_publication_done_v1";
|
|
53
|
+
export declare const PUBLICATION_CURSOR: IndexKey;
|
|
54
|
+
export declare const publicationHex: (v: Uint8Array) => string;
|
|
55
|
+
export declare const publicationBytes: (v: string) => Uint8Array<ArrayBuffer>;
|
|
56
|
+
export declare function checkPublicationRefs(refs: PublicationRef[]): PublicationRef[];
|
|
57
|
+
export declare function publicationValue(refs: PublicationRef[]): JsonValue;
|
|
58
|
+
export declare function catchUpPublications(port: PublicationPort): Promise<void>;
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
/** Private, rebuildable publication projection. All durable work uses the same
|
|
2
|
+
* database as the core; no signer or outgoing operation is needed here. */
|
|
3
|
+
import { blake3 } from '@noble/hashes/blake3.js';
|
|
4
|
+
import { encodeUtf8, decodeUtf8, encodeJson } from './json.js';
|
|
5
|
+
import { StoreError } from './store.js';
|
|
6
|
+
export const PUBLICATION_OBJECTS = 'lody_history_publication_objects_v1';
|
|
7
|
+
export const PUBLICATION_DONE = 'lody_history_publication_done_v1';
|
|
8
|
+
export const PUBLICATION_CURSOR = { table: 'lody_history_publication_cursor_v1', key: new Uint8Array() };
|
|
9
|
+
const REVISION = { table: PUBLICATION_CURSOR.table, key: encodeUtf8('revision') };
|
|
10
|
+
const READY = { table: PUBLICATION_CURSOR.table, key: encodeUtf8('ready') };
|
|
11
|
+
const BINDING_CURSOR = { table: 'lody_history_index_v1', key: new Uint8Array() };
|
|
12
|
+
const BINDINGS = 'lody_history_bindings_v1', MEMBERS = 'lody_history_published_v1', IDS = 'lody_history_published_id_v1';
|
|
13
|
+
const TASKS = 'lody_history_publication_tasks_v1', STATE = 'lody_history_publication_waiting_v1';
|
|
14
|
+
const WAIT = 'lody_history_publication_dependencies_v1', TARGETS = 'lody_history_publication_targets_v1';
|
|
15
|
+
const WAKE = 'lody_history_publication_wake_v1', INVALID = 'lody_history_publication_invalid_v1';
|
|
16
|
+
const PENDING = 'lody_history_pending_batches_v1';
|
|
17
|
+
const EMPTY = new Uint8Array(), YES = encodeUtf8('1'), PAGE = 64;
|
|
18
|
+
export const publicationHex = (v) => [...v].map(b => b.toString(16).padStart(2, '0')).join('');
|
|
19
|
+
export const publicationBytes = (v) => Uint8Array.from(v.match(/../g) ?? [], b => parseInt(b, 16));
|
|
20
|
+
const same = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
|
|
21
|
+
const pack = (v) => encodeUtf8(JSON.stringify(v));
|
|
22
|
+
const unpack = (v) => JSON.parse(decodeUtf8(v));
|
|
23
|
+
const counter = (raw) => raw === null ? 0n : BigInt(decodeUtf8(raw));
|
|
24
|
+
const row = (table, key, value) => ({ table, key, value });
|
|
25
|
+
const identityKey = (ref) => JSON.stringify(['message', ref.businessId, ref.segmentId]);
|
|
26
|
+
const targetKey = (key) => blake3(encodeUtf8(key));
|
|
27
|
+
const waitKey = (key, id) => { const out = new Uint8Array(48); out.set(targetKey(key)); out.set(id, 32); return out; };
|
|
28
|
+
export function checkPublicationRefs(refs) {
|
|
29
|
+
if (!Array.isArray(refs) || refs.length > 64 || pack(refs).length > 256 * 1024)
|
|
30
|
+
throw new StoreError('invalid', 'publication reference limit');
|
|
31
|
+
const seen = new Set();
|
|
32
|
+
for (const ref of refs) {
|
|
33
|
+
if (!ref || typeof ref.businessId !== 'string' || !ref.businessId.length || encodeUtf8(ref.businessId).length > 1024 ||
|
|
34
|
+
typeof ref.segmentId !== 'string' || !ref.segmentId.length || encodeUtf8(ref.segmentId).length > 1024 || typeof ref.sealed !== 'boolean' ||
|
|
35
|
+
typeof ref.nextSeq !== 'string' || !/^[1-9][0-9]*$/.test(ref.nextSeq) || BigInt(ref.nextSeq) > (1n << 64n) - 1n ||
|
|
36
|
+
(ref.digest !== undefined && (typeof ref.digest !== 'string' || !/^[0-9a-f]{64}$/.test(ref.digest))) ||
|
|
37
|
+
(ref.turnId !== undefined && (typeof ref.turnId !== 'string' || !/^[0-9a-f]{32}$/.test(ref.turnId) || /^0+$/.test(ref.turnId))))
|
|
38
|
+
throw new StoreError('invalid', 'publication reference');
|
|
39
|
+
const key = identityKey(ref);
|
|
40
|
+
if (seen.has(key))
|
|
41
|
+
throw new StoreError('invalid', 'duplicate publication identity');
|
|
42
|
+
seen.add(key);
|
|
43
|
+
}
|
|
44
|
+
return refs;
|
|
45
|
+
}
|
|
46
|
+
export function publicationValue(refs) {
|
|
47
|
+
return new Map([['version', '2'], ['messages', checkPublicationRefs(refs).map(ref => new Map(Object.entries(ref)))]]);
|
|
48
|
+
}
|
|
49
|
+
/** A revision serializes ingestion, dependency wakeup and complete-batch
|
|
50
|
+
* publication. Comparing the binding checkpoint rejects stale identity reads. */
|
|
51
|
+
async function snapshot(port) {
|
|
52
|
+
const keys = [REVISION, PUBLICATION_CURSOR, BINDING_CURSOR];
|
|
53
|
+
const values = await port.readIndex(keys);
|
|
54
|
+
return { cursor: counter(values[1]), expected: keys.map((key, i) => ({ ...key, value: values[i] })),
|
|
55
|
+
revision: row(REVISION.table, REVISION.key, encodeUtf8((counter(values[0]) + 1n).toString())) };
|
|
56
|
+
}
|
|
57
|
+
async function commit(port, at, changes, eventKeys = []) {
|
|
58
|
+
if (changes.reduce((n, r) => n + r.key.length + (r.value?.length ?? 0), 0) > 1024 * 1024)
|
|
59
|
+
throw new StoreError('invalid', 'publication transaction byte limit');
|
|
60
|
+
return port.commit(at.expected, [...changes, at.revision], eventKeys);
|
|
61
|
+
}
|
|
62
|
+
async function ingest(port) {
|
|
63
|
+
const at = await snapshot(port), bound = counter(at.expected[2].value);
|
|
64
|
+
const events = (await port.events(at.cursor, PAGE)).filter(record => record.cursor <= bound);
|
|
65
|
+
if (!events.length)
|
|
66
|
+
return false;
|
|
67
|
+
const touched = new Map();
|
|
68
|
+
for (const { event } of events)
|
|
69
|
+
if (event.kind === 'changed' && event.update) {
|
|
70
|
+
const key = publicationHex(event.update.turnId), old = touched.get(key);
|
|
71
|
+
touched.set(key, { id: event.update.turnId, created: old?.created === true || event.update.seq === 0n });
|
|
72
|
+
}
|
|
73
|
+
const ids = [...touched.values()], raw = await port.readIndex(ids.map(r => ({ table: PUBLICATION_OBJECTS, key: r.id })));
|
|
74
|
+
const done = await port.readIndex(ids.map(r => ({ table: PUBLICATION_DONE, key: r.id })));
|
|
75
|
+
const changes = [], messages = [];
|
|
76
|
+
for (let i = 0; i < ids.length; i++) {
|
|
77
|
+
const item = ids[i];
|
|
78
|
+
const object = raw[i] === null ? item.created ? await port.discover(item.id) : undefined : unpack(raw[i]);
|
|
79
|
+
if (!object)
|
|
80
|
+
continue;
|
|
81
|
+
if (raw[i] === null)
|
|
82
|
+
changes.push(row(PUBLICATION_OBJECTS, item.id, pack(object)));
|
|
83
|
+
if (object.kind === 'message')
|
|
84
|
+
messages.push({ object, hash: targetKey(object.key) });
|
|
85
|
+
if (object.kind === 'batch_receipt' && done[i] !== null)
|
|
86
|
+
changes.push(row(PENDING, item.id, null));
|
|
87
|
+
if (done[i] === null && (object.kind === 'batch_receipt' || object.kind === 'publication' || (object.direct && item.created)))
|
|
88
|
+
changes.push(row(TASKS, item.id, EMPTY));
|
|
89
|
+
}
|
|
90
|
+
const watched = await port.readIndex(messages.map(r => ({ table: TARGETS, key: r.hash })));
|
|
91
|
+
for (let i = 0; i < messages.length; i++)
|
|
92
|
+
if (watched[i] !== null)
|
|
93
|
+
changes.push(row(WAKE, messages[i].hash, encodeUtf8(messages[i].object.key)));
|
|
94
|
+
changes.push(row(PUBLICATION_CURSOR.table, PUBLICATION_CURSOR.key, encodeUtf8(events.at(-1).cursor.toString())));
|
|
95
|
+
await commit(port, at, changes);
|
|
96
|
+
return true;
|
|
97
|
+
}
|
|
98
|
+
async function wake(port) {
|
|
99
|
+
const at = await snapshot(port), [target] = await port.scanIndex(WAKE, EMPTY, 1);
|
|
100
|
+
if (!target)
|
|
101
|
+
return false;
|
|
102
|
+
const waiting = (await port.scanIndex(WAIT, target.key, PAGE)).filter(r => same(r.key.subarray(0, 32), target.key));
|
|
103
|
+
const changes = [];
|
|
104
|
+
for (const entry of waiting) {
|
|
105
|
+
changes.push(row(WAIT, entry.key, null), row(TASKS, entry.key.slice(32), EMPTY));
|
|
106
|
+
}
|
|
107
|
+
if (waiting.length < PAGE)
|
|
108
|
+
changes.push(row(WAKE, target.key, null), row(TARGETS, target.key, null));
|
|
109
|
+
await commit(port, at, changes);
|
|
110
|
+
return true;
|
|
111
|
+
}
|
|
112
|
+
async function apply(port) {
|
|
113
|
+
const at = await snapshot(port), [task] = await port.scanIndex(TASKS, EMPTY, 1);
|
|
114
|
+
if (!task)
|
|
115
|
+
return false;
|
|
116
|
+
const [rawObject, rawState, done] = await port.readIndex([{ table: PUBLICATION_OBJECTS, key: task.key }, { table: STATE, key: task.key }, { table: PUBLICATION_DONE, key: task.key }]);
|
|
117
|
+
if (!rawObject)
|
|
118
|
+
throw new StoreError('corrupt', 'publication task has no original Create');
|
|
119
|
+
const object = unpack(rawObject), previous = rawState ? unpack(rawState) : undefined;
|
|
120
|
+
const changes = [row(TASKS, task.key, null)];
|
|
121
|
+
for (const key of previous?.waiting ?? [])
|
|
122
|
+
changes.push(row(WAIT, waitKey(key, task.key), null));
|
|
123
|
+
const finish = async (reason) => {
|
|
124
|
+
changes.push(row(STATE, task.key, null), row(PUBLICATION_DONE, task.key, YES));
|
|
125
|
+
if (reason)
|
|
126
|
+
changes.push(row(INVALID, task.key, encodeUtf8(reason)));
|
|
127
|
+
await commit(port, at, changes);
|
|
128
|
+
return true;
|
|
129
|
+
};
|
|
130
|
+
if (done !== null)
|
|
131
|
+
return finish();
|
|
132
|
+
let refs;
|
|
133
|
+
try {
|
|
134
|
+
if (previous)
|
|
135
|
+
refs = checkPublicationRefs(previous.refs);
|
|
136
|
+
else if (object.direct) {
|
|
137
|
+
const [, businessId, segmentId] = JSON.parse(object.key);
|
|
138
|
+
refs = [{ businessId: businessId, segmentId: segmentId, turnId: publicationHex(task.key), digest: object.digest, nextSeq: '1', sealed: false }];
|
|
139
|
+
}
|
|
140
|
+
else {
|
|
141
|
+
const header = await port.header(task.key);
|
|
142
|
+
if (object.kind === 'batch_receipt') {
|
|
143
|
+
const status = header?.sealed ? undefined : await port.status(task.key);
|
|
144
|
+
changes.push(row(PENDING, task.key, !header?.sealed && status !== 'failed' && status !== 'committed' ? encodeUtf8(object.key) : null));
|
|
145
|
+
}
|
|
146
|
+
// A later Changed/Seal event will reschedule an unfinished receipt. Read
|
|
147
|
+
// only its header until the core has verified its sealed body.
|
|
148
|
+
if (!header?.sealed || !header.bodyVerified) {
|
|
149
|
+
await commit(port, at, changes);
|
|
150
|
+
return true;
|
|
151
|
+
}
|
|
152
|
+
const manifest = await port.manifest(task.key, object);
|
|
153
|
+
if (!manifest)
|
|
154
|
+
return finish();
|
|
155
|
+
refs = checkPublicationRefs(manifest);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
catch (error) {
|
|
159
|
+
if (!(error instanceof StoreError) || error.code !== 'invalid')
|
|
160
|
+
throw error;
|
|
161
|
+
return finish(error.message);
|
|
162
|
+
}
|
|
163
|
+
const keys = refs.map(identityKey), bindings = await port.readIndex(keys.map(key => ({ table: BINDINGS, key: encodeUtf8(key) })));
|
|
164
|
+
const waiting = new Set(), members = [];
|
|
165
|
+
for (let i = 0; i < refs.length; i++) {
|
|
166
|
+
const ref = refs[i], key = keys[i], rawBinding = bindings[i];
|
|
167
|
+
if (rawBinding === null) {
|
|
168
|
+
waiting.add(key);
|
|
169
|
+
continue;
|
|
170
|
+
}
|
|
171
|
+
const binding = unpack(rawBinding);
|
|
172
|
+
if (binding.version !== 1 || !Array.isArray(binding.owner) || !Array.isArray(binding.turnId) || !Array.isArray(binding.digest))
|
|
173
|
+
throw new StoreError('corrupt', 'publication binding');
|
|
174
|
+
const id = Uint8Array.from(binding.turnId);
|
|
175
|
+
if (binding.conflict || publicationHex(Uint8Array.from(binding.owner)) !== object.owner ||
|
|
176
|
+
(ref.digest !== undefined && publicationHex(Uint8Array.from(binding.digest)) !== ref.digest) ||
|
|
177
|
+
(ref.turnId !== undefined && publicationHex(id) !== ref.turnId))
|
|
178
|
+
return finish('publication identity conflict');
|
|
179
|
+
if (ref.nextSeq !== '1' || ref.sealed) {
|
|
180
|
+
const header = await port.header(id);
|
|
181
|
+
if (!header || header.nextSeq < BigInt(ref.nextSeq) || (ref.sealed && !header.sealed)) {
|
|
182
|
+
waiting.add(key);
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
members.push({ ref, id });
|
|
187
|
+
}
|
|
188
|
+
if (waiting.size) {
|
|
189
|
+
changes.push(row(STATE, task.key, pack({ refs, waiting: [...waiting] })));
|
|
190
|
+
for (const key of waiting)
|
|
191
|
+
changes.push(row(WAIT, waitKey(key, task.key), EMPTY), row(TARGETS, targetKey(key), YES));
|
|
192
|
+
await commit(port, at, changes);
|
|
193
|
+
return true;
|
|
194
|
+
}
|
|
195
|
+
const priorIds = await port.readIndex(keys.map(key => ({ table: IDS, key: encodeUtf8(key) })));
|
|
196
|
+
if (members.some(({ id }, i) => priorIds[i] !== null && !same(priorIds[i], id)))
|
|
197
|
+
return finish('publication identity already bound');
|
|
198
|
+
const eventKeys = [];
|
|
199
|
+
for (let i = 0; i < members.length; i++) {
|
|
200
|
+
const { ref, id } = members[i];
|
|
201
|
+
changes.push(row(IDS, encodeUtf8(identityKey(ref)), id), row(MEMBERS, id, encodeJson(new Map([['version', '2'], ['businessId', ref.businessId], ['segmentId', ref.segmentId]]))));
|
|
202
|
+
eventKeys.push({ table: MEMBERS, key: id });
|
|
203
|
+
}
|
|
204
|
+
changes.push(row(STATE, task.key, null), row(PUBLICATION_DONE, task.key, YES));
|
|
205
|
+
await commit(port, at, changes, eventKeys);
|
|
206
|
+
return true;
|
|
207
|
+
}
|
|
208
|
+
export async function catchUpPublications(port) {
|
|
209
|
+
const [revision, cursor, bindingCursor, ready] = await port.readIndex([REVISION, PUBLICATION_CURSOR, BINDING_CURSOR, READY]);
|
|
210
|
+
if (ready && revision && same(ready, revision) && counter(cursor) === counter(bindingCursor))
|
|
211
|
+
return;
|
|
212
|
+
for (;;) {
|
|
213
|
+
while (await ingest(port)) { /* durable bounded event pages */ }
|
|
214
|
+
while (await wake(port)) { /* bounded fanout, consumed dependencies are deleted */ }
|
|
215
|
+
let worked = false;
|
|
216
|
+
while (await apply(port))
|
|
217
|
+
worked = true;
|
|
218
|
+
if (!worked) {
|
|
219
|
+
const at = await snapshot(port);
|
|
220
|
+
if ((await port.scanIndex(WAKE, EMPTY, 1)).length || (await port.scanIndex(TASKS, EMPTY, 1)).length)
|
|
221
|
+
continue;
|
|
222
|
+
const [revision] = await port.readIndex([REVISION]);
|
|
223
|
+
const old = at.expected[0].value;
|
|
224
|
+
if (old === null ? revision === null : revision !== null && same(old, revision)) {
|
|
225
|
+
if ((await port.events(at.cursor, 1)).length)
|
|
226
|
+
return;
|
|
227
|
+
if (await commit(port, at, [row(READY.table, READY.key, at.revision.value)]))
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
// Publication events are part of the local log. Consume them as well so a
|
|
232
|
+
// stable reader's cursor covers the membership it is about to expose.
|
|
233
|
+
}
|
|
234
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** In-memory signer only. Does not provide key storage, trust or source authorization. */
|
|
2
|
+
export declare class Identity {
|
|
3
|
+
#private;
|
|
4
|
+
private constructor();
|
|
5
|
+
static fromSeed(seed: Uint8Array): Identity;
|
|
6
|
+
owner(): Uint8Array;
|
|
7
|
+
signHash(hash: Uint8Array): Uint8Array;
|
|
8
|
+
}
|
|
9
|
+
export declare function checkTurnId(id: Uint8Array): void;
|
|
10
|
+
/** Same timestamp48/counter12/random62 layout as Rust next_id.
|
|
11
|
+
* The host supplies the admitted stream maximum and a cryptographic random source.
|
|
12
|
+
* This function does not observe, persist or authorize IDs, or supply a clock.
|
|
13
|
+
*/
|
|
14
|
+
export declare function nextTurnId(nowMs: bigint, seen: Uint8Array | null, randomBytes: () => Uint8Array): Uint8Array;
|
package/dist/identity.js
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { ed25519 } from '@noble/curves/ed25519.js';
|
|
2
|
+
function bytes(value, length, name) {
|
|
3
|
+
if (!(value instanceof Uint8Array) || value.length !== length)
|
|
4
|
+
throw new Error(`${name} must be ${length} bytes`);
|
|
5
|
+
}
|
|
6
|
+
/** In-memory signer only. Does not provide key storage, trust or source authorization. */
|
|
7
|
+
export class Identity {
|
|
8
|
+
#seed;
|
|
9
|
+
#owner;
|
|
10
|
+
constructor(seed) {
|
|
11
|
+
bytes(seed, 32, 'seed');
|
|
12
|
+
this.#seed = seed.slice();
|
|
13
|
+
this.#owner = ed25519.getPublicKey(this.#seed);
|
|
14
|
+
}
|
|
15
|
+
static fromSeed(seed) { return new Identity(seed); }
|
|
16
|
+
owner() { return this.#owner.slice(); }
|
|
17
|
+
signHash(hash) {
|
|
18
|
+
bytes(hash, 32, 'hash');
|
|
19
|
+
return ed25519.sign(hash, this.#seed);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
export function checkTurnId(id) {
|
|
23
|
+
bytes(id, 16, 'TurnId');
|
|
24
|
+
if ((id[6] >>> 4) !== 7 || (id[8] >>> 6) !== 2)
|
|
25
|
+
throw new Error('expected UUIDv7');
|
|
26
|
+
}
|
|
27
|
+
/** Same timestamp48/counter12/random62 layout as Rust next_id.
|
|
28
|
+
* The host supplies the admitted stream maximum and a cryptographic random source.
|
|
29
|
+
* This function does not observe, persist or authorize IDs, or supply a clock.
|
|
30
|
+
*/
|
|
31
|
+
export function nextTurnId(nowMs, seen, randomBytes) {
|
|
32
|
+
if (typeof nowMs !== 'bigint' || nowMs < 0n || nowMs > (1n << 64n) - 1n)
|
|
33
|
+
throw new Error('clock outside u64');
|
|
34
|
+
let ms = nowMs, counter = 0;
|
|
35
|
+
if (seen !== null) {
|
|
36
|
+
checkTurnId(seen);
|
|
37
|
+
let seenMs = 0n;
|
|
38
|
+
for (let i = 0; i < 6; i++)
|
|
39
|
+
seenMs = (seenMs << 8n) | BigInt(seen[i]);
|
|
40
|
+
if (nowMs <= seenMs) {
|
|
41
|
+
ms = seenMs;
|
|
42
|
+
counter = ((seen[6] & 15) << 8 | seen[7]) + 1;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
if (counter === 4096) {
|
|
46
|
+
ms++;
|
|
47
|
+
counter = 0;
|
|
48
|
+
}
|
|
49
|
+
if (ms >= 1n << 48n)
|
|
50
|
+
throw new Error('UUID timestamp overflow');
|
|
51
|
+
const random = randomBytes();
|
|
52
|
+
bytes(random, 16, 'random output');
|
|
53
|
+
const id = random.slice();
|
|
54
|
+
for (let i = 5; i >= 0; i--) {
|
|
55
|
+
id[i] = Number(ms & 255n);
|
|
56
|
+
ms >>= 8n;
|
|
57
|
+
}
|
|
58
|
+
id[6] = 0x70 | counter >>> 8;
|
|
59
|
+
id[7] = counter & 255;
|
|
60
|
+
id[8] = (id[8] & 63) | 128;
|
|
61
|
+
return id;
|
|
62
|
+
}
|
package/dist/inbox.d.ts
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/** Durable byte receipts, not authentication, application or signature verification. */
|
|
2
|
+
import type { IndexedDbStorage, KvTransaction, Step } from './indexeddb.js';
|
|
3
|
+
type Storage = Pick<IndexedDbStorage, 'transact'>;
|
|
4
|
+
export type InboxErrorCode = 'invalid' | 'stale' | 'conflict' | 'capacity' | 'corrupt';
|
|
5
|
+
export declare class InboxError extends Error {
|
|
6
|
+
readonly code: InboxErrorCode;
|
|
7
|
+
readonly name = "InboxError";
|
|
8
|
+
constructor(code: InboxErrorCode, message: string);
|
|
9
|
+
}
|
|
10
|
+
export interface InboxLimits {
|
|
11
|
+
maxBatchBytes: number;
|
|
12
|
+
maxCursorBytes: number;
|
|
13
|
+
/** Maximum UTF-8 bytes in each stream/source name separately. */
|
|
14
|
+
maxNamespaceBytes: number;
|
|
15
|
+
maxRecords: bigint;
|
|
16
|
+
/** Record/index binary keys + values, excluding head, IDB compound space names
|
|
17
|
+
* and physical database overhead. Per namespace, not a whole-database quota. */
|
|
18
|
+
maxRetainedBytes: bigint;
|
|
19
|
+
maxPageRecords: number;
|
|
20
|
+
}
|
|
21
|
+
export interface InboxState {
|
|
22
|
+
cursor: Uint8Array | null;
|
|
23
|
+
nextSequence: bigint;
|
|
24
|
+
retainedBytes: bigint;
|
|
25
|
+
}
|
|
26
|
+
export interface InboxRecord {
|
|
27
|
+
sequence: bigint;
|
|
28
|
+
previousCursor: Uint8Array | null;
|
|
29
|
+
nextCursor: Uint8Array;
|
|
30
|
+
bytes: Uint8Array;
|
|
31
|
+
}
|
|
32
|
+
export type InboxReceipt = {
|
|
33
|
+
kind: 'received' | 'duplicate';
|
|
34
|
+
sequence: bigint;
|
|
35
|
+
};
|
|
36
|
+
/** Internal, transaction-scoped view. All receipt writes retain Inbox validation. */
|
|
37
|
+
export interface FramingInboxView {
|
|
38
|
+
namespace: Uint8Array;
|
|
39
|
+
state(): Step<InboxState>;
|
|
40
|
+
record(sequence: bigint): Step<InboxRecord | undefined>;
|
|
41
|
+
receive(prior: Uint8Array | null, next: Uint8Array, bytes: Uint8Array): Step<InboxReceipt>;
|
|
42
|
+
}
|
|
43
|
+
/** Share the application's storage owner. No GC, implicit reset or default limits.
|
|
44
|
+
* This browser-private layout is not Rust inbox state or a wire/snapshot format. */
|
|
45
|
+
export declare class Inbox {
|
|
46
|
+
#private;
|
|
47
|
+
private readonly storage;
|
|
48
|
+
private readonly stream;
|
|
49
|
+
private constructor();
|
|
50
|
+
static open(storage: Storage, stream: string, source: string, limits: InboxLimits): Inbox;
|
|
51
|
+
/** Internal replay boundary: one physical storage owner and matching logical stream.
|
|
52
|
+
* Namespace bytes are copied so callers cannot mutate Inbox identity. */
|
|
53
|
+
_replayTransact<T>(writable: boolean, targetStorage: Storage, targetStreamId: string, program: (tx: KvTransaction, namespace: Uint8Array) => Step<T>): Promise<T>;
|
|
54
|
+
state(): Promise<InboxState>;
|
|
55
|
+
/** Successful receipt means only that exact bytes and cursor committed together.
|
|
56
|
+
* Exact historical retries do not rewind the head. Input length limits apply
|
|
57
|
+
* before retry detection; record/byte capacity applies only to new receipts. */
|
|
58
|
+
receive(expectedPriorCursor: Uint8Array | null, nextCursor: Uint8Array, bytes: Uint8Array): Promise<InboxReceipt>;
|
|
59
|
+
/** Internal framing boundary; the two ledgers share an owner and route, never identity. */
|
|
60
|
+
_framingTransact<T>(writable: boolean, derived: Inbox, program: (tx: KvTransaction, raw: FramingInboxView, output: FramingInboxView) => Step<T>): Promise<T>;
|
|
61
|
+
/** Whether a receipt with exactly this cursor was ever persisted
|
|
62
|
+
* (read-only). The content-addressed history reader (N2) uses it to skip
|
|
63
|
+
* already-held batches without touching the receipt chain: its cursors
|
|
64
|
+
* are batch-content hashes, so presence is dedupe evidence. Mirror of
|
|
65
|
+
* `Inbox::contains_cursor` in src/inbox.rs. */
|
|
66
|
+
containsCursor(cursor: Uint8Array): Promise<boolean>;
|
|
67
|
+
records(afterSequence: bigint | null, limit: number): Promise<InboxRecord[]>;
|
|
68
|
+
}
|
|
69
|
+
export {};
|