@fedify/sqlite 2.0.0-dev.215 → 2.0.0-dev.226

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mq.js ADDED
@@ -0,0 +1,368 @@
1
+
2
+ import { Temporal } from "@js-temporal/polyfill";
3
+
4
+ import { SqliteDatabase } from "#sqlite";
5
+ import { getLogger } from "@logtape/logtape";
6
+
7
+ //#region src/mq.ts
8
+ const logger = getLogger([
9
+ "fedify",
10
+ "sqlite",
11
+ "mq"
12
+ ]);
13
+ var EnqueueEvent = class extends Event {
14
+ delayMs;
15
+ constructor(delayMs) {
16
+ super("enqueue");
17
+ this.delayMs = delayMs;
18
+ }
19
+ };
20
+ /**
21
+ * A message queue that uses SQLite as the underlying storage.
22
+ *
23
+ * This implementation is designed for single-node deployments and uses
24
+ * polling to check for new messages. It is not suitable for high-throughput
25
+ * scenarios or distributed environments.
26
+ *
27
+ * @example
28
+ * ```ts ignore
29
+ * import { createFederation } from "@fedify/fedify";
30
+ * import { SqliteMessageQueue } from "@fedify/sqlite";
31
+ * import { DatabaseSync } from "node:sqlite";
32
+ *
33
+ * const db = new DatabaseSync(":memory:");
34
+ * const federation = createFederation({
35
+ * // ...
36
+ * queue: new SqliteMessageQueue(db),
37
+ * });
38
+ * ```
39
+ */
40
+ var SqliteMessageQueue = class SqliteMessageQueue {
41
+ static #defaultTableName = "fedify_message";
42
+ static #tableNameRegex = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;
43
+ static #notifyChannels = /* @__PURE__ */ new Map();
44
+ static #activeInstances = /* @__PURE__ */ new Map();
45
+ static #getNotifyChannel(tableName) {
46
+ let channel = SqliteMessageQueue.#notifyChannels.get(tableName);
47
+ if (channel == null) {
48
+ channel = new EventTarget();
49
+ SqliteMessageQueue.#notifyChannels.set(tableName, channel);
50
+ }
51
+ return channel;
52
+ }
53
+ #db;
54
+ #tableName;
55
+ #pollIntervalMs;
56
+ #instanceId;
57
+ #maxRetries;
58
+ #retryDelayMs;
59
+ #journalMode;
60
+ #initialized;
61
+ /**
62
+ * SQLite message queue does not provide native retry mechanisms.
63
+ */
64
+ nativeRetrial = false;
65
+ /**
66
+ * Creates a new SQLite message queue.
67
+ * @param db The SQLite database to use. Supports `node:sqlite`, `bun:sqlite`.
68
+ * @param options The options for the message queue.
69
+ */
70
+ constructor(db, options = {}) {
71
+ this.db = db;
72
+ this.options = options;
73
+ this.#db = new SqliteDatabase(db);
74
+ this.#initialized = options.initialized ?? false;
75
+ this.#tableName = options.tableName ?? SqliteMessageQueue.#defaultTableName;
76
+ this.#instanceId = crypto.randomUUID();
77
+ this.#pollIntervalMs = Temporal.Duration.from(options.pollInterval ?? { seconds: 5 }).total("millisecond");
78
+ this.#maxRetries = options.maxRetries ?? 5;
79
+ this.#retryDelayMs = options.retryDelayMs ?? 100;
80
+ this.#journalMode = options.journalMode ?? "WAL";
81
+ if (!SqliteMessageQueue.#tableNameRegex.test(this.#tableName)) throw new Error(`Invalid table name for the message queue: ${this.#tableName}.\
82
+ Only letters, digits, and underscores are allowed.`);
83
+ this.#registerInstance();
84
+ }
85
+ #registerInstance() {
86
+ let instances = SqliteMessageQueue.#activeInstances.get(this.#tableName);
87
+ if (instances == null) {
88
+ instances = /* @__PURE__ */ new Set();
89
+ SqliteMessageQueue.#activeInstances.set(this.#tableName, instances);
90
+ }
91
+ instances.add(this.#instanceId);
92
+ }
93
+ /**
94
+ * {@inheritDoc MessageQueue.enqueue}
95
+ */
96
+ enqueue(message, options) {
97
+ this.initialize();
98
+ const id = crypto.randomUUID();
99
+ const encodedMessage = this.#encodeMessage(message);
100
+ const now = Temporal.Now.instant().epochMilliseconds;
101
+ const delay = options?.delay ?? Temporal.Duration.from({ seconds: 0 });
102
+ const scheduled = now + delay.total({ unit: "milliseconds" });
103
+ if (options?.delay) logger.debug("Enqueuing a message with a delay of {delay}...", {
104
+ delay,
105
+ message
106
+ });
107
+ else logger.debug("Enqueuing a message...", { message });
108
+ return this.#retryOnBusy(() => {
109
+ this.#db.prepare(`INSERT INTO "${this.#tableName}" (id, message, created, scheduled)
110
+ VALUES (?, ?, ?, ?)`).run(id, encodedMessage, now, scheduled);
111
+ logger.debug("Enqueued a message.", { message });
112
+ const delayMs = delay.total("millisecond");
113
+ SqliteMessageQueue.#getNotifyChannel(this.#tableName).dispatchEvent(new EnqueueEvent(delayMs));
114
+ });
115
+ }
116
+ /**
117
+ * {@inheritDoc MessageQueue.enqueueMany}
118
+ */
119
+ enqueueMany(messages, options) {
120
+ if (messages.length === 0) return Promise.resolve();
121
+ this.initialize();
122
+ const now = Temporal.Now.instant().epochMilliseconds;
123
+ const delay = options?.delay ?? Temporal.Duration.from({ seconds: 0 });
124
+ const scheduled = now + delay.total({ unit: "milliseconds" });
125
+ if (options?.delay) logger.debug("Enqueuing messages with a delay of {delay}...", {
126
+ delay,
127
+ messages
128
+ });
129
+ else logger.debug("Enqueuing messages...", { messages });
130
+ return this.#withTransactionRetries(() => {
131
+ const stmt = this.#db.prepare(`INSERT INTO "${this.#tableName}" (id, message, created, scheduled)
132
+ VALUES (?, ?, ?, ?)`);
133
+ for (const message of messages) {
134
+ const id = crypto.randomUUID();
135
+ const encodedMessage = this.#encodeMessage(message);
136
+ stmt.run(id, encodedMessage, now, scheduled);
137
+ }
138
+ logger.debug("Enqueued messages.", { messages });
139
+ const delayMs = delay.total("millisecond");
140
+ SqliteMessageQueue.#getNotifyChannel(this.#tableName).dispatchEvent(new EnqueueEvent(delayMs));
141
+ }).catch((error) => {
142
+ logger.error("Failed to enqueue messages to table {tableName}: {error}", {
143
+ tableName: this.#tableName,
144
+ messageCount: messages.length,
145
+ error
146
+ });
147
+ throw error;
148
+ });
149
+ }
150
+ /**
151
+ * {@inheritDoc MessageQueue.listen}
152
+ */
153
+ async listen(handler, options) {
154
+ this.initialize();
155
+ const { signal } = options ?? {};
156
+ logger.debug("Starting to listen for messages on table {tableName}...", { tableName: this.#tableName });
157
+ const channel = SqliteMessageQueue.#getNotifyChannel(this.#tableName);
158
+ const timeouts = /* @__PURE__ */ new Set();
159
+ const poll = async () => {
160
+ while (signal == null || !signal.aborted) {
161
+ const now = Temporal.Now.instant().epochMilliseconds;
162
+ const result = await this.#withTransactionRetries(() => {
163
+ return this.#db.prepare(`DELETE FROM "${this.#tableName}"
164
+ WHERE id = (
165
+ SELECT id FROM "${this.#tableName}"
166
+ WHERE scheduled <= ?
167
+ ORDER BY scheduled
168
+ LIMIT 1
169
+ )
170
+ RETURNING id, message`).get(now);
171
+ });
172
+ if (result) {
173
+ const message = this.#decodeMessage(result.message);
174
+ logger.debug("Processing message {id}...", {
175
+ id: result.id,
176
+ message
177
+ });
178
+ try {
179
+ await handler(message);
180
+ logger.debug("Processed message {id}.", { id: result.id });
181
+ } catch (error) {
182
+ logger.error("Failed to process message {id} from table {tableName}: {error}", {
183
+ id: result.id,
184
+ tableName: this.#tableName,
185
+ message,
186
+ error
187
+ });
188
+ }
189
+ continue;
190
+ }
191
+ break;
192
+ }
193
+ };
194
+ const onEnqueue = (event) => {
195
+ const delayMs = event.delayMs;
196
+ if (delayMs < 1) poll();
197
+ else timeouts.add(setTimeout(poll, delayMs));
198
+ };
199
+ channel.addEventListener("enqueue", onEnqueue);
200
+ signal?.addEventListener("abort", () => {
201
+ channel.removeEventListener("enqueue", onEnqueue);
202
+ for (const timeout of timeouts) clearTimeout(timeout);
203
+ });
204
+ await poll();
205
+ while (signal == null || !signal.aborted) {
206
+ let timeout;
207
+ await new Promise((resolve) => {
208
+ const onAbort = () => {
209
+ signal?.removeEventListener("abort", onAbort);
210
+ resolve(void 0);
211
+ };
212
+ signal?.addEventListener("abort", onAbort);
213
+ timeout = setTimeout(() => {
214
+ signal?.removeEventListener("abort", onAbort);
215
+ resolve(0);
216
+ }, this.#pollIntervalMs);
217
+ timeouts.add(timeout);
218
+ });
219
+ if (timeout != null) timeouts.delete(timeout);
220
+ await poll();
221
+ }
222
+ logger.debug("Stopped listening for messages on table {tableName}.", { tableName: this.#tableName });
223
+ }
224
+ /**
225
+ * Creates the message queue table if it does not already exist.
226
+ * Does nothing if the table already exists.
227
+ *
228
+ * This method also configures the SQLite journal mode for better concurrency.
229
+ * WAL (Write-Ahead Logging) mode is enabled by default to improve
230
+ * concurrent access in multi-process environments.
231
+ */
232
+ initialize() {
233
+ if (this.#initialized) return;
234
+ logger.debug("Initializing the message queue table {tableName}...", { tableName: this.#tableName });
235
+ this.#db.exec(`PRAGMA journal_mode=${this.#journalMode}`);
236
+ this.#withTransaction(() => {
237
+ this.#db.exec(`
238
+ CREATE TABLE IF NOT EXISTS "${this.#tableName}" (
239
+ id TEXT PRIMARY KEY,
240
+ message TEXT NOT NULL,
241
+ created INTEGER NOT NULL,
242
+ scheduled INTEGER NOT NULL
243
+ )
244
+ `);
245
+ this.#db.exec(`
246
+ CREATE INDEX IF NOT EXISTS "idx_${this.#tableName}_scheduled"
247
+ ON "${this.#tableName}" (scheduled)
248
+ `);
249
+ });
250
+ this.#initialized = true;
251
+ logger.debug("Initialized the message queue table {tableName}.", { tableName: this.#tableName });
252
+ }
253
+ /**
254
+ * Drops the table used by the message queue. Does nothing if the table
255
+ * does not exist.
256
+ */
257
+ drop() {
258
+ this.#db.exec(`DROP TABLE IF EXISTS "${this.#tableName}"`);
259
+ this.#initialized = false;
260
+ }
261
+ /**
262
+ * Closes the database connection.
263
+ */
264
+ [Symbol.dispose]() {
265
+ try {
266
+ this.#db.close();
267
+ this.#unregisterInstance();
268
+ } catch (error) {
269
+ logger.error("Failed to close the database connection for table {tableName}: {error}", {
270
+ tableName: this.#tableName,
271
+ error
272
+ });
273
+ }
274
+ }
275
+ #unregisterInstance() {
276
+ const instances = SqliteMessageQueue.#activeInstances.get(this.#tableName);
277
+ if (instances == null) return;
278
+ instances.delete(this.#instanceId);
279
+ if (instances.size === 0) {
280
+ SqliteMessageQueue.#activeInstances.delete(this.#tableName);
281
+ SqliteMessageQueue.#notifyChannels.delete(this.#tableName);
282
+ }
283
+ }
284
+ /**
285
+ * Checks if an error is a SQLITE_BUSY error or transaction conflict.
286
+ * Handles different error formats from node:sqlite and bun:sqlite.
287
+ */
288
+ #isBusyError(error) {
289
+ if (!(error instanceof Error)) return false;
290
+ if (error.message.includes("SQLITE_BUSY") || error.message.includes("database is locked") || error.message.includes("transaction within a transaction")) return true;
291
+ const errorWithCode = error;
292
+ if (errorWithCode.code === "SQLITE_BUSY") return true;
293
+ const errorWithErrno = error;
294
+ if (errorWithErrno.errno === 5) return true;
295
+ return false;
296
+ }
297
+ /**
298
+ * Retries a database operation with exponential backoff on SQLITE_BUSY errors.
299
+ */
300
+ async #retryOnBusy(operation) {
301
+ let lastError;
302
+ for (let attempt = 0; attempt <= this.#maxRetries; attempt++) try {
303
+ return operation();
304
+ } catch (error) {
305
+ lastError = error;
306
+ if (!this.#isBusyError(error)) {
307
+ logger.error("Database operation failed on table {tableName}: {error}", {
308
+ tableName: this.#tableName,
309
+ error
310
+ });
311
+ throw error;
312
+ }
313
+ if (attempt === this.#maxRetries) {
314
+ logger.error("Max retries ({maxRetries}) reached for SQLITE_BUSY error on table {tableName}.", {
315
+ maxRetries: this.#maxRetries,
316
+ tableName: this.#tableName,
317
+ error
318
+ });
319
+ throw error;
320
+ }
321
+ const delayMs = this.#retryDelayMs * Math.pow(2, attempt);
322
+ logger.debug("SQLITE_BUSY error on table {tableName}, retrying in {delayMs}ms (attempt {attempt}/{maxRetries})...", {
323
+ tableName: this.#tableName,
324
+ delayMs,
325
+ attempt: attempt + 1,
326
+ maxRetries: this.#maxRetries
327
+ });
328
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
329
+ }
330
+ throw lastError;
331
+ }
332
+ /**
333
+ * Executes a database operation within a transaction.
334
+ * Automatically handles BEGIN IMMEDIATE, COMMIT, and ROLLBACK.
335
+ */
336
+ #withTransaction(operation) {
337
+ let transactionStarted = false;
338
+ try {
339
+ this.#db.exec("BEGIN IMMEDIATE");
340
+ transactionStarted = true;
341
+ const result = operation();
342
+ this.#db.exec("COMMIT");
343
+ return result;
344
+ } catch (error) {
345
+ if (transactionStarted) try {
346
+ this.#db.exec("ROLLBACK");
347
+ } catch {}
348
+ throw error;
349
+ }
350
+ }
351
+ /**
352
+ * Executes a database operation within a transaction with retry logic.
353
+ * Automatically handles BEGIN IMMEDIATE, COMMIT, and ROLLBACK.
354
+ * Retries on SQLITE_BUSY errors with exponential backoff.
355
+ */
356
+ async #withTransactionRetries(operation) {
357
+ return await this.#retryOnBusy(() => this.#withTransaction(operation));
358
+ }
359
+ #encodeMessage(message) {
360
+ return JSON.stringify(message);
361
+ }
362
+ #decodeMessage(message) {
363
+ return JSON.parse(message);
364
+ }
365
+ };
366
+
367
+ //#endregion
368
+ export { SqliteMessageQueue };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fedify/sqlite",
3
- "version": "2.0.0-dev.215+84aa16bb",
3
+ "version": "2.0.0-dev.226+c28b813d",
4
4
  "description": "SQLite drivers for Fedify",
5
5
  "keywords": [
6
6
  "fedify",
@@ -46,6 +46,16 @@
46
46
  "require": "./dist/kv.cjs",
47
47
  "default": "./dist/kv.js"
48
48
  },
49
+ "./mq": {
50
+ "types": {
51
+ "import": "./dist/mq.d.ts",
52
+ "require": "./dist/mq.d.cts",
53
+ "default": "./dist/mq.d.ts"
54
+ },
55
+ "import": "./dist/mq.js",
56
+ "require": "./dist/mq.cjs",
57
+ "default": "./dist/mq.js"
58
+ },
49
59
  "./package.json": "./package.json"
50
60
  },
51
61
  "imports": {
@@ -62,12 +72,13 @@
62
72
  "es-toolkit": "^1.31.0"
63
73
  },
64
74
  "peerDependencies": {
65
- "@fedify/fedify": "^2.0.0-dev.215+84aa16bb"
75
+ "@fedify/fedify": "^2.0.0-dev.226+c28b813d"
66
76
  },
67
77
  "devDependencies": {
68
78
  "@std/async": "npm:@jsr/std__async@^1.0.13",
69
79
  "tsdown": "^0.12.9",
70
- "typescript": "^5.9.3"
80
+ "typescript": "^5.9.3",
81
+ "@fedify/testing": "^2.0.0-dev.226+c28b813d"
71
82
  },
72
83
  "scripts": {
73
84
  "build": "tsdown",
package/src/mod.ts CHANGED
@@ -3,3 +3,4 @@
3
3
  * @module
4
4
  */
5
5
  export { SqliteKvStore } from "./kv.ts";
6
+ export { SqliteMessageQueue } from "./mq.ts";
package/src/mq.test.ts ADDED
@@ -0,0 +1,23 @@
1
+ import { PlatformDatabase } from "#sqlite";
2
+ import { test } from "@fedify/fixture";
3
+ import { SqliteMessageQueue } from "@fedify/sqlite/mq";
4
+ import { getRandomKey, testMessageQueue } from "@fedify/testing";
5
+ import { mkdtemp } from "node:fs/promises";
6
+ import { tmpdir } from "node:os";
7
+ import { join } from "node:path";
8
+
9
+ const dbDir = await mkdtemp(join(tmpdir(), "fedify-sqlite-"));
10
+ const dbPath = join(dbDir, `${getRandomKey("sqlite")}.db`);
11
+ const db = new PlatformDatabase(dbPath);
12
+ const tableName = getRandomKey("message").replaceAll("-", "_");
13
+
14
+ test("SqliteMessageQueue", () =>
15
+ testMessageQueue(
16
+ () => new SqliteMessageQueue(db, { tableName }),
17
+ ({ mq1, mq2, controller }) => {
18
+ controller.abort();
19
+ mq1.drop();
20
+ mq1[Symbol.dispose]();
21
+ mq2[Symbol.dispose]();
22
+ },
23
+ ));