@dxos/feed 0.8.4-main.ef1bc66f44 → 0.8.4-main.fcfe5033a5
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 +0 -1
- package/dist/lib/neutral/{chunk-Q5PE2Q5P.mjs → chunk-53CMKQL5.mjs} +98 -99
- package/dist/lib/neutral/chunk-53CMKQL5.mjs.map +7 -0
- package/dist/lib/neutral/index.mjs +1 -5
- package/dist/lib/neutral/meta.json +1 -1
- package/dist/lib/neutral/testing/index.mjs +14 -7
- package/dist/lib/neutral/testing/index.mjs.map +3 -3
- package/dist/types/src/errors.d.ts +16 -56
- package/dist/types/src/errors.d.ts.map +1 -1
- package/dist/types/src/feed-store.d.ts +38 -3
- package/dist/types/src/feed-store.d.ts.map +1 -1
- package/dist/types/src/sync-client.d.ts +4 -3
- package/dist/types/src/sync-client.d.ts.map +1 -1
- package/dist/types/src/sync-server.d.ts +3 -2
- package/dist/types/src/sync-server.d.ts.map +1 -1
- package/dist/types/src/testing/test-builder.d.ts +2 -2
- package/dist/types/src/testing/test-builder.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +15 -13
- package/src/errors.ts +4 -17
- package/src/feed-store.test.ts +203 -96
- package/src/feed-store.ts +119 -113
- package/src/sync-client.ts +20 -13
- package/src/sync-server.ts +8 -4
- package/src/testing/test-builder.ts +11 -11
- package/dist/lib/neutral/chunk-Q5PE2Q5P.mjs.map +0 -7
package/src/feed-store.ts
CHANGED
|
@@ -12,7 +12,7 @@ import { type SpaceId } from '@dxos/keys';
|
|
|
12
12
|
import { FeedProtocol } from '@dxos/protocols';
|
|
13
13
|
import { SqlTransaction } from '@dxos/sql-sqlite';
|
|
14
14
|
|
|
15
|
-
import {
|
|
15
|
+
import { PositionConflictError } from './errors';
|
|
16
16
|
|
|
17
17
|
type AppendRequest = FeedProtocol.AppendRequest;
|
|
18
18
|
type AppendResponse = FeedProtocol.AppendResponse;
|
|
@@ -192,7 +192,7 @@ export class FeedStore {
|
|
|
192
192
|
// If spaceId is not provided in request (e.g. feedIds query), we can't easily validate token unless we look up spaceId for feedIds.
|
|
193
193
|
// Ideally spaceId should be required for token validation.
|
|
194
194
|
|
|
195
|
-
/*
|
|
195
|
+
/*
|
|
196
196
|
Logic:
|
|
197
197
|
1. If `cursor` is present, it's `token|insertionId`.
|
|
198
198
|
2. If `position` is present, it's `position` (legacy/manual).
|
|
@@ -355,115 +355,72 @@ export class FeedStore {
|
|
|
355
355
|
}).pipe(Effect.withSpan('FeedStore.setSyncState'));
|
|
356
356
|
|
|
357
357
|
/**
|
|
358
|
-
*
|
|
358
|
+
* Returns the number of stored blocks for a single feed in a space/namespace.
|
|
359
|
+
* Intended as a low-level primitive for callers (for example Cloudflare Worker code)
|
|
360
|
+
* that need to make retention decisions under constrained storage resources.
|
|
359
361
|
*/
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
if (!this.#options.assignPositions && block.position != null) {
|
|
378
|
-
const positionKey = `${feedPrivateId}|${block.position}`;
|
|
379
|
-
if (positionFeedIdByKey.has(positionKey)) {
|
|
380
|
-
yield* Effect.fail(
|
|
381
|
-
new DuplicateBlockPositionError({
|
|
382
|
-
feedId: block.feedId!,
|
|
383
|
-
position: block.position,
|
|
384
|
-
}),
|
|
385
|
-
);
|
|
386
|
-
}
|
|
387
|
-
positionFeedIdByKey.set(positionKey, block.feedId!);
|
|
388
|
-
}
|
|
362
|
+
countBlocks = (opts: {
|
|
363
|
+
spaceId: SpaceId;
|
|
364
|
+
feedNamespace: string;
|
|
365
|
+
feedId: string;
|
|
366
|
+
}): Effect.Effect<number, SqlError.SqlError, SqlClient.SqlClient> =>
|
|
367
|
+
Effect.gen(this, function* () {
|
|
368
|
+
const sql = yield* SqlClient.SqlClient;
|
|
369
|
+
const rows = yield* sql<{ count: number }>`
|
|
370
|
+
SELECT COUNT(*) AS count
|
|
371
|
+
FROM blocks
|
|
372
|
+
JOIN feeds ON blocks.feedPrivateId = feeds.feedPrivateId
|
|
373
|
+
WHERE feeds.spaceId = ${opts.spaceId}
|
|
374
|
+
AND feeds.feedNamespace = ${opts.feedNamespace}
|
|
375
|
+
AND feeds.feedId = ${opts.feedId}
|
|
376
|
+
`;
|
|
377
|
+
return rows[0]?.count ?? 0;
|
|
378
|
+
}).pipe(Effect.withSpan('FeedStore.countBlocks'));
|
|
389
379
|
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
380
|
+
/**
|
|
381
|
+
* Deletes the oldest blocks for a single feed in a space/namespace.
|
|
382
|
+
* This API intentionally does not enforce any retention policy (such as max size);
|
|
383
|
+
* callers decide when and how much to prune, which is useful for constrained
|
|
384
|
+
* environments like Cloudflare Workers.
|
|
385
|
+
*
|
|
386
|
+
* @returns Number of deleted rows.
|
|
387
|
+
*/
|
|
388
|
+
deleteOldestBlocks = (opts: {
|
|
389
|
+
spaceId: SpaceId;
|
|
390
|
+
feedNamespace: string;
|
|
391
|
+
feedId: string;
|
|
392
|
+
count: number;
|
|
393
|
+
}): Effect.Effect<number, SqlError.SqlError, SqlClient.SqlClient> =>
|
|
394
|
+
Effect.gen(this, function* () {
|
|
395
|
+
const sql = yield* SqlClient.SqlClient;
|
|
396
|
+
if (opts.count <= 0) {
|
|
397
|
+
return 0;
|
|
398
|
+
}
|
|
402
399
|
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
const key = `${lamportConflict.feedPrivateId}|${lamportConflict.actorId}|${lamportConflict.sequence}`;
|
|
418
|
-
yield* Effect.fail(
|
|
419
|
-
new DuplicateBlockLamportTimestampError({
|
|
420
|
-
feedId: lamportFeedIdByKey.get(key)!,
|
|
421
|
-
actorId: lamportConflict.actorId,
|
|
422
|
-
sequence: lamportConflict.sequence,
|
|
423
|
-
}),
|
|
424
|
-
);
|
|
425
|
-
}
|
|
426
|
-
}
|
|
400
|
+
const deletedRows = yield* sql<{ insertionId: number }>`
|
|
401
|
+
DELETE FROM blocks
|
|
402
|
+
WHERE insertionId IN (
|
|
403
|
+
SELECT blocks.insertionId
|
|
404
|
+
FROM blocks
|
|
405
|
+
JOIN feeds ON blocks.feedPrivateId = feeds.feedPrivateId
|
|
406
|
+
WHERE feeds.spaceId = ${opts.spaceId}
|
|
407
|
+
AND feeds.feedNamespace = ${opts.feedNamespace}
|
|
408
|
+
AND feeds.feedId = ${opts.feedId}
|
|
409
|
+
ORDER BY blocks.insertionId ASC
|
|
410
|
+
LIMIT ${opts.count}
|
|
411
|
+
)
|
|
412
|
+
RETURNING insertionId
|
|
413
|
+
`;
|
|
427
414
|
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
const positionConditions = positionedBlocks.map((block) => {
|
|
431
|
-
const feedPrivateId = feedPrivateIds.get(block.feedId!)!;
|
|
432
|
-
return sql`(feedPrivateId = ${feedPrivateId} AND position = ${block.position})`;
|
|
433
|
-
});
|
|
434
|
-
if (positionConditions.length > 0) {
|
|
435
|
-
const existingPositions = yield* sql<{ feedPrivateId: number; position: number }>`
|
|
436
|
-
SELECT feedPrivateId, position
|
|
437
|
-
FROM blocks
|
|
438
|
-
WHERE position IS NOT NULL
|
|
439
|
-
AND (${sql.or(positionConditions)})
|
|
440
|
-
LIMIT 1
|
|
441
|
-
`;
|
|
442
|
-
const positionConflict = existingPositions[0];
|
|
443
|
-
if (positionConflict) {
|
|
444
|
-
const key = `${positionConflict.feedPrivateId}|${positionConflict.position}`;
|
|
445
|
-
yield* Effect.fail(
|
|
446
|
-
new DuplicateBlockPositionError({
|
|
447
|
-
feedId: positionFeedIdByKey.get(key)!,
|
|
448
|
-
position: positionConflict.position,
|
|
449
|
-
}),
|
|
450
|
-
);
|
|
451
|
-
}
|
|
452
|
-
}
|
|
453
|
-
}
|
|
454
|
-
}),
|
|
455
|
-
);
|
|
415
|
+
return deletedRows.length;
|
|
416
|
+
}).pipe(Effect.withSpan('FeedStore.deleteOldestBlocks'));
|
|
456
417
|
|
|
457
418
|
/**
|
|
458
419
|
* Appends blocks for a space/namespace and optionally assigns global positions.
|
|
459
420
|
*/
|
|
460
421
|
append = (
|
|
461
422
|
request: AppendRequest,
|
|
462
|
-
): Effect.Effect<
|
|
463
|
-
AppendResponse,
|
|
464
|
-
SqlError.SqlError | DuplicateBlockPositionError | DuplicateBlockLamportTimestampError,
|
|
465
|
-
SqlClient.SqlClient | SqlTransaction.SqlTransaction
|
|
466
|
-
> =>
|
|
423
|
+
): Effect.Effect<AppendResponse, SqlError.SqlError, SqlClient.SqlClient | SqlTransaction.SqlTransaction> =>
|
|
467
424
|
Effect.gen(this, function* () {
|
|
468
425
|
if (!request.spaceId) {
|
|
469
426
|
return yield* Effect.die(new Error('spaceId required for append'));
|
|
@@ -506,8 +463,6 @@ export class FeedStore {
|
|
|
506
463
|
{ concurrency: 'unbounded' },
|
|
507
464
|
);
|
|
508
465
|
|
|
509
|
-
yield* this.#validateAppendBlocks(request.blocks, feedPrivateIds);
|
|
510
|
-
|
|
511
466
|
// 2. Get max position per namespace ONCE (not per block).
|
|
512
467
|
const maxPositions = new Map<string, number>();
|
|
513
468
|
if (this.#options.assignPositions) {
|
|
@@ -562,11 +517,7 @@ export class FeedStore {
|
|
|
562
517
|
appendLocal = Effect.fn('Feed.appendLocal')(
|
|
563
518
|
(
|
|
564
519
|
messages: { spaceId: string; feedId: string; feedNamespace: string; data: Uint8Array }[],
|
|
565
|
-
): Effect.Effect<
|
|
566
|
-
Block[],
|
|
567
|
-
SqlError.SqlError | DuplicateBlockPositionError | DuplicateBlockLamportTimestampError,
|
|
568
|
-
SqlClient.SqlClient | SqlTransaction.SqlTransaction
|
|
569
|
-
> =>
|
|
520
|
+
): Effect.Effect<Block[], SqlError.SqlError, SqlClient.SqlClient | SqlTransaction.SqlTransaction> =>
|
|
570
521
|
Effect.gen(this, function* () {
|
|
571
522
|
const sql = yield* SqlClient.SqlClient;
|
|
572
523
|
|
|
@@ -661,17 +612,24 @@ export class FeedStore {
|
|
|
661
612
|
blocksBySpaceNamespace.get(spaceNamespaceKey)!.blocks.push(block);
|
|
662
613
|
}
|
|
663
614
|
|
|
664
|
-
// 4. Call append once per (spaceId, namespace) batch.
|
|
665
|
-
|
|
666
|
-
|
|
615
|
+
// 4. Call append once per (spaceId, namespace) batch and assign returned positions.
|
|
616
|
+
const positionByBlock = new Map<Block, number | null>();
|
|
617
|
+
for (const { spaceId, feedNamespace, blocks: batchBlocks } of blocksBySpaceNamespace.values()) {
|
|
618
|
+
const { positions } = yield* this.append({
|
|
667
619
|
requestId: 'local-append',
|
|
668
|
-
blocks,
|
|
620
|
+
blocks: batchBlocks,
|
|
669
621
|
spaceId,
|
|
670
622
|
feedNamespace,
|
|
671
623
|
});
|
|
624
|
+
for (let i = 0; i < batchBlocks.length; i++) {
|
|
625
|
+
positionByBlock.set(batchBlocks[i], positions[i] ?? null);
|
|
626
|
+
}
|
|
672
627
|
}
|
|
673
628
|
|
|
674
|
-
return blocks
|
|
629
|
+
return blocks.map((block) => ({
|
|
630
|
+
...block,
|
|
631
|
+
position: positionByBlock.get(block) ?? block.position,
|
|
632
|
+
}));
|
|
675
633
|
}).pipe(Effect.withSpan('FeedStore.appendLocal')),
|
|
676
634
|
);
|
|
677
635
|
|
|
@@ -715,6 +673,54 @@ export class FeedStore {
|
|
|
715
673
|
`;
|
|
716
674
|
}
|
|
717
675
|
}).pipe(Effect.withSpan('FeedStore.setPosition'));
|
|
676
|
+
|
|
677
|
+
/**
|
|
678
|
+
* Gets all feeds and their blocks for a space, organized by feed ID and namespace.
|
|
679
|
+
* Used for space archive export.
|
|
680
|
+
*/
|
|
681
|
+
getAllFeedsForSpace = (opts: {
|
|
682
|
+
spaceId: SpaceId;
|
|
683
|
+
}): Effect.Effect<
|
|
684
|
+
Array<{
|
|
685
|
+
feedId: string;
|
|
686
|
+
feedNamespace: string;
|
|
687
|
+
blocks: Block[];
|
|
688
|
+
}>,
|
|
689
|
+
SqlError.SqlError,
|
|
690
|
+
SqlClient.SqlClient
|
|
691
|
+
> =>
|
|
692
|
+
Effect.gen(this, function* () {
|
|
693
|
+
const sql = yield* SqlClient.SqlClient;
|
|
694
|
+
|
|
695
|
+
const feeds = yield* sql<{ feedId: string; feedNamespace: string }>`
|
|
696
|
+
SELECT DISTINCT feedId, feedNamespace FROM feeds WHERE spaceId = ${opts.spaceId}
|
|
697
|
+
`;
|
|
698
|
+
|
|
699
|
+
const result: Array<{ feedId: string; feedNamespace: string; blocks: Block[] }> = [];
|
|
700
|
+
|
|
701
|
+
for (const feed of feeds) {
|
|
702
|
+
const blocks = yield* sql<Block>`
|
|
703
|
+
SELECT blocks.*, feeds.feedId, feeds.feedNamespace
|
|
704
|
+
FROM blocks
|
|
705
|
+
JOIN feeds ON blocks.feedPrivateId = feeds.feedPrivateId
|
|
706
|
+
WHERE feeds.spaceId = ${opts.spaceId}
|
|
707
|
+
AND feeds.feedId = ${feed.feedId}
|
|
708
|
+
AND feeds.feedNamespace = ${feed.feedNamespace}
|
|
709
|
+
ORDER BY blocks.sequence ASC
|
|
710
|
+
`;
|
|
711
|
+
|
|
712
|
+
result.push({
|
|
713
|
+
feedId: feed.feedId,
|
|
714
|
+
feedNamespace: feed.feedNamespace,
|
|
715
|
+
blocks: blocks.map((row) => ({
|
|
716
|
+
...row,
|
|
717
|
+
data: new Uint8Array(row.data),
|
|
718
|
+
})),
|
|
719
|
+
});
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
return result;
|
|
723
|
+
}).pipe(Effect.withSpan('FeedStore.getAllFeedsForSpace'));
|
|
718
724
|
}
|
|
719
725
|
|
|
720
726
|
const encodeCursor = (token: string, insertionId: number) => FeedCursor.make(`${token}|${insertionId}`);
|
package/src/sync-client.ts
CHANGED
|
@@ -7,6 +7,7 @@ import * as Array from 'effect/Array';
|
|
|
7
7
|
import * as Deferred from 'effect/Deferred';
|
|
8
8
|
import * as Effect from 'effect/Effect';
|
|
9
9
|
|
|
10
|
+
import { Context } from '@dxos/context';
|
|
10
11
|
import type { SpaceId } from '@dxos/keys';
|
|
11
12
|
import { type FeedProtocol } from '@dxos/protocols';
|
|
12
13
|
import type { SqlTransaction } from '@dxos/sql-sqlite';
|
|
@@ -30,7 +31,7 @@ export type SyncClientOptions = {
|
|
|
30
31
|
serverPeerId?: string;
|
|
31
32
|
feedStore: FeedStore;
|
|
32
33
|
/** Send a protocol message to the server. Returns Effect. */
|
|
33
|
-
sendMessage: (message: RequestMessage) => Effect.Effect<void, unknown, never>;
|
|
34
|
+
sendMessage: (ctx: Context, message: RequestMessage) => Effect.Effect<void, unknown, never>;
|
|
34
35
|
};
|
|
35
36
|
|
|
36
37
|
/**
|
|
@@ -83,11 +84,14 @@ export class SyncClient {
|
|
|
83
84
|
return Effect.andThen(Deferred.succeed(deferred, message), () => Effect.void);
|
|
84
85
|
}
|
|
85
86
|
|
|
86
|
-
pull(
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
87
|
+
pull(
|
|
88
|
+
ctx: Context,
|
|
89
|
+
opts: {
|
|
90
|
+
spaceId: SpaceId;
|
|
91
|
+
feedNamespace: string;
|
|
92
|
+
limit?: number;
|
|
93
|
+
},
|
|
94
|
+
): Effect.Effect<{ done: boolean }, unknown, SqlClient.SqlClient | SqlTransaction.SqlTransaction> {
|
|
91
95
|
const self = this;
|
|
92
96
|
return Effect.gen(function* () {
|
|
93
97
|
const lastPulledPosition = yield* self.#feedStore.getSyncState({
|
|
@@ -105,7 +109,7 @@ export class SyncClient {
|
|
|
105
109
|
position: lastPulledPosition,
|
|
106
110
|
limit: opts.limit,
|
|
107
111
|
};
|
|
108
|
-
yield* self.#sendMessage(self.#withPeerIds(request));
|
|
112
|
+
yield* self.#sendMessage(ctx, self.#withPeerIds(request));
|
|
109
113
|
const message = yield* Deferred.await(deferred);
|
|
110
114
|
const response = yield* self.#expectResponse<QueryResponse>(requestId, message, 'QueryResponse');
|
|
111
115
|
if (response.blocks.length === 0) {
|
|
@@ -132,11 +136,14 @@ export class SyncClient {
|
|
|
132
136
|
});
|
|
133
137
|
}
|
|
134
138
|
|
|
135
|
-
push(
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
139
|
+
push(
|
|
140
|
+
ctx: Context,
|
|
141
|
+
opts: {
|
|
142
|
+
spaceId: SpaceId;
|
|
143
|
+
feedNamespace: string;
|
|
144
|
+
limit?: number;
|
|
145
|
+
},
|
|
146
|
+
): Effect.Effect<{ done: boolean }, unknown, SqlClient.SqlClient | SqlTransaction.SqlTransaction> {
|
|
140
147
|
const self = this;
|
|
141
148
|
return Effect.gen(function* () {
|
|
142
149
|
const unpositioned = yield* self.#feedStore.query({
|
|
@@ -158,7 +165,7 @@ export class SyncClient {
|
|
|
158
165
|
feedNamespace: opts.feedNamespace,
|
|
159
166
|
blocks: unpositioned.blocks,
|
|
160
167
|
};
|
|
161
|
-
yield* self.#sendMessage(self.#withPeerIds(request));
|
|
168
|
+
yield* self.#sendMessage(ctx, self.#withPeerIds(request));
|
|
162
169
|
const message = yield* Deferred.await(deferred);
|
|
163
170
|
const response = yield* self.#expectResponse<AppendResponse>(requestId, message, 'AppendResponse');
|
|
164
171
|
yield* self.#feedStore.setPosition({
|
package/src/sync-server.ts
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
import type * as SqlClient from '@effect/sql/SqlClient';
|
|
6
6
|
import * as Effect from 'effect/Effect';
|
|
7
7
|
|
|
8
|
+
import { Context } from '@dxos/context';
|
|
8
9
|
import { type FeedProtocol } from '@dxos/protocols';
|
|
9
10
|
import type { SqlTransaction } from '@dxos/sql-sqlite';
|
|
10
11
|
|
|
@@ -20,7 +21,7 @@ export type SyncServerOptions = {
|
|
|
20
21
|
peerId: string;
|
|
21
22
|
feedStore: FeedStore;
|
|
22
23
|
/** Send a protocol message to a client. Receives full message (recipient is set by server). Returns Effect. */
|
|
23
|
-
sendMessage: (message: ProtocolMessage) => Effect.Effect<void, unknown, never>;
|
|
24
|
+
sendMessage: (ctx: Context, message: ProtocolMessage) => Effect.Effect<void, unknown, never>;
|
|
24
25
|
};
|
|
25
26
|
|
|
26
27
|
/**
|
|
@@ -30,7 +31,7 @@ export type SyncServerOptions = {
|
|
|
30
31
|
export class SyncServer {
|
|
31
32
|
readonly #peerId: string;
|
|
32
33
|
readonly #feedStore: FeedStore;
|
|
33
|
-
readonly #sendMessage:
|
|
34
|
+
readonly #sendMessage: SyncServerOptions['sendMessage'];
|
|
34
35
|
|
|
35
36
|
constructor(options: SyncServerOptions) {
|
|
36
37
|
this.#peerId = options.peerId;
|
|
@@ -42,6 +43,7 @@ export class SyncServer {
|
|
|
42
43
|
* Receive a message from a client. Handles QueryRequest and AppendRequest; sends response via sendMessage with correct peer ids.
|
|
43
44
|
*/
|
|
44
45
|
handleMessage(
|
|
46
|
+
ctx: Context,
|
|
45
47
|
message: ProtocolMessage,
|
|
46
48
|
): Effect.Effect<void, unknown, SqlClient.SqlClient | SqlTransaction.SqlTransaction> {
|
|
47
49
|
const self = this;
|
|
@@ -57,10 +59,11 @@ export class SyncServer {
|
|
|
57
59
|
const req = message as QueryRequest;
|
|
58
60
|
return Effect.gen(function* () {
|
|
59
61
|
const response: QueryResponse = yield* self.#feedStore.query(req);
|
|
60
|
-
yield* self.#sendMessage(withPeerIds({ _tag: 'QueryResponse', ...response }));
|
|
62
|
+
yield* self.#sendMessage(ctx, withPeerIds({ _tag: 'QueryResponse', ...response }));
|
|
61
63
|
}).pipe(
|
|
62
64
|
Effect.catchAll((err: unknown) =>
|
|
63
65
|
self.#sendMessage(
|
|
66
|
+
ctx,
|
|
64
67
|
withPeerIds({
|
|
65
68
|
_tag: 'Error',
|
|
66
69
|
message: err instanceof Error ? err.message : String(err),
|
|
@@ -73,10 +76,11 @@ export class SyncServer {
|
|
|
73
76
|
const req = message as AppendRequest;
|
|
74
77
|
return Effect.gen(function* () {
|
|
75
78
|
const response = yield* self.#feedStore.append(req);
|
|
76
|
-
yield* self.#sendMessage(withPeerIds({ _tag: 'AppendResponse', ...response }));
|
|
79
|
+
yield* self.#sendMessage(ctx, withPeerIds({ _tag: 'AppendResponse', ...response }));
|
|
77
80
|
}).pipe(
|
|
78
81
|
Effect.catchAll((err: unknown) =>
|
|
79
82
|
self.#sendMessage(
|
|
83
|
+
ctx,
|
|
80
84
|
withPeerIds({
|
|
81
85
|
_tag: 'Error',
|
|
82
86
|
message: err instanceof Error ? err.message : String(err),
|
|
@@ -9,7 +9,7 @@ import * as Effect from 'effect/Effect';
|
|
|
9
9
|
import * as Layer from 'effect/Layer';
|
|
10
10
|
import * as ManagedRuntime from 'effect/ManagedRuntime';
|
|
11
11
|
|
|
12
|
-
import { Resource } from '@dxos/context';
|
|
12
|
+
import { Context, Resource } from '@dxos/context';
|
|
13
13
|
import { RuntimeProvider } from '@dxos/effect';
|
|
14
14
|
import { type SpaceId } from '@dxos/keys';
|
|
15
15
|
import { FeedProtocol } from '@dxos/protocols';
|
|
@@ -52,7 +52,7 @@ export class TestBuilder extends Resource {
|
|
|
52
52
|
isServer: i === 0,
|
|
53
53
|
actorId: `peer-${i}`,
|
|
54
54
|
serverPeerId: i === 0 ? undefined : 'peer-0',
|
|
55
|
-
sendMessage: (msg) => this.#routeMessage(msg),
|
|
55
|
+
sendMessage: (ctx, msg) => this.#routeMessage(ctx, msg),
|
|
56
56
|
logSql,
|
|
57
57
|
}),
|
|
58
58
|
);
|
|
@@ -83,14 +83,14 @@ export class TestBuilder extends Resource {
|
|
|
83
83
|
}
|
|
84
84
|
|
|
85
85
|
/** Route a message to the peer identified by recipientPeerId. Runs the recipient's handleMessage with that peer's runtime. */
|
|
86
|
-
#routeMessage(msg: ProtocolMessage): Effect.Effect<void, unknown, never> {
|
|
86
|
+
#routeMessage(ctx: Context, msg: ProtocolMessage): Effect.Effect<void, unknown, never> {
|
|
87
87
|
const peer = this.#peers.find((p) => p.peerId === msg.recipientPeerId);
|
|
88
88
|
if (peer == null) {
|
|
89
89
|
return Effect.die(new Error(`TestPeer not found: ${msg.recipientPeerId}`));
|
|
90
90
|
}
|
|
91
91
|
const handleEffect =
|
|
92
92
|
peer.syncServer != null
|
|
93
|
-
? peer.syncServer.handleMessage(msg)
|
|
93
|
+
? peer.syncServer.handleMessage(ctx, msg)
|
|
94
94
|
: peer.syncClient != null
|
|
95
95
|
? peer.syncClient.handleMessage(msg)
|
|
96
96
|
: null;
|
|
@@ -129,7 +129,7 @@ export class TestPeer extends Resource {
|
|
|
129
129
|
isServer: boolean;
|
|
130
130
|
actorId: string;
|
|
131
131
|
serverPeerId?: string;
|
|
132
|
-
sendMessage: (msg: ProtocolMessage) => Effect.Effect<void, unknown, never>;
|
|
132
|
+
sendMessage: (ctx: Context, msg: ProtocolMessage) => Effect.Effect<void, unknown, never>;
|
|
133
133
|
logSql?: boolean;
|
|
134
134
|
}) {
|
|
135
135
|
super();
|
|
@@ -210,14 +210,14 @@ export class TestPeer extends Resource {
|
|
|
210
210
|
}
|
|
211
211
|
|
|
212
212
|
pull({ spaceId, feedNamespace, limit = 10 }: { spaceId: SpaceId; feedNamespace: string; limit?: number }) {
|
|
213
|
-
return this.#client
|
|
214
|
-
|
|
215
|
-
|
|
213
|
+
return this.#client!
|
|
214
|
+
.pull(Context.default(), { spaceId, feedNamespace, limit })
|
|
215
|
+
.pipe(RuntimeProvider.runPromise(this.#runtime.runtimeEffect));
|
|
216
216
|
}
|
|
217
217
|
|
|
218
218
|
push({ spaceId, feedNamespace, limit = 10 }: { spaceId: SpaceId; feedNamespace: string; limit?: number }) {
|
|
219
|
-
return this.#client
|
|
220
|
-
|
|
221
|
-
|
|
219
|
+
return this.#client!
|
|
220
|
+
.push(Context.default(), { spaceId, feedNamespace, limit })
|
|
221
|
+
.pipe(RuntimeProvider.runPromise(this.#runtime.runtimeEffect));
|
|
222
222
|
}
|
|
223
223
|
}
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../../../src/errors.ts", "../../../src/feed-store.ts", "../../../src/sync-server.ts", "../../../src/sync-client.ts"],
|
|
4
|
-
"sourcesContent": ["//\n// Copyright 2026 DXOS.org\n//\n\nimport { BaseError } from '@dxos/errors';\n\nexport class DuplicateBlockPositionError extends BaseError.extend('DuplicateBlockPositionError') {\n constructor(args: { feedId: string; position: number }) {\n super(`Non-unique block position detected (feedId=${args.feedId} position=${args.position}).`);\n }\n}\n\nexport class DuplicateBlockLamportTimestampError extends BaseError.extend('DuplicateBlockLamportTimestampError') {\n constructor(args: { feedId: string; actorId: string; sequence: number }) {\n super(\n `Non-unique block Lamport timestamp detected (feedId=${args.feedId} actorId=${args.actorId} sequence=${args.sequence}).`,\n );\n }\n}\n\nexport class PositionConflictError extends BaseError.extend('PositionConflictError') {\n constructor(args: {\n feedId?: string;\n actorId: string;\n sequence: number;\n currentPosition: number;\n requestedPosition: number | null;\n }) {\n super(\n `Block already has position ${args.currentPosition}, cannot set to ${args.requestedPosition} (feedId=${args.feedId} actorId=${args.actorId} sequence=${args.sequence}).`,\n );\n }\n}\n", "//\n// Copyright 2026 DXOS.org\n//\n\nimport * as SqlClient from '@effect/sql/SqlClient';\nimport type * as SqlError from '@effect/sql/SqlError';\nimport * as Effect from 'effect/Effect';\n\nimport { Event } from '@dxos/async';\nimport { assertArgument } from '@dxos/invariant';\nimport { type SpaceId } from '@dxos/keys';\nimport { FeedProtocol } from '@dxos/protocols';\nimport { SqlTransaction } from '@dxos/sql-sqlite';\n\nimport { DuplicateBlockLamportTimestampError, DuplicateBlockPositionError, PositionConflictError } from './errors';\n\ntype AppendRequest = FeedProtocol.AppendRequest;\ntype AppendResponse = FeedProtocol.AppendResponse;\ntype Block = FeedProtocol.Block;\nconst FeedCursor = FeedProtocol.FeedCursor;\ntype FeedCursor = FeedProtocol.FeedCursor;\nconst isWellKnownNamespace = FeedProtocol.isWellKnownNamespace;\ntype QueryRequest = FeedProtocol.QueryRequest;\ntype QueryResponse = FeedProtocol.QueryResponse;\ntype SubscribeRequest = FeedProtocol.SubscribeRequest;\ntype SubscribeResponse = FeedProtocol.SubscribeResponse;\n\nexport interface FeedStoreOptions {\n /**\n * The actor ID of the local user.\n */\n localActorId: string;\n\n /**\n * Whether to assign positions to appended blocks.\n * Only a single peer (usually the server) can assign positions.\n */\n assignPositions: boolean;\n}\n\n/**\n * Persistent storage for feed metadata, blocks, subscriptions, and sync state.\n *\n */\nexport class FeedStore {\n readonly #options: FeedStoreOptions;\n\n constructor(options: FeedStoreOptions) {\n this.#options = options;\n }\n\n /**\n * Emits after successful block append operations.\n */\n readonly onNewBlocks = new Event<void>();\n\n /**\n * Creates required feed store tables and indexes if they do not exist.\n */\n migrate = Effect.fn('FeedStore.migrate')(() =>\n Effect.gen(function* () {\n const sql = yield* SqlClient.SqlClient;\n\n // Feeds Table\n yield* sql`CREATE TABLE IF NOT EXISTS feeds (\n feedPrivateId INTEGER PRIMARY KEY AUTOINCREMENT,\n spaceId TEXT NOT NULL,\n feedId TEXT NOT NULL,\n feedNamespace TEXT\n )`;\n yield* sql`CREATE UNIQUE INDEX IF NOT EXISTS idx_feeds_spaceId_feedId ON feeds(spaceId, feedId)`;\n\n // Blocks Table\n yield* sql`CREATE TABLE IF NOT EXISTS blocks (\n insertionId INTEGER PRIMARY KEY AUTOINCREMENT,\n feedPrivateId INTEGER NOT NULL,\n position INTEGER,\n sequence INTEGER NOT NULL,\n actorId TEXT NOT NULL,\n prevSequence INTEGER,\n prevActorId TEXT,\n timestamp INTEGER NOT NULL,\n data BLOB NOT NULL,\n FOREIGN KEY(feedPrivateId) REFERENCES feeds(feedPrivateId)\n )`;\n yield* sql`CREATE UNIQUE INDEX IF NOT EXISTS idx_blocks_feedPrivateId_position ON blocks(feedPrivateId, position)`;\n yield* sql`CREATE UNIQUE INDEX IF NOT EXISTS idx_blocks_feedPrivateId_sequence_actorId ON blocks(feedPrivateId, sequence, actorId)`;\n\n // Subscriptions Table\n yield* sql`CREATE TABLE IF NOT EXISTS subscriptions (\n subscriptionId TEXT PRIMARY KEY,\n expiresAt INTEGER NOT NULL,\n feedPrivateIds TEXT NOT NULL -- JSON array\n )`;\n\n // Cursor Tokens Table\n yield* sql`CREATE TABLE IF NOT EXISTS cursor_tokens (\n spaceId TEXT PRIMARY KEY,\n token TEXT NOT NULL\n )`;\n\n // Sync State Table.\n yield* sql`CREATE TABLE IF NOT EXISTS sync_state (\n spaceId TEXT NOT NULL,\n feedNamespace TEXT NOT NULL,\n lastPulledPosition INTEGER NOT NULL DEFAULT -1,\n PRIMARY KEY (spaceId, feedNamespace)\n )`;\n }).pipe(Effect.withSpan('FeedStore.migrate')),\n );\n\n /**\n * Ensures a feed row exists and returns its internal feed ID.\n */\n #ensureFeed = Effect.fn('Feed.ensureFeed')(\n (\n spaceId: string,\n feedId: string,\n namespace?: string,\n ): Effect.Effect<number, SqlError.SqlError, SqlClient.SqlClient> =>\n Effect.gen(this, function* () {\n const sql = yield* SqlClient.SqlClient;\n\n const rows = yield* sql<{ feedPrivateId: number }>`\n SELECT feedPrivateId FROM feeds WHERE spaceId = ${spaceId} AND feedId = ${feedId}\n `;\n if (rows.length > 0) return rows[0].feedPrivateId;\n\n const newRows = yield* sql<{ feedPrivateId: number }>`\n INSERT INTO feeds (spaceId, feedId, feedNamespace) VALUES (${spaceId}, ${feedId}, ${namespace}) RETURNING feedPrivateId\n `;\n return newRows[0].feedPrivateId;\n }).pipe(Effect.withSpan('FeedStore.ensureFeed')),\n );\n\n /**\n * Ensures cursor token exists for a space and returns it.\n */\n #ensureCursorToken = Effect.fn('Feed.ensureCursorToken')(\n (spaceId: string): Effect.Effect<string, SqlError.SqlError, SqlClient.SqlClient> =>\n Effect.gen(this, function* () {\n const sql = yield* SqlClient.SqlClient;\n const rows = yield* sql<{ token: string }>`SELECT token FROM cursor_tokens WHERE spaceId = ${spaceId}`;\n if (rows.length > 0) return rows[0].token;\n\n const token = crypto.randomUUID().replace(/-/g, '').slice(0, 6);\n yield* sql`INSERT INTO cursor_tokens (spaceId, token) VALUES (${spaceId}, ${token})`;\n return token;\n }).pipe(Effect.withSpan('FeedStore.ensureCursorToken')),\n );\n\n /**\n * Queries feed blocks by feed IDs or subscription with cursor/position pagination.\n */\n query = Effect.fn('Feed.query')(\n (request: QueryRequest): Effect.Effect<QueryResponse, SqlError.SqlError, SqlClient.SqlClient> =>\n Effect.gen(this, function* () {\n const sql = yield* SqlClient.SqlClient;\n let feedIds: string[] | undefined = [];\n let cursorInsertionId = -1;\n let cursorToken: string | undefined;\n\n if (!request.spaceId) {\n return yield* Effect.die(new Error('spaceId is required'));\n }\n\n if (\n (request.position !== undefined ? 1 : 0) +\n (request.cursor !== undefined ? 1 : 0) +\n (request.unpositionedOnly === true ? 1 : 0) >\n 1\n ) {\n return yield* Effect.die(new Error('Only one of position, cursor, or unpositionedOnly can be used'));\n }\n\n if (request.cursor) {\n const { token, insertionId } = decodeCursor(request.cursor as FeedCursor);\n if (!token || insertionId === undefined || isNaN(insertionId)) {\n return yield* Effect.die(new Error(`Invalid cursor format`));\n }\n cursorToken = token;\n cursorInsertionId = insertionId;\n }\n\n // Validate Token if cursor used.\n const validCursorToken = yield* this.#ensureCursorToken(request.spaceId);\n if (request.cursor && cursorToken !== validCursorToken) {\n return yield* Effect.die(new Error(`Cursor token mismatch`));\n }\n\n // If cursor is provided, we must validate it against the space token.\n // If spaceId is not provided in request (e.g. feedIds query), we can't easily validate token unless we look up spaceId for feedIds.\n // Ideally spaceId should be required for token validation.\n\n /* \n Logic:\n 1. If `cursor` is present, it's `token|insertionId`.\n 2. If `position` is present, it's `position` (legacy/manual).\n \n We prioritize `cursor`.\n */\n\n const position = request.position ?? -1;\n\n // Resolve subscriptions or feed IDs.\n if (request.query && 'subscriptionId' in request.query) {\n const rows = yield* sql<{ feedPrivateIds: string; expiresAt: number }>`\n SELECT feedPrivateIds, expiresAt FROM subscriptions WHERE subscriptionId = ${request.query.subscriptionId}\n `;\n if (rows.length > 0) {\n const { feedPrivateIds, expiresAt } = rows[0];\n if (Date.now() <= expiresAt) {\n const privateIds = JSON.parse(feedPrivateIds) as number[];\n if (privateIds.length > 0) {\n const feedRows = yield* sql<{ feedId: string }>`\n SELECT feedId FROM feeds WHERE feedPrivateId IN ${sql.in(privateIds)}\n `;\n feedIds = feedRows.map((r) => r.feedId);\n }\n }\n }\n } else if (request.query && 'feedIds' in request.query) {\n feedIds = [...request.query.feedIds];\n } else {\n feedIds = undefined;\n }\n\n if (feedIds !== undefined && feedIds.length === 0) {\n return {\n requestId: request.requestId,\n blocks: [],\n nextCursor: encodeCursor(validCursorToken, -1),\n hasMore: false,\n };\n }\n\n // Fetch blocks.\n const query = sql<Block>`\n SELECT blocks.*, feeds.feedId, feeds.feedNamespace\n FROM blocks\n JOIN feeds ON blocks.feedPrivateId = feeds.feedPrivateId\n WHERE 1=1\n ${feedIds !== undefined ? sql`AND feeds.feedId IN ${sql.in(feedIds)}` : sql``}\n ${request.spaceId ? sql`AND feeds.spaceId = ${request.spaceId}` : sql``}\n ${sql`AND feeds.feedNamespace = ${request.feedNamespace}`}\n `;\n\n // Add filter based on cursor or position.\n const filter = request.cursor\n ? sql`AND blocks.insertionId > ${cursorInsertionId}`\n : request.unpositionedOnly\n ? sql`AND blocks.position IS NULL`\n : sql`AND (blocks.position > ${position} OR blocks.position IS NULL)`;\n\n const orderBy = request.cursor\n ? sql`ORDER BY blocks.insertionId ASC`\n : sql`ORDER BY blocks.position ASC NULLS LAST`;\n\n const requestLimit = request.limit;\n const queryLimit = requestLimit != null ? requestLimit + 1 : undefined;\n const rows = yield* sql<Block>`\n ${query}\n ${filter}\n ${orderBy}\n ${queryLimit != null ? sql`LIMIT ${queryLimit}` : sql``}\n `;\n\n const hasMore = requestLimit != null && rows.length > requestLimit;\n const slice = hasMore ? rows.slice(0, requestLimit) : rows;\n const blocks = slice.map((row) => ({\n ...row,\n // Have to clone buffer otherwise we get empty Uint8Array.\n data: new Uint8Array(row.data),\n }));\n\n let nextCursor: FeedCursor = request.cursor ?? encodeCursor(validCursorToken, -1);\n if (blocks.length > 0 && request.spaceId) {\n const lastBlock = blocks[blocks.length - 1];\n if (lastBlock.insertionId !== undefined) {\n nextCursor = encodeCursor(validCursorToken, lastBlock.insertionId);\n }\n }\n\n return { requestId: request.requestId, blocks, nextCursor, hasMore } satisfies QueryResponse;\n }).pipe(Effect.withSpan('FeedStore.query')),\n );\n\n /**\n * Creates a subscription and stores the resolved internal feed IDs.\n */\n subscribe = Effect.fn('Feed.subscribe')(\n (request: SubscribeRequest): Effect.Effect<SubscribeResponse, SqlError.SqlError, SqlClient.SqlClient> =>\n Effect.gen(this, function* () {\n const sql = yield* SqlClient.SqlClient;\n const ttl = 60 * 60 * 1000;\n const subscriptionId = crypto.randomUUID();\n const expiresAt = Date.now() + ttl;\n\n if (!request.spaceId) {\n // TODO(dmaretskyi): Define error type.\n return yield* Effect.die(new Error('spaceId required for subscribe'));\n }\n\n const feedPrivateIds = yield* Effect.forEach(\n request.feedIds,\n (feedId) => this.#ensureFeed(request.spaceId!, feedId),\n { concurrency: 'unbounded' },\n );\n\n yield* sql`\n INSERT INTO subscriptions (subscriptionId, expiresAt, feedPrivateIds)\n VALUES (${subscriptionId}, ${expiresAt}, ${JSON.stringify(feedPrivateIds)})\n `;\n\n return {\n requestId: request.requestId,\n subscriptionId,\n expiresAt,\n };\n }).pipe(Effect.withSpan('FeedStore.subscribe')),\n );\n\n /**\n * Get the last pulled position for the given space and namespace.\n * Returns -1 if no sync state exists yet.\n */\n getSyncState = (opts: {\n spaceId: SpaceId;\n feedNamespace: string;\n }): Effect.Effect<number, SqlError.SqlError, SqlClient.SqlClient> =>\n Effect.gen(this, function* () {\n const sql = yield* SqlClient.SqlClient;\n const rows = yield* sql<{ lastPulledPosition: number }>`\n SELECT lastPulledPosition FROM sync_state\n WHERE spaceId = ${opts.spaceId} AND feedNamespace = ${opts.feedNamespace}\n `;\n return rows[0]?.lastPulledPosition ?? -1;\n }).pipe(Effect.withSpan('FeedStore.getSyncState'));\n\n /**\n * Update the last pulled position for the given space and namespace.\n */\n setSyncState = (opts: {\n spaceId: SpaceId;\n feedNamespace: string;\n lastPulledPosition: number;\n }): Effect.Effect<void, SqlError.SqlError, SqlClient.SqlClient> =>\n Effect.gen(this, function* () {\n const sql = yield* SqlClient.SqlClient;\n yield* sql`\n INSERT INTO sync_state (spaceId, feedNamespace, lastPulledPosition)\n VALUES (${opts.spaceId}, ${opts.feedNamespace}, ${opts.lastPulledPosition})\n ON CONFLICT (spaceId, feedNamespace) DO UPDATE SET lastPulledPosition = ${opts.lastPulledPosition}\n `;\n }).pipe(Effect.withSpan('FeedStore.setSyncState'));\n\n /**\n * Validates that appended blocks do not introduce position or Lamport conflicts.\n */\n #validateAppendBlocks = Effect.fn('FeedStore.validateAppendBlocks')(\n (\n blocks: readonly Block[],\n feedPrivateIds: Map<string, number>,\n ): Effect.Effect<\n void,\n SqlError.SqlError | DuplicateBlockPositionError | DuplicateBlockLamportTimestampError,\n SqlClient.SqlClient\n > =>\n Effect.gen(this, function* () {\n const sql = yield* SqlClient.SqlClient;\n\n // Validate request-level uniqueness before writing.\n const positionFeedIdByKey = new Map<string, string>();\n const lamportFeedIdByKey = new Map<string, string>();\n for (const block of blocks) {\n const feedPrivateId = feedPrivateIds.get(block.feedId!)!;\n if (!this.#options.assignPositions && block.position != null) {\n const positionKey = `${feedPrivateId}|${block.position}`;\n if (positionFeedIdByKey.has(positionKey)) {\n yield* Effect.fail(\n new DuplicateBlockPositionError({\n feedId: block.feedId!,\n position: block.position,\n }),\n );\n }\n positionFeedIdByKey.set(positionKey, block.feedId!);\n }\n\n const lamportKey = `${feedPrivateId}|${block.actorId}|${block.sequence}`;\n if (lamportFeedIdByKey.has(lamportKey)) {\n yield* Effect.fail(\n new DuplicateBlockLamportTimestampError({\n feedId: block.feedId!,\n actorId: block.actorId,\n sequence: block.sequence,\n }),\n );\n }\n lamportFeedIdByKey.set(lamportKey, block.feedId!);\n }\n\n // Bulk-validate against persisted rows with exact tuple matching.\n const lamportConditions = blocks.map((block) => {\n const feedPrivateId = feedPrivateIds.get(block.feedId!)!;\n return sql`(feedPrivateId = ${feedPrivateId} AND actorId = ${block.actorId} AND sequence = ${block.sequence})`;\n });\n if (lamportConditions.length > 0) {\n const existingLamports = yield* sql<{ feedPrivateId: number; actorId: string; sequence: number }>`\n SELECT feedPrivateId, actorId, sequence\n FROM blocks\n WHERE ${sql.or(lamportConditions)}\n LIMIT 1\n `;\n const lamportConflict = existingLamports[0];\n if (lamportConflict) {\n const key = `${lamportConflict.feedPrivateId}|${lamportConflict.actorId}|${lamportConflict.sequence}`;\n yield* Effect.fail(\n new DuplicateBlockLamportTimestampError({\n feedId: lamportFeedIdByKey.get(key)!,\n actorId: lamportConflict.actorId,\n sequence: lamportConflict.sequence,\n }),\n );\n }\n }\n\n if (!this.#options.assignPositions) {\n const positionedBlocks = blocks.filter((block) => block.position != null);\n const positionConditions = positionedBlocks.map((block) => {\n const feedPrivateId = feedPrivateIds.get(block.feedId!)!;\n return sql`(feedPrivateId = ${feedPrivateId} AND position = ${block.position})`;\n });\n if (positionConditions.length > 0) {\n const existingPositions = yield* sql<{ feedPrivateId: number; position: number }>`\n SELECT feedPrivateId, position\n FROM blocks\n WHERE position IS NOT NULL\n AND (${sql.or(positionConditions)})\n LIMIT 1\n `;\n const positionConflict = existingPositions[0];\n if (positionConflict) {\n const key = `${positionConflict.feedPrivateId}|${positionConflict.position}`;\n yield* Effect.fail(\n new DuplicateBlockPositionError({\n feedId: positionFeedIdByKey.get(key)!,\n position: positionConflict.position,\n }),\n );\n }\n }\n }\n }),\n );\n\n /**\n * Appends blocks for a space/namespace and optionally assigns global positions.\n */\n append = (\n request: AppendRequest,\n ): Effect.Effect<\n AppendResponse,\n SqlError.SqlError | DuplicateBlockPositionError | DuplicateBlockLamportTimestampError,\n SqlClient.SqlClient | SqlTransaction.SqlTransaction\n > =>\n Effect.gen(this, function* () {\n if (!request.spaceId) {\n return yield* Effect.die(new Error('spaceId required for append'));\n }\n\n assertArgument(\n isWellKnownNamespace(request.feedNamespace),\n 'request.feedNamespace',\n 'specified well-known namespace',\n );\n\n // Validate all blocks upfront.\n for (const block of request.blocks) {\n assertArgument(block.feedId, 'block.feedId', 'feedId is required');\n }\n\n // Wrap in transaction to ensure atomicity when assigning positions.\n const sqlTransaction = yield* SqlTransaction.SqlTransaction;\n const positions = yield* sqlTransaction.withTransaction(\n Effect.gen(this, function* () {\n const sql = yield* SqlClient.SqlClient;\n\n // 1. Collect unique feed IDs and batch #ensureFeed calls.\n const feedKeys = new Map<string, { feedId: string }>();\n for (const block of request.blocks) {\n const key = block.feedId!;\n if (!feedKeys.has(key)) {\n feedKeys.set(key, { feedId: block.feedId! });\n }\n }\n\n const feedPrivateIds = new Map<string, number>();\n yield* Effect.forEach(\n [...feedKeys.entries()],\n ([key, { feedId }]) =>\n Effect.gen(this, function* () {\n const id = yield* this.#ensureFeed(request.spaceId!, feedId, request.feedNamespace);\n feedPrivateIds.set(key, id);\n }),\n { concurrency: 'unbounded' },\n );\n\n yield* this.#validateAppendBlocks(request.blocks, feedPrivateIds);\n\n // 2. Get max position per namespace ONCE (not per block).\n const maxPositions = new Map<string, number>();\n if (this.#options.assignPositions) {\n const maxPosResult = yield* sql<{ maxPos: number | null }>`\n SELECT MAX(position) as maxPos \n FROM blocks \n JOIN feeds ON blocks.feedPrivateId = feeds.feedPrivateId\n WHERE feeds.spaceId = ${request.spaceId} AND feeds.feedNamespace = ${request.feedNamespace}\n `;\n maxPositions.set(request.feedNamespace, maxPosResult[0]?.maxPos ?? -1);\n }\n\n // 3. Insert all blocks and compute positions.\n const positions: number[] = [];\n for (const block of request.blocks) {\n const key = block.feedId!;\n const feedPrivateId = feedPrivateIds.get(key)!;\n\n let positionToInsert: number | null = null;\n if (this.#options.assignPositions) {\n const currentMax = maxPositions.get(request.feedNamespace)!;\n positionToInsert = currentMax + 1;\n maxPositions.set(request.feedNamespace, positionToInsert); // Increment for next block in same namespace.\n positions.push(positionToInsert);\n } else if (block.position != null) {\n positionToInsert = block.position;\n }\n\n yield* sql`\n INSERT INTO blocks (\n feedPrivateId, position, sequence, actorId, \n prevSequence, prevActorId, timestamp, data\n ) VALUES (\n ${feedPrivateId}, ${positionToInsert}, ${block.sequence}, ${block.actorId},\n ${block.prevSequence}, ${block.prevActorId}, ${block.timestamp}, ${block.data}\n ) ON CONFLICT DO NOTHING\n `;\n }\n\n return positions;\n }),\n );\n\n this.onNewBlocks.emit();\n\n return { requestId: request.requestId, positions };\n }).pipe(Effect.withSpan('FeedStore.append'));\n\n /**\n * Creates local blocks with sequential predecessors and appends grouped batches.\n */\n appendLocal = Effect.fn('Feed.appendLocal')(\n (\n messages: { spaceId: string; feedId: string; feedNamespace: string; data: Uint8Array }[],\n ): Effect.Effect<\n Block[],\n SqlError.SqlError | DuplicateBlockPositionError | DuplicateBlockLamportTimestampError,\n SqlClient.SqlClient | SqlTransaction.SqlTransaction\n > =>\n Effect.gen(this, function* () {\n const sql = yield* SqlClient.SqlClient;\n\n // 1. Collect unique feeds and ensure they exist.\n type FeedKey = string; // `${spaceId}|${feedNamespace}|${feedId}`\n const feedKeys = new Map<FeedKey, { spaceId: string; feedId: string; feedNamespace: string }>();\n for (const msg of messages) {\n const key = `${msg.spaceId}|${msg.feedNamespace}|${msg.feedId}`;\n if (!feedKeys.has(key)) {\n feedKeys.set(key, { spaceId: msg.spaceId, feedId: msg.feedId, feedNamespace: msg.feedNamespace });\n }\n }\n\n // Batch ensure feeds and get their private IDs.\n const feedPrivateIds = new Map<FeedKey, number>();\n yield* Effect.forEach(\n [...feedKeys.entries()],\n ([key, { spaceId, feedId, feedNamespace }]) =>\n Effect.gen(this, function* () {\n const id = yield* this.#ensureFeed(spaceId, feedId, feedNamespace);\n feedPrivateIds.set(key, id);\n }),\n { concurrency: 'unbounded' },\n );\n\n // 2. Get last sequence for each unique feed (batch query).\n const lastSeqs = new Map<FeedKey, { sequence: number; actorId: string } | null>();\n for (const [key] of feedKeys) {\n const feedPrivateId = feedPrivateIds.get(key)!;\n const lastBlockResult = yield* sql<{ sequence: number; actorId: string }>`\n SELECT sequence, actorId FROM blocks \n WHERE feedPrivateId = ${feedPrivateId} \n ORDER BY sequence DESC \n LIMIT 1\n `;\n lastSeqs.set(key, lastBlockResult[0] ?? null);\n }\n\n // 3. Build all blocks with correct sequences.\n // Track in-flight sequences per feed to handle multiple messages to same feed.\n const currentSeqs = new Map<FeedKey, { sequence: number; actorId: string }>();\n const blocks: Block[] = [];\n const blocksBySpaceNamespace = new Map<string, { spaceId: string; feedNamespace: string; blocks: Block[] }>();\n\n for (const msg of messages) {\n const key = `${msg.spaceId}|${msg.feedNamespace}|${msg.feedId}`;\n\n // Determine predecessor: either from in-flight blocks or from DB.\n let sequence: number;\n let prevSequence: number | null;\n let prevActorId: string | null;\n\n const inFlight = currentSeqs.get(key);\n if (inFlight) {\n // We've already added blocks for this feed - continue from last in-flight.\n sequence = inFlight.sequence + 1;\n prevSequence = inFlight.sequence;\n prevActorId = inFlight.actorId;\n } else {\n // First block for this feed - use DB state.\n const lastBlock = lastSeqs.get(key);\n sequence = (lastBlock?.sequence ?? -1) + 1;\n prevSequence = lastBlock?.sequence ?? null;\n prevActorId = lastBlock?.actorId ?? null;\n }\n\n const block: Block = {\n feedId: msg.feedId,\n actorId: this.#options.localActorId,\n sequence,\n prevActorId,\n prevSequence,\n timestamp: Date.now(),\n data: msg.data,\n position: null, // Assigned by append.\n };\n\n blocks.push(block);\n\n // Update in-flight tracking.\n currentSeqs.set(key, { sequence, actorId: this.#options.localActorId });\n\n // Group by (spaceId, feedNamespace).\n const spaceNamespaceKey = `${msg.spaceId}|${msg.feedNamespace}`;\n if (!blocksBySpaceNamespace.has(spaceNamespaceKey)) {\n blocksBySpaceNamespace.set(spaceNamespaceKey, {\n spaceId: msg.spaceId,\n feedNamespace: msg.feedNamespace,\n blocks: [],\n });\n }\n blocksBySpaceNamespace.get(spaceNamespaceKey)!.blocks.push(block);\n }\n\n // 4. Call append once per (spaceId, namespace) batch.\n for (const { spaceId, feedNamespace, blocks } of blocksBySpaceNamespace.values()) {\n yield* this.append({\n requestId: 'local-append',\n blocks,\n spaceId,\n feedNamespace,\n });\n }\n\n return blocks;\n }).pipe(Effect.withSpan('FeedStore.appendLocal')),\n );\n\n /**\n * Sets positions for existing blocks while preventing conflicting reassignments.\n */\n setPosition = (request: {\n spaceId: string;\n blocks: (Pick<Block, 'feedId' | 'actorId' | 'sequence' | 'position'> & { feedNamespace: string })[];\n }): Effect.Effect<void, SqlError.SqlError | PositionConflictError, SqlClient.SqlClient> =>\n Effect.gen(this, function* () {\n const sql = yield* SqlClient.SqlClient;\n for (const block of request.blocks) {\n const existing = yield* sql<{ position: number | null }>`\n SELECT position FROM blocks\n WHERE feedPrivateId = (\n SELECT feedPrivateId FROM feeds\n WHERE spaceId = ${request.spaceId} AND feedId = ${block.feedId} AND feedNamespace = ${block.feedNamespace}\n )\n AND actorId = ${block.actorId} AND sequence = ${block.sequence}\n `;\n const current = existing[0];\n if (current?.position != null && current.position !== block.position) {\n yield* Effect.fail(\n new PositionConflictError({\n feedId: block.feedId,\n actorId: block.actorId,\n sequence: block.sequence,\n currentPosition: current.position,\n requestedPosition: block.position,\n }),\n );\n }\n yield* sql`\n UPDATE blocks SET position = ${block.position}\n WHERE feedPrivateId = (\n SELECT feedPrivateId FROM feeds\n WHERE spaceId = ${request.spaceId} AND feedId = ${block.feedId} AND feedNamespace = ${block.feedNamespace}\n )\n AND actorId = ${block.actorId} AND sequence = ${block.sequence}\n `;\n }\n }).pipe(Effect.withSpan('FeedStore.setPosition'));\n}\n\nconst encodeCursor = (token: string, insertionId: number) => FeedCursor.make(`${token}|${insertionId}`);\nconst decodeCursor = (cursor: FeedCursor) => {\n const [token, insertionId] = cursor.split('|');\n return { token, insertionId: Number(insertionId) };\n};\n", "//\n// Copyright 2026 DXOS.org\n//\n\nimport type * as SqlClient from '@effect/sql/SqlClient';\nimport * as Effect from 'effect/Effect';\n\nimport { type FeedProtocol } from '@dxos/protocols';\nimport type { SqlTransaction } from '@dxos/sql-sqlite';\n\nimport type { FeedStore } from './feed-store';\n\ntype AppendRequest = FeedProtocol.AppendRequest;\ntype ProtocolMessage = FeedProtocol.ProtocolMessage;\ntype QueryRequest = FeedProtocol.QueryRequest;\ntype QueryResponse = FeedProtocol.QueryResponse;\n\nexport type SyncServerOptions = {\n /** This server's peer id. Set as senderPeerId on all replies. */\n peerId: string;\n feedStore: FeedStore;\n /** Send a protocol message to a client. Receives full message (recipient is set by server). Returns Effect. */\n sendMessage: (message: ProtocolMessage) => Effect.Effect<void, unknown, never>;\n};\n\n/**\n * Server-side sync: receives protocol messages, runs query/append against the store, sends responses.\n * Reusable for many peers: sets senderPeerId = peerId and recipientPeerId = incoming message's senderPeerId on replies.\n */\nexport class SyncServer {\n readonly #peerId: string;\n readonly #feedStore: FeedStore;\n readonly #sendMessage: (message: ProtocolMessage) => Effect.Effect<void, unknown, never>;\n\n constructor(options: SyncServerOptions) {\n this.#peerId = options.peerId;\n this.#feedStore = options.feedStore;\n this.#sendMessage = options.sendMessage;\n }\n\n /**\n * Receive a message from a client. Handles QueryRequest and AppendRequest; sends response via sendMessage with correct peer ids.\n */\n handleMessage(\n message: ProtocolMessage,\n ): Effect.Effect<void, unknown, SqlClient.SqlClient | SqlTransaction.SqlTransaction> {\n const self = this;\n const recipientPeerId = message.senderPeerId;\n const withPeerIds = (payload: Omit<ProtocolMessage, 'senderPeerId' | 'recipientPeerId'>): ProtocolMessage =>\n ({\n ...payload,\n senderPeerId: self.#peerId,\n recipientPeerId,\n }) as ProtocolMessage;\n switch (message._tag) {\n case 'QueryRequest': {\n const req = message as QueryRequest;\n return Effect.gen(function* () {\n const response: QueryResponse = yield* self.#feedStore.query(req);\n yield* self.#sendMessage(withPeerIds({ _tag: 'QueryResponse', ...response }));\n }).pipe(\n Effect.catchAll((err: unknown) =>\n self.#sendMessage(\n withPeerIds({\n _tag: 'Error',\n message: err instanceof Error ? err.message : String(err),\n } as Omit<ProtocolMessage, 'senderPeerId' | 'recipientPeerId'>),\n ),\n ),\n );\n }\n case 'AppendRequest': {\n const req = message as AppendRequest;\n return Effect.gen(function* () {\n const response = yield* self.#feedStore.append(req);\n yield* self.#sendMessage(withPeerIds({ _tag: 'AppendResponse', ...response }));\n }).pipe(\n Effect.catchAll((err: unknown) =>\n self.#sendMessage(\n withPeerIds({\n _tag: 'Error',\n message: err instanceof Error ? err.message : String(err),\n } as Omit<ProtocolMessage, 'senderPeerId' | 'recipientPeerId'>),\n ),\n ),\n );\n }\n default:\n return Effect.void;\n }\n }\n}\n", "//\n// Copyright 2026 DXOS.org\n//\n\nimport type * as SqlClient from '@effect/sql/SqlClient';\nimport * as Array from 'effect/Array';\nimport * as Deferred from 'effect/Deferred';\nimport * as Effect from 'effect/Effect';\n\nimport type { SpaceId } from '@dxos/keys';\nimport { type FeedProtocol } from '@dxos/protocols';\nimport type { SqlTransaction } from '@dxos/sql-sqlite';\n\nimport type { FeedStore } from './feed-store';\n\ntype AppendResponse = FeedProtocol.AppendResponse;\ntype ProtocolMessage = FeedProtocol.ProtocolMessage;\ntype QueryResponse = FeedProtocol.QueryResponse;\ntype QueryRequestMessage = Extract<ProtocolMessage, { _tag: 'QueryRequest' }>;\ntype AppendRequestMessage = Extract<ProtocolMessage, { _tag: 'AppendRequest' }>;\ntype RequestMessage = QueryRequestMessage | AppendRequestMessage;\ntype RequestPayload =\n | Omit<QueryRequestMessage, 'senderPeerId' | 'recipientPeerId'>\n | Omit<AppendRequestMessage, 'senderPeerId' | 'recipientPeerId'>;\n\nexport type SyncClientOptions = {\n /** This client's peer id. Set as senderPeerId on all requests. */\n peerId: string;\n /** The server's peer id. Set as recipientPeerId on all requests. */\n serverPeerId?: string;\n feedStore: FeedStore;\n /** Send a protocol message to the server. Returns Effect. */\n sendMessage: (message: RequestMessage) => Effect.Effect<void, unknown, never>;\n};\n\n/**\n * Client-side sync: pull/push by sending protocol messages and handling responses.\n * Sets senderPeerId = peerId and recipientPeerId = serverPeerId on all requests.\n * Uses a map of requestId -> Deferred to match responses to in-flight requests.\n * handleMessage completes the Deferred for the requestId (if any) and removes the handler; no handler = noop.\n */\nexport class SyncClient {\n readonly #peerId: string;\n readonly #serverPeerId: string | undefined;\n readonly #feedStore: FeedStore;\n readonly #sendMessage: SyncClientOptions['sendMessage'];\n readonly #handlers = new Map<string, Deferred.Deferred<ProtocolMessage, Error>>();\n\n constructor(options: SyncClientOptions) {\n this.#peerId = options.peerId;\n this.#serverPeerId = options.serverPeerId;\n this.#feedStore = options.feedStore;\n this.#sendMessage = options.sendMessage;\n }\n\n #withPeerIds(payload: RequestPayload): RequestMessage {\n if (payload._tag === 'QueryRequest') {\n return {\n ...payload,\n senderPeerId: this.#peerId,\n recipientPeerId: this.#serverPeerId,\n };\n }\n return {\n ...payload,\n senderPeerId: this.#peerId,\n recipientPeerId: this.#serverPeerId,\n };\n }\n\n /**\n * Receive a message from the server. If a handler is registered for the message's requestId, complete it and remove; else noop.\n */\n handleMessage(message: ProtocolMessage): Effect.Effect<void, never, never> {\n const requestId = 'requestId' in message && message.requestId != null ? String(message.requestId) : undefined;\n if (requestId == null) return Effect.void;\n const deferred = this.#handlers.get(requestId);\n if (deferred == null) return Effect.void;\n this.#handlers.delete(requestId);\n if (message._tag === 'Error') {\n return Effect.andThen(Deferred.fail(deferred, new Error(message.message)), () => Effect.void);\n }\n return Effect.andThen(Deferred.succeed(deferred, message), () => Effect.void);\n }\n\n pull(opts: {\n spaceId: SpaceId;\n feedNamespace: string;\n limit?: number;\n }): Effect.Effect<{ done: boolean }, unknown, SqlClient.SqlClient | SqlTransaction.SqlTransaction> {\n const self = this;\n return Effect.gen(function* () {\n const lastPulledPosition = yield* self.#feedStore.getSyncState({\n spaceId: opts.spaceId,\n feedNamespace: opts.feedNamespace,\n });\n const requestId = crypto.randomUUID();\n const deferred = yield* Deferred.make<ProtocolMessage, Error>();\n self.#handlers.set(requestId, deferred);\n const request: RequestPayload = {\n _tag: 'QueryRequest',\n requestId,\n spaceId: opts.spaceId,\n feedNamespace: opts.feedNamespace,\n position: lastPulledPosition,\n limit: opts.limit,\n };\n yield* self.#sendMessage(self.#withPeerIds(request));\n const message = yield* Deferred.await(deferred);\n const response = yield* self.#expectResponse<QueryResponse>(requestId, message, 'QueryResponse');\n if (response.blocks.length === 0) {\n return { done: true };\n }\n yield* self.#feedStore.append({\n spaceId: opts.spaceId,\n feedNamespace: opts.feedNamespace,\n blocks: response.blocks,\n });\n\n // Update sync state with the max position from the pulled batch.\n const maxPulledPosition = response.blocks.reduce(\n (max, block) => (block.position != null && block.position > max ? block.position : max),\n lastPulledPosition,\n );\n yield* self.#feedStore.setSyncState({\n spaceId: opts.spaceId,\n feedNamespace: opts.feedNamespace,\n lastPulledPosition: maxPulledPosition,\n });\n\n return { done: false };\n });\n }\n\n push(opts: {\n spaceId: SpaceId;\n feedNamespace: string;\n limit?: number;\n }): Effect.Effect<{ done: boolean }, unknown, SqlClient.SqlClient | SqlTransaction.SqlTransaction> {\n const self = this;\n return Effect.gen(function* () {\n const unpositioned = yield* self.#feedStore.query({\n spaceId: opts.spaceId,\n feedNamespace: opts.feedNamespace,\n unpositionedOnly: true,\n limit: opts.limit,\n });\n if (unpositioned.blocks.length === 0) {\n return { done: true };\n }\n const requestId = crypto.randomUUID();\n const deferred = yield* Deferred.make<ProtocolMessage, Error>();\n self.#handlers.set(requestId, deferred);\n const request: RequestPayload = {\n _tag: 'AppendRequest',\n requestId,\n spaceId: opts.spaceId,\n feedNamespace: opts.feedNamespace,\n blocks: unpositioned.blocks,\n };\n yield* self.#sendMessage(self.#withPeerIds(request));\n const message = yield* Deferred.await(deferred);\n const response = yield* self.#expectResponse<AppendResponse>(requestId, message, 'AppendResponse');\n yield* self.#feedStore.setPosition({\n spaceId: opts.spaceId,\n blocks: Array.zipWith(response.positions, unpositioned.blocks, (position, block) => ({\n feedId: block.feedId,\n feedNamespace: opts.feedNamespace,\n actorId: block.actorId,\n sequence: block.sequence,\n position,\n })),\n });\n return { done: false };\n });\n }\n\n #expectResponse<T>(requestId: string, message: ProtocolMessage, expectedTag: string): Effect.Effect<T, Error, never> {\n if (message._tag === 'Error') {\n return Effect.fail(new Error(message.message));\n }\n const requestIdMsg = 'requestId' in message ? String(message.requestId) : undefined;\n if (message._tag !== expectedTag || requestIdMsg !== requestId) {\n return Effect.fail(new Error(`Unexpected message: expected ${expectedTag} with requestId ${requestId}`));\n }\n return Effect.succeed(message as T);\n }\n}\n"],
|
|
5
|
-
"mappings": ";AAIA,SAASA,iBAAiB;AAEnB,IAAMC,8BAAN,cAA0CC,UAAUC,OAAO,6BAAA,EAAA;EAChE,YAAYC,MAA4C;AACtD,UAAM,8CAA8CA,KAAKC,MAAM,aAAaD,KAAKE,QAAQ,IAAI;EAC/F;AACF;AAEO,IAAMC,sCAAN,cAAkDL,UAAUC,OAAO,qCAAA,EAAA;EACxE,YAAYC,MAA6D;AACvE,UACE,uDAAuDA,KAAKC,MAAM,YAAYD,KAAKI,OAAO,aAAaJ,KAAKK,QAAQ,IAAI;EAE5H;AACF;AAEO,IAAMC,wBAAN,cAAoCR,UAAUC,OAAO,uBAAA,EAAA;EAC1D,YAAYC,MAMT;AACD,UACE,8BAA8BA,KAAKO,eAAe,mBAAmBP,KAAKQ,iBAAiB,YAAYR,KAAKC,MAAM,YAAYD,KAAKI,OAAO,aAAaJ,KAAKK,QAAQ,IAAI;EAE5K;AACF;;;AC5BA,YAAYI,eAAe;AAE3B,YAAYC,Y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AAIE;AAC1E,QAAIH,QAAQJ,SAASoD,eAAeC,iBAAiBhD,WAAW;AAC9D,aAAcQ,aAAK,IAAIC,MAAM,gCAAgCsC,WAAAA,mBAA8B/C,SAAAA,EAAW,CAAA;IACxG;AACA,WAAcU,gBAAQX,OAAAA;EACxB;AACF;",
|
|
6
|
-
"names": ["BaseError", "DuplicateBlockPositionError", "BaseError", "extend", "args", "feedId", "position", "DuplicateBlockLamportTimestampError", "actorId", "sequence", "PositionConflictError", "currentPosition", "requestedPosition", "SqlClient", "Effect", "Event", "assertArgument", "FeedProtocol", "SqlTransaction", "FeedCursor", "FeedProtocol", "isWellKnownNamespace", "FeedStore", "options", "onNewBlocks", "Event", "migrate", "fn", "gen", "sql", "SqlClient", "pipe", "withSpan", "spaceId", "feedId", "namespace", "rows", "length", "feedPrivateId", "newRows", "token", "crypto", "randomUUID", "replace", "slice", "query", "request", "feedIds", "cursorInsertionId", "cursorToken", "die", "Error", "position", "undefined", "cursor", "unpositionedOnly", "insertionId", "decodeCursor", "isNaN", "validCursorToken", "subscriptionId", "feedPrivateIds", "expiresAt", "Date", "now", "privateIds", "JSON", "parse", "feedRows", "in", "map", "r", "requestId", "blocks", "nextCursor", "encodeCursor", "hasMore", "feedNamespace", "filter", "orderBy", "requestLimit", "limit", "queryLimit", "row", "data", "Uint8Array", "lastBlock", "subscribe", "ttl", "forEach", "concurrency", "stringify", "getSyncState", "opts", "lastPulledPosition", "setSyncState", "positionFeedIdByKey", "Map", "lamportFeedIdByKey", "block", "get", "assignPositions", "positionKey", "has", "fail", "DuplicateBlockPositionError", "set", "lamportKey", "actorId", "sequence", "DuplicateBlockLamportTimestampError", "lamportConditions", "existingLamports", "or", "lamportConflict", "key", "positionedBlocks", "positionConditions", "existingPositions", "positionConflict", "append", "assertArgument", "sqlTransaction", "SqlTransaction", "positions", "withTransaction", "feedKeys", "entries", "id", "maxPositions", "maxPosResult", "maxPos", "positionToInsert", "currentMax", "push", "prevSequence", "prevActorId", "timestamp", "emit", "appendLocal", "messages", "msg", "lastSeqs", "lastBlockResult", "currentSeqs", "blocksBySpaceNamespace", "inFlight", "localActorId", "spaceNamespaceKey", "values", "setPosition", "existing", "current", "PositionConflictError", "currentPosition", "requestedPosition", "make", "split", "Number", "Effect", "SyncServer", "options", "peerId", "feedStore", "sendMessage", "handleMessage", "message", "self", "recipientPeerId", "senderPeerId", "withPeerIds", "payload", "_tag", "req", "gen", "response", "query", "pipe", "catchAll", "err", "Error", "String", "append", "void", "Array", "Deferred", "Effect", "SyncClient", "Map", "options", "peerId", "serverPeerId", "feedStore", "sendMessage", "payload", "_tag", "senderPeerId", "recipientPeerId", "handleMessage", "message", "requestId", "String", "undefined", "void", "deferred", "get", "delete", "andThen", "fail", "Error", "succeed", "pull", "opts", "self", "gen", "lastPulledPosition", "getSyncState", "spaceId", "feedNamespace", "crypto", "randomUUID", "make", "set", "request", "position", "limit", "await", "response", "blocks", "length", "done", "append", "maxPulledPosition", "reduce", "max", "block", "setSyncState", "push", "unpositioned", "query", "unpositionedOnly", "setPosition", "zipWith", "positions", "feedId", "actorId", "sequence", "expectedTag", "requestIdMsg"]
|
|
7
|
-
}
|