@dxos/feed 0.8.4-main.fbb7a13 → 0.8.4-main.fcc0d83b33
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 +6 -2
- package/dist/lib/neutral/chunk-PENEKCN2.mjs +742 -0
- package/dist/lib/neutral/chunk-PENEKCN2.mjs.map +7 -0
- package/dist/lib/neutral/index.mjs +13 -0
- package/dist/lib/neutral/meta.json +1 -0
- package/dist/lib/neutral/testing/index.mjs +174 -0
- package/dist/lib/neutral/testing/index.mjs.map +7 -0
- package/dist/types/src/errors.d.ts +39 -0
- package/dist/types/src/errors.d.ts.map +1 -0
- package/dist/types/src/feed-store.d.ts +103 -9
- package/dist/types/src/feed-store.d.ts.map +1 -1
- package/dist/types/src/index.d.ts +3 -1
- package/dist/types/src/index.d.ts.map +1 -1
- package/dist/types/src/sync-client.d.ts +54 -0
- package/dist/types/src/sync-client.d.ts.map +1 -0
- package/dist/types/src/sync-server.d.ts +28 -0
- package/dist/types/src/sync-server.d.ts.map +1 -0
- package/dist/types/src/testing/index.d.ts +1 -1
- package/dist/types/src/testing/index.d.ts.map +1 -1
- package/dist/types/src/testing/test-builder.d.ts +78 -0
- package/dist/types/src/testing/test-builder.d.ts.map +1 -0
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +19 -21
- package/src/errors.ts +20 -0
- package/src/feed-store.test.ts +397 -40
- package/src/feed-store.ts +499 -142
- package/src/index.ts +3 -1
- package/src/sync-client.ts +199 -0
- package/src/sync-server.ts +96 -0
- package/src/sync.test.ts +151 -91
- package/src/testing/index.ts +1 -1
- package/src/testing/test-builder.ts +223 -0
- package/dist/lib/browser/index.mjs +0 -342
- package/dist/lib/browser/index.mjs.map +0 -7
- package/dist/lib/browser/meta.json +0 -1
- package/dist/lib/browser/testing/index.mjs +0 -1
- package/dist/lib/node-esm/index.mjs +0 -344
- package/dist/lib/node-esm/index.mjs.map +0 -7
- package/dist/lib/node-esm/meta.json +0 -1
- package/dist/lib/node-esm/testing/index.mjs +0 -2
- package/dist/lib/node-esm/testing/index.mjs.map +0 -7
- package/dist/types/src/protocol.d.ts +0 -120
- package/dist/types/src/protocol.d.ts.map +0 -1
- package/src/protocol.ts +0 -110
- /package/dist/lib/{browser/testing → neutral}/index.mjs.map +0 -0
|
@@ -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 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 /**\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 } 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 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* 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(\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 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* 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,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,WA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;AACjF,QAAIjD,QAAQJ,SAAS,SAAS;AAC5B,aAAca,aAAK,IAAIC,MAAMV,QAAQA,OAAO,CAAA;IAC9C;AACA,UAAMkD,eAAe,eAAelD,UAAUE,OAAOF,QAAQC,SAAS,IAAIE;AAC1E,QAAIH,QAAQJ,SAASqD,eAAeC,iBAAiBjD,WAAW;AAC9D,aAAcQ,aAAK,IAAIC,MAAM,gCAAgCuC,WAAAA,mBAA8BhD,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", "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", "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", "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
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"inputs":{"src/errors.ts":{"bytes":1997,"imports":[{"path":"@dxos/errors","kind":"import-statement","external":true}],"format":"esm"},"src/feed-store.ts":{"bytes":84904,"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":22105,"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}],"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-PENEKCN2.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-PENEKCN2.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-PENEKCN2.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":57960},"dist/lib/neutral/chunk-PENEKCN2.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}],"exports":["FeedStore","PositionConflictError","SyncClient","SyncServer"],"inputs":{"src/errors.ts":{"bytesInOutput":382},"src/feed-store.ts":{"bytesInOutput":20881},"src/sync-server.ts":{"bytesInOutput":1685},"src/sync-client.ts":{"bytesInOutput":4748}},"bytes":27903}}}
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import {
|
|
2
|
+
FeedStore,
|
|
3
|
+
SyncClient,
|
|
4
|
+
SyncServer
|
|
5
|
+
} from "../chunk-PENEKCN2.mjs";
|
|
6
|
+
|
|
7
|
+
// src/testing/test-builder.ts
|
|
8
|
+
import * as Statement from "@effect/sql/Statement";
|
|
9
|
+
import * as Array from "effect/Array";
|
|
10
|
+
import * as Effect from "effect/Effect";
|
|
11
|
+
import * as Layer from "effect/Layer";
|
|
12
|
+
import * as ManagedRuntime from "effect/ManagedRuntime";
|
|
13
|
+
import { Context, Resource } from "@dxos/context";
|
|
14
|
+
import { RuntimeProvider } from "@dxos/effect";
|
|
15
|
+
import { FeedProtocol } from "@dxos/protocols";
|
|
16
|
+
import { SqlTransaction } from "@dxos/sql-sqlite";
|
|
17
|
+
import { layerMemory } from "@dxos/sql-sqlite/platform";
|
|
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";
|
|
20
|
+
var WellKnownNamespaces = FeedProtocol.WellKnownNamespaces;
|
|
21
|
+
var TestBuilder = class extends Resource {
|
|
22
|
+
#peers = [];
|
|
23
|
+
#spaceId;
|
|
24
|
+
#feedNamespace;
|
|
25
|
+
constructor({ numPeers, spaceId, feedNamespace = WellKnownNamespaces.data, logSql = false }) {
|
|
26
|
+
super();
|
|
27
|
+
this.#spaceId = spaceId;
|
|
28
|
+
this.#feedNamespace = feedNamespace;
|
|
29
|
+
this.#peers = Array.makeBy(numPeers, (i) => new TestPeer({
|
|
30
|
+
isServer: i === 0,
|
|
31
|
+
actorId: `peer-${i}`,
|
|
32
|
+
serverPeerId: i === 0 ? void 0 : "peer-0",
|
|
33
|
+
sendMessage: (ctx, msg) => this.#routeMessage(ctx, msg),
|
|
34
|
+
logSql
|
|
35
|
+
}));
|
|
36
|
+
}
|
|
37
|
+
get peers() {
|
|
38
|
+
return this.#peers;
|
|
39
|
+
}
|
|
40
|
+
get server() {
|
|
41
|
+
return this.#peers[0];
|
|
42
|
+
}
|
|
43
|
+
async _open() {
|
|
44
|
+
await Promise.all(this.#peers.map((peer) => peer.open()));
|
|
45
|
+
}
|
|
46
|
+
async _close() {
|
|
47
|
+
await Promise.all(this.#peers.map((peer) => peer.close()));
|
|
48
|
+
}
|
|
49
|
+
async pull(client, { limit = 10 } = {}) {
|
|
50
|
+
return client.pull({
|
|
51
|
+
spaceId: this.#spaceId,
|
|
52
|
+
feedNamespace: this.#feedNamespace,
|
|
53
|
+
limit
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
async push(client, { limit = 10 } = {}) {
|
|
57
|
+
return client.push({
|
|
58
|
+
spaceId: this.#spaceId,
|
|
59
|
+
feedNamespace: this.#feedNamespace,
|
|
60
|
+
limit
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
/** Route a message to the peer identified by recipientPeerId. Runs the recipient's handleMessage with that peer's runtime. */
|
|
64
|
+
#routeMessage(ctx, msg) {
|
|
65
|
+
const peer = this.#peers.find((p) => p.peerId === msg.recipientPeerId);
|
|
66
|
+
if (peer == null) {
|
|
67
|
+
return Effect.die(new Error(`TestPeer not found: ${msg.recipientPeerId}`));
|
|
68
|
+
}
|
|
69
|
+
const handleEffect = peer.syncServer != null ? peer.syncServer.handleMessage(ctx, msg) : peer.syncClient != null ? peer.syncClient.handleMessage(msg) : null;
|
|
70
|
+
if (handleEffect == null) {
|
|
71
|
+
return Effect.die(new Error(`TestPeer has no handler: ${msg.recipientPeerId}`));
|
|
72
|
+
}
|
|
73
|
+
return Effect.promise(() => RuntimeProvider.runPromise(peer.runtime.runtimeEffect)(handleEffect));
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
var loggingTransformer = (stmt, _make, _, _span) => Effect.sync(() => {
|
|
77
|
+
const [sql, params] = stmt.compile();
|
|
78
|
+
console.log(sql.trim());
|
|
79
|
+
console.log(params);
|
|
80
|
+
return stmt;
|
|
81
|
+
});
|
|
82
|
+
var TestPeer = class extends Resource {
|
|
83
|
+
#peerId;
|
|
84
|
+
#feedStore;
|
|
85
|
+
#runtime;
|
|
86
|
+
#client;
|
|
87
|
+
#server;
|
|
88
|
+
constructor({ isServer, actorId, serverPeerId, sendMessage, logSql = false }) {
|
|
89
|
+
super();
|
|
90
|
+
this.#peerId = actorId;
|
|
91
|
+
this.#feedStore = new FeedStore({
|
|
92
|
+
localActorId: actorId,
|
|
93
|
+
assignPositions: isServer
|
|
94
|
+
});
|
|
95
|
+
const baseLayer = layerMemory.pipe(Layer.provide(logSql ? Statement.setTransformer(loggingTransformer) : Layer.empty));
|
|
96
|
+
const transactionLayer = SqlTransaction.layer.pipe(Layer.provide(baseLayer));
|
|
97
|
+
this.#runtime = ManagedRuntime.make(Layer.merge(baseLayer, transactionLayer).pipe(Layer.orDie));
|
|
98
|
+
if (isServer) {
|
|
99
|
+
this.#server = new SyncServer({
|
|
100
|
+
peerId: actorId,
|
|
101
|
+
feedStore: this.#feedStore,
|
|
102
|
+
sendMessage
|
|
103
|
+
});
|
|
104
|
+
} else {
|
|
105
|
+
this.#client = new SyncClient({
|
|
106
|
+
peerId: actorId,
|
|
107
|
+
serverPeerId,
|
|
108
|
+
feedStore: this.#feedStore,
|
|
109
|
+
sendMessage
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
get peerId() {
|
|
114
|
+
return this.#peerId;
|
|
115
|
+
}
|
|
116
|
+
get feedStore() {
|
|
117
|
+
return this.#feedStore;
|
|
118
|
+
}
|
|
119
|
+
get runtime() {
|
|
120
|
+
return this.#runtime;
|
|
121
|
+
}
|
|
122
|
+
get syncClient() {
|
|
123
|
+
return this.#client;
|
|
124
|
+
}
|
|
125
|
+
get syncServer() {
|
|
126
|
+
return this.#server;
|
|
127
|
+
}
|
|
128
|
+
async _open() {
|
|
129
|
+
await this.#feedStore.migrate().pipe(RuntimeProvider.runPromise(this.#runtime.runtimeEffect));
|
|
130
|
+
}
|
|
131
|
+
async _close() {
|
|
132
|
+
await this.#runtime.dispose();
|
|
133
|
+
}
|
|
134
|
+
export() {
|
|
135
|
+
return Effect.gen(function* () {
|
|
136
|
+
const sql = yield* SqlExport.SqlExport;
|
|
137
|
+
return yield* sql.export;
|
|
138
|
+
}).pipe(RuntimeProvider.runPromise(this.#runtime.runtimeEffect));
|
|
139
|
+
}
|
|
140
|
+
getSyncState({ spaceId, feedNamespace }) {
|
|
141
|
+
return this.#feedStore.getSyncState({
|
|
142
|
+
spaceId,
|
|
143
|
+
feedNamespace
|
|
144
|
+
}).pipe(RuntimeProvider.runPromise(this.#runtime.runtimeEffect));
|
|
145
|
+
}
|
|
146
|
+
query(req) {
|
|
147
|
+
return this.#feedStore.query(req).pipe(RuntimeProvider.runPromise(this.#runtime.runtimeEffect));
|
|
148
|
+
}
|
|
149
|
+
append(req) {
|
|
150
|
+
return this.#feedStore.append(req).pipe(RuntimeProvider.runPromise(this.#runtime.runtimeEffect));
|
|
151
|
+
}
|
|
152
|
+
appendLocal(req) {
|
|
153
|
+
return this.#feedStore.appendLocal(req).pipe(RuntimeProvider.runPromise(this.#runtime.runtimeEffect));
|
|
154
|
+
}
|
|
155
|
+
pull({ spaceId, feedNamespace, limit = 10 }) {
|
|
156
|
+
return this.#client.pull(Context.default(void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 153 }), {
|
|
157
|
+
spaceId,
|
|
158
|
+
feedNamespace,
|
|
159
|
+
limit
|
|
160
|
+
}).pipe(RuntimeProvider.runPromise(this.#runtime.runtimeEffect));
|
|
161
|
+
}
|
|
162
|
+
push({ spaceId, feedNamespace, limit = 10 }) {
|
|
163
|
+
return this.#client.push(Context.default(void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 160 }), {
|
|
164
|
+
spaceId,
|
|
165
|
+
feedNamespace,
|
|
166
|
+
limit
|
|
167
|
+
}).pipe(RuntimeProvider.runPromise(this.#runtime.runtimeEffect));
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
export {
|
|
171
|
+
TestBuilder,
|
|
172
|
+
TestPeer
|
|
173
|
+
};
|
|
174
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 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 { 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;;EAE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AAyB,KAAE,WAAA,MAAA,GAAA,EAAA,KAAA,gBAAA,WAAA,KAAA,SAAA,aAAA,CAAA;;EAE3B,OAAA,KAAA;AAEAC,WAAAA,KAAwD,WAAE,OAAA,GAAA,EAAA,KAAA,gBAAA,WAAA,KAAA,SAAA,aAAA,CAAA;;EAE1D,YAAA,KAAA;AAEAzC,WAAOX,KAASa,WAAAA,YAAuB,GAAE,EAA+D,KAAE,gBAAA,WAAA,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
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { BaseError } from '@dxos/errors';
|
|
2
|
+
declare const PositionConflictError_base: {
|
|
3
|
+
new (options?: import("@dxos/errors").BaseErrorOptions): {
|
|
4
|
+
cause?: unknown;
|
|
5
|
+
stack?: string;
|
|
6
|
+
name: "PositionConflictError";
|
|
7
|
+
context: Record<string, unknown>;
|
|
8
|
+
readonly message: string;
|
|
9
|
+
readonly _tag: "PositionConflictError";
|
|
10
|
+
};
|
|
11
|
+
isError(error: unknown): error is Error;
|
|
12
|
+
name: "PositionConflictError";
|
|
13
|
+
is(error: unknown): error is BaseError;
|
|
14
|
+
wrap(options?: Omit<import("@dxos/errors").BaseErrorOptions, 'cause'> & {
|
|
15
|
+
ifTypeDiffers?: boolean;
|
|
16
|
+
}): (error: unknown) => {
|
|
17
|
+
cause?: unknown;
|
|
18
|
+
stack?: string;
|
|
19
|
+
name: "PositionConflictError";
|
|
20
|
+
context: Record<string, unknown>;
|
|
21
|
+
readonly message: string;
|
|
22
|
+
readonly _tag: "PositionConflictError";
|
|
23
|
+
};
|
|
24
|
+
extend<Name extends string = string>(name: Name, message?: string): any;
|
|
25
|
+
captureStackTrace(targetObject: object, constructorOpt?: Function): void;
|
|
26
|
+
prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined;
|
|
27
|
+
stackTraceLimit: number;
|
|
28
|
+
};
|
|
29
|
+
export declare class PositionConflictError extends PositionConflictError_base {
|
|
30
|
+
constructor(args: {
|
|
31
|
+
feedId?: string;
|
|
32
|
+
actorId: string;
|
|
33
|
+
sequence: number;
|
|
34
|
+
currentPosition: number;
|
|
35
|
+
requestedPosition: number | null;
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
export {};
|
|
39
|
+
//# sourceMappingURL=errors.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../../src/errors.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEzC,qBAAa,qBAAsB,SAAQ,0BAAyC;IAClF,YAAY,IAAI,EAAE;QAChB,MAAM,CAAC,EAAE,MAAM,CAAC;QAChB,OAAO,EAAE,MAAM,CAAC;QAChB,QAAQ,EAAE,MAAM,CAAC;QACjB,eAAe,EAAE,MAAM,CAAC;QACxB,iBAAiB,EAAE,MAAM,GAAG,IAAI,CAAC;KAClC,EAKA;CACF"}
|
|
@@ -2,26 +2,120 @@ import * as SqlClient from '@effect/sql/SqlClient';
|
|
|
2
2
|
import type * as SqlError from '@effect/sql/SqlError';
|
|
3
3
|
import * as Effect from 'effect/Effect';
|
|
4
4
|
import { Event } from '@dxos/async';
|
|
5
|
-
import { type
|
|
5
|
+
import { type SpaceId } from '@dxos/keys';
|
|
6
|
+
import { FeedProtocol } from '@dxos/protocols';
|
|
7
|
+
import { SqlTransaction } from '@dxos/sql-sqlite';
|
|
8
|
+
import { PositionConflictError } from './errors';
|
|
9
|
+
type AppendRequest = FeedProtocol.AppendRequest;
|
|
10
|
+
type AppendResponse = FeedProtocol.AppendResponse;
|
|
11
|
+
type Block = FeedProtocol.Block;
|
|
6
12
|
export interface FeedStoreOptions {
|
|
13
|
+
/**
|
|
14
|
+
* The actor ID of the local user.
|
|
15
|
+
*/
|
|
7
16
|
localActorId: string;
|
|
17
|
+
/**
|
|
18
|
+
* Whether to assign positions to appended blocks.
|
|
19
|
+
* Only a single peer (usually the server) can assign positions.
|
|
20
|
+
*/
|
|
8
21
|
assignPositions: boolean;
|
|
9
22
|
}
|
|
23
|
+
/**
|
|
24
|
+
* Persistent storage for feed metadata, blocks, subscriptions, and sync state.
|
|
25
|
+
*
|
|
26
|
+
*/
|
|
10
27
|
export declare class FeedStore {
|
|
11
|
-
private
|
|
12
|
-
constructor(
|
|
28
|
+
#private;
|
|
29
|
+
constructor(options: FeedStoreOptions);
|
|
30
|
+
/**
|
|
31
|
+
* Emits after successful block append operations.
|
|
32
|
+
*/
|
|
13
33
|
readonly onNewBlocks: Event<void>;
|
|
34
|
+
/**
|
|
35
|
+
* Creates required feed store tables and indexes if they do not exist.
|
|
36
|
+
*/
|
|
14
37
|
migrate: () => Effect.Effect<void, SqlError.SqlError, SqlClient.SqlClient>;
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
38
|
+
/**
|
|
39
|
+
* Queries feed blocks by feed IDs or subscription with cursor/position pagination.
|
|
40
|
+
*/
|
|
41
|
+
query: (request: FeedProtocol.QueryRequest) => Effect.Effect<FeedProtocol.QueryResponse, SqlError.SqlError, SqlClient.SqlClient>;
|
|
42
|
+
/**
|
|
43
|
+
* Creates a subscription and stores the resolved internal feed IDs.
|
|
44
|
+
*/
|
|
45
|
+
subscribe: (request: FeedProtocol.SubscribeRequest) => Effect.Effect<FeedProtocol.SubscribeResponse, SqlError.SqlError, SqlClient.SqlClient>;
|
|
46
|
+
/**
|
|
47
|
+
* Get the last pulled position for the given space and namespace.
|
|
48
|
+
* Returns -1 if no sync state exists yet.
|
|
49
|
+
*/
|
|
50
|
+
getSyncState: (opts: {
|
|
51
|
+
spaceId: SpaceId;
|
|
52
|
+
feedNamespace: string;
|
|
53
|
+
}) => Effect.Effect<number, SqlError.SqlError, SqlClient.SqlClient>;
|
|
54
|
+
/**
|
|
55
|
+
* Update the last pulled position for the given space and namespace.
|
|
56
|
+
*/
|
|
57
|
+
setSyncState: (opts: {
|
|
58
|
+
spaceId: SpaceId;
|
|
59
|
+
feedNamespace: string;
|
|
60
|
+
lastPulledPosition: number;
|
|
61
|
+
}) => Effect.Effect<void, SqlError.SqlError, SqlClient.SqlClient>;
|
|
62
|
+
/**
|
|
63
|
+
* Returns the number of stored blocks for a single feed in a space/namespace.
|
|
64
|
+
* Intended as a low-level primitive for callers (for example Cloudflare Worker code)
|
|
65
|
+
* that need to make retention decisions under constrained storage resources.
|
|
66
|
+
*/
|
|
67
|
+
countBlocks: (opts: {
|
|
68
|
+
spaceId: SpaceId;
|
|
69
|
+
feedNamespace: string;
|
|
70
|
+
feedId: string;
|
|
71
|
+
}) => Effect.Effect<number, SqlError.SqlError, SqlClient.SqlClient>;
|
|
72
|
+
/**
|
|
73
|
+
* Deletes the oldest blocks for a single feed in a space/namespace.
|
|
74
|
+
* This API intentionally does not enforce any retention policy (such as max size);
|
|
75
|
+
* callers decide when and how much to prune, which is useful for constrained
|
|
76
|
+
* environments like Cloudflare Workers.
|
|
77
|
+
*
|
|
78
|
+
* @returns Number of deleted rows.
|
|
79
|
+
*/
|
|
80
|
+
deleteOldestBlocks: (opts: {
|
|
81
|
+
spaceId: SpaceId;
|
|
82
|
+
feedNamespace: string;
|
|
83
|
+
feedId: string;
|
|
84
|
+
count: number;
|
|
85
|
+
}) => Effect.Effect<number, SqlError.SqlError, SqlClient.SqlClient>;
|
|
86
|
+
/**
|
|
87
|
+
* Appends blocks for a space/namespace and optionally assigns global positions.
|
|
88
|
+
*/
|
|
89
|
+
append: (request: AppendRequest) => Effect.Effect<AppendResponse, SqlError.SqlError, SqlClient.SqlClient | SqlTransaction.SqlTransaction>;
|
|
90
|
+
/**
|
|
91
|
+
* Creates local blocks with sequential predecessors and appends grouped batches.
|
|
92
|
+
*/
|
|
20
93
|
appendLocal: (messages: {
|
|
21
94
|
spaceId: string;
|
|
22
95
|
feedId: string;
|
|
23
96
|
feedNamespace: string;
|
|
24
97
|
data: Uint8Array;
|
|
25
|
-
}[]) => Effect.Effect<Block[], SqlError.SqlError, SqlClient.SqlClient>;
|
|
98
|
+
}[]) => Effect.Effect<FeedProtocol.Block[], SqlError.SqlError, SqlClient.SqlClient | SqlTransaction.SqlTransaction>;
|
|
99
|
+
/**
|
|
100
|
+
* Sets positions for existing blocks while preventing conflicting reassignments.
|
|
101
|
+
*/
|
|
102
|
+
setPosition: (request: {
|
|
103
|
+
spaceId: string;
|
|
104
|
+
blocks: (Pick<Block, 'feedId' | 'actorId' | 'sequence' | 'position'> & {
|
|
105
|
+
feedNamespace: string;
|
|
106
|
+
})[];
|
|
107
|
+
}) => Effect.Effect<void, SqlError.SqlError | PositionConflictError, SqlClient.SqlClient>;
|
|
108
|
+
/**
|
|
109
|
+
* Gets all feeds and their blocks for a space, organized by feed ID and namespace.
|
|
110
|
+
* Used for space archive export.
|
|
111
|
+
*/
|
|
112
|
+
getAllFeedsForSpace: (opts: {
|
|
113
|
+
spaceId: SpaceId;
|
|
114
|
+
}) => Effect.Effect<Array<{
|
|
115
|
+
feedId: string;
|
|
116
|
+
feedNamespace: string;
|
|
117
|
+
blocks: Block[];
|
|
118
|
+
}>, SqlError.SqlError, SqlClient.SqlClient>;
|
|
26
119
|
}
|
|
120
|
+
export {};
|
|
27
121
|
//# sourceMappingURL=feed-store.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"feed-store.d.ts","sourceRoot":"","sources":["../../../src/feed-store.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,SAAS,MAAM,uBAAuB,CAAC;AACnD,OAAO,KAAK,KAAK,QAAQ,MAAM,sBAAsB,CAAC;AACtD,OAAO,KAAK,MAAM,MAAM,eAAe,CAAC;AAExC,OAAO,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AAEpC,OAAO,
|
|
1
|
+
{"version":3,"file":"feed-store.d.ts","sourceRoot":"","sources":["../../../src/feed-store.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,SAAS,MAAM,uBAAuB,CAAC;AACnD,OAAO,KAAK,KAAK,QAAQ,MAAM,sBAAsB,CAAC;AACtD,OAAO,KAAK,MAAM,MAAM,eAAe,CAAC;AAExC,OAAO,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AAEpC,OAAO,EAAE,KAAK,OAAO,EAAE,MAAM,YAAY,CAAC;AAC1C,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC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],"names":[],"mappings":"AAIA,cAAc,cAAc,CAAC;AAC7B,cAAc,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AAIA,cAAc,cAAc,CAAC;AAC7B,cAAc,UAAU,CAAC;AACzB,cAAc,eAAe,CAAC;AAC9B,cAAc,eAAe,CAAC"}
|