@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.
Files changed (55) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +397 -0
  3. package/dist/codec.d.ts +66 -0
  4. package/dist/codec.js +275 -0
  5. package/dist/crypto.d.ts +21 -0
  6. package/dist/crypto.js +103 -0
  7. package/dist/durable-framing.d.ts +44 -0
  8. package/dist/durable-framing.js +207 -0
  9. package/dist/framing.d.ts +28 -0
  10. package/dist/framing.js +144 -0
  11. package/dist/history-publication.d.ts +58 -0
  12. package/dist/history-publication.js +234 -0
  13. package/dist/identity.d.ts +14 -0
  14. package/dist/identity.js +62 -0
  15. package/dist/inbox.d.ts +69 -0
  16. package/dist/inbox.js +262 -0
  17. package/dist/index.d.ts +9 -0
  18. package/dist/index.js +6 -0
  19. package/dist/indexeddb.d.ts +38 -0
  20. package/dist/indexeddb.js +299 -0
  21. package/dist/json.d.ts +23 -0
  22. package/dist/json.js +221 -0
  23. package/dist/lody-history.d.ts +397 -0
  24. package/dist/lody-history.js +1559 -0
  25. package/dist/projection.d.ts +53 -0
  26. package/dist/projection.js +543 -0
  27. package/dist/replay.d.ts +63 -0
  28. package/dist/replay.js +201 -0
  29. package/dist/sender.d.ts +26 -0
  30. package/dist/sender.js +67 -0
  31. package/dist/store.d.ts +384 -0
  32. package/dist/store.js +1437 -0
  33. package/dist/sync/coverage.d.ts +276 -0
  34. package/dist/sync/coverage.js +1084 -0
  35. package/dist/sync/crypto.d.ts +64 -0
  36. package/dist/sync/crypto.js +155 -0
  37. package/dist/sync/execute.d.ts +142 -0
  38. package/dist/sync/execute.js +321 -0
  39. package/dist/sync/history.d.ts +214 -0
  40. package/dist/sync/history.js +786 -0
  41. package/dist/sync/index.d.ts +17 -0
  42. package/dist/sync/index.js +9 -0
  43. package/dist/sync/link.d.ts +192 -0
  44. package/dist/sync/link.js +663 -0
  45. package/dist/sync/mod.d.ts +24 -0
  46. package/dist/sync/mod.js +15 -0
  47. package/dist/sync/policy.d.ts +62 -0
  48. package/dist/sync/policy.js +128 -0
  49. package/dist/sync/registry.d.ts +129 -0
  50. package/dist/sync/registry.js +333 -0
  51. package/dist/sync/transport.d.ts +91 -0
  52. package/dist/sync/transport.js +162 -0
  53. package/dist/sync/work.d.ts +351 -0
  54. package/dist/sync/work.js +1344 -0
  55. package/package.json +47 -0
@@ -0,0 +1,333 @@
1
+ import { decodeUtf8, encodeUtf8 } from '../json.js';
2
+ /**
3
+ * Durable registration of sync remotes (RS1-01), the IndexedDB mirror of
4
+ * src/sync/registry.rs. Registration state is routing/configuration only:
5
+ * none of it feeds the signed node hash, so renaming, disabling, rebinding or
6
+ * removing a remote never changes Turn bytes, hashes or signatures (RS0-01 §1).
7
+ *
8
+ * Storage layout (private to this module, not a wire format) — byte-for-byte
9
+ * the Rust layout, so one physical database is readable from both ends:
10
+ *
11
+ * | Keys | Range | Value |
12
+ * | --- | --- | --- |
13
+ * | `[0x01] \|\| remote_id[16]` | start `[0x01]`, end `[0x02)` | current RemoteRecord |
14
+ * | `[0x02] \|\| remote_id[16] \|\| seq[8 BE]` | start `[0x02]\|\|id`, end prefix successor | superseded record, append-only |
15
+ *
16
+ * Values are `[version byte] || serde_json` with a fixed DTO field order, so
17
+ * the encoding is deterministic and identical to the Rust serde encoding.
18
+ * The leading version byte is authoritative: a mismatch is reported as
19
+ * `unsupportedVersion` and never silently decoded, including by get/list.
20
+ * Identity keys carry no URL, name or token, so identity survives renames
21
+ * and endpoint moves. Every multi-step mutation runs in one IDB transaction;
22
+ * a semantic rejection aborts it and the previous state stays byte-identical.
23
+ * This module performs no network I/O and never awaits inside a transaction.
24
+ */
25
+ /** KV space holding all remote registry keys (same name as the Rust space). */
26
+ export const REMOTE_SPACE = 'rsync_remote';
27
+ /** Current record encoding version. */
28
+ export const RECORD_VERSION = 1;
29
+ /** Record keys start with this tag: `[RECORD_KEY_TAG][16B remote_id]`. */
30
+ export const RECORD_KEY_TAG = 0x01;
31
+ /** Archive keys start with this tag: `[ARCHIVE_KEY_TAG][16B remote_id][8B seq]`. */
32
+ export const ARCHIVE_KEY_TAG = 0x02;
33
+ export const GenerationSource = {
34
+ AppMarker: 'app_marker',
35
+ ServerHeader: 'server_header',
36
+ Unknown: 'unknown',
37
+ };
38
+ /** Scope-key discriminator used by the coverage/work layouts, byte-identical
39
+ * to Rust `GenerationSource::key_tag`. Deliberately nonzero: a key written
40
+ * before the source entered the scope encoding carries the leading zero of
41
+ * the big-endian stream length at this position, so such legacy keys can
42
+ * never collide with a scoped key and are orphaned instead of silently
43
+ * trusted. */
44
+ export function generationSourceKeyTag(source) {
45
+ return { app_marker: 1, server_header: 2, unknown: 3 }[source];
46
+ }
47
+ /** The full generation identity inside a coverage/work scope key:
48
+ * `gen_len[1] || gen[..] || source_tag[1]`. Generations with equal bytes but
49
+ * different provenance never share a key, so a provenance change (including
50
+ * to `unknown`) inherits nothing. Byte-identical to Rust
51
+ * `generation_key_fragment`. */
52
+ export function generationKeyFragment(generation) {
53
+ const gen = generation.bytes;
54
+ if (gen.length > 255)
55
+ throw new RegistryError('invalid', 'generation too long');
56
+ return cat(Uint8Array.of(gen.length), gen.slice(), Uint8Array.of(generationSourceKeyTag(generation.source)));
57
+ }
58
+ /** Errors returned by RemoteRegistry. `code` mirrors the Rust RegistryError variants. */
59
+ export class RegistryError extends Error {
60
+ code;
61
+ constructor(code, message = code, options) {
62
+ super(message, options);
63
+ this.code = code;
64
+ this.name = 'RegistryError';
65
+ }
66
+ }
67
+ const invalid = (message) => new RegistryError('invalid', message);
68
+ const corrupt = (message) => new RegistryError('corrupt', message);
69
+ const ALL = Number.MAX_SAFE_INTEGER;
70
+ function compare(a, b) {
71
+ for (let i = 0; i < Math.min(a.length, b.length); i++)
72
+ if (a[i] !== b[i])
73
+ return a[i] - b[i];
74
+ return a.length - b.length;
75
+ }
76
+ function equal(a, b) { return compare(a, b) === 0; }
77
+ function cat(...parts) {
78
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
79
+ let n = 0;
80
+ for (const p of parts) {
81
+ out.set(p, n);
82
+ n += p.length;
83
+ }
84
+ return out;
85
+ }
86
+ /** Smallest byte string strictly greater than `key`, or undefined when `key`
87
+ * is all `0xff` (its range then extends to the end of the space). */
88
+ function successor(key) {
89
+ const out = key.slice();
90
+ for (let i = out.length - 1; i >= 0; i--)
91
+ if (out[i] !== 255) {
92
+ out[i] = out[i] + 1;
93
+ return out.slice(0, i + 1);
94
+ }
95
+ return undefined;
96
+ }
97
+ /** Record key for one remote: `[RECORD_KEY_TAG][16B remote_id]`. */
98
+ export function recordKey(id) {
99
+ const key = new Uint8Array(17);
100
+ key[0] = RECORD_KEY_TAG;
101
+ key.set(idCopy(id), 1);
102
+ return key;
103
+ }
104
+ /** Scan prefix for one remote's generation archive: `[ARCHIVE_KEY_TAG][16B id]`. */
105
+ export function archivePrefix(id) {
106
+ const key = new Uint8Array(17);
107
+ key[0] = ARCHIVE_KEY_TAG;
108
+ key.set(idCopy(id), 1);
109
+ return key;
110
+ }
111
+ function archiveKey(id, seq) {
112
+ if (seq < 0n || seq > (1n << 64n) - 1n)
113
+ throw invalid('u64 archive sequence required');
114
+ const key = new Uint8Array(25);
115
+ key.set(archivePrefix(id), 0);
116
+ new DataView(key.buffer).setBigUint64(17, seq);
117
+ return key;
118
+ }
119
+ function idCopy(id) {
120
+ if (!(id instanceof Uint8Array) || id.length !== 16)
121
+ throw invalid('remote id must be a 16-byte Uint8Array');
122
+ return id.slice();
123
+ }
124
+ function byteArray(value, what) {
125
+ if (!Array.isArray(value) || value.some(v => !Number.isInteger(v) || v < 0 || v > 255))
126
+ throw corrupt(`record JSON: ${what} must be a byte array`);
127
+ return value;
128
+ }
129
+ function encodeRecord(record) {
130
+ const dto = {
131
+ v: RECORD_VERSION,
132
+ id: [...idCopy(record.id)],
133
+ name: record.name,
134
+ url: record.endpoint.url,
135
+ stream: record.endpoint.stream,
136
+ generation: [...record.generation.bytes],
137
+ generation_source: record.generation.source,
138
+ enabled: record.enabled,
139
+ };
140
+ // Fixed DTO field order keeps the serde_json layout deterministic and
141
+ // byte-identical to the Rust encoding.
142
+ return cat(Uint8Array.of(RECORD_VERSION), encodeUtf8(JSON.stringify(dto)));
143
+ }
144
+ function decodeRecord(bytes) {
145
+ if (!bytes.length)
146
+ throw corrupt('empty record');
147
+ const version = bytes[0];
148
+ if (version !== RECORD_VERSION)
149
+ throw new RegistryError('unsupportedVersion', `unsupported remote record version: ${version}`);
150
+ let dto;
151
+ try {
152
+ const parsed = JSON.parse(decodeUtf8(bytes.slice(1)));
153
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed))
154
+ throw Error('record must be an object');
155
+ const o = parsed;
156
+ if (!Number.isInteger(o.v) || typeof o.name !== 'string' || typeof o.url !== 'string' || typeof o.stream !== 'string' || !Array.isArray(o.generation) ||
157
+ (o.generation_source !== 'app_marker' && o.generation_source !== 'server_header' && o.generation_source !== 'unknown') || typeof o.enabled !== 'boolean')
158
+ throw Error('record fields');
159
+ dto = {
160
+ v: o.v,
161
+ id: byteArray(o.id, 'id'),
162
+ name: o.name,
163
+ url: o.url,
164
+ stream: o.stream,
165
+ generation: byteArray(o.generation, 'generation'),
166
+ generation_source: o.generation_source,
167
+ enabled: o.enabled,
168
+ };
169
+ }
170
+ catch (e) {
171
+ if (e instanceof RegistryError)
172
+ throw e;
173
+ throw corrupt(`record JSON: ${e instanceof Error ? e.message : String(e)}`);
174
+ }
175
+ if (dto.v !== RECORD_VERSION)
176
+ throw new RegistryError('unsupportedVersion', `unsupported remote record version: ${dto.v}`);
177
+ if (dto.id.length !== 16)
178
+ throw corrupt('record JSON: id must be 16 bytes');
179
+ return {
180
+ id: Uint8Array.from(dto.id),
181
+ name: dto.name,
182
+ endpoint: { url: dto.url, stream: dto.stream },
183
+ generation: { bytes: Uint8Array.from(dto.generation), source: dto.generation_source },
184
+ enabled: dto.enabled,
185
+ };
186
+ }
187
+ /** A locally generated random remote id (UUIDv4-shaped, never a URL derivation). */
188
+ function newRemoteId() {
189
+ const bytes = new Uint8Array(16);
190
+ globalThis.crypto.getRandomValues(bytes);
191
+ bytes[6] = (bytes[6] & 0x0f) | 0x40;
192
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
193
+ return bytes;
194
+ }
195
+ function sameGeneration(a, b) {
196
+ return a.source === b.source && equal(a.bytes, b.bytes);
197
+ }
198
+ /** The current generation of one remote, read inside the caller's
199
+ * transaction (the Rust `generation_in`): a confirm that must be bound to
200
+ * the registry's current generation reads it through this in-transaction
201
+ * path, so a rebind committed before the confirm's transaction starts is
202
+ * always observed (G009 — no read/cache window outside the write
203
+ * transaction). Composition point for the work store's confirm. */
204
+ export function* generationIn(tx, id) {
205
+ const raw = yield* tx.get(REMOTE_SPACE, recordKey(id));
206
+ return raw === undefined ? undefined : decodeRecord(raw).generation;
207
+ }
208
+ /**
209
+ * Registry of sync remotes over a shared IndexedDbStorage owner.
210
+ *
211
+ * Construct with the same IndexedDbStorage the host's Store uses, so registry
212
+ * writes and stream content commit through one fixed owner (one physical
213
+ * database; the space prefix keeps registry keys disjoint from stream keys).
214
+ * The registry never opens its own connection and never touches the network.
215
+ */
216
+ export class RemoteRegistry {
217
+ storage;
218
+ constructor(storage) {
219
+ this.storage = storage;
220
+ }
221
+ *load(tx, id) {
222
+ const raw = yield* tx.get(REMOTE_SPACE, recordKey(id));
223
+ if (raw === undefined)
224
+ throw new RegistryError('notFound', `remote not found: ${[...id]}`);
225
+ return decodeRecord(raw);
226
+ }
227
+ *nextArchiveSeq(tx, id) {
228
+ const prefix = archivePrefix(id);
229
+ const rows = yield* tx.scan(REMOTE_SPACE, prefix, successor(prefix), ALL);
230
+ const last = rows[rows.length - 1];
231
+ if (!last)
232
+ return 0n;
233
+ if (last[0].length !== 25)
234
+ throw corrupt('corrupt archive key');
235
+ return new DataView(last[0].buffer, last[0].byteOffset, 25).getBigUint64(17) + 1n;
236
+ }
237
+ /** Register a new remote in one write transaction and return its fresh id. */
238
+ async register(name, endpoint, generation) {
239
+ if (!name.length)
240
+ throw invalid('empty remote name');
241
+ if (!endpoint.url.length)
242
+ throw invalid('empty remote url');
243
+ if (!endpoint.stream.length)
244
+ throw invalid('empty remote stream');
245
+ const id = newRemoteId();
246
+ const bytes = encodeRecord({ id, name, endpoint, generation, enabled: true });
247
+ await this.storage.transact(true, function* (tx) {
248
+ yield* tx.put(REMOTE_SPACE, recordKey(id), bytes);
249
+ });
250
+ return id;
251
+ }
252
+ /** All registered remotes in key order. A record with an unsupported
253
+ * version fails the whole listing instead of being silently skipped. */
254
+ async list() {
255
+ const low = Uint8Array.of(RECORD_KEY_TAG), high = successor(low);
256
+ return this.storage.transact(false, function* (tx) {
257
+ const rows = yield* tx.scan(REMOTE_SPACE, low, high, ALL);
258
+ return rows.map(([, raw]) => decodeRecord(raw));
259
+ });
260
+ }
261
+ /** Fetch one remote, or undefined when unregistered. */
262
+ async get(id) {
263
+ const copied = idCopy(id);
264
+ return this.storage.transact(false, function* (tx) {
265
+ const raw = yield* tx.get(REMOTE_SPACE, recordKey(copied));
266
+ return raw === undefined ? undefined : decodeRecord(raw);
267
+ });
268
+ }
269
+ /** Rename one remote. Only the display name changes: id, endpoint and
270
+ * generation are carried over untouched. */
271
+ async rename(id, newName) {
272
+ if (!newName.length)
273
+ throw invalid('empty remote name');
274
+ const copied = idCopy(id), self = this;
275
+ await this.storage.transact(true, function* (tx) {
276
+ const record = yield* self.load(tx, copied);
277
+ yield* tx.put(REMOTE_SPACE, recordKey(copied), encodeRecord({ ...record, name: newName }));
278
+ });
279
+ }
280
+ /** Enable or disable one remote. Disabling is persistent and deletes no
281
+ * shared stream content, pending work or coverage. */
282
+ async setEnabled(id, enabled) {
283
+ const copied = idCopy(id), self = this;
284
+ await this.storage.transact(true, function* (tx) {
285
+ const record = yield* self.load(tx, copied);
286
+ yield* tx.put(REMOTE_SPACE, recordKey(copied), encodeRecord({ ...record, enabled }));
287
+ });
288
+ }
289
+ /** Rebind the endpoint and generation of one remote, compare-and-swap on
290
+ * the generation: succeeds only when the stored generation equals
291
+ * `expected`. On success the previous record is appended to the
292
+ * generation archive (one write transaction); on conflict the record is
293
+ * unchanged and the current generation is carried on the thrown error
294
+ * for an explicit, deliberate re-bind. */
295
+ async rebind(id, expected, newEndpoint, newGeneration) {
296
+ const copied = idCopy(id);
297
+ const self = this;
298
+ await this.storage.transact(true, function* (tx) {
299
+ const record = yield* self.load(tx, copied);
300
+ if (!sameGeneration(record.generation, expected))
301
+ throw new RegistryError('generationConflict', 'generation changed; current generation carried on error', { cause: { current: record.generation } });
302
+ const seq = yield* self.nextArchiveSeq(tx, copied);
303
+ yield* tx.put(REMOTE_SPACE, archiveKey(copied, seq), encodeRecord(record));
304
+ yield* tx.put(REMOTE_SPACE, recordKey(copied), encodeRecord({ ...record, endpoint: newEndpoint, generation: newGeneration }));
305
+ });
306
+ }
307
+ /** Remove one remote's registration record. Only the registry record is
308
+ * deleted: stream content, Turn hashes and shared coverage stay. The
309
+ * generation archive is retained for later audit. */
310
+ async remove(id) {
311
+ const copied = idCopy(id), self = this;
312
+ await this.storage.transact(true, function* (tx) {
313
+ yield* self.load(tx, copied);
314
+ yield* tx.delete(REMOTE_SPACE, recordKey(copied));
315
+ });
316
+ }
317
+ /** The current generation of one remote, for ack validation: a success
318
+ * callback bound to a task's generation must be refused when it no longer
319
+ * matches (CASE-02). */
320
+ async currentGeneration(id) {
321
+ return (await this.get(id))?.generation;
322
+ }
323
+ /** The superseded records of one remote in archive order. Each entry is
324
+ * the complete record as it was before a successful `rebind`. */
325
+ async generationArchive(id) {
326
+ const copied = idCopy(id);
327
+ const prefix = archivePrefix(copied), end = successor(prefix);
328
+ return this.storage.transact(false, function* (tx) {
329
+ const rows = yield* tx.scan(REMOTE_SPACE, prefix, end, ALL);
330
+ return rows.map(([, raw]) => decodeRecord(raw));
331
+ });
332
+ }
333
+ }
@@ -0,0 +1,91 @@
1
+ import type { StreamsAuthProvider } from '@loro-dev/streams-client';
2
+ import type { AsyncPayloadCrypto } from './crypto.js';
3
+ import type { SendTransport } from './execute.js';
4
+ import type { BackwardByteSource, BackwardPage } from './history.js';
5
+ /**
6
+ * A real Durable-Streams transport for the sync layer (N1), the IndexedDB-side
7
+ * mirror of src/sync/transport.rs: one StreamsTransport per remote stream,
8
+ * wrapping `@loro-dev/streams-client`. The upload executor consumes the
9
+ * SendTransport port (frozen packages appended as raw bodies, resolved only
10
+ * after the service's durable ack); the Link download loop consumes `head`
11
+ * and `readOnce`. The transport never runs inside a database transaction and
12
+ * performs no retries of its own (the client never retries an append without
13
+ * a producer session, and Roost supplies none) — the sync scheduler owns all
14
+ * retry policy, with byte-identical frozen packages on every resend.
15
+ *
16
+ * Credentials are injected by the host through the client's auth provider;
17
+ * nothing credential-shaped is stored here or logged. Error mapping mirrors
18
+ * the Rust side exactly: retryable temporary failures (network, timeout,
19
+ * gateway 5xx, rate limiting) are TransportError 'unavailable' — the task
20
+ * stays re-acquirable with the same frozen bytes; everything else (410 trim,
21
+ * conflict, bad request, forbidden) is 'rejected', surfaced to the host and
22
+ * never silently confirmed.
23
+ */
24
+ /** The content type every Roost sync stream uses: raw bytes; the RST1
25
+ * framing of the payloads is ours, never the service's JSON mode. */
26
+ export declare const SYNC_CONTENT_TYPE = "application/octet-stream";
27
+ /** Stream-tail metadata from `StreamsTransport.head`. */
28
+ export type HeadInfo = {
29
+ /** The stream's current tail offset (opaque). */
30
+ nextOffset: string;
31
+ /** Whether the stream is closed (a final EOF position exists). */
32
+ closed: boolean;
33
+ };
34
+ /** One catch-up page from `StreamsTransport.readOnce`. */
35
+ export type ReadPage = {
36
+ /** The raw log bytes of this page (wire bytes; envelopes when crypto is
37
+ * installed). Empty when the read caught up with the tail. Decrypt and
38
+ * envelope reassembly belong to the download loop. */
39
+ payload: Uint8Array;
40
+ /** The opaque offset the next read must use (never parsed). */
41
+ nextOffset: string;
42
+ /** True when this page reached the current tail. */
43
+ upToDate: boolean;
44
+ /** True when the stream is closed and this is its final position. */
45
+ closed: boolean;
46
+ };
47
+ /** The download-side read port of one remote stream. StreamsTransport
48
+ * implements it; deterministic test doubles script it. */
49
+ export interface ReadTransport {
50
+ readOnce(offset?: string): Promise<ReadPage>;
51
+ /** Present when catch-up pages are envelopes; the download loop opens
52
+ * them. Test doubles that serve plaintext RST1 omit this. */
53
+ readonly payloadCrypto?: AsyncPayloadCrypto;
54
+ }
55
+ /** A Durable-Streams transport for one remote stream: one binding per
56
+ * (remote, physical stream); URL and auth come from the host's endpoint
57
+ * configuration. */
58
+ export declare class StreamsTransport implements SendTransport, ReadTransport, BackwardByteSource {
59
+ #private;
60
+ /** Bind a client to one stream URL (`http(s)://host/ds/{bucket}/{stream}`).
61
+ * `auth` is the host-injected credential provider (static token or a
62
+ * refresh callback the client drives on 401); omit for a local service
63
+ * without authentication. A malformed URL is a typed rejection, mirroring
64
+ * the Rust fallible constructor. */
65
+ constructor(url: string | URL, auth?: StreamsAuthProvider, fetchFn?: typeof fetch);
66
+ /** Install host-injected payload crypto. Encrypt runs here on first
67
+ * append of a frozen package; decrypt of catch-up pages belongs to
68
+ * the download loop. */
69
+ withCrypto(crypto: AsyncPayloadCrypto): this;
70
+ get payloadCrypto(): AsyncPayloadCrypto | undefined;
71
+ /** Declare the stream exists with the sync content type (idempotent:
72
+ * an existing stream is a successful no-op). Appending before this
73
+ * returns 404 on a fresh service. */
74
+ createStream(): Promise<void>;
75
+ /** Stream-tail metadata (opaque tail offset and the closed flag). */
76
+ head(): Promise<HeadInfo>;
77
+ /** One bounded backward page immediately before `from` (omitted reads
78
+ * before the current tail). The service supplies the message-span list;
79
+ * this adapter never infers boundaries from payload bytes. Requires a
80
+ * streams-client build that exports `readBackward` (sibling package). */
81
+ readBackward(from: string | undefined, limitBytes: number): Promise<BackwardPage>;
82
+ /** One catch-up page from `offset` (opaque; omitted reads from the
83
+ * beginning). No long-poll here: the caller's loop decides when to poll
84
+ * again, keeping waits out of the transport. */
85
+ readOnce(offset?: string): Promise<ReadPage>;
86
+ seal(pkg: Uint8Array): Promise<Uint8Array>;
87
+ appendWire(body: Uint8Array): Promise<void>;
88
+ /** Append one frozen package as the raw body. Direct callers without a
89
+ * work-store bind still cache the first ciphertext in this instance. */
90
+ append(pkg: Uint8Array): Promise<void>;
91
+ }
@@ -0,0 +1,162 @@
1
+ import { isRetryableStreamError, StreamsClient } from '@loro-dev/streams-client';
2
+ import { blake3 } from '@noble/hashes/blake3.js';
3
+ import { sealEnvelopeAsync } from './crypto.js';
4
+ import { TransportError } from './execute.js';
5
+ /**
6
+ * A real Durable-Streams transport for the sync layer (N1), the IndexedDB-side
7
+ * mirror of src/sync/transport.rs: one StreamsTransport per remote stream,
8
+ * wrapping `@loro-dev/streams-client`. The upload executor consumes the
9
+ * SendTransport port (frozen packages appended as raw bodies, resolved only
10
+ * after the service's durable ack); the Link download loop consumes `head`
11
+ * and `readOnce`. The transport never runs inside a database transaction and
12
+ * performs no retries of its own (the client never retries an append without
13
+ * a producer session, and Roost supplies none) — the sync scheduler owns all
14
+ * retry policy, with byte-identical frozen packages on every resend.
15
+ *
16
+ * Credentials are injected by the host through the client's auth provider;
17
+ * nothing credential-shaped is stored here or logged. Error mapping mirrors
18
+ * the Rust side exactly: retryable temporary failures (network, timeout,
19
+ * gateway 5xx, rate limiting) are TransportError 'unavailable' — the task
20
+ * stays re-acquirable with the same frozen bytes; everything else (410 trim,
21
+ * conflict, bad request, forbidden) is 'rejected', surfaced to the host and
22
+ * never silently confirmed.
23
+ */
24
+ /** The content type every Roost sync stream uses: raw bytes; the RST1
25
+ * framing of the payloads is ours, never the service's JSON mode. */
26
+ export const SYNC_CONTENT_TYPE = 'application/octet-stream';
27
+ const statusOf = (error) => 'status' in error ? error.status : undefined;
28
+ /** Map the client's typed errors onto the sync transport's two outcomes (the
29
+ * exact mirror of the Rust `map_error`). */
30
+ const mapError = (error) => {
31
+ const status = statusOf(error);
32
+ if (isRetryableStreamError(error) || status === 429 || (status !== undefined && status >= 500 && status <= 599))
33
+ return new TransportError('unavailable');
34
+ return new TransportError('rejected', error.message);
35
+ };
36
+ function unwrap(result) {
37
+ if (!result.ok)
38
+ throw mapError(result.result);
39
+ return result.result;
40
+ }
41
+ /** A Durable-Streams transport for one remote stream: one binding per
42
+ * (remote, physical stream); URL and auth come from the host's endpoint
43
+ * configuration. */
44
+ export class StreamsTransport {
45
+ #client;
46
+ #crypto;
47
+ /** First successful ciphertext for each frozen plaintext package. */
48
+ #sealed = new Map();
49
+ /** Bind a client to one stream URL (`http(s)://host/ds/{bucket}/{stream}`).
50
+ * `auth` is the host-injected credential provider (static token or a
51
+ * refresh callback the client drives on 401); omit for a local service
52
+ * without authentication. A malformed URL is a typed rejection, mirroring
53
+ * the Rust fallible constructor. */
54
+ constructor(url, auth, fetchFn) {
55
+ try {
56
+ this.#client = new StreamsClient({ url, auth, fetch: fetchFn });
57
+ }
58
+ catch (e) {
59
+ throw new TransportError('rejected', `client setup failed: ${e instanceof Error ? e.message : e}`);
60
+ }
61
+ }
62
+ /** Install host-injected payload crypto. Encrypt runs here on first
63
+ * append of a frozen package; decrypt of catch-up pages belongs to
64
+ * the download loop. */
65
+ withCrypto(crypto) {
66
+ this.#crypto = crypto;
67
+ return this;
68
+ }
69
+ get payloadCrypto() {
70
+ return this.#crypto;
71
+ }
72
+ /** Declare the stream exists with the sync content type (idempotent:
73
+ * an existing stream is a successful no-op). Appending before this
74
+ * returns 404 on a fresh service. */
75
+ async createStream() {
76
+ unwrap(await this.#client.create({ contentType: SYNC_CONTENT_TYPE }));
77
+ }
78
+ /** Stream-tail metadata (opaque tail offset and the closed flag). */
79
+ async head() {
80
+ const out = unwrap(await this.#client.head());
81
+ return { nextOffset: out.nextOffset, closed: out.closed };
82
+ }
83
+ /** One bounded backward page immediately before `from` (omitted reads
84
+ * before the current tail). The service supplies the message-span list;
85
+ * this adapter never infers boundaries from payload bytes. Requires a
86
+ * streams-client build that exports `readBackward` (sibling package). */
87
+ async readBackward(from, limitBytes) {
88
+ if (!Number.isSafeInteger(limitBytes) || limitBytes <= 0)
89
+ throw new TransportError('rejected', 'backward page limit must be a positive safe integer');
90
+ const out = unwrap(await this.#client.readBackward(from === undefined ? { limitBytes } : { before: from, limitBytes }));
91
+ const messages = out.messages.map((span) => {
92
+ const messageLen = Number(span.messageLen);
93
+ const msgOffset = Number(span.msgOffset);
94
+ if (!Number.isSafeInteger(messageLen) || !Number.isSafeInteger(msgOffset)
95
+ || !Number.isSafeInteger(span.relStart) || !Number.isSafeInteger(span.relEnd))
96
+ throw new TransportError('rejected', 'backward span integer exceeds a safe integer');
97
+ return {
98
+ relStart: span.relStart,
99
+ relEnd: span.relEnd,
100
+ messageStart: span.messageStart,
101
+ messageLen,
102
+ msgOffset,
103
+ };
104
+ });
105
+ return {
106
+ payload: out.payload,
107
+ endOffset: out.endOffset,
108
+ prevOffset: out.prevOffset,
109
+ reachedStart: out.atStart,
110
+ messages,
111
+ };
112
+ }
113
+ /** One catch-up page from `offset` (opaque; omitted reads from the
114
+ * beginning). No long-poll here: the caller's loop decides when to poll
115
+ * again, keeping waits out of the transport. */
116
+ async readOnce(offset) {
117
+ const out = unwrap(await this.#client.readOnce(offset === undefined ? {} : { offset }));
118
+ const payload = out.payload === null ? new Uint8Array() : out.payload.body;
119
+ return {
120
+ payload,
121
+ nextOffset: out.nextOffset,
122
+ upToDate: out.upToDate,
123
+ closed: out.closed,
124
+ };
125
+ }
126
+ async seal(pkg) {
127
+ if (this.#crypto === undefined)
128
+ return pkg;
129
+ try {
130
+ return await sealEnvelopeAsync(this.#crypto, pkg);
131
+ }
132
+ catch (e) {
133
+ throw new TransportError('rejected', e instanceof Error ? e.message : String(e));
134
+ }
135
+ }
136
+ async appendWire(body) {
137
+ unwrap(await this.#client.append({ part: { contentType: SYNC_CONTENT_TYPE, body } }));
138
+ }
139
+ /** Append one frozen package as the raw body. Direct callers without a
140
+ * work-store bind still cache the first ciphertext in this instance. */
141
+ async append(pkg) {
142
+ let body = pkg;
143
+ if (this.#crypto !== undefined) {
144
+ const fingerprint = Array.from(blake3(pkg), (b) => b.toString(16).padStart(2, '0')).join('');
145
+ const existing = this.#sealed.get(fingerprint);
146
+ if (existing !== undefined)
147
+ body = await existing;
148
+ else {
149
+ const pending = this.seal(pkg);
150
+ this.#sealed.set(fingerprint, pending);
151
+ try {
152
+ body = await pending;
153
+ }
154
+ catch (error) {
155
+ this.#sealed.delete(fingerprint);
156
+ throw error;
157
+ }
158
+ }
159
+ }
160
+ await this.appendWire(body);
161
+ }
162
+ }