@fedify/amqp 2.5.0-dev.2687 → 2.5.0-dev.2726

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fedify/amqp",
3
- "version": "2.5.0-dev.2687+924da5ce",
3
+ "version": "2.5.0-dev.2726+da549263",
4
4
  "description": "AMQP/RabbitMQ driver for Fedify",
5
5
  "keywords": [
6
6
  "fedify",
@@ -52,7 +52,7 @@
52
52
  },
53
53
  "peerDependencies": {
54
54
  "amqplib": "^0.10.9",
55
- "@fedify/fedify": "^2.5.0-dev.2687+924da5ce"
55
+ "@fedify/fedify": "^2.5.0-dev.2726+da549263"
56
56
  },
57
57
  "devDependencies": {
58
58
  "@alinea/suite": "^0.6.3",
@@ -60,8 +60,25 @@
60
60
  "@types/amqplib": "^0.10.8",
61
61
  "tsdown": "^0.22.0",
62
62
  "typescript": "^6.0.3",
63
- "@fedify/testing": "^2.5.0-dev.2687+924da5ce"
63
+ "@fedify/testing": "^2.5.0-dev.2726+da549263"
64
64
  },
65
+ "files": [
66
+ "dist/",
67
+ "package.json",
68
+ "!dist/**/*.test.{js,cjs,mjs,ts,cts,mts}",
69
+ "!dist/**/*.test.d.{ts,cts,mts}",
70
+ "!dist/**/*.test.*.map",
71
+ "!dist/**/*.bench.{js,cjs,mjs,ts,cts,mts}",
72
+ "!dist/**/*.bench.d.{ts,cts,mts}",
73
+ "!dist/**/*.bench.*.map",
74
+ "!dist/**/*.snap",
75
+ "!dist/**/__snapshots__/**",
76
+ "!dist/**/__fixtures__/**",
77
+ "!dist/**/test/**",
78
+ "!dist/**/tests/**",
79
+ "!dist/**/testdata/**",
80
+ "!dist/**/fixtures/**"
81
+ ],
65
82
  "scripts": {
66
83
  "build:self": "tsdown",
67
84
  "build": "pnpm --filter @fedify/amqp... run build:self",
package/deno.json DELETED
@@ -1,49 +0,0 @@
1
- {
2
- "name": "@fedify/amqp",
3
- "version": "2.5.0-dev.2687+924da5ce",
4
- "license": "MIT",
5
- "exports": {
6
- ".": "./src/mod.ts",
7
- "./mq": "./src/mq.ts"
8
- },
9
- "imports": {
10
- "@alinea/suite": "jsr:@alinea/suite@^0.6.3"
11
- },
12
- "exclude": [
13
- ".github",
14
- "dist",
15
- "node_modules",
16
- "npm",
17
- "pnpm-lock.yaml"
18
- ],
19
- "publish": {
20
- "exclude": [
21
- "**/*.test.ts",
22
- "tsdown.config.ts"
23
- ]
24
- },
25
- "tasks": {
26
- "build": "pnpm build",
27
- "check": "deno check *.ts",
28
- "test": "deno test --allow-net --allow-env",
29
- "test:node": {
30
- "dependencies": [
31
- "build"
32
- ],
33
- "command": "node --experimental-transform-types --test"
34
- },
35
- "test:bun": {
36
- "dependencies": [
37
- "build"
38
- ],
39
- "command": "bun test --timeout 15000"
40
- },
41
- "test-all": {
42
- "dependencies": [
43
- "test",
44
- "test:node",
45
- "test:bun"
46
- ]
47
- }
48
- }
49
- }
package/src/mod.ts DELETED
@@ -1 +0,0 @@
1
- export * from "./mq.ts";
package/src/mq.test.ts DELETED
@@ -1,426 +0,0 @@
1
- import { suite } from "@alinea/suite";
2
- import { AmqpMessageQueue } from "@fedify/amqp/mq";
3
- import { getRandomKey, testMessageQueue, waitFor } from "@fedify/testing";
4
- import * as temporal from "@js-temporal/polyfill";
5
- import { deepStrictEqual, ok } from "node:assert/strict";
6
- import { setTimeout as delay } from "node:timers/promises";
7
- // @deno-types="npm:@types/amqplib"
8
- import { type Channel, type ChannelModel, connect } from "amqplib";
9
- import process from "node:process";
10
-
11
- const Temporal = globalThis.Temporal ?? temporal.Temporal;
12
-
13
- const AMQP_URL = process.env.AMQP_URL;
14
- const unitTest = suite(import.meta);
15
- const test = AMQP_URL ? unitTest : unitTest.skip;
16
-
17
- unitTest("AmqpMessageQueue declares non-atomic batch enqueueing", () => {
18
- const mq = new AmqpMessageQueue({} as ChannelModel);
19
- ok(!mq.atomicEnqueueMany);
20
- });
21
-
22
- class FakeDepthChannel {
23
- #closed = false;
24
-
25
- constructor(private readonly connection: FakeDepthConnection) {}
26
-
27
- on(): void {}
28
-
29
- assertQueue(queue: string, options?: { expires?: number }): Promise<void> {
30
- if (this.#closed) {
31
- return Promise.reject(new Error("Channel is closed"));
32
- }
33
- if (
34
- options?.expires != null &&
35
- this.connection.preconditionOnExpires.has(queue)
36
- ) {
37
- this.#closed = true;
38
- this.connection.preconditionOnExpires.delete(queue);
39
- return Promise.reject(
40
- Object.assign(new Error("PRECONDITION_FAILED"), { code: 406 }),
41
- );
42
- }
43
- this.connection.queues.add(queue);
44
- if (options?.expires != null) {
45
- this.connection.queueExpires.set(queue, options.expires);
46
- }
47
- return Promise.resolve();
48
- }
49
-
50
- sendToQueue(queue: string): boolean {
51
- if (this.#closed) throw new Error("Channel is closed");
52
- this.connection.messageCounts.set(
53
- queue,
54
- (this.connection.messageCounts.get(queue) ?? 0) + 1,
55
- );
56
- return true;
57
- }
58
-
59
- async checkQueue(queue: string): Promise<{ messageCount: number }> {
60
- if (this.#closed) throw new Error("Channel is closed");
61
- this.connection.activeChecks++;
62
- this.connection.maxActiveChecks = Math.max(
63
- this.connection.maxActiveChecks,
64
- this.connection.activeChecks,
65
- );
66
- try {
67
- if (this.connection.checkDelayMs > 0) {
68
- await delay(this.connection.checkDelayMs);
69
- }
70
- return { messageCount: this.connection.messageCounts.get(queue) ?? 0 };
71
- } finally {
72
- this.connection.activeChecks--;
73
- }
74
- }
75
-
76
- close(): Promise<void> {
77
- this.#closed = true;
78
- return Promise.resolve();
79
- }
80
- }
81
-
82
- class FakeDepthConnection {
83
- readonly queues = new Set<string>();
84
- readonly queueExpires = new Map<string, number>();
85
- readonly messageCounts = new Map<string, number>();
86
- readonly preconditionOnExpires = new Set<string>();
87
- activeChecks = 0;
88
- channelCount = 0;
89
- maxActiveChecks = 0;
90
-
91
- constructor(readonly checkDelayMs: number = 25) {}
92
-
93
- createChannel(): Promise<Channel> {
94
- this.channelCount++;
95
- return Promise.resolve(new FakeDepthChannel(this) as unknown as Channel);
96
- }
97
- }
98
-
99
- unitTest(
100
- "AmqpMessageQueue.getDepth() probes delayed queues concurrently",
101
- async () => {
102
- const conn = new FakeDepthConnection();
103
- const mq = new AmqpMessageQueue(conn as unknown as ChannelModel, {
104
- queue: "ready",
105
- delayedQueuePrefix: "delayed_",
106
- });
107
-
108
- await mq.enqueue("first", {
109
- delay: Temporal.Duration.from({ milliseconds: 1_000 }),
110
- });
111
- await mq.enqueue("second", {
112
- delay: Temporal.Duration.from({ milliseconds: 2_000 }),
113
- });
114
- await mq.enqueue("third", {
115
- delay: Temporal.Duration.from({ milliseconds: 3_000 }),
116
- });
117
-
118
- deepStrictEqual(await mq.getDepth(), {
119
- queued: 3,
120
- ready: 0,
121
- delayed: 3,
122
- });
123
- ok(conn.maxActiveChecks > 1);
124
- },
125
- );
126
-
127
- unitTest("AmqpMessageQueue sets delayed queue expiry", async () => {
128
- const conn = new FakeDepthConnection();
129
- const mq = new AmqpMessageQueue(conn as unknown as ChannelModel, {
130
- queue: "ready",
131
- delayedQueuePrefix: "delayed_",
132
- });
133
-
134
- await mq.enqueue("delayed", {
135
- delay: Temporal.Duration.from({ milliseconds: 1_000 }),
136
- });
137
-
138
- deepStrictEqual(conn.queueExpires.get("delayed_1000"), 61_000);
139
- });
140
-
141
- unitTest(
142
- "AmqpMessageQueue falls back for existing delayed queues without expiry",
143
- async () => {
144
- const conn = new FakeDepthConnection();
145
- conn.preconditionOnExpires.add("delayed_1000");
146
- const mq = new AmqpMessageQueue(conn as unknown as ChannelModel, {
147
- queue: "ready",
148
- delayedQueuePrefix: "delayed_",
149
- });
150
-
151
- await mq.enqueue("delayed", {
152
- delay: Temporal.Duration.from({ milliseconds: 1_000 }),
153
- });
154
-
155
- deepStrictEqual(conn.messageCounts.get("delayed_1000"), 1);
156
- deepStrictEqual(conn.queueExpires.get("delayed_1000"), undefined);
157
- ok(conn.channelCount > 1);
158
- },
159
- );
160
-
161
- unitTest("AmqpMessageQueue reuses depth probe channels", async () => {
162
- const conn = new FakeDepthConnection(0);
163
- const mq = new AmqpMessageQueue(conn as unknown as ChannelModel, {
164
- queue: "ready",
165
- delayedQueuePrefix: "delayed_",
166
- });
167
-
168
- for (let milliseconds = 1; milliseconds <= 12; milliseconds++) {
169
- await mq.enqueue("delayed", {
170
- delay: Temporal.Duration.from({ milliseconds }),
171
- });
172
- }
173
- conn.channelCount = 0;
174
-
175
- deepStrictEqual(await mq.getDepth(), {
176
- queued: 12,
177
- ready: 0,
178
- delayed: 12,
179
- });
180
- ok(
181
- conn.channelCount <= 9,
182
- `expected at most 9 depth probe channels, got ${conn.channelCount}`,
183
- );
184
- });
185
-
186
- unitTest(
187
- "AmqpMessageQueue keeps delayed queues past cleanup threshold",
188
- async () => {
189
- const conn = new FakeDepthConnection(0);
190
- const mq = new AmqpMessageQueue(conn as unknown as ChannelModel, {
191
- queue: "ready",
192
- delayedQueuePrefix: "delayed_",
193
- });
194
-
195
- for (let milliseconds = 1; milliseconds <= 4097; milliseconds++) {
196
- await mq.enqueue("delayed", {
197
- delay: Temporal.Duration.from({ milliseconds }),
198
- });
199
- }
200
-
201
- deepStrictEqual(await mq.getDepth(), {
202
- queued: 4097,
203
- ready: 0,
204
- delayed: 4097,
205
- });
206
- },
207
- );
208
-
209
- unitTest(
210
- "AmqpMessageQueue.getDepth() keeps delayed queues past local expiry",
211
- async () => {
212
- const now = Date.now;
213
- const started = now();
214
- Date.now = () => started;
215
- try {
216
- const conn = new FakeDepthConnection();
217
- const mq = new AmqpMessageQueue(conn as unknown as ChannelModel, {
218
- queue: "ready",
219
- delayedQueuePrefix: "delayed_",
220
- });
221
-
222
- await mq.enqueue("delayed", {
223
- delay: Temporal.Duration.from({ milliseconds: 1_000 }),
224
- });
225
- Date.now = () => started + 62_000;
226
-
227
- deepStrictEqual(await mq.getDepth(), {
228
- queued: 1,
229
- ready: 0,
230
- delayed: 1,
231
- });
232
- } finally {
233
- Date.now = now;
234
- }
235
- },
236
- );
237
-
238
- function getConnection(): Promise<ChannelModel> {
239
- return connect(AMQP_URL!);
240
- }
241
-
242
- const connections: ChannelModel[] = [];
243
- const queue = getRandomKey("queue");
244
- const delayedQueuePrefix = getRandomKey("delayed") + "_";
245
-
246
- test(
247
- "AmqpMessageQueue",
248
- { sanitizeOps: false, sanitizeExit: false, sanitizeResources: false },
249
- () =>
250
- testMessageQueue(
251
- async () => {
252
- const conn = await getConnection();
253
- connections.push(conn);
254
- return new AmqpMessageQueue(conn, { queue, delayedQueuePrefix });
255
- },
256
- async ({ controller }) => {
257
- controller.abort();
258
- for (const conn of connections) {
259
- await conn.close();
260
- }
261
- },
262
- ),
263
- );
264
-
265
- test(
266
- "AmqpMessageQueue.getDepth()",
267
- { sanitizeOps: false, sanitizeExit: false, sanitizeResources: false },
268
- async () => {
269
- const conn = await getConnection();
270
- const queue = getRandomKey("depth_queue");
271
- const delayedQueuePrefix = getRandomKey("depth_delayed") + "_";
272
- const mq = new AmqpMessageQueue(conn, { queue, delayedQueuePrefix });
273
- try {
274
- deepStrictEqual(await mq.getDepth(), {
275
- queued: 0,
276
- ready: 0,
277
- delayed: 0,
278
- });
279
- await mq.enqueue("ready");
280
- await mq.enqueue("delayed", {
281
- delay: Temporal.Duration.from({ seconds: 60 }),
282
- });
283
- const started = Date.now();
284
- while (Date.now() - started < 15_000) {
285
- const depth = await mq.getDepth();
286
- if (depth.queued === 2 && depth.ready === 1 && depth.delayed === 1) {
287
- break;
288
- }
289
- await delay(100);
290
- }
291
- deepStrictEqual(await mq.getDepth(), {
292
- queued: 2,
293
- ready: 1,
294
- delayed: 1,
295
- });
296
- } finally {
297
- const channel = await conn.createChannel().catch(() => undefined);
298
- try {
299
- await channel?.deleteQueue(queue).catch(() => {});
300
- await channel
301
- ?.deleteQueue(`${delayedQueuePrefix}60000`)
302
- .catch(() => {});
303
- } finally {
304
- await channel?.close().catch(() => {});
305
- await conn.close().catch(() => {});
306
- }
307
- }
308
- },
309
- );
310
-
311
- // Test with ordering key support (requires rabbitmq_consistent_hash_exchange plugin)
312
- const orderingConnections: ChannelModel[] = [];
313
- const orderingQueue = getRandomKey("ordering_queue");
314
- const orderingDelayedQueuePrefix = getRandomKey("ordering_delayed") + "_";
315
- const orderingExchange = getRandomKey("ordering_exchange");
316
- const orderingQueuePrefix = getRandomKey("ordering_partition") + "_";
317
-
318
- // Only run ordering key tests if AMQP_ORDERING_TEST env var is set
319
- // (requires rabbitmq_consistent_hash_exchange plugin to be enabled)
320
- const orderingTest = process.env.AMQP_ORDERING_TEST
321
- ? test
322
- : suite(import.meta).skip;
323
-
324
- orderingTest(
325
- "AmqpMessageQueue [ordering]",
326
- { sanitizeOps: false, sanitizeExit: false, sanitizeResources: false },
327
- () =>
328
- testMessageQueue(
329
- async () => {
330
- const conn = await getConnection();
331
- orderingConnections.push(conn);
332
- return new AmqpMessageQueue(conn, {
333
- queue: orderingQueue,
334
- delayedQueuePrefix: orderingDelayedQueuePrefix,
335
- ordering: {
336
- exchange: orderingExchange,
337
- queuePrefix: orderingQueuePrefix,
338
- partitions: 4,
339
- },
340
- });
341
- },
342
- async ({ controller }) => {
343
- controller.abort();
344
- for (const conn of orderingConnections) {
345
- await conn.close();
346
- }
347
- },
348
- { testOrderingKey: true },
349
- ),
350
- );
351
-
352
- test(
353
- "AmqpMessageQueue [nativeRetrial: false]",
354
- { sanitizeOps: false, sanitizeExit: false, sanitizeResources: false },
355
- async () => {
356
- const conn = await getConnection();
357
- const randomSuffix = Math.random().toString(36).substring(2);
358
- const queue = `fedify_queue_${randomSuffix}`;
359
- const delayedQueuePrefix = `fedify_delayed_${randomSuffix}_`;
360
- const mq = new AmqpMessageQueue(conn, { queue, delayedQueuePrefix });
361
- ok(!mq.nativeRetrial);
362
-
363
- const controller = new AbortController();
364
- let i = 0;
365
- const listening = mq.listen(
366
- (message: string) => {
367
- if (message !== "Hello, world!") return;
368
- if (i++ < 1) {
369
- throw new Error("Test error to check native retrial");
370
- }
371
- },
372
- { signal: controller.signal },
373
- );
374
-
375
- await mq.enqueue("Hello, world!");
376
-
377
- await waitFor(() => i >= 1, 15_000);
378
- deepStrictEqual(i, 1);
379
- await delay(5_000);
380
-
381
- controller.abort();
382
- await listening;
383
- await conn.close();
384
-
385
- deepStrictEqual(i, 1);
386
- },
387
- );
388
-
389
- test(
390
- "AmqpMessageQueue [nativeRetrial: true]",
391
- { sanitizeOps: false, sanitizeExit: false, sanitizeResources: false },
392
- async () => {
393
- const conn = await getConnection();
394
- const randomSuffix = Math.random().toString(36).substring(2);
395
- const queue = `fedify_queue_${randomSuffix}`;
396
- const delayedQueuePrefix = `fedify_delayed_${randomSuffix}_`;
397
- const mq = new AmqpMessageQueue(conn, {
398
- queue,
399
- delayedQueuePrefix,
400
- nativeRetrial: true,
401
- });
402
- ok(mq.nativeRetrial);
403
-
404
- const controller = new AbortController();
405
- let i = 0;
406
- const listening = mq.listen(
407
- (message: string) => {
408
- if (message !== "Hello, world!") return;
409
- if (i++ < 1) {
410
- throw new Error("Test error to check native retrial");
411
- }
412
- },
413
- { signal: controller.signal },
414
- );
415
-
416
- await mq.enqueue("Hello, world!");
417
-
418
- await waitFor(() => i > 1, 15_000);
419
-
420
- controller.abort();
421
- await listening;
422
- await conn.close();
423
-
424
- ok(i > 1);
425
- },
426
- );
package/src/mq.ts DELETED
@@ -1,596 +0,0 @@
1
- import type {
2
- MessageQueue,
3
- MessageQueueDepth,
4
- MessageQueueEnqueueOptions,
5
- MessageQueueListenOptions,
6
- } from "@fedify/fedify";
7
- // @deno-types="npm:@types/amqplib@^0.10.7"
8
- import type { Channel, ChannelModel, ConsumeMessage } from "amqplib";
9
- import { Buffer } from "node:buffer";
10
-
11
- function isQueueNotFoundError(error: unknown): boolean {
12
- return (
13
- typeof error === "object" &&
14
- error != null &&
15
- "code" in error &&
16
- error.code === 404
17
- );
18
- }
19
-
20
- function isPreconditionFailedError(error: unknown): boolean {
21
- return (
22
- typeof error === "object" &&
23
- error != null &&
24
- "code" in error &&
25
- error.code === 406
26
- );
27
- }
28
-
29
- const depthProbeConcurrency = 8;
30
- const delayedQueueExpiryMargin = 60_000;
31
- const delayedQueueCleanupThreshold = 4096;
32
-
33
- /**
34
- * Options for ordering key support in {@link AmqpMessageQueue}.
35
- *
36
- * Ordering key support requires the `rabbitmq_consistent_hash_exchange`
37
- * plugin to be enabled on the RabbitMQ server. You can enable it by running:
38
- *
39
- * ```sh
40
- * rabbitmq-plugins enable rabbitmq_consistent_hash_exchange
41
- * ```
42
- *
43
- * @since 2.0.0
44
- */
45
- export interface AmqpOrderingOptions {
46
- /**
47
- * The name of the consistent hash exchange to use for ordering.
48
- * Defaults to `"fedify_ordering"`.
49
- * @default `"fedify_ordering"`
50
- */
51
- readonly exchange?: string;
52
-
53
- /**
54
- * The prefix to use for ordering queues.
55
- * Defaults to `"fedify_ordering_"`.
56
- * @default `"fedify_ordering_"`
57
- */
58
- readonly queuePrefix?: string;
59
-
60
- /**
61
- * The number of partitions (queues) to use for ordering.
62
- * More partitions allow better parallelism for different ordering keys.
63
- * Defaults to `4`.
64
- * @default `4`
65
- */
66
- readonly partitions?: number;
67
- }
68
-
69
- /**
70
- * Options for {@link AmqpMessageQueue}.
71
- */
72
- export interface AmqpMessageQueueOptions {
73
- /**
74
- * The name of the queue to use. Defaults to `"fedify_queue"`.
75
- * @default `"fedify_queue"`
76
- */
77
- readonly queue?: string;
78
-
79
- /**
80
- * The prefix to use for the delayed queue. Defaults to `"fedify_delayed_"`.
81
- * Defaults to `"fedify_delayed_"`.
82
- * @default `"fedify_delayed_"`
83
- */
84
- readonly delayedQueuePrefix?: string;
85
-
86
- /**
87
- * Whether the queue will survive a broker restart. Defaults to `true`.
88
- * @default `true`
89
- */
90
- readonly durable?: boolean;
91
-
92
- /**
93
- * Whether to use native retrial mechanism. If set to `true`, the queue will
94
- * not acknowledge messages that are not processed successfully, allowing
95
- * them to be retried later. If set to `false`, messages will be acknowledged
96
- * whether they are processed successfully or not.
97
- *
98
- * Both approaches have their own advantages and disadvantages. With native
99
- * retrials, much less chance of losing messages, but timing of retrials is
100
- * less predictable. With non-native retrials, retrials are handled by Fedify
101
- * itself, which allows for more control over the timing and behavior of
102
- * retrials, but may result in lost messages if the process crashes before
103
- * acknowledging the message.
104
- * @default `false`
105
- * @since 0.3.0
106
- */
107
- readonly nativeRetrial?: boolean;
108
-
109
- /**
110
- * Options for ordering key support. If provided, the message queue will
111
- * support the `orderingKey` option in {@link MessageQueueEnqueueOptions}.
112
- * Messages with the same ordering key will be processed in order,
113
- * while messages with different ordering keys can be processed in parallel.
114
- *
115
- * This feature requires the `rabbitmq_consistent_hash_exchange` plugin
116
- * to be enabled on the RabbitMQ server. See {@link AmqpOrderingOptions}
117
- * for more details.
118
- *
119
- * If not provided, ordering key support is disabled and any `orderingKey`
120
- * option passed to `enqueue()` will be ignored.
121
- *
122
- * @since 0.4.0
123
- */
124
- readonly ordering?: AmqpOrderingOptions;
125
- }
126
-
127
- /**
128
- * A message queue that uses AMQP.
129
- *
130
- * @example
131
- * ``` typescript
132
- * import { createFederation } from "@fedify/fedify";
133
- * import { AmqpMessageQueue } from "@fedify/amqp";
134
- * import { connect } from "amqplib";
135
- *
136
- * const federation = createFederation({
137
- * queue: new AmqpMessageQueue(await connect("amqp://localhost")),
138
- * // ... other configurations
139
- * });
140
- * ```
141
- */
142
- export class AmqpMessageQueue implements MessageQueue {
143
- readonly atomicEnqueueMany = false;
144
-
145
- #connection: ChannelModel;
146
- #queue: string;
147
- #delayedQueuePrefix: string;
148
- #durable: boolean;
149
- #senderChannel?: Channel;
150
- #ordering?: {
151
- exchange: string;
152
- queuePrefix: string;
153
- partitions: number;
154
- };
155
- #delayedQueues: Set<string> = new Set();
156
- #delayedQueueCleanup?: Promise<void>;
157
- #orderingPrepared: boolean = false;
158
-
159
- readonly nativeRetrial: boolean;
160
-
161
- /**
162
- * Creates a new `AmqpMessageQueue`.
163
- * @param connection A connection to the AMQP server.
164
- * @param options Options for the message queue.
165
- */
166
- constructor(connection: ChannelModel, options: AmqpMessageQueueOptions = {}) {
167
- this.#connection = connection;
168
- this.#queue = options.queue ?? "fedify_queue";
169
- this.#delayedQueuePrefix = options.delayedQueuePrefix ?? "fedify_delayed_";
170
- this.#durable = options.durable ?? true;
171
- this.nativeRetrial = options.nativeRetrial ?? false;
172
- if (options.ordering != null) {
173
- this.#ordering = {
174
- exchange: options.ordering.exchange ?? "fedify_ordering",
175
- queuePrefix: options.ordering.queuePrefix ?? "fedify_ordering_",
176
- partitions: options.ordering.partitions ?? 4,
177
- };
178
- }
179
- }
180
-
181
- async #prepareQueue(channel: Channel): Promise<void> {
182
- await channel.assertQueue(this.#queue, {
183
- durable: this.#durable,
184
- });
185
- }
186
-
187
- #getOrderingQueueName(partition: number): string {
188
- return `${this.#ordering!.queuePrefix}${partition}`;
189
- }
190
-
191
- async #prepareOrdering(channel: Channel): Promise<void> {
192
- if (this.#ordering == null || this.#orderingPrepared) return;
193
- // Declare the consistent hash exchange
194
- await channel.assertExchange(this.#ordering.exchange, "x-consistent-hash", {
195
- durable: this.#durable,
196
- });
197
- // Declare and bind ordering queues with Single Active Consumer
198
- for (let i = 0; i < this.#ordering.partitions; i++) {
199
- const queueName = this.#getOrderingQueueName(i);
200
- await channel.assertQueue(queueName, {
201
- durable: this.#durable,
202
- arguments: {
203
- "x-single-active-consumer": true,
204
- },
205
- });
206
- // Bind with weight "1" (equal distribution)
207
- await channel.bindQueue(queueName, this.#ordering.exchange, "1");
208
- }
209
- this.#orderingPrepared = true;
210
- }
211
-
212
- async #getSenderChannel(): Promise<Channel> {
213
- if (this.#senderChannel != null) return this.#senderChannel;
214
- const channel = await this.#connection.createChannel();
215
- this.#senderChannel = channel;
216
- await this.#prepareQueue(channel);
217
- await this.#prepareOrdering(channel);
218
- return channel;
219
- }
220
-
221
- async #dropSenderChannel(channel: Channel): Promise<void> {
222
- if (this.#senderChannel === channel) this.#senderChannel = undefined;
223
- try {
224
- await channel.close();
225
- } catch {
226
- // The channel may already have been closed by an AMQP exception.
227
- }
228
- }
229
-
230
- /**
231
- * Enqueues a message to be processed.
232
- *
233
- * When an `orderingKey` is provided without a `delay`, the message is routed
234
- * through the consistent hash exchange, ensuring messages with the same
235
- * ordering key are processed by the same consumer in FIFO order.
236
- *
237
- * When both `orderingKey` and `delay` are provided, the message is first
238
- * placed in a delay queue, then routed to the consistent hash exchange
239
- * after the delay expires. This ensures ordering is preserved even for
240
- * delayed messages.
241
- *
242
- * @param message The message to enqueue.
243
- * @param options The options for enqueueing the message.
244
- */
245
- async enqueue(
246
- // oxlint-disable-next-line typescript/no-explicit-any
247
- message: any,
248
- options?: MessageQueueEnqueueOptions,
249
- ): Promise<void> {
250
- let channel = await this.#getSenderChannel();
251
- const delay = options?.delay?.total("millisecond");
252
- const orderingKey = options?.orderingKey;
253
-
254
- // If ordering key is provided and ordering is enabled, use consistent hash
255
- // Treat delay <= 0 the same as no delay for routing purposes
256
- if (
257
- orderingKey != null &&
258
- this.#ordering != null &&
259
- (delay == null || delay <= 0)
260
- ) {
261
- channel.publish(
262
- this.#ordering.exchange,
263
- orderingKey, // routing key = ordering key
264
- Buffer.from(JSON.stringify(message), "utf-8"),
265
- {
266
- persistent: this.#durable,
267
- contentType: "application/json",
268
- },
269
- );
270
- return;
271
- }
272
-
273
- // For delayed messages or messages without ordering key, use direct queue
274
- let queue: string;
275
- let deadLetterExchange: string | undefined;
276
- let deadLetterRoutingKey: string | undefined;
277
-
278
- if (delay == null || delay <= 0) {
279
- queue = this.#queue;
280
- } else {
281
- const delayStr = delay.toLocaleString("en", { useGrouping: false });
282
- // For delayed messages with ordering key, route to ordering exchange
283
- if (orderingKey != null && this.#ordering != null) {
284
- queue = `${this.#delayedQueuePrefix}ordering_${delayStr}`;
285
- deadLetterExchange = this.#ordering.exchange;
286
- deadLetterRoutingKey = orderingKey;
287
- } else {
288
- queue = this.#delayedQueuePrefix + delayStr;
289
- deadLetterExchange = "";
290
- deadLetterRoutingKey = this.#queue;
291
- }
292
- channel = await this.#assertDelayedQueue(channel, queue, {
293
- deadLetterExchange,
294
- deadLetterRoutingKey,
295
- delay,
296
- });
297
- this.#trackDelayedQueue(queue);
298
- }
299
- channel.sendToQueue(queue, Buffer.from(JSON.stringify(message), "utf-8"), {
300
- persistent: this.#durable,
301
- contentType: "application/json",
302
- });
303
- }
304
-
305
- /**
306
- * Enqueues multiple messages to be processed.
307
- *
308
- * When an `orderingKey` is provided without a `delay`, the messages are
309
- * routed through the consistent hash exchange, ensuring messages with the
310
- * same ordering key are processed by the same consumer in FIFO order.
311
- *
312
- * When both `orderingKey` and `delay` are provided, the messages are first
313
- * placed in a delay queue, then routed to the consistent hash exchange
314
- * after the delay expires. This ensures ordering is preserved even for
315
- * delayed messages.
316
- *
317
- * @param messages The messages to enqueue.
318
- * @param options The options for enqueueing the messages.
319
- */
320
- async enqueueMany(
321
- // oxlint-disable-next-line typescript/no-explicit-any
322
- messages: readonly any[],
323
- options?: MessageQueueEnqueueOptions,
324
- ): Promise<void> {
325
- let channel = await this.#getSenderChannel();
326
- const delay = options?.delay?.total("millisecond");
327
- const orderingKey = options?.orderingKey;
328
-
329
- // If ordering key is provided and ordering is enabled, use consistent hash
330
- // Treat delay <= 0 the same as no delay for routing purposes
331
- if (
332
- orderingKey != null &&
333
- this.#ordering != null &&
334
- (delay == null || delay <= 0)
335
- ) {
336
- for (const message of messages) {
337
- channel.publish(
338
- this.#ordering.exchange,
339
- orderingKey, // routing key = ordering key
340
- Buffer.from(JSON.stringify(message), "utf-8"),
341
- {
342
- persistent: this.#durable,
343
- contentType: "application/json",
344
- },
345
- );
346
- }
347
- return;
348
- }
349
-
350
- // For delayed messages or messages without ordering key, use direct queue
351
- let queue: string;
352
- let deadLetterExchange: string | undefined;
353
- let deadLetterRoutingKey: string | undefined;
354
-
355
- if (delay == null || delay <= 0) {
356
- queue = this.#queue;
357
- } else {
358
- const delayStr = delay.toLocaleString("en", { useGrouping: false });
359
- // For delayed messages with ordering key, route to ordering exchange
360
- if (orderingKey != null && this.#ordering != null) {
361
- queue = `${this.#delayedQueuePrefix}ordering_${delayStr}`;
362
- deadLetterExchange = this.#ordering.exchange;
363
- deadLetterRoutingKey = orderingKey;
364
- } else {
365
- queue = this.#delayedQueuePrefix + delayStr;
366
- deadLetterExchange = "";
367
- deadLetterRoutingKey = this.#queue;
368
- }
369
- channel = await this.#assertDelayedQueue(channel, queue, {
370
- deadLetterExchange,
371
- deadLetterRoutingKey,
372
- delay,
373
- });
374
- this.#trackDelayedQueue(queue);
375
- }
376
-
377
- for (const message of messages) {
378
- channel.sendToQueue(
379
- queue,
380
- Buffer.from(JSON.stringify(message), "utf-8"),
381
- {
382
- persistent: this.#durable,
383
- contentType: "application/json",
384
- },
385
- );
386
- }
387
- }
388
-
389
- #trackDelayedQueue(queue: string): void {
390
- this.#delayedQueues.add(queue);
391
- if (
392
- this.#delayedQueues.size > delayedQueueCleanupThreshold &&
393
- this.#delayedQueueCleanup == null
394
- ) {
395
- this.#delayedQueueCleanup = this.#pruneMissingDelayedQueues()
396
- .catch(() => undefined)
397
- .finally(() => {
398
- this.#delayedQueueCleanup = undefined;
399
- });
400
- }
401
- }
402
-
403
- async #assertDelayedQueue(
404
- channel: Channel,
405
- queue: string,
406
- options: {
407
- deadLetterExchange?: string;
408
- deadLetterRoutingKey?: string;
409
- delay: number;
410
- },
411
- ): Promise<Channel> {
412
- const assertOptions = {
413
- autoDelete: true,
414
- durable: this.#durable,
415
- deadLetterExchange: options.deadLetterExchange,
416
- deadLetterRoutingKey: options.deadLetterRoutingKey,
417
- messageTtl: options.delay,
418
- };
419
- try {
420
- await channel.assertQueue(queue, {
421
- ...assertOptions,
422
- expires: options.delay + delayedQueueExpiryMargin,
423
- });
424
- return channel;
425
- } catch (error) {
426
- if (!isPreconditionFailedError(error)) throw error;
427
- await this.#dropSenderChannel(channel);
428
- }
429
-
430
- const fallbackChannel = await this.#getSenderChannel();
431
- await fallbackChannel.assertQueue(queue, assertOptions);
432
- return fallbackChannel;
433
- }
434
-
435
- async #createDepthChannel(): Promise<Channel> {
436
- const channel = await this.#connection.createChannel();
437
- channel.on("error", () => undefined);
438
- return channel;
439
- }
440
-
441
- async #checkQueueDepths(
442
- queueNames: readonly string[],
443
- ): Promise<readonly (readonly [string, number | undefined])[]> {
444
- const results = new Array<readonly [string, number | undefined]>(
445
- queueNames.length,
446
- );
447
- let nextIndex = 0;
448
- const worker = async () => {
449
- let channel: Channel | undefined;
450
- const closeChannel = async () => {
451
- if (channel == null) return;
452
- const currentChannel = channel;
453
- channel = undefined;
454
- try {
455
- await currentChannel.close();
456
- } catch {
457
- // The channel can already be closed by a failed passive queue check.
458
- }
459
- };
460
- const checkQueue = async (queue: string): Promise<number | undefined> => {
461
- channel ??= await this.#createDepthChannel();
462
- try {
463
- return (await channel.checkQueue(queue)).messageCount;
464
- } catch (error) {
465
- await closeChannel();
466
- if (!isQueueNotFoundError(error)) throw error;
467
- return undefined;
468
- }
469
- };
470
- try {
471
- while (nextIndex < queueNames.length) {
472
- const index = nextIndex++;
473
- const queue = queueNames[index];
474
- results[index] = [queue, await checkQueue(queue)];
475
- }
476
- } finally {
477
- await closeChannel();
478
- }
479
- };
480
- const workers = Array.from(
481
- { length: Math.min(depthProbeConcurrency, queueNames.length) },
482
- () => worker(),
483
- );
484
- await Promise.all(workers);
485
- return results;
486
- }
487
-
488
- async #pruneMissingDelayedQueues(): Promise<void> {
489
- const delayedQueues = [...this.#delayedQueues];
490
- for (const [queue, messageCount] of await this.#checkQueueDepths(
491
- delayedQueues,
492
- )) {
493
- if (messageCount == null) this.#delayedQueues.delete(queue);
494
- }
495
- }
496
-
497
- async getDepth(): Promise<MessageQueueDepth> {
498
- const readyQueues = [this.#queue];
499
- if (this.#ordering != null) {
500
- for (let i = 0; i < this.#ordering.partitions; i++) {
501
- readyQueues.push(this.#getOrderingQueueName(i));
502
- }
503
- }
504
-
505
- let ready = 0;
506
- for (const [, messageCount] of await this.#checkQueueDepths(readyQueues)) {
507
- ready += messageCount ?? 0;
508
- }
509
-
510
- let delayed = 0;
511
- const delayedQueues = [...this.#delayedQueues];
512
- for (const [queue, messageCount] of await this.#checkQueueDepths(
513
- delayedQueues,
514
- )) {
515
- if (messageCount == null) {
516
- this.#delayedQueues.delete(queue);
517
- } else {
518
- delayed += messageCount;
519
- }
520
- }
521
-
522
- return {
523
- queued: ready + delayed,
524
- ready,
525
- delayed,
526
- };
527
- }
528
-
529
- async listen(
530
- // oxlint-disable-next-line typescript/no-explicit-any
531
- handler: (message: any) => void | Promise<void>,
532
- options: MessageQueueListenOptions = {},
533
- ): Promise<void> {
534
- const channel = await this.#connection.createChannel();
535
- await this.#prepareQueue(channel);
536
- await this.#prepareOrdering(channel);
537
- await channel.prefetch(1);
538
-
539
- const messageHandler = (msg: ConsumeMessage | null) => {
540
- if (msg == null) return;
541
- const message = JSON.parse(msg.content.toString("utf-8"));
542
- try {
543
- const result = handler(message);
544
- if (result instanceof Promise) {
545
- if (this.nativeRetrial) {
546
- result
547
- .then(() => channel.ack(msg))
548
- .catch(() => channel.nack(msg, undefined, true));
549
- } else {
550
- result.finally(() => channel.ack(msg));
551
- }
552
- } else if (this.nativeRetrial) {
553
- channel.ack(msg);
554
- }
555
- } catch {
556
- if (this.nativeRetrial) {
557
- channel.nack(msg, undefined, true);
558
- }
559
- } finally {
560
- if (!this.nativeRetrial) {
561
- channel.ack(msg);
562
- }
563
- }
564
- };
565
-
566
- // Consume from main queue
567
- const consumerTags: string[] = [];
568
- const reply = await channel.consume(this.#queue, messageHandler, {
569
- noAck: false,
570
- });
571
- consumerTags.push(reply.consumerTag);
572
-
573
- // Also consume from ordering queues if ordering is enabled
574
- if (this.#ordering != null) {
575
- for (let i = 0; i < this.#ordering.partitions; i++) {
576
- const queueName = this.#getOrderingQueueName(i);
577
- const orderingReply = await channel.consume(queueName, messageHandler, {
578
- noAck: false,
579
- });
580
- consumerTags.push(orderingReply.consumerTag);
581
- }
582
- }
583
-
584
- return await new Promise((resolve) => {
585
- if (options.signal?.aborted) resolve();
586
- options.signal?.addEventListener("abort", async () => {
587
- // Cancel all consumers
588
- for (const tag of consumerTags) {
589
- await channel.cancel(tag);
590
- }
591
- await channel.close();
592
- resolve();
593
- });
594
- });
595
- }
596
- }
@@ -1,5 +0,0 @@
1
- {
2
- "extends": "../../tsconfig.node.json",
3
- "include": ["**/*.ts", "**/*.tsx", "**/*.mts", "**/*.cts"],
4
- "exclude": ["dist", "dist-tests", "node_modules"]
5
- }
package/tsdown.config.ts DELETED
@@ -1,15 +0,0 @@
1
- import { defineConfig } from "tsdown";
2
-
3
- export default defineConfig({
4
- entry: ["src/mod.ts", "src/mq.ts"],
5
- dts: { compilerOptions: { isolatedDeclarations: true, declaration: true } },
6
- unbundle: true,
7
- format: ["esm", "cjs"],
8
- platform: "node",
9
- outExtensions({ format }) {
10
- return {
11
- js: format === "cjs" ? ".cjs" : ".js",
12
- dts: format === "cjs" ? ".d.cts" : ".d.ts",
13
- };
14
- },
15
- });