@dxos/feed 0.8.4-main.c85a9c8dae → 0.8.4-main.cb12b3f963
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/dist/lib/neutral/{chunk-2ENONWPH.mjs → chunk-7BI3SMZT.mjs} +89 -24
- package/dist/lib/neutral/chunk-7BI3SMZT.mjs.map +7 -0
- package/dist/lib/neutral/index.mjs +1 -1
- package/dist/lib/neutral/meta.json +1 -1
- package/dist/lib/neutral/testing/index.mjs +8 -7
- package/dist/lib/neutral/testing/index.mjs.map +3 -3
- package/dist/types/src/errors.d.ts +6 -6
- package/dist/types/src/errors.d.ts.map +1 -1
- package/dist/types/src/feed-store.d.ts +12 -1
- 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 +5 -5
- package/dist/types/src/testing/test-builder.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +15 -20
- package/src/feed-store.test.ts +3 -1
- package/src/feed-store.ts +71 -10
- package/src/sync-client.ts +56 -17
- package/src/sync-server.ts +8 -4
- package/src/testing/test-builder.ts +7 -7
- package/dist/lib/neutral/chunk-2ENONWPH.mjs.map +0 -7
|
@@ -77,7 +77,9 @@ var FeedStore = class {
|
|
|
77
77
|
const rows = yield* sql`
|
|
78
78
|
SELECT feedPrivateId FROM feeds WHERE spaceId = ${spaceId} AND feedId = ${feedId}
|
|
79
79
|
`;
|
|
80
|
-
if (rows.length > 0)
|
|
80
|
+
if (rows.length > 0) {
|
|
81
|
+
return rows[0].feedPrivateId;
|
|
82
|
+
}
|
|
81
83
|
const newRows = yield* sql`
|
|
82
84
|
INSERT INTO feeds (spaceId, feedId, feedNamespace) VALUES (${spaceId}, ${feedId}, ${namespace}) RETURNING feedPrivateId
|
|
83
85
|
`;
|
|
@@ -89,7 +91,9 @@ var FeedStore = class {
|
|
|
89
91
|
#ensureCursorToken = Effect.fn("Feed.ensureCursorToken")((spaceId) => Effect.gen(this, function* () {
|
|
90
92
|
const sql = yield* SqlClient.SqlClient;
|
|
91
93
|
const rows = yield* sql`SELECT token FROM cursor_tokens WHERE spaceId = ${spaceId}`;
|
|
92
|
-
if (rows.length > 0)
|
|
94
|
+
if (rows.length > 0) {
|
|
95
|
+
return rows[0].token;
|
|
96
|
+
}
|
|
93
97
|
const token = crypto.randomUUID().replace(/-/g, "").slice(0, 6);
|
|
94
98
|
yield* sql`INSERT INTO cursor_tokens (spaceId, token) VALUES (${spaceId}, ${token})`;
|
|
95
99
|
return token;
|
|
@@ -461,6 +465,19 @@ var FeedStore = class {
|
|
|
461
465
|
setPosition = (request) => Effect.gen(this, function* () {
|
|
462
466
|
const sql = yield* SqlClient.SqlClient;
|
|
463
467
|
for (const block of request.blocks) {
|
|
468
|
+
const updated = yield* sql`
|
|
469
|
+
UPDATE blocks SET position = ${block.position}
|
|
470
|
+
WHERE feedPrivateId = (
|
|
471
|
+
SELECT feedPrivateId FROM feeds
|
|
472
|
+
WHERE spaceId = ${request.spaceId} AND feedId = ${block.feedId} AND feedNamespace = ${block.feedNamespace}
|
|
473
|
+
)
|
|
474
|
+
AND actorId = ${block.actorId} AND sequence = ${block.sequence}
|
|
475
|
+
AND (position IS NULL OR position = ${block.position})
|
|
476
|
+
RETURNING position
|
|
477
|
+
`;
|
|
478
|
+
if (updated.length > 0) {
|
|
479
|
+
continue;
|
|
480
|
+
}
|
|
464
481
|
const existing = yield* sql`
|
|
465
482
|
SELECT position FROM blocks
|
|
466
483
|
WHERE feedPrivateId = (
|
|
@@ -479,16 +496,39 @@ var FeedStore = class {
|
|
|
479
496
|
requestedPosition: block.position
|
|
480
497
|
}));
|
|
481
498
|
}
|
|
482
|
-
yield* sql`
|
|
483
|
-
UPDATE blocks SET position = ${block.position}
|
|
484
|
-
WHERE feedPrivateId = (
|
|
485
|
-
SELECT feedPrivateId FROM feeds
|
|
486
|
-
WHERE spaceId = ${request.spaceId} AND feedId = ${block.feedId} AND feedNamespace = ${block.feedNamespace}
|
|
487
|
-
)
|
|
488
|
-
AND actorId = ${block.actorId} AND sequence = ${block.sequence}
|
|
489
|
-
`;
|
|
490
499
|
}
|
|
491
500
|
}).pipe(Effect.withSpan("FeedStore.setPosition"));
|
|
501
|
+
/**
|
|
502
|
+
* Gets all feeds and their blocks for a space, organized by feed ID and namespace.
|
|
503
|
+
* Used for space archive export.
|
|
504
|
+
*/
|
|
505
|
+
getAllFeedsForSpace = (opts) => Effect.gen(this, function* () {
|
|
506
|
+
const sql = yield* SqlClient.SqlClient;
|
|
507
|
+
const feeds = yield* sql`
|
|
508
|
+
SELECT DISTINCT feedId, feedNamespace FROM feeds WHERE spaceId = ${opts.spaceId}
|
|
509
|
+
`;
|
|
510
|
+
const result = [];
|
|
511
|
+
for (const feed of feeds) {
|
|
512
|
+
const blocks = yield* sql`
|
|
513
|
+
SELECT blocks.*, feeds.feedId, feeds.feedNamespace
|
|
514
|
+
FROM blocks
|
|
515
|
+
JOIN feeds ON blocks.feedPrivateId = feeds.feedPrivateId
|
|
516
|
+
WHERE feeds.spaceId = ${opts.spaceId}
|
|
517
|
+
AND feeds.feedId = ${feed.feedId}
|
|
518
|
+
AND feeds.feedNamespace = ${feed.feedNamespace}
|
|
519
|
+
ORDER BY blocks.sequence ASC
|
|
520
|
+
`;
|
|
521
|
+
result.push({
|
|
522
|
+
feedId: feed.feedId,
|
|
523
|
+
feedNamespace: feed.feedNamespace,
|
|
524
|
+
blocks: blocks.map((row) => ({
|
|
525
|
+
...row,
|
|
526
|
+
data: new Uint8Array(row.data)
|
|
527
|
+
}))
|
|
528
|
+
});
|
|
529
|
+
}
|
|
530
|
+
return result;
|
|
531
|
+
}).pipe(Effect.withSpan("FeedStore.getAllFeedsForSpace"));
|
|
492
532
|
};
|
|
493
533
|
var encodeCursor = (token, insertionId) => FeedCursor.make(`${token}|${insertionId}`);
|
|
494
534
|
var decodeCursor = (cursor) => {
|
|
@@ -513,7 +553,7 @@ var SyncServer = class {
|
|
|
513
553
|
/**
|
|
514
554
|
* Receive a message from a client. Handles QueryRequest and AppendRequest; sends response via sendMessage with correct peer ids.
|
|
515
555
|
*/
|
|
516
|
-
handleMessage(message) {
|
|
556
|
+
handleMessage(ctx, message) {
|
|
517
557
|
const self = this;
|
|
518
558
|
const recipientPeerId = message.senderPeerId;
|
|
519
559
|
const withPeerIds = (payload) => ({
|
|
@@ -526,11 +566,11 @@ var SyncServer = class {
|
|
|
526
566
|
const req = message;
|
|
527
567
|
return Effect2.gen(function* () {
|
|
528
568
|
const response = yield* self.#feedStore.query(req);
|
|
529
|
-
yield* self.#sendMessage(withPeerIds({
|
|
569
|
+
yield* self.#sendMessage(ctx, withPeerIds({
|
|
530
570
|
_tag: "QueryResponse",
|
|
531
571
|
...response
|
|
532
572
|
}));
|
|
533
|
-
}).pipe(Effect2.catchAll((err) => self.#sendMessage(withPeerIds({
|
|
573
|
+
}).pipe(Effect2.catchAll((err) => self.#sendMessage(ctx, withPeerIds({
|
|
534
574
|
_tag: "Error",
|
|
535
575
|
message: err instanceof Error ? err.message : String(err)
|
|
536
576
|
}))));
|
|
@@ -539,11 +579,11 @@ var SyncServer = class {
|
|
|
539
579
|
const req = message;
|
|
540
580
|
return Effect2.gen(function* () {
|
|
541
581
|
const response = yield* self.#feedStore.append(req);
|
|
542
|
-
yield* self.#sendMessage(withPeerIds({
|
|
582
|
+
yield* self.#sendMessage(ctx, withPeerIds({
|
|
543
583
|
_tag: "AppendResponse",
|
|
544
584
|
...response
|
|
545
585
|
}));
|
|
546
|
-
}).pipe(Effect2.catchAll((err) => self.#sendMessage(withPeerIds({
|
|
586
|
+
}).pipe(Effect2.catchAll((err) => self.#sendMessage(ctx, withPeerIds({
|
|
547
587
|
_tag: "Error",
|
|
548
588
|
message: err instanceof Error ? err.message : String(err)
|
|
549
589
|
}))));
|
|
@@ -558,6 +598,7 @@ var SyncServer = class {
|
|
|
558
598
|
import * as Array from "effect/Array";
|
|
559
599
|
import * as Deferred from "effect/Deferred";
|
|
560
600
|
import * as Effect3 from "effect/Effect";
|
|
601
|
+
import { ContextDisposedError } from "@dxos/context";
|
|
561
602
|
var SyncClient = class {
|
|
562
603
|
#peerId;
|
|
563
604
|
#serverPeerId;
|
|
@@ -589,16 +630,20 @@ var SyncClient = class {
|
|
|
589
630
|
*/
|
|
590
631
|
handleMessage(message) {
|
|
591
632
|
const requestId = "requestId" in message && message.requestId != null ? String(message.requestId) : void 0;
|
|
592
|
-
if (requestId == null)
|
|
633
|
+
if (requestId == null) {
|
|
634
|
+
return Effect3.void;
|
|
635
|
+
}
|
|
593
636
|
const deferred = this.#handlers.get(requestId);
|
|
594
|
-
if (deferred == null)
|
|
637
|
+
if (deferred == null) {
|
|
638
|
+
return Effect3.void;
|
|
639
|
+
}
|
|
595
640
|
this.#handlers.delete(requestId);
|
|
596
641
|
if (message._tag === "Error") {
|
|
597
642
|
return Effect3.andThen(Deferred.fail(deferred, new Error(message.message)), () => Effect3.void);
|
|
598
643
|
}
|
|
599
644
|
return Effect3.andThen(Deferred.succeed(deferred, message), () => Effect3.void);
|
|
600
645
|
}
|
|
601
|
-
pull(opts) {
|
|
646
|
+
pull(ctx, opts) {
|
|
602
647
|
const self = this;
|
|
603
648
|
return Effect3.gen(function* () {
|
|
604
649
|
const lastPulledPosition = yield* self.#feedStore.getSyncState({
|
|
@@ -608,6 +653,13 @@ var SyncClient = class {
|
|
|
608
653
|
const requestId = crypto.randomUUID();
|
|
609
654
|
const deferred = yield* Deferred.make();
|
|
610
655
|
self.#handlers.set(requestId, deferred);
|
|
656
|
+
const cleanupDispose = ctx.disposed ? () => {
|
|
657
|
+
} : ctx.onDispose(() => {
|
|
658
|
+
Effect3.runFork(Deferred.fail(deferred, new ContextDisposedError()));
|
|
659
|
+
});
|
|
660
|
+
if (ctx.disposed) {
|
|
661
|
+
yield* Deferred.fail(deferred, new ContextDisposedError());
|
|
662
|
+
}
|
|
611
663
|
const request = {
|
|
612
664
|
_tag: "QueryRequest",
|
|
613
665
|
requestId,
|
|
@@ -616,8 +668,11 @@ var SyncClient = class {
|
|
|
616
668
|
position: lastPulledPosition,
|
|
617
669
|
limit: opts.limit
|
|
618
670
|
};
|
|
619
|
-
yield* self.#sendMessage(self.#withPeerIds(request));
|
|
620
|
-
const message = yield* Deferred.await(deferred)
|
|
671
|
+
yield* self.#sendMessage(ctx, self.#withPeerIds(request));
|
|
672
|
+
const message = yield* Effect3.ensuring(Deferred.await(deferred), Effect3.sync(() => {
|
|
673
|
+
cleanupDispose();
|
|
674
|
+
self.#handlers.delete(requestId);
|
|
675
|
+
}));
|
|
621
676
|
const response = yield* self.#expectResponse(requestId, message, "QueryResponse");
|
|
622
677
|
if (response.blocks.length === 0) {
|
|
623
678
|
return {
|
|
@@ -640,7 +695,7 @@ var SyncClient = class {
|
|
|
640
695
|
};
|
|
641
696
|
});
|
|
642
697
|
}
|
|
643
|
-
push(opts) {
|
|
698
|
+
push(ctx, opts) {
|
|
644
699
|
const self = this;
|
|
645
700
|
return Effect3.gen(function* () {
|
|
646
701
|
const unpositioned = yield* self.#feedStore.query({
|
|
@@ -657,6 +712,13 @@ var SyncClient = class {
|
|
|
657
712
|
const requestId = crypto.randomUUID();
|
|
658
713
|
const deferred = yield* Deferred.make();
|
|
659
714
|
self.#handlers.set(requestId, deferred);
|
|
715
|
+
const cleanupDispose = ctx.disposed ? () => {
|
|
716
|
+
} : ctx.onDispose(() => {
|
|
717
|
+
Effect3.runFork(Deferred.fail(deferred, new ContextDisposedError()));
|
|
718
|
+
});
|
|
719
|
+
if (ctx.disposed) {
|
|
720
|
+
yield* Deferred.fail(deferred, new ContextDisposedError());
|
|
721
|
+
}
|
|
660
722
|
const request = {
|
|
661
723
|
_tag: "AppendRequest",
|
|
662
724
|
requestId,
|
|
@@ -664,8 +726,11 @@ var SyncClient = class {
|
|
|
664
726
|
feedNamespace: opts.feedNamespace,
|
|
665
727
|
blocks: unpositioned.blocks
|
|
666
728
|
};
|
|
667
|
-
yield* self.#sendMessage(self.#withPeerIds(request));
|
|
668
|
-
const message = yield* Deferred.await(deferred)
|
|
729
|
+
yield* self.#sendMessage(ctx, self.#withPeerIds(request));
|
|
730
|
+
const message = yield* Effect3.ensuring(Deferred.await(deferred), Effect3.sync(() => {
|
|
731
|
+
cleanupDispose();
|
|
732
|
+
self.#handlers.delete(requestId);
|
|
733
|
+
}));
|
|
669
734
|
const response = yield* self.#expectResponse(requestId, message, "AppendResponse");
|
|
670
735
|
yield* self.#feedStore.setPosition({
|
|
671
736
|
spaceId: opts.spaceId,
|
|
@@ -700,4 +765,4 @@ export {
|
|
|
700
765
|
SyncServer,
|
|
701
766
|
SyncClient
|
|
702
767
|
};
|
|
703
|
-
//# sourceMappingURL=chunk-
|
|
768
|
+
//# sourceMappingURL=chunk-7BI3SMZT.mjs.map
|
|
@@ -0,0 +1,7 @@
|
|
|
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 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 message: `Block already has position ${args.currentPosition}, cannot set to ${args.requestedPosition} (feedId=${args.feedId} actorId=${args.actorId} sequence=${args.sequence}).`,\n context: args,\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 { 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) {\n return rows[0].feedPrivateId;\n }\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) {\n return rows[0].token;\n }\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 * Returns the number of stored blocks for a single feed in a space/namespace.\n * Intended as a low-level primitive for callers (for example Cloudflare Worker code)\n * that need to make retention decisions under constrained storage resources.\n */\n countBlocks = (opts: {\n spaceId: SpaceId;\n feedNamespace: string;\n feedId: 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<{ count: number }>`\n SELECT COUNT(*) AS count\n FROM blocks\n JOIN feeds ON blocks.feedPrivateId = feeds.feedPrivateId\n WHERE feeds.spaceId = ${opts.spaceId}\n AND feeds.feedNamespace = ${opts.feedNamespace}\n AND feeds.feedId = ${opts.feedId}\n `;\n return rows[0]?.count ?? 0;\n }).pipe(Effect.withSpan('FeedStore.countBlocks'));\n\n /**\n * Deletes the oldest blocks for a single feed in a space/namespace.\n * This API intentionally does not enforce any retention policy (such as max size);\n * callers decide when and how much to prune, which is useful for constrained\n * environments like Cloudflare Workers.\n *\n * @returns Number of deleted rows.\n */\n deleteOldestBlocks = (opts: {\n spaceId: SpaceId;\n feedNamespace: string;\n feedId: string;\n count: number;\n }): Effect.Effect<number, SqlError.SqlError, SqlClient.SqlClient> =>\n Effect.gen(this, function* () {\n const sql = yield* SqlClient.SqlClient;\n if (opts.count <= 0) {\n return 0;\n }\n\n const deletedRows = yield* sql<{ insertionId: number }>`\n DELETE FROM blocks\n WHERE insertionId IN (\n SELECT blocks.insertionId\n FROM blocks\n JOIN feeds ON blocks.feedPrivateId = feeds.feedPrivateId\n WHERE feeds.spaceId = ${opts.spaceId}\n AND feeds.feedNamespace = ${opts.feedNamespace}\n AND feeds.feedId = ${opts.feedId}\n ORDER BY blocks.insertionId ASC\n LIMIT ${opts.count}\n )\n RETURNING insertionId\n `;\n\n return deletedRows.length;\n }).pipe(Effect.withSpan('FeedStore.deleteOldestBlocks'));\n\n /**\n * Appends blocks for a space/namespace and optionally assigns global positions.\n */\n append = (\n request: AppendRequest,\n ): Effect.Effect<AppendResponse, SqlError.SqlError, SqlClient.SqlClient | SqlTransaction.SqlTransaction> =>\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 // 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<Block[], SqlError.SqlError, SqlClient.SqlClient | SqlTransaction.SqlTransaction> =>\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 and assign returned positions.\n const positionByBlock = new Map<Block, number | null>();\n for (const { spaceId, feedNamespace, blocks: batchBlocks } of blocksBySpaceNamespace.values()) {\n const { positions } = yield* this.append({\n requestId: 'local-append',\n blocks: batchBlocks,\n spaceId,\n feedNamespace,\n });\n for (let i = 0; i < batchBlocks.length; i++) {\n positionByBlock.set(batchBlocks[i], positions[i] ?? null);\n }\n }\n\n return blocks.map((block) => ({\n ...block,\n position: positionByBlock.get(block) ?? block.position,\n }));\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 // Fold the conflict check into the UPDATE itself: only write when the row is\n // unset or already at the requested position. RETURNING tells us whether the\n // write took effect, so we avoid the per-block SELECT round-trip on the\n // common path. Conflicts (rare) take the slow path below.\n const updated = yield* sql<{ position: number | null }>`\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 AND (position IS NULL OR position = ${block.position})\n RETURNING position\n `;\n if (updated.length > 0) {\n continue;\n }\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 }\n }).pipe(Effect.withSpan('FeedStore.setPosition'));\n\n /**\n * Gets all feeds and their blocks for a space, organized by feed ID and namespace.\n * Used for space archive export.\n */\n getAllFeedsForSpace = (opts: {\n spaceId: SpaceId;\n }): Effect.Effect<\n Array<{\n feedId: string;\n feedNamespace: string;\n blocks: Block[];\n }>,\n SqlError.SqlError,\n SqlClient.SqlClient\n > =>\n Effect.gen(this, function* () {\n const sql = yield* SqlClient.SqlClient;\n\n const feeds = yield* sql<{ feedId: string; feedNamespace: string }>`\n SELECT DISTINCT feedId, feedNamespace FROM feeds WHERE spaceId = ${opts.spaceId}\n `;\n\n const result: Array<{ feedId: string; feedNamespace: string; blocks: Block[] }> = [];\n\n for (const feed of feeds) {\n const blocks = yield* sql<Block>`\n SELECT blocks.*, feeds.feedId, feeds.feedNamespace\n FROM blocks\n JOIN feeds ON blocks.feedPrivateId = feeds.feedPrivateId\n WHERE feeds.spaceId = ${opts.spaceId}\n AND feeds.feedId = ${feed.feedId}\n AND feeds.feedNamespace = ${feed.feedNamespace}\n ORDER BY blocks.sequence ASC\n `;\n\n result.push({\n feedId: feed.feedId,\n feedNamespace: feed.feedNamespace,\n blocks: blocks.map((row) => ({\n ...row,\n data: new Uint8Array(row.data),\n })),\n });\n }\n\n return result;\n }).pipe(Effect.withSpan('FeedStore.getAllFeedsForSpace'));\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 { Context } from '@dxos/context';\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: (ctx: Context, 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: SyncServerOptions['sendMessage'];\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 ctx: Context,\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(ctx, withPeerIds({ _tag: 'QueryResponse', ...response }));\n }).pipe(\n Effect.catchAll((err: unknown) =>\n self.#sendMessage(\n ctx,\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(ctx, withPeerIds({ _tag: 'AppendResponse', ...response }));\n }).pipe(\n Effect.catchAll((err: unknown) =>\n self.#sendMessage(\n ctx,\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 { Context, ContextDisposedError } from '@dxos/context';\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: (ctx: Context, 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) {\n return Effect.void;\n }\n const deferred = this.#handlers.get(requestId);\n if (deferred == null) {\n return Effect.void;\n }\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(\n ctx: Context,\n opts: {\n spaceId: SpaceId;\n feedNamespace: string;\n limit?: number;\n },\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 cleanupDispose = ctx.disposed\n ? () => {}\n : ctx.onDispose(() => {\n Effect.runFork(Deferred.fail(deferred, new ContextDisposedError()));\n });\n if (ctx.disposed) {\n yield* Deferred.fail(deferred, new ContextDisposedError());\n }\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(ctx, self.#withPeerIds(request));\n const message = yield* Effect.ensuring(\n Deferred.await(deferred),\n Effect.sync(() => {\n cleanupDispose();\n self.#handlers.delete(requestId);\n }),\n );\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(\n ctx: Context,\n opts: {\n spaceId: SpaceId;\n feedNamespace: string;\n limit?: number;\n },\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 cleanupDispose = ctx.disposed\n ? () => {}\n : ctx.onDispose(() => {\n Effect.runFork(Deferred.fail(deferred, new ContextDisposedError()));\n });\n if (ctx.disposed) {\n yield* Deferred.fail(deferred, new ContextDisposedError());\n }\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(ctx, self.#withPeerIds(request));\n const message = yield* Effect.ensuring(\n Deferred.await(deferred),\n Effect.sync(() => {\n cleanupDispose();\n self.#handlers.delete(requestId);\n }),\n );\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,wBAAN,cAAoCD,UAAUE,OAAO,uBAAA,EAAA;EAC1D,YAAYC,MAMT;AACD,UAAM;MACJC,SAAS,8BAA8BD,KAAKE,eAAe,mBAAmBF,KAAKG,iBAAiB,YAAYH,KAAKI,MAAM,YAAYJ,KAAKK,OAAO,aAAaL,KAAKM,QAAQ;MAC7KC,SAASP;IACX,CAAA;EACF;AACF;;;ACfA,YAAYQ,eAAe;AAE3B,YAAYC,YAAY;AAExB,SAASC,aAAa;AACtB,SAASC,sBAAsB;AAE/B,SAASC,oBAAoB;AAC7B,SAASC,sBAAsB;AAO/B,IAAMC,aAAaC,aAAaD;AAEhC,IAAME,uBAAuBD,aAAaC;AAuBnC,IAAMC,YAAN,MAAMA;EACF;EAET,YAAYC,SAA2B;AACrC,SAAK,WAAWA;EAClB;;;;EAKSC,cAAc,IAAIC,MAAAA;;;;EAK3BC,UAAiBC,UAAG,mBAAA,EAAqB,MAChCC,WAAI,aAAA;AACT,UAAMC,MAAM,OAAiBC;AAG7B,WAAOD;;;;;;AAMP,WAAOA;AAGP,WAAOA;;;;;;;;;;;;AAYP,WAAOA;AACP,WAAOA;AAGP,WAAOA;;;;;AAOP,WAAOA;;;;AAMP,WAAOA;;;;;;EAMT,CAAA,EAAGE,KAAYC,gBAAS,mBAAA,CAAA,CAAA;;;;EAM1B,cAAqBL,UAAG,iBAA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U,aAAaV;MACvB;AACA,aAAOrB,KAAK,aAAaF,KAAKE,KAAK,aAAac,OAAAA,CAAAA;AAChD,YAAM7B,UAAU,OAAcgC,iBACnBC,eAAM5B,QAAAA,GACR6B,aAAK,MAAA;AACVT,uBAAAA;AACAV,aAAK,UAAUR,OAAON,SAAAA;MACxB,CAAA,CAAA;AAEF,YAAMkC,WAAW,OAAOpB,KAAK,gBAAgCd,WAAWD,SAAS,gBAAA;AACjF,aAAOe,KAAK,WAAWkC,YAAY;QACjC9B,SAASL,KAAKK;QACdiB,QAAcc,cAAQf,SAASgB,WAAWL,aAAaV,QAAQ,CAACN,UAAUa,WAAW;UACnFS,QAAQT,MAAMS;UACdhC,eAAeN,KAAKM;UACpBiC,SAASV,MAAMU;UACfC,UAAUX,MAAMW;UAChBxB;QACF,EAAA;MACF,CAAA;AACA,aAAO;QAAEQ,MAAM;MAAM;IACvB,CAAA;EACF;EAEA,gBAAmBrC,WAAmBD,SAA0BuD,aAAmB;AACjF,QAAIvD,QAAQJ,SAAS,SAAS;AAC5B,aAAca,aAAK,IAAIC,MAAMV,QAAQA,OAAO,CAAA;IAC9C;AACA,UAAMwD,eAAe,eAAexD,UAAUE,OAAOF,QAAQC,SAAS,IAAIE;AAC1E,QAAIH,QAAQJ,SAAS2D,eAAeC,iBAAiBvD,WAAW;AAC9D,aAAcQ,aAAK,IAAIC,MAAM,gCAAgC6C,WAAAA,mBAA8BtD,SAAAA,EAAW,CAAA;IACxG;AACA,WAAcU,gBAAQX,OAAAA;EACxB;AACF;",
|
|
6
|
+
"names": ["BaseError", "PositionConflictError", "extend", "args", "message", "currentPosition", "requestedPosition", "feedId", "actorId", "sequence", "context", "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", "countBlocks", "count", "deleteOldestBlocks", "deletedRows", "append", "assertArgument", "block", "sqlTransaction", "SqlTransaction", "positions", "withTransaction", "feedKeys", "Map", "key", "has", "set", "entries", "id", "maxPositions", "assignPositions", "maxPosResult", "maxPos", "get", "positionToInsert", "currentMax", "push", "sequence", "actorId", "prevSequence", "prevActorId", "timestamp", "emit", "appendLocal", "messages", "msg", "lastSeqs", "lastBlockResult", "currentSeqs", "blocksBySpaceNamespace", "inFlight", "localActorId", "spaceNamespaceKey", "positionByBlock", "batchBlocks", "values", "i", "setPosition", "updated", "existing", "current", "fail", "PositionConflictError", "currentPosition", "requestedPosition", "getAllFeedsForSpace", "feeds", "result", "feed", "make", "split", "Number", "Effect", "SyncServer", "options", "peerId", "feedStore", "sendMessage", "handleMessage", "ctx", "message", "self", "recipientPeerId", "senderPeerId", "withPeerIds", "payload", "_tag", "req", "gen", "response", "query", "pipe", "catchAll", "err", "Error", "String", "append", "void", "Array", "Deferred", "Effect", "ContextDisposedError", "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", "ctx", "opts", "self", "gen", "lastPulledPosition", "getSyncState", "spaceId", "feedNamespace", "crypto", "randomUUID", "make", "set", "cleanupDispose", "disposed", "onDispose", "runFork", "request", "position", "limit", "ensuring", "await", "sync", "response", "blocks", "length", "done", "append", "maxPulledPosition", "reduce", "max", "block", "setSyncState", "push", "unpositioned", "query", "unpositionedOnly", "setPosition", "zipWith", "positions", "feedId", "actorId", "sequence", "expectedTag", "requestIdMsg"]
|
|
7
|
+
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"inputs":{"src/errors.ts":{"bytes":
|
|
1
|
+
{"inputs":{"src/errors.ts":{"bytes":1997,"imports":[{"path":"@dxos/errors","kind":"import-statement","external":true}],"format":"esm"},"src/feed-store.ts":{"bytes":86376,"imports":[{"path":"@effect/sql/SqlClient","kind":"import-statement","external":true},{"path":"effect/Effect","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/protocols","kind":"import-statement","external":true},{"path":"@dxos/sql-sqlite","kind":"import-statement","external":true},{"path":"src/errors.ts","kind":"import-statement","original":"./errors"}],"format":"esm"},"src/sync-server.ts":{"bytes":9358,"imports":[{"path":"effect/Effect","kind":"import-statement","external":true}],"format":"esm"},"src/sync-client.ts":{"bytes":25245,"imports":[{"path":"effect/Array","kind":"import-statement","external":true},{"path":"effect/Deferred","kind":"import-statement","external":true},{"path":"effect/Effect","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true}],"format":"esm"},"src/index.ts":{"bytes":658,"imports":[{"path":"src/feed-store.ts","kind":"import-statement","original":"./feed-store"},{"path":"src/errors.ts","kind":"import-statement","original":"./errors"},{"path":"src/sync-server.ts","kind":"import-statement","original":"./sync-server"},{"path":"src/sync-client.ts","kind":"import-statement","original":"./sync-client"}],"format":"esm"},"src/testing/test-builder.ts":{"bytes":23925,"imports":[{"path":"@effect/sql/Statement","kind":"import-statement","external":true},{"path":"effect/Array","kind":"import-statement","external":true},{"path":"effect/Effect","kind":"import-statement","external":true},{"path":"effect/Layer","kind":"import-statement","external":true},{"path":"effect/ManagedRuntime","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/effect","kind":"import-statement","external":true},{"path":"@dxos/protocols","kind":"import-statement","external":true},{"path":"@dxos/sql-sqlite","kind":"import-statement","external":true},{"path":"@dxos/sql-sqlite/platform","kind":"import-statement","external":true},{"path":"@dxos/sql-sqlite/SqlExport","kind":"import-statement","external":true},{"path":"src/feed-store.ts","kind":"import-statement","original":"../feed-store"},{"path":"src/sync-client.ts","kind":"import-statement","original":"../sync-client"},{"path":"src/sync-server.ts","kind":"import-statement","original":"../sync-server"}],"format":"esm"},"src/testing/index.ts":{"bytes":388,"imports":[{"path":"src/testing/test-builder.ts","kind":"import-statement","original":"./test-builder"}],"format":"esm"}},"outputs":{"dist/lib/neutral/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":93},"dist/lib/neutral/index.mjs":{"imports":[{"path":"dist/lib/neutral/chunk-7BI3SMZT.mjs","kind":"import-statement"}],"exports":["FeedStore","PositionConflictError","SyncClient","SyncServer"],"entryPoint":"src/index.ts","inputs":{"src/index.ts":{"bytesInOutput":0}},"bytes":217},"dist/lib/neutral/testing/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":11479},"dist/lib/neutral/testing/index.mjs":{"imports":[{"path":"dist/lib/neutral/chunk-7BI3SMZT.mjs","kind":"import-statement"},{"path":"@effect/sql/Statement","kind":"import-statement","external":true},{"path":"effect/Array","kind":"import-statement","external":true},{"path":"effect/Effect","kind":"import-statement","external":true},{"path":"effect/Layer","kind":"import-statement","external":true},{"path":"effect/ManagedRuntime","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/effect","kind":"import-statement","external":true},{"path":"@dxos/protocols","kind":"import-statement","external":true},{"path":"@dxos/sql-sqlite","kind":"import-statement","external":true},{"path":"@dxos/sql-sqlite/platform","kind":"import-statement","external":true},{"path":"@dxos/sql-sqlite/SqlExport","kind":"import-statement","external":true}],"exports":["TestBuilder","TestPeer"],"entryPoint":"src/testing/index.ts","inputs":{"src/testing/test-builder.ts":{"bytesInOutput":5447},"src/testing/index.ts":{"bytesInOutput":0}},"bytes":5633},"dist/lib/neutral/chunk-7BI3SMZT.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":60209},"dist/lib/neutral/chunk-7BI3SMZT.mjs":{"imports":[{"path":"@dxos/errors","kind":"import-statement","external":true},{"path":"@effect/sql/SqlClient","kind":"import-statement","external":true},{"path":"effect/Effect","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/protocols","kind":"import-statement","external":true},{"path":"@dxos/sql-sqlite","kind":"import-statement","external":true},{"path":"effect/Effect","kind":"import-statement","external":true},{"path":"effect/Array","kind":"import-statement","external":true},{"path":"effect/Deferred","kind":"import-statement","external":true},{"path":"effect/Effect","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true}],"exports":["FeedStore","PositionConflictError","SyncClient","SyncServer"],"inputs":{"src/errors.ts":{"bytesInOutput":382},"src/feed-store.ts":{"bytesInOutput":21049},"src/sync-server.ts":{"bytesInOutput":1685},"src/sync-client.ts":{"bytesInOutput":5584}},"bytes":28907}}}
|
|
@@ -2,7 +2,7 @@ import {
|
|
|
2
2
|
FeedStore,
|
|
3
3
|
SyncClient,
|
|
4
4
|
SyncServer
|
|
5
|
-
} from "../chunk-
|
|
5
|
+
} from "../chunk-7BI3SMZT.mjs";
|
|
6
6
|
|
|
7
7
|
// src/testing/test-builder.ts
|
|
8
8
|
import * as Statement from "@effect/sql/Statement";
|
|
@@ -10,12 +10,13 @@ import * as Array from "effect/Array";
|
|
|
10
10
|
import * as Effect from "effect/Effect";
|
|
11
11
|
import * as Layer from "effect/Layer";
|
|
12
12
|
import * as ManagedRuntime from "effect/ManagedRuntime";
|
|
13
|
-
import { Resource } from "@dxos/context";
|
|
13
|
+
import { Context, Resource } from "@dxos/context";
|
|
14
14
|
import { RuntimeProvider } from "@dxos/effect";
|
|
15
15
|
import { FeedProtocol } from "@dxos/protocols";
|
|
16
16
|
import { SqlTransaction } from "@dxos/sql-sqlite";
|
|
17
17
|
import { layerMemory } from "@dxos/sql-sqlite/platform";
|
|
18
18
|
import * as SqlExport from "@dxos/sql-sqlite/SqlExport";
|
|
19
|
+
var __dxlog_file = "/__w/dxos/dxos/packages/core/echo/feed/src/testing/test-builder.ts";
|
|
19
20
|
var WellKnownNamespaces = FeedProtocol.WellKnownNamespaces;
|
|
20
21
|
var TestBuilder = class extends Resource {
|
|
21
22
|
#peers = [];
|
|
@@ -29,7 +30,7 @@ var TestBuilder = class extends Resource {
|
|
|
29
30
|
isServer: i === 0,
|
|
30
31
|
actorId: `peer-${i}`,
|
|
31
32
|
serverPeerId: i === 0 ? void 0 : "peer-0",
|
|
32
|
-
sendMessage: (msg) => this.#routeMessage(msg),
|
|
33
|
+
sendMessage: (ctx, msg) => this.#routeMessage(ctx, msg),
|
|
33
34
|
logSql
|
|
34
35
|
}));
|
|
35
36
|
}
|
|
@@ -60,12 +61,12 @@ var TestBuilder = class extends Resource {
|
|
|
60
61
|
});
|
|
61
62
|
}
|
|
62
63
|
/** Route a message to the peer identified by recipientPeerId. Runs the recipient's handleMessage with that peer's runtime. */
|
|
63
|
-
#routeMessage(msg) {
|
|
64
|
+
#routeMessage(ctx, msg) {
|
|
64
65
|
const peer = this.#peers.find((p) => p.peerId === msg.recipientPeerId);
|
|
65
66
|
if (peer == null) {
|
|
66
67
|
return Effect.die(new Error(`TestPeer not found: ${msg.recipientPeerId}`));
|
|
67
68
|
}
|
|
68
|
-
const handleEffect = peer.syncServer != null ? peer.syncServer.handleMessage(msg) : peer.syncClient != null ? peer.syncClient.handleMessage(msg) : null;
|
|
69
|
+
const handleEffect = peer.syncServer != null ? peer.syncServer.handleMessage(ctx, msg) : peer.syncClient != null ? peer.syncClient.handleMessage(msg) : null;
|
|
69
70
|
if (handleEffect == null) {
|
|
70
71
|
return Effect.die(new Error(`TestPeer has no handler: ${msg.recipientPeerId}`));
|
|
71
72
|
}
|
|
@@ -152,14 +153,14 @@ var TestPeer = class extends Resource {
|
|
|
152
153
|
return this.#feedStore.appendLocal(req).pipe(RuntimeProvider.runPromise(this.#runtime.runtimeEffect));
|
|
153
154
|
}
|
|
154
155
|
pull({ spaceId, feedNamespace, limit = 10 }) {
|
|
155
|
-
return this.#client.pull({
|
|
156
|
+
return this.#client.pull(Context.default(void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 153 }), {
|
|
156
157
|
spaceId,
|
|
157
158
|
feedNamespace,
|
|
158
159
|
limit
|
|
159
160
|
}).pipe(RuntimeProvider.runPromise(this.#runtime.runtimeEffect));
|
|
160
161
|
}
|
|
161
162
|
push({ spaceId, feedNamespace, limit = 10 }) {
|
|
162
|
-
return this.#client.push({
|
|
163
|
+
return this.#client.push(Context.default(void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 160 }), {
|
|
163
164
|
spaceId,
|
|
164
165
|
feedNamespace,
|
|
165
166
|
limit
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/testing/test-builder.ts"],
|
|
4
|
-
"sourcesContent": ["//\n// Copyright 2026 DXOS.org\n//\n\nimport type * as SqlClient from '@effect/sql/SqlClient';\nimport * as Statement from '@effect/sql/Statement';\nimport * as Array from 'effect/Array';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\nimport * as ManagedRuntime from 'effect/ManagedRuntime';\n\nimport { Resource } from '@dxos/context';\nimport { RuntimeProvider } from '@dxos/effect';\nimport { type SpaceId } from '@dxos/keys';\nimport { FeedProtocol } from '@dxos/protocols';\nimport { SqlTransaction } from '@dxos/sql-sqlite';\nimport { layerMemory } from '@dxos/sql-sqlite/platform';\nimport * as SqlExport from '@dxos/sql-sqlite/SqlExport';\n\nimport { FeedStore } from '../feed-store';\nimport { SyncClient } from '../sync-client';\nimport { SyncServer } from '../sync-server';\n\ntype ProtocolMessage = FeedProtocol.ProtocolMessage;\nconst WellKnownNamespaces = FeedProtocol.WellKnownNamespaces;\ntype AppendRequest = FeedProtocol.AppendRequest;\ntype QueryRequest = FeedProtocol.QueryRequest;\n\nexport class TestBuilder extends Resource {\n #peers: TestPeer[] = [];\n readonly #spaceId: SpaceId;\n readonly #feedNamespace: string;\n\n constructor({\n numPeers,\n spaceId,\n feedNamespace = WellKnownNamespaces.data,\n logSql = false,\n }: {\n numPeers: number;\n spaceId: SpaceId;\n feedNamespace?: string;\n logSql?: boolean;\n }) {\n super();\n this.#spaceId = spaceId;\n this.#feedNamespace = feedNamespace;\n this.#peers = Array.makeBy(\n numPeers,\n (i) =>\n new TestPeer({\n isServer: i === 0,\n actorId: `peer-${i}`,\n serverPeerId: i === 0 ? undefined : 'peer-0',\n sendMessage: (msg) => this.#routeMessage(msg),\n logSql,\n }),\n );\n }\n\n get peers() {\n return this.#peers;\n }\n\n get server() {\n return this.#peers[0];\n }\n\n protected override async _open(): Promise<void> {\n await Promise.all(this.#peers.map((peer) => peer.open()));\n }\n\n protected override async _close(): Promise<void> {\n await Promise.all(this.#peers.map((peer) => peer.close()));\n }\n\n async pull(client: TestPeer, { limit = 10 }: { limit?: number } = {}): Promise<{ done: boolean }> {\n return client.pull({ spaceId: this.#spaceId, feedNamespace: this.#feedNamespace, limit });\n }\n\n async push(client: TestPeer, { limit = 10 }: { limit?: number } = {}): Promise<{ done: boolean }> {\n return client.push({ spaceId: this.#spaceId, feedNamespace: this.#feedNamespace, limit });\n }\n\n /** Route a message to the peer identified by recipientPeerId. Runs the recipient's handleMessage with that peer's runtime. */\n #routeMessage(msg: ProtocolMessage): Effect.Effect<void, unknown, never> {\n const peer = this.#peers.find((p) => p.peerId === msg.recipientPeerId);\n if (peer == null) {\n return Effect.die(new Error(`TestPeer not found: ${msg.recipientPeerId}`));\n }\n const handleEffect =\n peer.syncServer != null\n ? peer.syncServer.handleMessage(msg)\n : peer.syncClient != null\n ? peer.syncClient.handleMessage(msg)\n : null;\n if (handleEffect == null) {\n return Effect.die(new Error(`TestPeer has no handler: ${msg.recipientPeerId}`));\n }\n return Effect.promise(() => RuntimeProvider.runPromise(peer.runtime.runtimeEffect)(handleEffect));\n }\n}\n\nconst loggingTransformer: Statement.Statement.Transformer = (stmt, _make, _, _span) =>\n Effect.sync(() => {\n const [sql, params] = stmt.compile();\n console.log(sql.trim());\n console.log(params);\n return stmt;\n });\n\nexport class TestPeer extends Resource {\n readonly #peerId: string;\n #feedStore: FeedStore;\n #runtime: ManagedRuntime.ManagedRuntime<\n SqlClient.SqlClient | SqlExport.SqlExport | SqlTransaction.SqlTransaction,\n never\n >;\n #client?: SyncClient;\n #server?: SyncServer;\n\n constructor({\n isServer,\n actorId,\n serverPeerId,\n sendMessage,\n logSql = false,\n }: {\n isServer: boolean;\n actorId: string;\n serverPeerId?: string;\n sendMessage: (msg: ProtocolMessage) => Effect.Effect<void, unknown, never>;\n logSql?: boolean;\n }) {\n super();\n this.#peerId = actorId;\n this.#feedStore = new FeedStore({ localActorId: actorId, assignPositions: isServer });\n const baseLayer = layerMemory.pipe(\n Layer.provide(logSql ? Statement.setTransformer(loggingTransformer) : Layer.empty),\n );\n const transactionLayer = SqlTransaction.layer.pipe(Layer.provide(baseLayer));\n this.#runtime = ManagedRuntime.make(Layer.merge(baseLayer, transactionLayer).pipe(Layer.orDie));\n if (isServer) {\n this.#server = new SyncServer({\n peerId: actorId,\n feedStore: this.#feedStore,\n sendMessage,\n });\n } else {\n this.#client = new SyncClient({\n peerId: actorId,\n serverPeerId: serverPeerId!,\n feedStore: this.#feedStore,\n sendMessage,\n });\n }\n }\n\n get peerId() {\n return this.#peerId;\n }\n\n get feedStore() {\n return this.#feedStore;\n }\n\n get runtime() {\n return this.#runtime;\n }\n\n get syncClient() {\n return this.#client;\n }\n\n get syncServer() {\n return this.#server;\n }\n\n protected override async _open(): Promise<void> {\n await this.#feedStore.migrate().pipe(RuntimeProvider.runPromise(this.#runtime.runtimeEffect));\n }\n\n protected override async _close(): Promise<void> {\n await this.#runtime.dispose();\n }\n\n export(): Promise<Uint8Array> {\n return Effect.gen(function* () {\n const sql = yield* SqlExport.SqlExport;\n return yield* sql.export;\n }).pipe(RuntimeProvider.runPromise(this.#runtime.runtimeEffect));\n }\n\n getSyncState({ spaceId, feedNamespace }: { spaceId: SpaceId; feedNamespace: string }) {\n return this.#feedStore\n .getSyncState({ spaceId, feedNamespace })\n .pipe(RuntimeProvider.runPromise(this.#runtime.runtimeEffect));\n }\n\n query(req: QueryRequest) {\n return this.#feedStore.query(req).pipe(RuntimeProvider.runPromise(this.#runtime.runtimeEffect));\n }\n\n append(req: AppendRequest) {\n return this.#feedStore.append(req).pipe(RuntimeProvider.runPromise(this.#runtime.runtimeEffect));\n }\n\n appendLocal(req: Parameters<FeedStore['appendLocal']>[0]) {\n return this.#feedStore.appendLocal(req).pipe(RuntimeProvider.runPromise(this.#runtime.runtimeEffect));\n }\n\n pull({ spaceId, feedNamespace, limit = 10 }: { spaceId: SpaceId; feedNamespace: string; limit?: number }) {\n return this.#client!\n .pull({ spaceId, feedNamespace, limit })\n .pipe(RuntimeProvider.runPromise(this.#runtime.runtimeEffect));\n }\n\n push({ spaceId, feedNamespace, limit = 10 }: { spaceId: SpaceId; feedNamespace: string; limit?: number }) {\n return this.#client!\n .push({ spaceId, feedNamespace, limit })\n .pipe(RuntimeProvider.runPromise(this.#runtime.runtimeEffect));\n }\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;AAKA,YAAYA,eAAe;AAC3B,YAAYC,WAAW;AACvB,YAAYC,YAAY;AACxB,YAAYC,WAAW;AACvB,YAAYC,oBAAoB;AAEhC,SAASC,gBAAgB;
|
|
6
|
-
"names": ["Statement", "Array", "Effect", "Layer", "ManagedRuntime", "Resource", "RuntimeProvider", "FeedProtocol", "SqlTransaction", "layerMemory", "SqlExport", "WellKnownNamespaces", "
|
|
4
|
+
"sourcesContent": ["//\n// Copyright 2026 DXOS.org\n//\n\nimport type * as SqlClient from '@effect/sql/SqlClient';\nimport * as Statement from '@effect/sql/Statement';\nimport * as Array from 'effect/Array';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\nimport * as ManagedRuntime from 'effect/ManagedRuntime';\n\nimport { Context, Resource } from '@dxos/context';\nimport { RuntimeProvider } from '@dxos/effect';\nimport { type SpaceId } from '@dxos/keys';\nimport { FeedProtocol } from '@dxos/protocols';\nimport { SqlTransaction } from '@dxos/sql-sqlite';\nimport { layerMemory } from '@dxos/sql-sqlite/platform';\nimport * as SqlExport from '@dxos/sql-sqlite/SqlExport';\n\nimport { FeedStore } from '../feed-store';\nimport { SyncClient } from '../sync-client';\nimport { SyncServer } from '../sync-server';\n\ntype ProtocolMessage = FeedProtocol.ProtocolMessage;\nconst WellKnownNamespaces = FeedProtocol.WellKnownNamespaces;\ntype AppendRequest = FeedProtocol.AppendRequest;\ntype QueryRequest = FeedProtocol.QueryRequest;\n\nexport class TestBuilder extends Resource {\n #peers: TestPeer[] = [];\n readonly #spaceId: SpaceId;\n readonly #feedNamespace: string;\n\n constructor({\n numPeers,\n spaceId,\n feedNamespace = WellKnownNamespaces.data,\n logSql = false,\n }: {\n numPeers: number;\n spaceId: SpaceId;\n feedNamespace?: string;\n logSql?: boolean;\n }) {\n super();\n this.#spaceId = spaceId;\n this.#feedNamespace = feedNamespace;\n this.#peers = Array.makeBy(\n numPeers,\n (i) =>\n new TestPeer({\n isServer: i === 0,\n actorId: `peer-${i}`,\n serverPeerId: i === 0 ? undefined : 'peer-0',\n sendMessage: (ctx, msg) => this.#routeMessage(ctx, msg),\n logSql,\n }),\n );\n }\n\n get peers() {\n return this.#peers;\n }\n\n get server() {\n return this.#peers[0];\n }\n\n protected override async _open(): Promise<void> {\n await Promise.all(this.#peers.map((peer) => peer.open()));\n }\n\n protected override async _close(): Promise<void> {\n await Promise.all(this.#peers.map((peer) => peer.close()));\n }\n\n async pull(client: TestPeer, { limit = 10 }: { limit?: number } = {}): Promise<{ done: boolean }> {\n return client.pull({ spaceId: this.#spaceId, feedNamespace: this.#feedNamespace, limit });\n }\n\n async push(client: TestPeer, { limit = 10 }: { limit?: number } = {}): Promise<{ done: boolean }> {\n return client.push({ spaceId: this.#spaceId, feedNamespace: this.#feedNamespace, limit });\n }\n\n /** Route a message to the peer identified by recipientPeerId. Runs the recipient's handleMessage with that peer's runtime. */\n #routeMessage(ctx: Context, msg: ProtocolMessage): Effect.Effect<void, unknown, never> {\n const peer = this.#peers.find((p) => p.peerId === msg.recipientPeerId);\n if (peer == null) {\n return Effect.die(new Error(`TestPeer not found: ${msg.recipientPeerId}`));\n }\n const handleEffect =\n peer.syncServer != null\n ? peer.syncServer.handleMessage(ctx, msg)\n : peer.syncClient != null\n ? peer.syncClient.handleMessage(msg)\n : null;\n if (handleEffect == null) {\n return Effect.die(new Error(`TestPeer has no handler: ${msg.recipientPeerId}`));\n }\n return Effect.promise(() => RuntimeProvider.runPromise(peer.runtime.runtimeEffect)(handleEffect));\n }\n}\n\nconst loggingTransformer: Statement.Statement.Transformer = (stmt, _make, _, _span) =>\n Effect.sync(() => {\n const [sql, params] = stmt.compile();\n console.log(sql.trim());\n console.log(params);\n return stmt;\n });\n\nexport class TestPeer extends Resource {\n readonly #peerId: string;\n #feedStore: FeedStore;\n #runtime: ManagedRuntime.ManagedRuntime<\n SqlClient.SqlClient | SqlExport.SqlExport | SqlTransaction.SqlTransaction,\n never\n >;\n #client?: SyncClient;\n #server?: SyncServer;\n\n constructor({\n isServer,\n actorId,\n serverPeerId,\n sendMessage,\n logSql = false,\n }: {\n isServer: boolean;\n actorId: string;\n serverPeerId?: string;\n sendMessage: (ctx: Context, msg: ProtocolMessage) => Effect.Effect<void, unknown, never>;\n logSql?: boolean;\n }) {\n super();\n this.#peerId = actorId;\n this.#feedStore = new FeedStore({ localActorId: actorId, assignPositions: isServer });\n const baseLayer = layerMemory.pipe(\n Layer.provide(logSql ? Statement.setTransformer(loggingTransformer) : Layer.empty),\n );\n const transactionLayer = SqlTransaction.layer.pipe(Layer.provide(baseLayer));\n this.#runtime = ManagedRuntime.make(Layer.merge(baseLayer, transactionLayer).pipe(Layer.orDie));\n if (isServer) {\n this.#server = new SyncServer({\n peerId: actorId,\n feedStore: this.#feedStore,\n sendMessage,\n });\n } else {\n this.#client = new SyncClient({\n peerId: actorId,\n serverPeerId: serverPeerId!,\n feedStore: this.#feedStore,\n sendMessage,\n });\n }\n }\n\n get peerId() {\n return this.#peerId;\n }\n\n get feedStore() {\n return this.#feedStore;\n }\n\n get runtime() {\n return this.#runtime;\n }\n\n get syncClient() {\n return this.#client;\n }\n\n get syncServer() {\n return this.#server;\n }\n\n protected override async _open(): Promise<void> {\n await this.#feedStore.migrate().pipe(RuntimeProvider.runPromise(this.#runtime.runtimeEffect));\n }\n\n protected override async _close(): Promise<void> {\n await this.#runtime.dispose();\n }\n\n export(): Promise<Uint8Array> {\n return Effect.gen(function* () {\n const sql = yield* SqlExport.SqlExport;\n return yield* sql.export;\n }).pipe(RuntimeProvider.runPromise(this.#runtime.runtimeEffect));\n }\n\n getSyncState({ spaceId, feedNamespace }: { spaceId: SpaceId; feedNamespace: string }) {\n return this.#feedStore\n .getSyncState({ spaceId, feedNamespace })\n .pipe(RuntimeProvider.runPromise(this.#runtime.runtimeEffect));\n }\n\n query(req: QueryRequest) {\n return this.#feedStore.query(req).pipe(RuntimeProvider.runPromise(this.#runtime.runtimeEffect));\n }\n\n append(req: AppendRequest) {\n return this.#feedStore.append(req).pipe(RuntimeProvider.runPromise(this.#runtime.runtimeEffect));\n }\n\n appendLocal(req: Parameters<FeedStore['appendLocal']>[0]) {\n return this.#feedStore.appendLocal(req).pipe(RuntimeProvider.runPromise(this.#runtime.runtimeEffect));\n }\n\n pull({ spaceId, feedNamespace, limit = 10 }: { spaceId: SpaceId; feedNamespace: string; limit?: number }) {\n return this.#client!\n .pull(Context.default(), { spaceId, feedNamespace, limit })\n .pipe(RuntimeProvider.runPromise(this.#runtime.runtimeEffect));\n }\n\n push({ spaceId, feedNamespace, limit = 10 }: { spaceId: SpaceId; feedNamespace: string; limit?: number }) {\n return this.#client!\n .push(Context.default(), { spaceId, feedNamespace, limit })\n .pipe(RuntimeProvider.runPromise(this.#runtime.runtimeEffect));\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;AAKA,YAAYA,eAAe;AAC3B,YAAYC,WAAW;AACvB,YAAYC,YAAY;AACxB,YAAYC,WAAW;AACvB,YAAYC,oBAAoB;AAEhC,SAASC,SAASC,gBAAgB;AAClC,SAASC,uBAAuB;AAEhC,SAASC,oBAAoB;AAC7B,SAASC,sBAAsB;AAC/B,SAASC,mBAAmB;AAC5B,YAAYC,eAAe;AAO3B,IAAA,eAAMC;IAKJ,sBAAwB,aAAA;AACf,IAAkB,cAAlB,cAAkB,SAAA;EAClB,SAAA,CAAA;EAET;;cAYO,EAAA,UAAWC,SAAAA,gBAAAA,oBAAAA,MAAAA,SAAAA,MAAAA,GAAAA;AAChB,UAAK;AACL,SAAK,WAASC;0BAIEC;kBACA,aAAOA,UAAG,CAAA,MAAA,IAAA,SAAA;MACpBC,UAAAA,MAAcD;MACdE,SAAAA,QAAcC,CAAAA;MACdC,cAAAA,MAAAA,IAAAA,SAAAA;MACF,aAAA,CAAA,KAAA,QAAA,KAAA,cAAA,KAAA,GAAA;MAEN;IAEIC,CAAAA,CAAAA;;EAEJ,IAAA,QAAA;AAEIC,WAAAA,KAAS;;EAEb,IAAA,SAAA;AAEA,WAAyBC,KAAuB,OAAA,CAAA;;EAEhD,MAAA,QAAA;AAEA,UAAyBC,QAAwB,IAAA,KAAA,OAAA,IAAA,CAAA,SAAA,KAAA,KAAA,CAAA,CAAA;;EAEjD,MAAA,SAAA;AAEA,UAAMC,QAAqB,IAAIC,KAAAA,OAAgC,IAAK,CAAA,SAA8B,KAAA,MAAA,CAAA,CAAA;;aAC3EZ,QAAS,EAAI,QAAC,GAAQ,IAAA,CAAA,GAAA;WAAEa,OAAAA,KA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AA,KAAA,SAAA,aAAA,CAAA;;kBAE3Eb,eAAAA,QAAAA,GAAAA,GAAAA;WAASa,KAAAA,QAAAA,KAAAA,QAAAA,QAAAA,QAAAA,EAAAA,YAAAA,YAAAA,GAAAA,cAAAA,GAAAA,IAAAA,CAAAA,GAAAA;MAAeD;MAClDkC;MACL;IAEAO,CAAK,EAAErD,KAAAA,gBAASa,WAAuB,KAAiE,SAAE,aAAA,CAAA;;kBAE3Eb,eAAAA,QAAAA,GAAAA,GAAAA;WAASa,KAAAA,QAAAA,KAAAA,QAAAA,QAAAA,QAAAA,EAAAA,YAAAA,YAAAA,GAAAA,cAAAA,GAAAA,IAAAA,CAAAA,GAAAA;MAAeD;MAClDkC;MACL;IACF,CAAA,EAAA,KAAA,gBAAA,WAAA,KAAA,SAAA,aAAA,CAAA;;;",
|
|
6
|
+
"names": ["Statement", "Array", "Effect", "Layer", "ManagedRuntime", "Context", "Resource", "RuntimeProvider", "FeedProtocol", "SqlTransaction", "layerMemory", "SqlExport", "WellKnownNamespaces", "spaceId", "Array", "i", "serverPeerId", "sendMessage", "ctx", "logSql", "peers", "server", "_open", "_close", "pull", "limit", "feedNamespace", "Effect", "die", "Error", "recipientPeerId", "handleEffect", "peer", "syncServer", "handleMessage", "msg", "promise", "RuntimeProvider", "runtime", "trim", "console", "params", "stmt", "TestPeer", "actorId", "localActorId", "assignPositions", "isServer", "layerMemory", "ManagedRuntime", "Layer", "baseLayer", "transactionLayer", "SyncServer", "peerId", "feedStore", "syncClient", "export", "sql", "pipe", "runPromise", "getSyncState", "query", "req", "append", "appendLocal", "push"]
|
|
7
7
|
}
|
|
@@ -1,27 +1,27 @@
|
|
|
1
1
|
import { BaseError } from '@dxos/errors';
|
|
2
2
|
declare const PositionConflictError_base: {
|
|
3
3
|
new (options?: import("@dxos/errors").BaseErrorOptions): {
|
|
4
|
+
cause?: unknown;
|
|
5
|
+
stack?: string;
|
|
4
6
|
name: "PositionConflictError";
|
|
5
7
|
context: Record<string, unknown>;
|
|
6
8
|
readonly message: string;
|
|
7
9
|
readonly _tag: "PositionConflictError";
|
|
8
|
-
stack?: string;
|
|
9
|
-
cause?: unknown;
|
|
10
10
|
};
|
|
11
|
+
isError(error: unknown): error is Error;
|
|
11
12
|
name: "PositionConflictError";
|
|
12
13
|
is(error: unknown): error is BaseError;
|
|
13
|
-
wrap(options?: Omit<import("@dxos/errors").BaseErrorOptions,
|
|
14
|
+
wrap(options?: Omit<import("@dxos/errors").BaseErrorOptions, 'cause'> & {
|
|
14
15
|
ifTypeDiffers?: boolean;
|
|
15
16
|
}): (error: unknown) => {
|
|
17
|
+
cause?: unknown;
|
|
18
|
+
stack?: string;
|
|
16
19
|
name: "PositionConflictError";
|
|
17
20
|
context: Record<string, unknown>;
|
|
18
21
|
readonly message: string;
|
|
19
22
|
readonly _tag: "PositionConflictError";
|
|
20
|
-
stack?: string;
|
|
21
|
-
cause?: unknown;
|
|
22
23
|
};
|
|
23
24
|
extend<Name extends string = string>(name: Name, message?: string): any;
|
|
24
|
-
isError(error: unknown): error is Error;
|
|
25
25
|
captureStackTrace(targetObject: object, constructorOpt?: Function): void;
|
|
26
26
|
prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined;
|
|
27
27
|
stackTraceLimit: number;
|