@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.
- package/README.md +6 -2
- package/dist/lib/neutral/chunk-2ENONWPH.mjs +703 -0
- package/dist/lib/neutral/chunk-2ENONWPH.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 +173 -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 +92 -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 +53 -0
- package/dist/types/src/sync-client.d.ts.map +1 -0
- package/dist/types/src/sync-server.d.ts +27 -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 +16 -13
- package/src/errors.ts +20 -0
- package/src/feed-store.test.ts +394 -39
- package/src/feed-store.ts +445 -140
- package/src/index.ts +3 -1
- package/src/sync-client.ts +188 -0
- package/src/sync-server.ts +92 -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,703 @@
|
|
|
1
|
+
// src/errors.ts
|
|
2
|
+
import { BaseError } from "@dxos/errors";
|
|
3
|
+
var PositionConflictError = class extends BaseError.extend("PositionConflictError") {
|
|
4
|
+
constructor(args) {
|
|
5
|
+
super({
|
|
6
|
+
message: `Block already has position ${args.currentPosition}, cannot set to ${args.requestedPosition} (feedId=${args.feedId} actorId=${args.actorId} sequence=${args.sequence}).`,
|
|
7
|
+
context: args
|
|
8
|
+
});
|
|
9
|
+
}
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
// src/feed-store.ts
|
|
13
|
+
import * as SqlClient from "@effect/sql/SqlClient";
|
|
14
|
+
import * as Effect from "effect/Effect";
|
|
15
|
+
import { Event } from "@dxos/async";
|
|
16
|
+
import { assertArgument } from "@dxos/invariant";
|
|
17
|
+
import { FeedProtocol } from "@dxos/protocols";
|
|
18
|
+
import { SqlTransaction } from "@dxos/sql-sqlite";
|
|
19
|
+
var FeedCursor = FeedProtocol.FeedCursor;
|
|
20
|
+
var isWellKnownNamespace = FeedProtocol.isWellKnownNamespace;
|
|
21
|
+
var FeedStore = class {
|
|
22
|
+
#options;
|
|
23
|
+
constructor(options) {
|
|
24
|
+
this.#options = options;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Emits after successful block append operations.
|
|
28
|
+
*/
|
|
29
|
+
onNewBlocks = new Event();
|
|
30
|
+
/**
|
|
31
|
+
* Creates required feed store tables and indexes if they do not exist.
|
|
32
|
+
*/
|
|
33
|
+
migrate = Effect.fn("FeedStore.migrate")(() => Effect.gen(function* () {
|
|
34
|
+
const sql = yield* SqlClient.SqlClient;
|
|
35
|
+
yield* sql`CREATE TABLE IF NOT EXISTS feeds (
|
|
36
|
+
feedPrivateId INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
37
|
+
spaceId TEXT NOT NULL,
|
|
38
|
+
feedId TEXT NOT NULL,
|
|
39
|
+
feedNamespace TEXT
|
|
40
|
+
)`;
|
|
41
|
+
yield* sql`CREATE UNIQUE INDEX IF NOT EXISTS idx_feeds_spaceId_feedId ON feeds(spaceId, feedId)`;
|
|
42
|
+
yield* sql`CREATE TABLE IF NOT EXISTS blocks (
|
|
43
|
+
insertionId INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
44
|
+
feedPrivateId INTEGER NOT NULL,
|
|
45
|
+
position INTEGER,
|
|
46
|
+
sequence INTEGER NOT NULL,
|
|
47
|
+
actorId TEXT NOT NULL,
|
|
48
|
+
prevSequence INTEGER,
|
|
49
|
+
prevActorId TEXT,
|
|
50
|
+
timestamp INTEGER NOT NULL,
|
|
51
|
+
data BLOB NOT NULL,
|
|
52
|
+
FOREIGN KEY(feedPrivateId) REFERENCES feeds(feedPrivateId)
|
|
53
|
+
)`;
|
|
54
|
+
yield* sql`CREATE UNIQUE INDEX IF NOT EXISTS idx_blocks_feedPrivateId_position ON blocks(feedPrivateId, position)`;
|
|
55
|
+
yield* sql`CREATE UNIQUE INDEX IF NOT EXISTS idx_blocks_feedPrivateId_sequence_actorId ON blocks(feedPrivateId, sequence, actorId)`;
|
|
56
|
+
yield* sql`CREATE TABLE IF NOT EXISTS subscriptions (
|
|
57
|
+
subscriptionId TEXT PRIMARY KEY,
|
|
58
|
+
expiresAt INTEGER NOT NULL,
|
|
59
|
+
feedPrivateIds TEXT NOT NULL -- JSON array
|
|
60
|
+
)`;
|
|
61
|
+
yield* sql`CREATE TABLE IF NOT EXISTS cursor_tokens (
|
|
62
|
+
spaceId TEXT PRIMARY KEY,
|
|
63
|
+
token TEXT NOT NULL
|
|
64
|
+
)`;
|
|
65
|
+
yield* sql`CREATE TABLE IF NOT EXISTS sync_state (
|
|
66
|
+
spaceId TEXT NOT NULL,
|
|
67
|
+
feedNamespace TEXT NOT NULL,
|
|
68
|
+
lastPulledPosition INTEGER NOT NULL DEFAULT -1,
|
|
69
|
+
PRIMARY KEY (spaceId, feedNamespace)
|
|
70
|
+
)`;
|
|
71
|
+
}).pipe(Effect.withSpan("FeedStore.migrate")));
|
|
72
|
+
/**
|
|
73
|
+
* Ensures a feed row exists and returns its internal feed ID.
|
|
74
|
+
*/
|
|
75
|
+
#ensureFeed = Effect.fn("Feed.ensureFeed")((spaceId, feedId, namespace) => Effect.gen(this, function* () {
|
|
76
|
+
const sql = yield* SqlClient.SqlClient;
|
|
77
|
+
const rows = yield* sql`
|
|
78
|
+
SELECT feedPrivateId FROM feeds WHERE spaceId = ${spaceId} AND feedId = ${feedId}
|
|
79
|
+
`;
|
|
80
|
+
if (rows.length > 0) return rows[0].feedPrivateId;
|
|
81
|
+
const newRows = yield* sql`
|
|
82
|
+
INSERT INTO feeds (spaceId, feedId, feedNamespace) VALUES (${spaceId}, ${feedId}, ${namespace}) RETURNING feedPrivateId
|
|
83
|
+
`;
|
|
84
|
+
return newRows[0].feedPrivateId;
|
|
85
|
+
}).pipe(Effect.withSpan("FeedStore.ensureFeed")));
|
|
86
|
+
/**
|
|
87
|
+
* Ensures cursor token exists for a space and returns it.
|
|
88
|
+
*/
|
|
89
|
+
#ensureCursorToken = Effect.fn("Feed.ensureCursorToken")((spaceId) => Effect.gen(this, function* () {
|
|
90
|
+
const sql = yield* SqlClient.SqlClient;
|
|
91
|
+
const rows = yield* sql`SELECT token FROM cursor_tokens WHERE spaceId = ${spaceId}`;
|
|
92
|
+
if (rows.length > 0) return rows[0].token;
|
|
93
|
+
const token = crypto.randomUUID().replace(/-/g, "").slice(0, 6);
|
|
94
|
+
yield* sql`INSERT INTO cursor_tokens (spaceId, token) VALUES (${spaceId}, ${token})`;
|
|
95
|
+
return token;
|
|
96
|
+
}).pipe(Effect.withSpan("FeedStore.ensureCursorToken")));
|
|
97
|
+
/**
|
|
98
|
+
* Queries feed blocks by feed IDs or subscription with cursor/position pagination.
|
|
99
|
+
*/
|
|
100
|
+
query = Effect.fn("Feed.query")((request) => Effect.gen(this, function* () {
|
|
101
|
+
const sql = yield* SqlClient.SqlClient;
|
|
102
|
+
let feedIds = [];
|
|
103
|
+
let cursorInsertionId = -1;
|
|
104
|
+
let cursorToken;
|
|
105
|
+
if (!request.spaceId) {
|
|
106
|
+
return yield* Effect.die(new Error("spaceId is required"));
|
|
107
|
+
}
|
|
108
|
+
if ((request.position !== void 0 ? 1 : 0) + (request.cursor !== void 0 ? 1 : 0) + (request.unpositionedOnly === true ? 1 : 0) > 1) {
|
|
109
|
+
return yield* Effect.die(new Error("Only one of position, cursor, or unpositionedOnly can be used"));
|
|
110
|
+
}
|
|
111
|
+
if (request.cursor) {
|
|
112
|
+
const { token, insertionId } = decodeCursor(request.cursor);
|
|
113
|
+
if (!token || insertionId === void 0 || isNaN(insertionId)) {
|
|
114
|
+
return yield* Effect.die(new Error(`Invalid cursor format`));
|
|
115
|
+
}
|
|
116
|
+
cursorToken = token;
|
|
117
|
+
cursorInsertionId = insertionId;
|
|
118
|
+
}
|
|
119
|
+
const validCursorToken = yield* this.#ensureCursorToken(request.spaceId);
|
|
120
|
+
if (request.cursor && cursorToken !== validCursorToken) {
|
|
121
|
+
return yield* Effect.die(new Error(`Cursor token mismatch`));
|
|
122
|
+
}
|
|
123
|
+
const position = request.position ?? -1;
|
|
124
|
+
if (request.query && "subscriptionId" in request.query) {
|
|
125
|
+
const rows2 = yield* sql`
|
|
126
|
+
SELECT feedPrivateIds, expiresAt FROM subscriptions WHERE subscriptionId = ${request.query.subscriptionId}
|
|
127
|
+
`;
|
|
128
|
+
if (rows2.length > 0) {
|
|
129
|
+
const { feedPrivateIds, expiresAt } = rows2[0];
|
|
130
|
+
if (Date.now() <= expiresAt) {
|
|
131
|
+
const privateIds = JSON.parse(feedPrivateIds);
|
|
132
|
+
if (privateIds.length > 0) {
|
|
133
|
+
const feedRows = yield* sql`
|
|
134
|
+
SELECT feedId FROM feeds WHERE feedPrivateId IN ${sql.in(privateIds)}
|
|
135
|
+
`;
|
|
136
|
+
feedIds = feedRows.map((r) => r.feedId);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
} else if (request.query && "feedIds" in request.query) {
|
|
141
|
+
feedIds = [
|
|
142
|
+
...request.query.feedIds
|
|
143
|
+
];
|
|
144
|
+
} else {
|
|
145
|
+
feedIds = void 0;
|
|
146
|
+
}
|
|
147
|
+
if (feedIds !== void 0 && feedIds.length === 0) {
|
|
148
|
+
return {
|
|
149
|
+
requestId: request.requestId,
|
|
150
|
+
blocks: [],
|
|
151
|
+
nextCursor: encodeCursor(validCursorToken, -1),
|
|
152
|
+
hasMore: false
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
const query = sql`
|
|
156
|
+
SELECT blocks.*, feeds.feedId, feeds.feedNamespace
|
|
157
|
+
FROM blocks
|
|
158
|
+
JOIN feeds ON blocks.feedPrivateId = feeds.feedPrivateId
|
|
159
|
+
WHERE 1=1
|
|
160
|
+
${feedIds !== void 0 ? sql`AND feeds.feedId IN ${sql.in(feedIds)}` : sql``}
|
|
161
|
+
${request.spaceId ? sql`AND feeds.spaceId = ${request.spaceId}` : sql``}
|
|
162
|
+
${sql`AND feeds.feedNamespace = ${request.feedNamespace}`}
|
|
163
|
+
`;
|
|
164
|
+
const filter = request.cursor ? sql`AND blocks.insertionId > ${cursorInsertionId}` : request.unpositionedOnly ? sql`AND blocks.position IS NULL` : sql`AND (blocks.position > ${position} OR blocks.position IS NULL)`;
|
|
165
|
+
const orderBy = request.cursor ? sql`ORDER BY blocks.insertionId ASC` : sql`ORDER BY blocks.position ASC NULLS LAST`;
|
|
166
|
+
const requestLimit = request.limit;
|
|
167
|
+
const queryLimit = requestLimit != null ? requestLimit + 1 : void 0;
|
|
168
|
+
const rows = yield* sql`
|
|
169
|
+
${query}
|
|
170
|
+
${filter}
|
|
171
|
+
${orderBy}
|
|
172
|
+
${queryLimit != null ? sql`LIMIT ${queryLimit}` : sql``}
|
|
173
|
+
`;
|
|
174
|
+
const hasMore = requestLimit != null && rows.length > requestLimit;
|
|
175
|
+
const slice = hasMore ? rows.slice(0, requestLimit) : rows;
|
|
176
|
+
const blocks = slice.map((row) => ({
|
|
177
|
+
...row,
|
|
178
|
+
// Have to clone buffer otherwise we get empty Uint8Array.
|
|
179
|
+
data: new Uint8Array(row.data)
|
|
180
|
+
}));
|
|
181
|
+
let nextCursor = request.cursor ?? encodeCursor(validCursorToken, -1);
|
|
182
|
+
if (blocks.length > 0 && request.spaceId) {
|
|
183
|
+
const lastBlock = blocks[blocks.length - 1];
|
|
184
|
+
if (lastBlock.insertionId !== void 0) {
|
|
185
|
+
nextCursor = encodeCursor(validCursorToken, lastBlock.insertionId);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
return {
|
|
189
|
+
requestId: request.requestId,
|
|
190
|
+
blocks,
|
|
191
|
+
nextCursor,
|
|
192
|
+
hasMore
|
|
193
|
+
};
|
|
194
|
+
}).pipe(Effect.withSpan("FeedStore.query")));
|
|
195
|
+
/**
|
|
196
|
+
* Creates a subscription and stores the resolved internal feed IDs.
|
|
197
|
+
*/
|
|
198
|
+
subscribe = Effect.fn("Feed.subscribe")((request) => Effect.gen(this, function* () {
|
|
199
|
+
const sql = yield* SqlClient.SqlClient;
|
|
200
|
+
const ttl = 60 * 60 * 1e3;
|
|
201
|
+
const subscriptionId = crypto.randomUUID();
|
|
202
|
+
const expiresAt = Date.now() + ttl;
|
|
203
|
+
if (!request.spaceId) {
|
|
204
|
+
return yield* Effect.die(new Error("spaceId required for subscribe"));
|
|
205
|
+
}
|
|
206
|
+
const feedPrivateIds = yield* Effect.forEach(request.feedIds, (feedId) => this.#ensureFeed(request.spaceId, feedId), {
|
|
207
|
+
concurrency: "unbounded"
|
|
208
|
+
});
|
|
209
|
+
yield* sql`
|
|
210
|
+
INSERT INTO subscriptions (subscriptionId, expiresAt, feedPrivateIds)
|
|
211
|
+
VALUES (${subscriptionId}, ${expiresAt}, ${JSON.stringify(feedPrivateIds)})
|
|
212
|
+
`;
|
|
213
|
+
return {
|
|
214
|
+
requestId: request.requestId,
|
|
215
|
+
subscriptionId,
|
|
216
|
+
expiresAt
|
|
217
|
+
};
|
|
218
|
+
}).pipe(Effect.withSpan("FeedStore.subscribe")));
|
|
219
|
+
/**
|
|
220
|
+
* Get the last pulled position for the given space and namespace.
|
|
221
|
+
* Returns -1 if no sync state exists yet.
|
|
222
|
+
*/
|
|
223
|
+
getSyncState = (opts) => Effect.gen(this, function* () {
|
|
224
|
+
const sql = yield* SqlClient.SqlClient;
|
|
225
|
+
const rows = yield* sql`
|
|
226
|
+
SELECT lastPulledPosition FROM sync_state
|
|
227
|
+
WHERE spaceId = ${opts.spaceId} AND feedNamespace = ${opts.feedNamespace}
|
|
228
|
+
`;
|
|
229
|
+
return rows[0]?.lastPulledPosition ?? -1;
|
|
230
|
+
}).pipe(Effect.withSpan("FeedStore.getSyncState"));
|
|
231
|
+
/**
|
|
232
|
+
* Update the last pulled position for the given space and namespace.
|
|
233
|
+
*/
|
|
234
|
+
setSyncState = (opts) => Effect.gen(this, function* () {
|
|
235
|
+
const sql = yield* SqlClient.SqlClient;
|
|
236
|
+
yield* sql`
|
|
237
|
+
INSERT INTO sync_state (spaceId, feedNamespace, lastPulledPosition)
|
|
238
|
+
VALUES (${opts.spaceId}, ${opts.feedNamespace}, ${opts.lastPulledPosition})
|
|
239
|
+
ON CONFLICT (spaceId, feedNamespace) DO UPDATE SET lastPulledPosition = ${opts.lastPulledPosition}
|
|
240
|
+
`;
|
|
241
|
+
}).pipe(Effect.withSpan("FeedStore.setSyncState"));
|
|
242
|
+
/**
|
|
243
|
+
* Returns the number of stored blocks for a single feed in a space/namespace.
|
|
244
|
+
* Intended as a low-level primitive for callers (for example Cloudflare Worker code)
|
|
245
|
+
* that need to make retention decisions under constrained storage resources.
|
|
246
|
+
*/
|
|
247
|
+
countBlocks = (opts) => Effect.gen(this, function* () {
|
|
248
|
+
const sql = yield* SqlClient.SqlClient;
|
|
249
|
+
const rows = yield* sql`
|
|
250
|
+
SELECT COUNT(*) AS count
|
|
251
|
+
FROM blocks
|
|
252
|
+
JOIN feeds ON blocks.feedPrivateId = feeds.feedPrivateId
|
|
253
|
+
WHERE feeds.spaceId = ${opts.spaceId}
|
|
254
|
+
AND feeds.feedNamespace = ${opts.feedNamespace}
|
|
255
|
+
AND feeds.feedId = ${opts.feedId}
|
|
256
|
+
`;
|
|
257
|
+
return rows[0]?.count ?? 0;
|
|
258
|
+
}).pipe(Effect.withSpan("FeedStore.countBlocks"));
|
|
259
|
+
/**
|
|
260
|
+
* Deletes the oldest blocks for a single feed in a space/namespace.
|
|
261
|
+
* This API intentionally does not enforce any retention policy (such as max size);
|
|
262
|
+
* callers decide when and how much to prune, which is useful for constrained
|
|
263
|
+
* environments like Cloudflare Workers.
|
|
264
|
+
*
|
|
265
|
+
* @returns Number of deleted rows.
|
|
266
|
+
*/
|
|
267
|
+
deleteOldestBlocks = (opts) => Effect.gen(this, function* () {
|
|
268
|
+
const sql = yield* SqlClient.SqlClient;
|
|
269
|
+
if (opts.count <= 0) {
|
|
270
|
+
return 0;
|
|
271
|
+
}
|
|
272
|
+
const deletedRows = yield* sql`
|
|
273
|
+
DELETE FROM blocks
|
|
274
|
+
WHERE insertionId IN (
|
|
275
|
+
SELECT blocks.insertionId
|
|
276
|
+
FROM blocks
|
|
277
|
+
JOIN feeds ON blocks.feedPrivateId = feeds.feedPrivateId
|
|
278
|
+
WHERE feeds.spaceId = ${opts.spaceId}
|
|
279
|
+
AND feeds.feedNamespace = ${opts.feedNamespace}
|
|
280
|
+
AND feeds.feedId = ${opts.feedId}
|
|
281
|
+
ORDER BY blocks.insertionId ASC
|
|
282
|
+
LIMIT ${opts.count}
|
|
283
|
+
)
|
|
284
|
+
RETURNING insertionId
|
|
285
|
+
`;
|
|
286
|
+
return deletedRows.length;
|
|
287
|
+
}).pipe(Effect.withSpan("FeedStore.deleteOldestBlocks"));
|
|
288
|
+
/**
|
|
289
|
+
* Appends blocks for a space/namespace and optionally assigns global positions.
|
|
290
|
+
*/
|
|
291
|
+
append = (request) => Effect.gen(this, function* () {
|
|
292
|
+
if (!request.spaceId) {
|
|
293
|
+
return yield* Effect.die(new Error("spaceId required for append"));
|
|
294
|
+
}
|
|
295
|
+
assertArgument(isWellKnownNamespace(request.feedNamespace), "request.feedNamespace", "specified well-known namespace");
|
|
296
|
+
for (const block of request.blocks) {
|
|
297
|
+
assertArgument(block.feedId, "block.feedId", "feedId is required");
|
|
298
|
+
}
|
|
299
|
+
const sqlTransaction = yield* SqlTransaction.SqlTransaction;
|
|
300
|
+
const positions = yield* sqlTransaction.withTransaction(Effect.gen(this, function* () {
|
|
301
|
+
const sql = yield* SqlClient.SqlClient;
|
|
302
|
+
const feedKeys = /* @__PURE__ */ new Map();
|
|
303
|
+
for (const block of request.blocks) {
|
|
304
|
+
const key = block.feedId;
|
|
305
|
+
if (!feedKeys.has(key)) {
|
|
306
|
+
feedKeys.set(key, {
|
|
307
|
+
feedId: block.feedId
|
|
308
|
+
});
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
const feedPrivateIds = /* @__PURE__ */ new Map();
|
|
312
|
+
yield* Effect.forEach([
|
|
313
|
+
...feedKeys.entries()
|
|
314
|
+
], ([key, { feedId }]) => Effect.gen(this, function* () {
|
|
315
|
+
const id = yield* this.#ensureFeed(request.spaceId, feedId, request.feedNamespace);
|
|
316
|
+
feedPrivateIds.set(key, id);
|
|
317
|
+
}), {
|
|
318
|
+
concurrency: "unbounded"
|
|
319
|
+
});
|
|
320
|
+
const maxPositions = /* @__PURE__ */ new Map();
|
|
321
|
+
if (this.#options.assignPositions) {
|
|
322
|
+
const maxPosResult = yield* sql`
|
|
323
|
+
SELECT MAX(position) as maxPos
|
|
324
|
+
FROM blocks
|
|
325
|
+
JOIN feeds ON blocks.feedPrivateId = feeds.feedPrivateId
|
|
326
|
+
WHERE feeds.spaceId = ${request.spaceId} AND feeds.feedNamespace = ${request.feedNamespace}
|
|
327
|
+
`;
|
|
328
|
+
maxPositions.set(request.feedNamespace, maxPosResult[0]?.maxPos ?? -1);
|
|
329
|
+
}
|
|
330
|
+
const positions2 = [];
|
|
331
|
+
for (const block of request.blocks) {
|
|
332
|
+
const key = block.feedId;
|
|
333
|
+
const feedPrivateId = feedPrivateIds.get(key);
|
|
334
|
+
let positionToInsert = null;
|
|
335
|
+
if (this.#options.assignPositions) {
|
|
336
|
+
const currentMax = maxPositions.get(request.feedNamespace);
|
|
337
|
+
positionToInsert = currentMax + 1;
|
|
338
|
+
maxPositions.set(request.feedNamespace, positionToInsert);
|
|
339
|
+
positions2.push(positionToInsert);
|
|
340
|
+
} else if (block.position != null) {
|
|
341
|
+
positionToInsert = block.position;
|
|
342
|
+
}
|
|
343
|
+
yield* sql`
|
|
344
|
+
INSERT INTO blocks (
|
|
345
|
+
feedPrivateId, position, sequence, actorId,
|
|
346
|
+
prevSequence, prevActorId, timestamp, data
|
|
347
|
+
) VALUES (
|
|
348
|
+
${feedPrivateId}, ${positionToInsert}, ${block.sequence}, ${block.actorId},
|
|
349
|
+
${block.prevSequence}, ${block.prevActorId}, ${block.timestamp}, ${block.data}
|
|
350
|
+
) ON CONFLICT DO NOTHING
|
|
351
|
+
`;
|
|
352
|
+
}
|
|
353
|
+
return positions2;
|
|
354
|
+
}));
|
|
355
|
+
this.onNewBlocks.emit();
|
|
356
|
+
return {
|
|
357
|
+
requestId: request.requestId,
|
|
358
|
+
positions
|
|
359
|
+
};
|
|
360
|
+
}).pipe(Effect.withSpan("FeedStore.append"));
|
|
361
|
+
/**
|
|
362
|
+
* Creates local blocks with sequential predecessors and appends grouped batches.
|
|
363
|
+
*/
|
|
364
|
+
appendLocal = Effect.fn("Feed.appendLocal")((messages) => Effect.gen(this, function* () {
|
|
365
|
+
const sql = yield* SqlClient.SqlClient;
|
|
366
|
+
const feedKeys = /* @__PURE__ */ new Map();
|
|
367
|
+
for (const msg of messages) {
|
|
368
|
+
const key = `${msg.spaceId}|${msg.feedNamespace}|${msg.feedId}`;
|
|
369
|
+
if (!feedKeys.has(key)) {
|
|
370
|
+
feedKeys.set(key, {
|
|
371
|
+
spaceId: msg.spaceId,
|
|
372
|
+
feedId: msg.feedId,
|
|
373
|
+
feedNamespace: msg.feedNamespace
|
|
374
|
+
});
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
const feedPrivateIds = /* @__PURE__ */ new Map();
|
|
378
|
+
yield* Effect.forEach([
|
|
379
|
+
...feedKeys.entries()
|
|
380
|
+
], ([key, { spaceId, feedId, feedNamespace }]) => Effect.gen(this, function* () {
|
|
381
|
+
const id = yield* this.#ensureFeed(spaceId, feedId, feedNamespace);
|
|
382
|
+
feedPrivateIds.set(key, id);
|
|
383
|
+
}), {
|
|
384
|
+
concurrency: "unbounded"
|
|
385
|
+
});
|
|
386
|
+
const lastSeqs = /* @__PURE__ */ new Map();
|
|
387
|
+
for (const [key] of feedKeys) {
|
|
388
|
+
const feedPrivateId = feedPrivateIds.get(key);
|
|
389
|
+
const lastBlockResult = yield* sql`
|
|
390
|
+
SELECT sequence, actorId FROM blocks
|
|
391
|
+
WHERE feedPrivateId = ${feedPrivateId}
|
|
392
|
+
ORDER BY sequence DESC
|
|
393
|
+
LIMIT 1
|
|
394
|
+
`;
|
|
395
|
+
lastSeqs.set(key, lastBlockResult[0] ?? null);
|
|
396
|
+
}
|
|
397
|
+
const currentSeqs = /* @__PURE__ */ new Map();
|
|
398
|
+
const blocks = [];
|
|
399
|
+
const blocksBySpaceNamespace = /* @__PURE__ */ new Map();
|
|
400
|
+
for (const msg of messages) {
|
|
401
|
+
const key = `${msg.spaceId}|${msg.feedNamespace}|${msg.feedId}`;
|
|
402
|
+
let sequence;
|
|
403
|
+
let prevSequence;
|
|
404
|
+
let prevActorId;
|
|
405
|
+
const inFlight = currentSeqs.get(key);
|
|
406
|
+
if (inFlight) {
|
|
407
|
+
sequence = inFlight.sequence + 1;
|
|
408
|
+
prevSequence = inFlight.sequence;
|
|
409
|
+
prevActorId = inFlight.actorId;
|
|
410
|
+
} else {
|
|
411
|
+
const lastBlock = lastSeqs.get(key);
|
|
412
|
+
sequence = (lastBlock?.sequence ?? -1) + 1;
|
|
413
|
+
prevSequence = lastBlock?.sequence ?? null;
|
|
414
|
+
prevActorId = lastBlock?.actorId ?? null;
|
|
415
|
+
}
|
|
416
|
+
const block = {
|
|
417
|
+
feedId: msg.feedId,
|
|
418
|
+
actorId: this.#options.localActorId,
|
|
419
|
+
sequence,
|
|
420
|
+
prevActorId,
|
|
421
|
+
prevSequence,
|
|
422
|
+
timestamp: Date.now(),
|
|
423
|
+
data: msg.data,
|
|
424
|
+
position: null
|
|
425
|
+
};
|
|
426
|
+
blocks.push(block);
|
|
427
|
+
currentSeqs.set(key, {
|
|
428
|
+
sequence,
|
|
429
|
+
actorId: this.#options.localActorId
|
|
430
|
+
});
|
|
431
|
+
const spaceNamespaceKey = `${msg.spaceId}|${msg.feedNamespace}`;
|
|
432
|
+
if (!blocksBySpaceNamespace.has(spaceNamespaceKey)) {
|
|
433
|
+
blocksBySpaceNamespace.set(spaceNamespaceKey, {
|
|
434
|
+
spaceId: msg.spaceId,
|
|
435
|
+
feedNamespace: msg.feedNamespace,
|
|
436
|
+
blocks: []
|
|
437
|
+
});
|
|
438
|
+
}
|
|
439
|
+
blocksBySpaceNamespace.get(spaceNamespaceKey).blocks.push(block);
|
|
440
|
+
}
|
|
441
|
+
const positionByBlock = /* @__PURE__ */ new Map();
|
|
442
|
+
for (const { spaceId, feedNamespace, blocks: batchBlocks } of blocksBySpaceNamespace.values()) {
|
|
443
|
+
const { positions } = yield* this.append({
|
|
444
|
+
requestId: "local-append",
|
|
445
|
+
blocks: batchBlocks,
|
|
446
|
+
spaceId,
|
|
447
|
+
feedNamespace
|
|
448
|
+
});
|
|
449
|
+
for (let i = 0; i < batchBlocks.length; i++) {
|
|
450
|
+
positionByBlock.set(batchBlocks[i], positions[i] ?? null);
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
return blocks.map((block) => ({
|
|
454
|
+
...block,
|
|
455
|
+
position: positionByBlock.get(block) ?? block.position
|
|
456
|
+
}));
|
|
457
|
+
}).pipe(Effect.withSpan("FeedStore.appendLocal")));
|
|
458
|
+
/**
|
|
459
|
+
* Sets positions for existing blocks while preventing conflicting reassignments.
|
|
460
|
+
*/
|
|
461
|
+
setPosition = (request) => Effect.gen(this, function* () {
|
|
462
|
+
const sql = yield* SqlClient.SqlClient;
|
|
463
|
+
for (const block of request.blocks) {
|
|
464
|
+
const existing = yield* sql`
|
|
465
|
+
SELECT position FROM blocks
|
|
466
|
+
WHERE feedPrivateId = (
|
|
467
|
+
SELECT feedPrivateId FROM feeds
|
|
468
|
+
WHERE spaceId = ${request.spaceId} AND feedId = ${block.feedId} AND feedNamespace = ${block.feedNamespace}
|
|
469
|
+
)
|
|
470
|
+
AND actorId = ${block.actorId} AND sequence = ${block.sequence}
|
|
471
|
+
`;
|
|
472
|
+
const current = existing[0];
|
|
473
|
+
if (current?.position != null && current.position !== block.position) {
|
|
474
|
+
yield* Effect.fail(new PositionConflictError({
|
|
475
|
+
feedId: block.feedId,
|
|
476
|
+
actorId: block.actorId,
|
|
477
|
+
sequence: block.sequence,
|
|
478
|
+
currentPosition: current.position,
|
|
479
|
+
requestedPosition: block.position
|
|
480
|
+
}));
|
|
481
|
+
}
|
|
482
|
+
yield* sql`
|
|
483
|
+
UPDATE blocks SET position = ${block.position}
|
|
484
|
+
WHERE feedPrivateId = (
|
|
485
|
+
SELECT feedPrivateId FROM feeds
|
|
486
|
+
WHERE spaceId = ${request.spaceId} AND feedId = ${block.feedId} AND feedNamespace = ${block.feedNamespace}
|
|
487
|
+
)
|
|
488
|
+
AND actorId = ${block.actorId} AND sequence = ${block.sequence}
|
|
489
|
+
`;
|
|
490
|
+
}
|
|
491
|
+
}).pipe(Effect.withSpan("FeedStore.setPosition"));
|
|
492
|
+
};
|
|
493
|
+
var encodeCursor = (token, insertionId) => FeedCursor.make(`${token}|${insertionId}`);
|
|
494
|
+
var decodeCursor = (cursor) => {
|
|
495
|
+
const [token, insertionId] = cursor.split("|");
|
|
496
|
+
return {
|
|
497
|
+
token,
|
|
498
|
+
insertionId: Number(insertionId)
|
|
499
|
+
};
|
|
500
|
+
};
|
|
501
|
+
|
|
502
|
+
// src/sync-server.ts
|
|
503
|
+
import * as Effect2 from "effect/Effect";
|
|
504
|
+
var SyncServer = class {
|
|
505
|
+
#peerId;
|
|
506
|
+
#feedStore;
|
|
507
|
+
#sendMessage;
|
|
508
|
+
constructor(options) {
|
|
509
|
+
this.#peerId = options.peerId;
|
|
510
|
+
this.#feedStore = options.feedStore;
|
|
511
|
+
this.#sendMessage = options.sendMessage;
|
|
512
|
+
}
|
|
513
|
+
/**
|
|
514
|
+
* Receive a message from a client. Handles QueryRequest and AppendRequest; sends response via sendMessage with correct peer ids.
|
|
515
|
+
*/
|
|
516
|
+
handleMessage(message) {
|
|
517
|
+
const self = this;
|
|
518
|
+
const recipientPeerId = message.senderPeerId;
|
|
519
|
+
const withPeerIds = (payload) => ({
|
|
520
|
+
...payload,
|
|
521
|
+
senderPeerId: self.#peerId,
|
|
522
|
+
recipientPeerId
|
|
523
|
+
});
|
|
524
|
+
switch (message._tag) {
|
|
525
|
+
case "QueryRequest": {
|
|
526
|
+
const req = message;
|
|
527
|
+
return Effect2.gen(function* () {
|
|
528
|
+
const response = yield* self.#feedStore.query(req);
|
|
529
|
+
yield* self.#sendMessage(withPeerIds({
|
|
530
|
+
_tag: "QueryResponse",
|
|
531
|
+
...response
|
|
532
|
+
}));
|
|
533
|
+
}).pipe(Effect2.catchAll((err) => self.#sendMessage(withPeerIds({
|
|
534
|
+
_tag: "Error",
|
|
535
|
+
message: err instanceof Error ? err.message : String(err)
|
|
536
|
+
}))));
|
|
537
|
+
}
|
|
538
|
+
case "AppendRequest": {
|
|
539
|
+
const req = message;
|
|
540
|
+
return Effect2.gen(function* () {
|
|
541
|
+
const response = yield* self.#feedStore.append(req);
|
|
542
|
+
yield* self.#sendMessage(withPeerIds({
|
|
543
|
+
_tag: "AppendResponse",
|
|
544
|
+
...response
|
|
545
|
+
}));
|
|
546
|
+
}).pipe(Effect2.catchAll((err) => self.#sendMessage(withPeerIds({
|
|
547
|
+
_tag: "Error",
|
|
548
|
+
message: err instanceof Error ? err.message : String(err)
|
|
549
|
+
}))));
|
|
550
|
+
}
|
|
551
|
+
default:
|
|
552
|
+
return Effect2.void;
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
};
|
|
556
|
+
|
|
557
|
+
// src/sync-client.ts
|
|
558
|
+
import * as Array from "effect/Array";
|
|
559
|
+
import * as Deferred from "effect/Deferred";
|
|
560
|
+
import * as Effect3 from "effect/Effect";
|
|
561
|
+
var SyncClient = class {
|
|
562
|
+
#peerId;
|
|
563
|
+
#serverPeerId;
|
|
564
|
+
#feedStore;
|
|
565
|
+
#sendMessage;
|
|
566
|
+
#handlers = /* @__PURE__ */ new Map();
|
|
567
|
+
constructor(options) {
|
|
568
|
+
this.#peerId = options.peerId;
|
|
569
|
+
this.#serverPeerId = options.serverPeerId;
|
|
570
|
+
this.#feedStore = options.feedStore;
|
|
571
|
+
this.#sendMessage = options.sendMessage;
|
|
572
|
+
}
|
|
573
|
+
#withPeerIds(payload) {
|
|
574
|
+
if (payload._tag === "QueryRequest") {
|
|
575
|
+
return {
|
|
576
|
+
...payload,
|
|
577
|
+
senderPeerId: this.#peerId,
|
|
578
|
+
recipientPeerId: this.#serverPeerId
|
|
579
|
+
};
|
|
580
|
+
}
|
|
581
|
+
return {
|
|
582
|
+
...payload,
|
|
583
|
+
senderPeerId: this.#peerId,
|
|
584
|
+
recipientPeerId: this.#serverPeerId
|
|
585
|
+
};
|
|
586
|
+
}
|
|
587
|
+
/**
|
|
588
|
+
* Receive a message from the server. If a handler is registered for the message's requestId, complete it and remove; else noop.
|
|
589
|
+
*/
|
|
590
|
+
handleMessage(message) {
|
|
591
|
+
const requestId = "requestId" in message && message.requestId != null ? String(message.requestId) : void 0;
|
|
592
|
+
if (requestId == null) return Effect3.void;
|
|
593
|
+
const deferred = this.#handlers.get(requestId);
|
|
594
|
+
if (deferred == null) return Effect3.void;
|
|
595
|
+
this.#handlers.delete(requestId);
|
|
596
|
+
if (message._tag === "Error") {
|
|
597
|
+
return Effect3.andThen(Deferred.fail(deferred, new Error(message.message)), () => Effect3.void);
|
|
598
|
+
}
|
|
599
|
+
return Effect3.andThen(Deferred.succeed(deferred, message), () => Effect3.void);
|
|
600
|
+
}
|
|
601
|
+
pull(opts) {
|
|
602
|
+
const self = this;
|
|
603
|
+
return Effect3.gen(function* () {
|
|
604
|
+
const lastPulledPosition = yield* self.#feedStore.getSyncState({
|
|
605
|
+
spaceId: opts.spaceId,
|
|
606
|
+
feedNamespace: opts.feedNamespace
|
|
607
|
+
});
|
|
608
|
+
const requestId = crypto.randomUUID();
|
|
609
|
+
const deferred = yield* Deferred.make();
|
|
610
|
+
self.#handlers.set(requestId, deferred);
|
|
611
|
+
const request = {
|
|
612
|
+
_tag: "QueryRequest",
|
|
613
|
+
requestId,
|
|
614
|
+
spaceId: opts.spaceId,
|
|
615
|
+
feedNamespace: opts.feedNamespace,
|
|
616
|
+
position: lastPulledPosition,
|
|
617
|
+
limit: opts.limit
|
|
618
|
+
};
|
|
619
|
+
yield* self.#sendMessage(self.#withPeerIds(request));
|
|
620
|
+
const message = yield* Deferred.await(deferred);
|
|
621
|
+
const response = yield* self.#expectResponse(requestId, message, "QueryResponse");
|
|
622
|
+
if (response.blocks.length === 0) {
|
|
623
|
+
return {
|
|
624
|
+
done: true
|
|
625
|
+
};
|
|
626
|
+
}
|
|
627
|
+
yield* self.#feedStore.append({
|
|
628
|
+
spaceId: opts.spaceId,
|
|
629
|
+
feedNamespace: opts.feedNamespace,
|
|
630
|
+
blocks: response.blocks
|
|
631
|
+
});
|
|
632
|
+
const maxPulledPosition = response.blocks.reduce((max, block) => block.position != null && block.position > max ? block.position : max, lastPulledPosition);
|
|
633
|
+
yield* self.#feedStore.setSyncState({
|
|
634
|
+
spaceId: opts.spaceId,
|
|
635
|
+
feedNamespace: opts.feedNamespace,
|
|
636
|
+
lastPulledPosition: maxPulledPosition
|
|
637
|
+
});
|
|
638
|
+
return {
|
|
639
|
+
done: false
|
|
640
|
+
};
|
|
641
|
+
});
|
|
642
|
+
}
|
|
643
|
+
push(opts) {
|
|
644
|
+
const self = this;
|
|
645
|
+
return Effect3.gen(function* () {
|
|
646
|
+
const unpositioned = yield* self.#feedStore.query({
|
|
647
|
+
spaceId: opts.spaceId,
|
|
648
|
+
feedNamespace: opts.feedNamespace,
|
|
649
|
+
unpositionedOnly: true,
|
|
650
|
+
limit: opts.limit
|
|
651
|
+
});
|
|
652
|
+
if (unpositioned.blocks.length === 0) {
|
|
653
|
+
return {
|
|
654
|
+
done: true
|
|
655
|
+
};
|
|
656
|
+
}
|
|
657
|
+
const requestId = crypto.randomUUID();
|
|
658
|
+
const deferred = yield* Deferred.make();
|
|
659
|
+
self.#handlers.set(requestId, deferred);
|
|
660
|
+
const request = {
|
|
661
|
+
_tag: "AppendRequest",
|
|
662
|
+
requestId,
|
|
663
|
+
spaceId: opts.spaceId,
|
|
664
|
+
feedNamespace: opts.feedNamespace,
|
|
665
|
+
blocks: unpositioned.blocks
|
|
666
|
+
};
|
|
667
|
+
yield* self.#sendMessage(self.#withPeerIds(request));
|
|
668
|
+
const message = yield* Deferred.await(deferred);
|
|
669
|
+
const response = yield* self.#expectResponse(requestId, message, "AppendResponse");
|
|
670
|
+
yield* self.#feedStore.setPosition({
|
|
671
|
+
spaceId: opts.spaceId,
|
|
672
|
+
blocks: Array.zipWith(response.positions, unpositioned.blocks, (position, block) => ({
|
|
673
|
+
feedId: block.feedId,
|
|
674
|
+
feedNamespace: opts.feedNamespace,
|
|
675
|
+
actorId: block.actorId,
|
|
676
|
+
sequence: block.sequence,
|
|
677
|
+
position
|
|
678
|
+
}))
|
|
679
|
+
});
|
|
680
|
+
return {
|
|
681
|
+
done: false
|
|
682
|
+
};
|
|
683
|
+
});
|
|
684
|
+
}
|
|
685
|
+
#expectResponse(requestId, message, expectedTag) {
|
|
686
|
+
if (message._tag === "Error") {
|
|
687
|
+
return Effect3.fail(new Error(message.message));
|
|
688
|
+
}
|
|
689
|
+
const requestIdMsg = "requestId" in message ? String(message.requestId) : void 0;
|
|
690
|
+
if (message._tag !== expectedTag || requestIdMsg !== requestId) {
|
|
691
|
+
return Effect3.fail(new Error(`Unexpected message: expected ${expectedTag} with requestId ${requestId}`));
|
|
692
|
+
}
|
|
693
|
+
return Effect3.succeed(message);
|
|
694
|
+
}
|
|
695
|
+
};
|
|
696
|
+
|
|
697
|
+
export {
|
|
698
|
+
PositionConflictError,
|
|
699
|
+
FeedStore,
|
|
700
|
+
SyncServer,
|
|
701
|
+
SyncClient
|
|
702
|
+
};
|
|
703
|
+
//# sourceMappingURL=chunk-2ENONWPH.mjs.map
|