-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathQueue.ts
More file actions
287 lines (225 loc) · 6.99 KB
/
Queue.ts
File metadata and controls
287 lines (225 loc) · 6.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
import amqp from 'amqplib';
import { Connection } from './Connection';
import { logger } from './Logger';
export class Queue {
private topics: string[] = [];
private options = {
durable: false,
retryTimeout: -1,
deadLetterAfter: -1,
enableNack: true,
ephemeral: false,
exclusive: false,
prefetch: 1,
maxPriority: -1,
names: {
queueName: '',
nackQueue: '',
retryTopic: '',
nackTopic: '',
dlqQueue: '',
},
};
constructor(private readonly connection: Connection, private readonly baseQueueName: string) {
// empty
}
public async listen<T = unknown>(callback: (data: T, message?: amqp.ConsumeMessage) => Promise<boolean>) {
if (this.hasTimeout() && !this.hasDeadLetter()) {
throw new Error('If you use retryTimeout, you need to specify a deadLetterAfter');
}
if (this.topics.length === 0) {
throw new Error('You must specify an least one topic');
}
let channel: amqp.Channel;
const configureChannel = async (newChannel: amqp.Channel) => {
channel = newChannel;
this.genrateQueueNames();
await this.configureNackQueue(this.connection.getExchange(), channel);
await this.configureDLQQueue(channel);
await this.configureQueue(this.connection.getExchange(), channel);
await channel.prefetch(this.options.prefetch);
const consumeFn = async (msg: amqp.ConsumeMessage | null) => {
if (!msg) {
return;
}
try {
const payload = JSON.parse(msg.content.toString()) as T;
logger.debug({
message: 'RECEIVED',
queue: this.baseQueueName,
data: payload,
});
const result = await callback(payload, msg);
if (!result) {
await this.handleFailedMessage(channel, msg);
return;
}
channel.ack(msg);
} catch (err) {
try {
await this.handleFailedMessage(channel, msg);
} catch {
logger.error({
message: 'Failed to handle failed message',
});
}
}
};
logger.debug(`Listening to queue ${this.baseQueueName}...`);
await channel.consume(this.options.names.queueName, consumeFn, { noAck: false });
};
this.connection.on('connected', async () => {
const oldChannel = channel;
const newChannel = await this.getChannel();
logger.debug(`Channel connected ${this.baseQueueName}`);
if (newChannel === channel) {
return;
}
logger.debug(`New channel found for queue ${this.baseQueueName}`);
await configureChannel(newChannel);
try {
oldChannel?.close();
} catch (err) {
// nothing;
}
});
configureChannel(await this.getChannel());
}
public topic(topic: string) {
this.topics = [...new Set([...this.topics, topic])];
return this;
}
public durable(durable = true) {
this.options.durable = durable;
return this;
}
public retryTimeout(timeout: number) {
if (timeout < 1) {
throw new Error('Invalid timeout');
}
this.options.retryTimeout = timeout;
return this;
}
public deadLetterAfter(numberOfFailures: number) {
this.options.deadLetterAfter = numberOfFailures;
return this;
}
public disableNack() {
this.options.enableNack = false;
return this;
}
public ephemeral() {
this.options.ephemeral = true;
return this;
}
public exclusive() {
this.options.exclusive = true;
return this;
}
public prefetch(quantity: number) {
if (quantity <= 0) {
throw new Error('prefetch must be greater than zero');
}
this.options.prefetch = quantity;
return this;
}
public priority(max: number) {
if (max <= 1 || max > 255) {
throw new Error('invalid priority (must be between 1 and 255)');
}
this.options.maxPriority = max;
return this;
}
private getChannel() {
return this.connection.loadChannel({
name: `__receiver__pref: ${this.options.prefetch}: ${this.baseQueueName}`,
});
}
private genrateQueueNames() {
const id = Math.ceil(Math.random() * Number.MAX_SAFE_INTEGER);
const suffix = this.options.ephemeral ? `.ephemeral.${id}` : '';
const name = `${this.baseQueueName}${suffix}`;
const queueName = name;
const nackQueue = name + '.nack';
const retryTopic = name + '.retry';
const nackTopic = name + '.nack';
const dlqQueue = name + '.dlq';
this.options.names = {
queueName,
nackQueue,
retryTopic,
nackTopic,
dlqQueue,
};
}
private async configureDLQQueue(ch: amqp.Channel) {
if (!this.hasDeadLetter()) {
return;
}
if (this.options.ephemeral) {
throw new Error('you cannot use DQL with ephemeral queues');
}
await ch.assertQueue(this.options.names.dlqQueue, {
durable: true,
autoDelete: false,
arguments: {},
});
}
private async configureNackQueue(exchange: string, ch: amqp.Channel) {
if (!this.options.enableNack) {
return;
}
let args: Record<string, any> = {};
if (this.hasTimeout()) {
args = {
'x-dead-letter-exchange': exchange,
'x-dead-letter-routing-key': this.options.names.retryTopic,
'x-message-ttl': this.options.retryTimeout,
};
}
await ch.assertQueue(this.options.names.nackQueue, {
durable: this.options.durable,
autoDelete: this.options.ephemeral || false,
arguments: args,
});
await ch.bindQueue(this.options.names.nackQueue, exchange, this.options.names.nackTopic);
}
private async configureQueue(exchange: string, ch: amqp.Channel) {
const args: Record<string, any> = {};
if (this.options.enableNack) {
args['x-dead-letter-exchange'] = exchange;
args['x-dead-letter-routing-key'] = this.options.names.nackTopic;
}
await ch.assertQueue(this.options.names.queueName, {
durable: this.options.durable,
autoDelete: this.options.ephemeral || false,
exclusive: this.options.exclusive || false,
arguments: args,
});
for (const topic of this.topics) {
await ch.bindQueue(this.options.names.queueName, exchange, topic);
}
if (this.options.enableNack && this.hasTimeout()) {
await ch.bindQueue(this.options.names.queueName, exchange, this.options.names.retryTopic);
}
}
private async handleFailedMessage(channel: amqp.Channel, msg: amqp.ConsumeMessage) {
if (!this.hasDeadLetter() || !msg.properties?.headers['x-death']) {
channel.nack(msg, false, false);
return;
}
const failedAttempts = msg.properties.headers['x-death'][0].count;
if (failedAttempts >= this.options.deadLetterAfter) {
channel.sendToQueue(this.options.names.dlqQueue, msg.content);
channel.ack(msg);
return;
}
channel.nack(msg, false, false);
}
private hasTimeout() {
return this.options.retryTimeout > 0;
}
private hasDeadLetter() {
return this.options.deadLetterAfter > 0;
}
}