@dxos/feed 0.8.4-main.59c2e9b → 0.8.4-main.6fa680abb7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +6 -2
  2. package/dist/lib/neutral/chunk-2ENONWPH.mjs +703 -0
  3. package/dist/lib/neutral/chunk-2ENONWPH.mjs.map +7 -0
  4. package/dist/lib/neutral/index.mjs +13 -0
  5. package/dist/lib/neutral/meta.json +1 -0
  6. package/dist/lib/neutral/testing/index.mjs +173 -0
  7. package/dist/lib/neutral/testing/index.mjs.map +7 -0
  8. package/dist/types/src/errors.d.ts +39 -0
  9. package/dist/types/src/errors.d.ts.map +1 -0
  10. package/dist/types/src/feed-store.d.ts +92 -9
  11. package/dist/types/src/feed-store.d.ts.map +1 -1
  12. package/dist/types/src/index.d.ts +3 -1
  13. package/dist/types/src/index.d.ts.map +1 -1
  14. package/dist/types/src/sync-client.d.ts +53 -0
  15. package/dist/types/src/sync-client.d.ts.map +1 -0
  16. package/dist/types/src/sync-server.d.ts +27 -0
  17. package/dist/types/src/sync-server.d.ts.map +1 -0
  18. package/dist/types/src/testing/index.d.ts +1 -1
  19. package/dist/types/src/testing/index.d.ts.map +1 -1
  20. package/dist/types/src/testing/test-builder.d.ts +78 -0
  21. package/dist/types/src/testing/test-builder.d.ts.map +1 -0
  22. package/dist/types/tsconfig.tsbuildinfo +1 -1
  23. package/package.json +16 -13
  24. package/src/errors.ts +20 -0
  25. package/src/feed-store.test.ts +394 -39
  26. package/src/feed-store.ts +445 -140
  27. package/src/index.ts +3 -1
  28. package/src/sync-client.ts +188 -0
  29. package/src/sync-server.ts +92 -0
  30. package/src/sync.test.ts +151 -91
  31. package/src/testing/index.ts +1 -1
  32. package/src/testing/test-builder.ts +223 -0
  33. package/dist/lib/browser/index.mjs +0 -342
  34. package/dist/lib/browser/index.mjs.map +0 -7
  35. package/dist/lib/browser/meta.json +0 -1
  36. package/dist/lib/browser/testing/index.mjs +0 -1
  37. package/dist/lib/node-esm/index.mjs +0 -344
  38. package/dist/lib/node-esm/index.mjs.map +0 -7
  39. package/dist/lib/node-esm/meta.json +0 -1
  40. package/dist/lib/node-esm/testing/index.mjs +0 -2
  41. package/dist/lib/node-esm/testing/index.mjs.map +0 -7
  42. package/dist/types/src/protocol.d.ts +0 -120
  43. package/dist/types/src/protocol.d.ts.map +0 -1
  44. package/src/protocol.ts +0 -110
  45. /package/dist/lib/{browser/testing → neutral}/index.mjs.map +0 -0
package/src/feed-store.ts CHANGED
@@ -7,73 +7,112 @@ import type * as SqlError from '@effect/sql/SqlError';
7
7
  import * as Effect from 'effect/Effect';
8
8
 
9
9
  import { Event } from '@dxos/async';
10
-
11
- import {
12
- type AppendRequest,
13
- type AppendResponse,
14
- type Block,
15
- FeedCursor,
16
- type QueryRequest,
17
- type QueryResponse,
18
- type SubscribeRequest,
19
- type SubscribeResponse,
20
- } from './protocol';
10
+ import { assertArgument } from '@dxos/invariant';
11
+ import { type SpaceId } from '@dxos/keys';
12
+ import { FeedProtocol } from '@dxos/protocols';
13
+ import { SqlTransaction } from '@dxos/sql-sqlite';
14
+
15
+ import { PositionConflictError } from './errors';
16
+
17
+ type AppendRequest = FeedProtocol.AppendRequest;
18
+ type AppendResponse = FeedProtocol.AppendResponse;
19
+ type Block = FeedProtocol.Block;
20
+ const FeedCursor = FeedProtocol.FeedCursor;
21
+ type FeedCursor = FeedProtocol.FeedCursor;
22
+ const isWellKnownNamespace = FeedProtocol.isWellKnownNamespace;
23
+ type QueryRequest = FeedProtocol.QueryRequest;
24
+ type QueryResponse = FeedProtocol.QueryResponse;
25
+ type SubscribeRequest = FeedProtocol.SubscribeRequest;
26
+ type SubscribeResponse = FeedProtocol.SubscribeResponse;
21
27
 
22
28
  export interface FeedStoreOptions {
29
+ /**
30
+ * The actor ID of the local user.
31
+ */
23
32
  localActorId: string;
33
+
34
+ /**
35
+ * Whether to assign positions to appended blocks.
36
+ * Only a single peer (usually the server) can assign positions.
37
+ */
24
38
  assignPositions: boolean;
25
39
  }
26
40
 
41
+ /**
42
+ * Persistent storage for feed metadata, blocks, subscriptions, and sync state.
43
+ *
44
+ */
27
45
  export class FeedStore {
28
- constructor(private readonly _options: FeedStoreOptions) {}
46
+ readonly #options: FeedStoreOptions;
29
47
 
48
+ constructor(options: FeedStoreOptions) {
49
+ this.#options = options;
50
+ }
51
+
52
+ /**
53
+ * Emits after successful block append operations.
54
+ */
30
55
  readonly onNewBlocks = new Event<void>();
31
56
 
32
- migrate = Effect.fn('FeedStore.migrate')(function* () {
33
- const sql = yield* SqlClient.SqlClient;
57
+ /**
58
+ * Creates required feed store tables and indexes if they do not exist.
59
+ */
60
+ migrate = Effect.fn('FeedStore.migrate')(() =>
61
+ Effect.gen(function* () {
62
+ const sql = yield* SqlClient.SqlClient;
34
63
 
35
- // Feeds Table
36
- yield* sql`CREATE TABLE IF NOT EXISTS feeds (
64
+ // Feeds Table
65
+ yield* sql`CREATE TABLE IF NOT EXISTS feeds (
37
66
  feedPrivateId INTEGER PRIMARY KEY AUTOINCREMENT,
38
67
  spaceId TEXT NOT NULL,
39
68
  feedId TEXT NOT NULL,
40
69
  feedNamespace TEXT
41
70
  )`;
42
- yield* sql`CREATE UNIQUE INDEX IF NOT EXISTS idx_feeds_spaceId_feedId ON feeds(spaceId, feedId)`;
71
+ yield* sql`CREATE UNIQUE INDEX IF NOT EXISTS idx_feeds_spaceId_feedId ON feeds(spaceId, feedId)`;
43
72
 
44
- // Blocks Table
45
- yield* sql`CREATE TABLE IF NOT EXISTS blocks (
73
+ // Blocks Table
74
+ yield* sql`CREATE TABLE IF NOT EXISTS blocks (
46
75
  insertionId INTEGER PRIMARY KEY AUTOINCREMENT,
47
76
  feedPrivateId INTEGER NOT NULL,
48
77
  position INTEGER,
49
78
  sequence INTEGER NOT NULL,
50
79
  actorId TEXT NOT NULL,
51
- predSequence INTEGER,
52
- predActorId TEXT,
80
+ prevSequence INTEGER,
81
+ prevActorId TEXT,
53
82
  timestamp INTEGER NOT NULL,
54
83
  data BLOB NOT NULL,
55
84
  FOREIGN KEY(feedPrivateId) REFERENCES feeds(feedPrivateId)
56
85
  )`;
57
- yield* sql`CREATE UNIQUE INDEX IF NOT EXISTS idx_blocks_feedPrivateId_position ON blocks(feedPrivateId, position)`;
58
- yield* sql`CREATE UNIQUE INDEX IF NOT EXISTS idx_blocks_feedPrivateId_sequence_actorId ON blocks(feedPrivateId, sequence, actorId)`;
86
+ yield* sql`CREATE UNIQUE INDEX IF NOT EXISTS idx_blocks_feedPrivateId_position ON blocks(feedPrivateId, position)`;
87
+ yield* sql`CREATE UNIQUE INDEX IF NOT EXISTS idx_blocks_feedPrivateId_sequence_actorId ON blocks(feedPrivateId, sequence, actorId)`;
59
88
 
60
- // Subscriptions Table
61
- yield* sql`CREATE TABLE IF NOT EXISTS subscriptions (
89
+ // Subscriptions Table
90
+ yield* sql`CREATE TABLE IF NOT EXISTS subscriptions (
62
91
  subscriptionId TEXT PRIMARY KEY,
63
92
  expiresAt INTEGER NOT NULL,
64
93
  feedPrivateIds TEXT NOT NULL -- JSON array
65
94
  )`;
66
95
 
67
- // Cursor Tokens Table
68
- yield* sql`CREATE TABLE IF NOT EXISTS cursor_tokens (
96
+ // Cursor Tokens Table
97
+ yield* sql`CREATE TABLE IF NOT EXISTS cursor_tokens (
69
98
  spaceId TEXT PRIMARY KEY,
70
99
  token TEXT NOT NULL
71
100
  )`;
72
- });
73
101
 
74
- // Internal Logic
102
+ // Sync State Table.
103
+ yield* sql`CREATE TABLE IF NOT EXISTS sync_state (
104
+ spaceId TEXT NOT NULL,
105
+ feedNamespace TEXT NOT NULL,
106
+ lastPulledPosition INTEGER NOT NULL DEFAULT -1,
107
+ PRIMARY KEY (spaceId, feedNamespace)
108
+ )`;
109
+ }).pipe(Effect.withSpan('FeedStore.migrate')),
110
+ );
75
111
 
76
- private _ensureFeed = Effect.fn('Feed.ensureFeed')(
112
+ /**
113
+ * Ensures a feed row exists and returns its internal feed ID.
114
+ */
115
+ #ensureFeed = Effect.fn('Feed.ensureFeed')(
77
116
  (
78
117
  spaceId: string,
79
118
  feedId: string,
@@ -91,10 +130,13 @@ export class FeedStore {
91
130
  INSERT INTO feeds (spaceId, feedId, feedNamespace) VALUES (${spaceId}, ${feedId}, ${namespace}) RETURNING feedPrivateId
92
131
  `;
93
132
  return newRows[0].feedPrivateId;
94
- }),
133
+ }).pipe(Effect.withSpan('FeedStore.ensureFeed')),
95
134
  );
96
135
 
97
- private _ensureCursorToken = Effect.fn('Feed.ensureCursorToken')(
136
+ /**
137
+ * Ensures cursor token exists for a space and returns it.
138
+ */
139
+ #ensureCursorToken = Effect.fn('Feed.ensureCursorToken')(
98
140
  (spaceId: string): Effect.Effect<string, SqlError.SqlError, SqlClient.SqlClient> =>
99
141
  Effect.gen(this, function* () {
100
142
  const sql = yield* SqlClient.SqlClient;
@@ -104,11 +146,12 @@ export class FeedStore {
104
146
  const token = crypto.randomUUID().replace(/-/g, '').slice(0, 6);
105
147
  yield* sql`INSERT INTO cursor_tokens (spaceId, token) VALUES (${spaceId}, ${token})`;
106
148
  return token;
107
- }),
149
+ }).pipe(Effect.withSpan('FeedStore.ensureCursorToken')),
108
150
  );
109
151
 
110
- // RPCs
111
-
152
+ /**
153
+ * Queries feed blocks by feed IDs or subscription with cursor/position pagination.
154
+ */
112
155
  query = Effect.fn('Feed.query')(
113
156
  (request: QueryRequest): Effect.Effect<QueryResponse, SqlError.SqlError, SqlClient.SqlClient> =>
114
157
  Effect.gen(this, function* () {
@@ -121,6 +164,15 @@ export class FeedStore {
121
164
  return yield* Effect.die(new Error('spaceId is required'));
122
165
  }
123
166
 
167
+ if (
168
+ (request.position !== undefined ? 1 : 0) +
169
+ (request.cursor !== undefined ? 1 : 0) +
170
+ (request.unpositionedOnly === true ? 1 : 0) >
171
+ 1
172
+ ) {
173
+ return yield* Effect.die(new Error('Only one of position, cursor, or unpositionedOnly can be used'));
174
+ }
175
+
124
176
  if (request.cursor) {
125
177
  const { token, insertionId } = decodeCursor(request.cursor as FeedCursor);
126
178
  if (!token || insertionId === undefined || isNaN(insertionId)) {
@@ -130,8 +182,8 @@ export class FeedStore {
130
182
  cursorInsertionId = insertionId;
131
183
  }
132
184
 
133
- // Validate Token if cursor used
134
- const validCursorToken = yield* this._ensureCursorToken(request.spaceId);
185
+ // Validate Token if cursor used.
186
+ const validCursorToken = yield* this.#ensureCursorToken(request.spaceId);
135
187
  if (request.cursor && cursorToken !== validCursorToken) {
136
188
  return yield* Effect.die(new Error(`Cursor token mismatch`));
137
189
  }
@@ -140,7 +192,7 @@ export class FeedStore {
140
192
  // If spaceId is not provided in request (e.g. feedIds query), we can't easily validate token unless we look up spaceId for feedIds.
141
193
  // Ideally spaceId should be required for token validation.
142
194
 
143
- /*
195
+ /*
144
196
  Logic:
145
197
  1. If `cursor` is present, it's `token|insertionId`.
146
198
  2. If `position` is present, it's `position` (legacy/manual).
@@ -150,8 +202,8 @@ export class FeedStore {
150
202
 
151
203
  const position = request.position ?? -1;
152
204
 
153
- // Resolve Subscriptions or FeedIds
154
- if ('subscriptionId' in request.query) {
205
+ // Resolve subscriptions or feed IDs.
206
+ if (request.query && 'subscriptionId' in request.query) {
155
207
  const rows = yield* sql<{ feedPrivateIds: string; expiresAt: number }>`
156
208
  SELECT feedPrivateIds, expiresAt FROM subscriptions WHERE subscriptionId = ${request.query.subscriptionId}
157
209
  `;
@@ -167,50 +219,57 @@ export class FeedStore {
167
219
  }
168
220
  }
169
221
  }
170
- } else if ('feedIds' in request.query) {
171
- feedIds = [...(request.query as any).feedIds];
222
+ } else if (request.query && 'feedIds' in request.query) {
223
+ feedIds = [...request.query.feedIds];
172
224
  } else {
173
225
  feedIds = undefined;
174
226
  }
175
227
 
176
228
  if (feedIds !== undefined && feedIds.length === 0) {
177
- return { requestId: request.requestId, blocks: [], nextCursor: encodeCursor(validCursorToken, -1) };
229
+ return {
230
+ requestId: request.requestId,
231
+ blocks: [],
232
+ nextCursor: encodeCursor(validCursorToken, -1),
233
+ hasMore: false,
234
+ };
178
235
  }
179
236
 
180
- // Fetch Blocks
237
+ // Fetch blocks.
181
238
  const query = sql<Block>`
182
- SELECT blocks.*, feeds.feedId
239
+ SELECT blocks.*, feeds.feedId, feeds.feedNamespace
183
240
  FROM blocks
184
241
  JOIN feeds ON blocks.feedPrivateId = feeds.feedPrivateId
185
242
  WHERE 1=1
186
243
  ${feedIds !== undefined ? sql`AND feeds.feedId IN ${sql.in(feedIds)}` : sql``}
187
244
  ${request.spaceId ? sql`AND feeds.spaceId = ${request.spaceId}` : sql``}
188
- ${
189
- 'feedNamespace' in request.query && request.query.feedNamespace
190
- ? sql`AND feeds.feedNamespace = ${request.query.feedNamespace}`
191
- : sql``
192
- }
245
+ ${sql`AND feeds.feedNamespace = ${request.feedNamespace}`}
193
246
  `;
194
247
 
195
- // Add filter based on cursor or position
248
+ // Add filter based on cursor or position.
196
249
  const filter = request.cursor
197
250
  ? sql`AND blocks.insertionId > ${cursorInsertionId}`
198
- : sql`AND (blocks.position > ${position} OR blocks.position IS NULL)`;
251
+ : request.unpositionedOnly
252
+ ? sql`AND blocks.position IS NULL`
253
+ : sql`AND (blocks.position > ${position} OR blocks.position IS NULL)`;
199
254
 
200
255
  const orderBy = request.cursor
201
256
  ? sql`ORDER BY blocks.insertionId ASC`
202
257
  : sql`ORDER BY blocks.position ASC NULLS LAST`;
203
258
 
259
+ const requestLimit = request.limit;
260
+ const queryLimit = requestLimit != null ? requestLimit + 1 : undefined;
204
261
  const rows = yield* sql<Block>`
205
262
  ${query}
206
263
  ${filter}
207
264
  ${orderBy}
208
- ${request.limit ? sql`LIMIT ${request.limit}` : sql``}
265
+ ${queryLimit != null ? sql`LIMIT ${queryLimit}` : sql``}
209
266
  `;
210
267
 
211
- const blocks = rows.map((row) => ({
268
+ const hasMore = requestLimit != null && rows.length > requestLimit;
269
+ const slice = hasMore ? rows.slice(0, requestLimit) : rows;
270
+ const blocks = slice.map((row) => ({
212
271
  ...row,
213
- // Have to buffer otherwise we get empty Uint8Array.
272
+ // Have to clone buffer otherwise we get empty Uint8Array.
214
273
  data: new Uint8Array(row.data),
215
274
  }));
216
275
 
@@ -222,10 +281,13 @@ export class FeedStore {
222
281
  }
223
282
  }
224
283
 
225
- return { requestId: request.requestId, blocks, nextCursor } satisfies QueryResponse;
226
- }),
284
+ return { requestId: request.requestId, blocks, nextCursor, hasMore } satisfies QueryResponse;
285
+ }).pipe(Effect.withSpan('FeedStore.query')),
227
286
  );
228
287
 
288
+ /**
289
+ * Creates a subscription and stores the resolved internal feed IDs.
290
+ */
229
291
  subscribe = Effect.fn('Feed.subscribe')(
230
292
  (request: SubscribeRequest): Effect.Effect<SubscribeResponse, SqlError.SqlError, SqlClient.SqlClient> =>
231
293
  Effect.gen(this, function* () {
@@ -241,7 +303,7 @@ export class FeedStore {
241
303
 
242
304
  const feedPrivateIds = yield* Effect.forEach(
243
305
  request.feedIds,
244
- (feedId) => this._ensureFeed(request.spaceId!, feedId),
306
+ (feedId) => this.#ensureFeed(request.spaceId!, feedId),
245
307
  { concurrency: 'unbounded' },
246
308
  );
247
309
 
@@ -255,119 +317,362 @@ export class FeedStore {
255
317
  subscriptionId,
256
318
  expiresAt,
257
319
  };
258
- }),
320
+ }).pipe(Effect.withSpan('FeedStore.subscribe')),
259
321
  );
260
322
 
261
- append = Effect.fn('Feed.append')(
262
- (request: AppendRequest): Effect.Effect<AppendResponse, SqlError.SqlError, SqlClient.SqlClient> =>
263
- Effect.gen(this, function* () {
264
- const sql = yield* SqlClient.SqlClient;
265
- const positions: number[] = [];
266
-
267
- if (!request.spaceId) {
268
- return yield* Effect.die(new Error('spaceId required for append'));
269
- }
270
-
271
- for (const block of request.blocks) {
272
- const feedId = request.feedId ?? block.actorId;
273
- const feedPrivateId = yield* this._ensureFeed(request.spaceId, feedId, request.namespace);
323
+ /**
324
+ * Get the last pulled position for the given space and namespace.
325
+ * Returns -1 if no sync state exists yet.
326
+ */
327
+ getSyncState = (opts: {
328
+ spaceId: SpaceId;
329
+ feedNamespace: string;
330
+ }): Effect.Effect<number, SqlError.SqlError, SqlClient.SqlClient> =>
331
+ Effect.gen(this, function* () {
332
+ const sql = yield* SqlClient.SqlClient;
333
+ const rows = yield* sql<{ lastPulledPosition: number }>`
334
+ SELECT lastPulledPosition FROM sync_state
335
+ WHERE spaceId = ${opts.spaceId} AND feedNamespace = ${opts.feedNamespace}
336
+ `;
337
+ return rows[0]?.lastPulledPosition ?? -1;
338
+ }).pipe(Effect.withSpan('FeedStore.getSyncState'));
339
+
340
+ /**
341
+ * Update the last pulled position for the given space and namespace.
342
+ */
343
+ setSyncState = (opts: {
344
+ spaceId: SpaceId;
345
+ feedNamespace: string;
346
+ lastPulledPosition: number;
347
+ }): Effect.Effect<void, SqlError.SqlError, SqlClient.SqlClient> =>
348
+ Effect.gen(this, function* () {
349
+ const sql = yield* SqlClient.SqlClient;
350
+ yield* sql`
351
+ INSERT INTO sync_state (spaceId, feedNamespace, lastPulledPosition)
352
+ VALUES (${opts.spaceId}, ${opts.feedNamespace}, ${opts.lastPulledPosition})
353
+ ON CONFLICT (spaceId, feedNamespace) DO UPDATE SET lastPulledPosition = ${opts.lastPulledPosition}
354
+ `;
355
+ }).pipe(Effect.withSpan('FeedStore.setSyncState'));
356
+
357
+ /**
358
+ * Returns the number of stored blocks for a single feed in a space/namespace.
359
+ * Intended as a low-level primitive for callers (for example Cloudflare Worker code)
360
+ * that need to make retention decisions under constrained storage resources.
361
+ */
362
+ countBlocks = (opts: {
363
+ spaceId: SpaceId;
364
+ feedNamespace: string;
365
+ feedId: string;
366
+ }): Effect.Effect<number, SqlError.SqlError, SqlClient.SqlClient> =>
367
+ Effect.gen(this, function* () {
368
+ const sql = yield* SqlClient.SqlClient;
369
+ const rows = yield* sql<{ count: number }>`
370
+ SELECT COUNT(*) AS count
371
+ FROM blocks
372
+ JOIN feeds ON blocks.feedPrivateId = feeds.feedPrivateId
373
+ WHERE feeds.spaceId = ${opts.spaceId}
374
+ AND feeds.feedNamespace = ${opts.feedNamespace}
375
+ AND feeds.feedId = ${opts.feedId}
376
+ `;
377
+ return rows[0]?.count ?? 0;
378
+ }).pipe(Effect.withSpan('FeedStore.countBlocks'));
379
+
380
+ /**
381
+ * Deletes the oldest blocks for a single feed in a space/namespace.
382
+ * This API intentionally does not enforce any retention policy (such as max size);
383
+ * callers decide when and how much to prune, which is useful for constrained
384
+ * environments like Cloudflare Workers.
385
+ *
386
+ * @returns Number of deleted rows.
387
+ */
388
+ deleteOldestBlocks = (opts: {
389
+ spaceId: SpaceId;
390
+ feedNamespace: string;
391
+ feedId: string;
392
+ count: number;
393
+ }): Effect.Effect<number, SqlError.SqlError, SqlClient.SqlClient> =>
394
+ Effect.gen(this, function* () {
395
+ const sql = yield* SqlClient.SqlClient;
396
+ if (opts.count <= 0) {
397
+ return 0;
398
+ }
399
+
400
+ const deletedRows = yield* sql<{ insertionId: number }>`
401
+ DELETE FROM blocks
402
+ WHERE insertionId IN (
403
+ SELECT blocks.insertionId
404
+ FROM blocks
405
+ JOIN feeds ON blocks.feedPrivateId = feeds.feedPrivateId
406
+ WHERE feeds.spaceId = ${opts.spaceId}
407
+ AND feeds.feedNamespace = ${opts.feedNamespace}
408
+ AND feeds.feedId = ${opts.feedId}
409
+ ORDER BY blocks.insertionId ASC
410
+ LIMIT ${opts.count}
411
+ )
412
+ RETURNING insertionId
413
+ `;
414
+
415
+ return deletedRows.length;
416
+ }).pipe(Effect.withSpan('FeedStore.deleteOldestBlocks'));
417
+
418
+ /**
419
+ * Appends blocks for a space/namespace and optionally assigns global positions.
420
+ */
421
+ append = (
422
+ request: AppendRequest,
423
+ ): Effect.Effect<AppendResponse, SqlError.SqlError, SqlClient.SqlClient | SqlTransaction.SqlTransaction> =>
424
+ Effect.gen(this, function* () {
425
+ if (!request.spaceId) {
426
+ return yield* Effect.die(new Error('spaceId required for append'));
427
+ }
428
+
429
+ assertArgument(
430
+ isWellKnownNamespace(request.feedNamespace),
431
+ 'request.feedNamespace',
432
+ 'specified well-known namespace',
433
+ );
434
+
435
+ // Validate all blocks upfront.
436
+ for (const block of request.blocks) {
437
+ assertArgument(block.feedId, 'block.feedId', 'feedId is required');
438
+ }
439
+
440
+ // Wrap in transaction to ensure atomicity when assigning positions.
441
+ const sqlTransaction = yield* SqlTransaction.SqlTransaction;
442
+ const positions = yield* sqlTransaction.withTransaction(
443
+ Effect.gen(this, function* () {
444
+ const sql = yield* SqlClient.SqlClient;
445
+
446
+ // 1. Collect unique feed IDs and batch #ensureFeed calls.
447
+ const feedKeys = new Map<string, { feedId: string }>();
448
+ for (const block of request.blocks) {
449
+ const key = block.feedId!;
450
+ if (!feedKeys.has(key)) {
451
+ feedKeys.set(key, { feedId: block.feedId! });
452
+ }
453
+ }
274
454
 
275
- let nextPos = null;
276
- if (this._options.assignPositions) {
455
+ const feedPrivateIds = new Map<string, number>();
456
+ yield* Effect.forEach(
457
+ [...feedKeys.entries()],
458
+ ([key, { feedId }]) =>
459
+ Effect.gen(this, function* () {
460
+ const id = yield* this.#ensureFeed(request.spaceId!, feedId, request.feedNamespace);
461
+ feedPrivateIds.set(key, id);
462
+ }),
463
+ { concurrency: 'unbounded' },
464
+ );
465
+
466
+ // 2. Get max position per namespace ONCE (not per block).
467
+ const maxPositions = new Map<string, number>();
468
+ if (this.#options.assignPositions) {
277
469
  const maxPosResult = yield* sql<{ maxPos: number | null }>`
278
- SELECT MAX(position) as maxPos
279
- FROM blocks
280
- JOIN feeds ON blocks.feedPrivateId = feeds.feedPrivateId
281
- WHERE feeds.spaceId = ${request.spaceId}
282
- `;
283
- nextPos = (maxPosResult[0]?.maxPos ?? -1) + 1;
284
- positions.push(nextPos);
470
+ SELECT MAX(position) as maxPos
471
+ FROM blocks
472
+ JOIN feeds ON blocks.feedPrivateId = feeds.feedPrivateId
473
+ WHERE feeds.spaceId = ${request.spaceId} AND feeds.feedNamespace = ${request.feedNamespace}
474
+ `;
475
+ maxPositions.set(request.feedNamespace, maxPosResult[0]?.maxPos ?? -1);
285
476
  }
286
477
 
287
- yield* sql`
288
- INSERT INTO blocks (
289
- feedPrivateId, position, sequence, actorId,
290
- predSequence, predActorId, timestamp, data
291
- ) VALUES (
292
- ${feedPrivateId}, ${nextPos}, ${block.sequence}, ${block.actorId},
293
- ${block.predSequence}, ${block.predActorId}, ${block.timestamp}, ${block.data}
294
- ) ON CONFLICT DO NOTHING
478
+ // 3. Insert all blocks and compute positions.
479
+ const positions: number[] = [];
480
+ for (const block of request.blocks) {
481
+ const key = block.feedId!;
482
+ const feedPrivateId = feedPrivateIds.get(key)!;
483
+
484
+ let positionToInsert: number | null = null;
485
+ if (this.#options.assignPositions) {
486
+ const currentMax = maxPositions.get(request.feedNamespace)!;
487
+ positionToInsert = currentMax + 1;
488
+ maxPositions.set(request.feedNamespace, positionToInsert); // Increment for next block in same namespace.
489
+ positions.push(positionToInsert);
490
+ } else if (block.position != null) {
491
+ positionToInsert = block.position;
492
+ }
493
+
494
+ yield* sql`
495
+ INSERT INTO blocks (
496
+ feedPrivateId, position, sequence, actorId,
497
+ prevSequence, prevActorId, timestamp, data
498
+ ) VALUES (
499
+ ${feedPrivateId}, ${positionToInsert}, ${block.sequence}, ${block.actorId},
500
+ ${block.prevSequence}, ${block.prevActorId}, ${block.timestamp}, ${block.data}
501
+ ) ON CONFLICT DO NOTHING
295
502
  `;
296
- }
503
+ }
297
504
 
298
- this.onNewBlocks.emit();
505
+ return positions;
506
+ }),
507
+ );
299
508
 
300
- return { requestId: request.requestId, positions };
301
- }),
302
- );
509
+ this.onNewBlocks.emit();
303
510
 
511
+ return { requestId: request.requestId, positions };
512
+ }).pipe(Effect.withSpan('FeedStore.append'));
513
+
514
+ /**
515
+ * Creates local blocks with sequential predecessors and appends grouped batches.
516
+ */
304
517
  appendLocal = Effect.fn('Feed.appendLocal')(
305
518
  (
306
519
  messages: { spaceId: string; feedId: string; feedNamespace: string; data: Uint8Array }[],
307
- ): Effect.Effect<Block[], SqlError.SqlError, SqlClient.SqlClient> =>
520
+ ): Effect.Effect<Block[], SqlError.SqlError, SqlClient.SqlClient | SqlTransaction.SqlTransaction> =>
308
521
  Effect.gen(this, function* () {
309
522
  const sql = yield* SqlClient.SqlClient;
310
- const blocks: Block[] = [];
311
-
312
- // Group by spaceId for efficient processing? Or just iterate.
313
- // Assuming small batch.
314
523
 
524
+ // 1. Collect unique feeds and ensure they exist.
525
+ type FeedKey = string; // `${spaceId}|${feedNamespace}|${feedId}`
526
+ const feedKeys = new Map<FeedKey, { spaceId: string; feedId: string; feedNamespace: string }>();
315
527
  for (const msg of messages) {
316
- // Get last block for this feed to determine sequence and predecessor.
317
- // Assumes we are the writer (localActorId).
318
- // If we are not localActorId, we shouldn't be creating blocks this way?
319
- // The user said: "uses local actorId". So feedId in message might be ignored?
320
- // Or message provides feedId?
321
- // User said: "client provides (only data + spaceId, feedId, feedNamespace)".
322
- // If client provides feedId, does it match localActorId?
323
- // If localActorId is fixed for the device, and we are appending to "my" feed, feedId should be localActorId.
324
- // If the client explicitly passes feedId, maybe they want to write to a specific feed (e.g. if they have multiple identities?).
325
- // But spec says "uses local actorId". I will use `this._options.localActorId`.
326
- // But `messages` arg has `feedId`.
327
- // I'll assume `msg.feedId` must match `localActorId` or we just use `localActorId` and ignore `msg.feedId`?
328
- // User: "client provides ... feedId".
329
- // I will use passed feedId but it should probably match localActorId if we are signing? (No signing here yet).
330
- // I'll use passed `feedId`.
331
-
332
- const feedPrivateId = yield* this._ensureFeed(msg.spaceId, msg.feedId, msg.feedNamespace);
333
-
334
- // Get last block to determine sequence.
528
+ const key = `${msg.spaceId}|${msg.feedNamespace}|${msg.feedId}`;
529
+ if (!feedKeys.has(key)) {
530
+ feedKeys.set(key, { spaceId: msg.spaceId, feedId: msg.feedId, feedNamespace: msg.feedNamespace });
531
+ }
532
+ }
533
+
534
+ // Batch ensure feeds and get their private IDs.
535
+ const feedPrivateIds = new Map<FeedKey, number>();
536
+ yield* Effect.forEach(
537
+ [...feedKeys.entries()],
538
+ ([key, { spaceId, feedId, feedNamespace }]) =>
539
+ Effect.gen(this, function* () {
540
+ const id = yield* this.#ensureFeed(spaceId, feedId, feedNamespace);
541
+ feedPrivateIds.set(key, id);
542
+ }),
543
+ { concurrency: 'unbounded' },
544
+ );
545
+
546
+ // 2. Get last sequence for each unique feed (batch query).
547
+ const lastSeqs = new Map<FeedKey, { sequence: number; actorId: string } | null>();
548
+ for (const [key] of feedKeys) {
549
+ const feedPrivateId = feedPrivateIds.get(key)!;
335
550
  const lastBlockResult = yield* sql<{ sequence: number; actorId: string }>`
336
- SELECT sequence, actorId FROM blocks
337
- WHERE feedPrivateId = ${feedPrivateId}
338
- ORDER BY sequence DESC
339
- LIMIT 1
340
- `; // This gets checks only THIS feed.
551
+ SELECT sequence, actorId FROM blocks
552
+ WHERE feedPrivateId = ${feedPrivateId}
553
+ ORDER BY sequence DESC
554
+ LIMIT 1
555
+ `;
556
+ lastSeqs.set(key, lastBlockResult[0] ?? null);
557
+ }
558
+
559
+ // 3. Build all blocks with correct sequences.
560
+ // Track in-flight sequences per feed to handle multiple messages to same feed.
561
+ const currentSeqs = new Map<FeedKey, { sequence: number; actorId: string }>();
562
+ const blocks: Block[] = [];
563
+ const blocksBySpaceNamespace = new Map<string, { spaceId: string; feedNamespace: string; blocks: Block[] }>();
341
564
 
342
- const lastBlock = lastBlockResult[0];
343
- const sequence = (lastBlock?.sequence ?? -1) + 1;
344
- const predSequence = lastBlock?.sequence ?? null;
345
- const predActorId = lastBlock?.actorId ?? null;
565
+ for (const msg of messages) {
566
+ const key = `${msg.spaceId}|${msg.feedNamespace}|${msg.feedId}`;
567
+
568
+ // Determine predecessor: either from in-flight blocks or from DB.
569
+ let sequence: number;
570
+ let prevSequence: number | null;
571
+ let prevActorId: string | null;
572
+
573
+ const inFlight = currentSeqs.get(key);
574
+ if (inFlight) {
575
+ // We've already added blocks for this feed - continue from last in-flight.
576
+ sequence = inFlight.sequence + 1;
577
+ prevSequence = inFlight.sequence;
578
+ prevActorId = inFlight.actorId;
579
+ } else {
580
+ // First block for this feed - use DB state.
581
+ const lastBlock = lastSeqs.get(key);
582
+ sequence = (lastBlock?.sequence ?? -1) + 1;
583
+ prevSequence = lastBlock?.sequence ?? null;
584
+ prevActorId = lastBlock?.actorId ?? null;
585
+ }
346
586
 
347
587
  const block: Block = {
348
- feedId: undefined,
349
- actorId: this._options.localActorId,
588
+ feedId: msg.feedId,
589
+ actorId: this.#options.localActorId,
350
590
  sequence,
351
- predActorId,
352
- predSequence,
591
+ prevActorId,
592
+ prevSequence,
353
593
  timestamp: Date.now(),
354
594
  data: msg.data,
355
- position: null, // assigned by append
595
+ position: null, // Assigned by append.
356
596
  };
597
+
357
598
  blocks.push(block);
358
599
 
359
- // Call append to persist (and assign position if allowed).
360
- yield* this.append({
600
+ // Update in-flight tracking.
601
+ currentSeqs.set(key, { sequence, actorId: this.#options.localActorId });
602
+
603
+ // Group by (spaceId, feedNamespace).
604
+ const spaceNamespaceKey = `${msg.spaceId}|${msg.feedNamespace}`;
605
+ if (!blocksBySpaceNamespace.has(spaceNamespaceKey)) {
606
+ blocksBySpaceNamespace.set(spaceNamespaceKey, {
607
+ spaceId: msg.spaceId,
608
+ feedNamespace: msg.feedNamespace,
609
+ blocks: [],
610
+ });
611
+ }
612
+ blocksBySpaceNamespace.get(spaceNamespaceKey)!.blocks.push(block);
613
+ }
614
+
615
+ // 4. Call append once per (spaceId, namespace) batch and assign returned positions.
616
+ const positionByBlock = new Map<Block, number | null>();
617
+ for (const { spaceId, feedNamespace, blocks: batchBlocks } of blocksBySpaceNamespace.values()) {
618
+ const { positions } = yield* this.append({
361
619
  requestId: 'local-append',
362
- namespace: msg.feedNamespace,
363
- blocks: [block],
364
- spaceId: msg.spaceId,
365
- feedId: msg.feedId,
620
+ blocks: batchBlocks,
621
+ spaceId,
622
+ feedNamespace,
366
623
  });
624
+ for (let i = 0; i < batchBlocks.length; i++) {
625
+ positionByBlock.set(batchBlocks[i], positions[i] ?? null);
626
+ }
367
627
  }
368
- return blocks;
369
- }),
628
+
629
+ return blocks.map((block) => ({
630
+ ...block,
631
+ position: positionByBlock.get(block) ?? block.position,
632
+ }));
633
+ }).pipe(Effect.withSpan('FeedStore.appendLocal')),
370
634
  );
635
+
636
+ /**
637
+ * Sets positions for existing blocks while preventing conflicting reassignments.
638
+ */
639
+ setPosition = (request: {
640
+ spaceId: string;
641
+ blocks: (Pick<Block, 'feedId' | 'actorId' | 'sequence' | 'position'> & { feedNamespace: string })[];
642
+ }): Effect.Effect<void, SqlError.SqlError | PositionConflictError, SqlClient.SqlClient> =>
643
+ Effect.gen(this, function* () {
644
+ const sql = yield* SqlClient.SqlClient;
645
+ for (const block of request.blocks) {
646
+ const existing = yield* sql<{ position: number | null }>`
647
+ SELECT position FROM blocks
648
+ WHERE feedPrivateId = (
649
+ SELECT feedPrivateId FROM feeds
650
+ WHERE spaceId = ${request.spaceId} AND feedId = ${block.feedId} AND feedNamespace = ${block.feedNamespace}
651
+ )
652
+ AND actorId = ${block.actorId} AND sequence = ${block.sequence}
653
+ `;
654
+ const current = existing[0];
655
+ if (current?.position != null && current.position !== block.position) {
656
+ yield* Effect.fail(
657
+ new PositionConflictError({
658
+ feedId: block.feedId,
659
+ actorId: block.actorId,
660
+ sequence: block.sequence,
661
+ currentPosition: current.position,
662
+ requestedPosition: block.position,
663
+ }),
664
+ );
665
+ }
666
+ yield* sql`
667
+ UPDATE blocks SET position = ${block.position}
668
+ WHERE feedPrivateId = (
669
+ SELECT feedPrivateId FROM feeds
670
+ WHERE spaceId = ${request.spaceId} AND feedId = ${block.feedId} AND feedNamespace = ${block.feedNamespace}
671
+ )
672
+ AND actorId = ${block.actorId} AND sequence = ${block.sequence}
673
+ `;
674
+ }
675
+ }).pipe(Effect.withSpan('FeedStore.setPosition'));
371
676
  }
372
677
 
373
678
  const encodeCursor = (token: string, insertionId: number) => FeedCursor.make(`${token}|${insertionId}`);