-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.ts
419 lines (378 loc) · 11.7 KB
/
index.ts
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
/*!
* Job Queue for @imqueue framework
*
* Copyright (c) 2018, imqueue.com <[email protected]>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
* INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
* LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
import IMQ, {
AnyJson,
ILogger,
IMessageQueue,
IMQMode,
IMQOptions,
} from '@imqueue/core';
/**
* Job queues options
*/
export interface JobQueueOptions {
/**
* Name of the job queue. In worker/publisher mode worker and
* publisher must share the same job queue name.
* Mandatory.
*
* @type {string}
*/
name: string;
/**
* Connection params of the queue engine cluster (typically -
* host and port). By default the broker is redis.
* Optional.
* By default is [{ host: "localhost", port: 6379 }].
*
* @type {Array<{host: string, port: number}>}
*/
cluster?: { host: string; port: number; }[];
/**
* Logger to be used for producing log and error messages.
* Optional.
* By default is console.
*
* @type {ILogger}
*/
logger?: ILogger;
/**
* Safe message delivery or not? When safe delivery is enabled (by default)
* queue is processing jobs with guarantied job data delivery. If process
* fails or dies - job data is re-queued for future processing by another
* worker.
* Optional.
* Default is true.
*
* @type {boolean}
*/
safe?: boolean;
/**
* TTL in milliseconds of the job in worker queue during safe delivery.
* If worker does not finish processing after this TTL - job is re-queued
* for other workers to be processed.
* Optional.
* By default is 10000.
*/
safeLockTtl?: number;
/**
* Job queue prefix in queue broker.
* Optional.
* By default is "imq-job".
*/
prefix?: string;
}
export interface JobQueuePopHandler<T> {
/**
* Handles popped from a queue job. If it throws error job will be
* re-scheduled with the same delay as it was pushed into queue,
* If it returns positive number it will be treated as new delay to
* re-schedule message in the queue. Normally, if re-schedule is not needed
* it should return nothing (undefined, void return).
* If worker goes down during the job processing, job will be re-scheduled
* after configured by options safeLockTtl.
*
* @example
* ```typescript
* // job logged and not re-scheduled (normal typical job processing)
* queue.onPop(job => {
* console.log(job);
* });
* // job logged and re-schedule immediately
* queue.onPop(job => {
* console.log(job);
* return 0;
* });
* // job logged and not re-scheduled (normal typical job processing)
* queue.onPop(job => {
* console.log(job);
* return -1;
* });
* // job re-scheduled with the initial delay (job throws)
* queue.on(job => {
* throw new Error('Job error');
* });
* // job re-scheduled with new delay of 1 second
* queue.onPop(job => {
* console.log(job);
* return 1000; // re-run after 1 second
* });
* ```
*
* @param {T} job
* @return {Promise<number | void>}
*/
(job: T): number | void | Promise<number | void>;
}
export interface PushOptions {
/**
* Delay before message to be processed by workers
*/
delay?: number;
/**
* Time to live for message in queue in milliseconds
*/
ttl?: number;
}
export interface AnyJobQueue<T> {
name: string;
readonly logger: ILogger;
start(): Promise<T>;
stop(): Promise<T>;
destroy(): Promise<void>;
}
export interface AnyJobQueueWorker<T, U> {
onPop(handler: JobQueuePopHandler<U>): T;
}
export interface AnyJobQueuePublisher<T, U> {
push(job: U, options?: PushOptions): T;
}
/**
* Abstract job queue, handles base implementations of AnyJobQueue interface.
*/
export abstract class BaseJobQueue<T, U> implements AnyJobQueue<T> {
protected imq: IMessageQueue;
protected handler: JobQueuePopHandler<U>;
public readonly logger: ILogger;
protected constructor(
protected options: JobQueueOptions,
) {
this.logger = options.logger || console;
}
/**
* Full name of this queue
*
* @type {string}
*/
public get name(): string {
return this.options.name;
}
/**
* Starts processing job queue
*
* @return {Promise<T>} - this queue
*/
public async start(): Promise<T> {
await this.imq.start();
return this as any as T;
}
/**
* Stops processing job queue
*
* @return {Promise<T>} - this queue
*/
public async stop(): Promise<T> {
await this.imq.stop();
return this as any as T;
}
/**
* Destroys job queue
*
* @return {Promise<void>}
*/
public async destroy() {
await this.imq.destroy();
}
}
/**
* Creates and returns IMQOptions derived from a given JobQueueOptions
*
* @param {JobQueueOptions} options
* @param {ILogger} logger
* @return {Partial<IMQOptions>}
* @private
*/
function toIMQOptions(
options: JobQueueOptions,
logger: ILogger,
): Partial<IMQOptions> {
return {
cluster: options.cluster,
cleanup: false,
safeDelivery: typeof options.safe === 'undefined'
? true : options.safe,
safeDeliveryTtl: typeof options.safeLockTtl === 'undefined'
? 10000 : options.safeLockTtl,
prefix: options.prefix || 'imq-job',
logger,
};
}
// noinspection JSUnusedGlobalSymbols
/**
* Implements simple scheduled job queue publisher. Job queue publisher is only
* responsible for pushing queue messages.
*/
export class JobQueuePublisher<T> extends BaseJobQueue<JobQueuePublisher<T>, T>
implements AnyJobQueuePublisher<JobQueuePublisher<T>, T>
{
/**
* Constructor. Instantiates new JobQueue instance.
*
* @constructor
* @param {JobQueueOptions} options
*/
public constructor(options: JobQueueOptions) {
super(options);
this.imq = IMQ.create(
options.name,
toIMQOptions(options, this.logger),
IMQMode.PUBLISHER,
);
}
/**
* Pushes new job to this queue
*
* @param {T} job - job data itself of user defined type
* @param {PushOptions} options - push options, like delay and ttl for job
* @return {JobQueue<T>} - this queue
*/
public push(job: T, options?: PushOptions): JobQueuePublisher<T> {
options = options || {} as PushOptions;
this.imq.send(this.name, {
job: job as unknown as AnyJson,
...(options.ttl ? { expire: Date.now() + options.ttl } : {}),
...(options.delay ? { delay: options.delay } : {}),
}, options.delay).catch(err =>
this.logger.log('JobQueue push error:', err),
);
return this;
}
}
// noinspection JSUnusedGlobalSymbols
/**
* Implements simple scheduled job queue worker. Job queue worker is only
* responsible for processing queue messages.
*/
export class JobQueueWorker<T> extends BaseJobQueue<JobQueueWorker<T>, T>
implements AnyJobQueueWorker<JobQueueWorker<T>, T>
{
/**
* Constructor. Instantiates new JobQueue instance.
*
* @constructor
* @param {JobQueueOptions} options
*/
public constructor(options: JobQueueOptions) {
super(options);
this.imq = IMQ.create(
options.name,
toIMQOptions(options, this.logger),
IMQMode.WORKER,
);
}
/**
* Sets up job handler, which is called when the job is popped from this
* queue.
*
* @param {JobQueuePopHandler<T>} handler - job pop handler
* @return {JobQueueWorker<T>} - this queue
*/
public onPop(handler: JobQueuePopHandler<T>): JobQueueWorker<T> {
this.handler = handler;
this.imq.removeAllListeners('message');
this.imq.on('message', async (message: any) => {
const { job, expire, delay } = message;
let rescheduleDelay: number | void | undefined | Promise<any>;
try {
rescheduleDelay = this.handler(job);
if (rescheduleDelay &&
typeof rescheduleDelay === 'object' &&
rescheduleDelay &&
(rescheduleDelay as any).then
) {
// it's promise
rescheduleDelay = await rescheduleDelay;
}
} catch (err) {
rescheduleDelay = delay;
this.logger.log('Error handling job:', err);
}
if (typeof expire === 'number' && expire <= Date.now()) {
return ; // remove job from queue
}
if (typeof rescheduleDelay === 'number' && rescheduleDelay >= 0) {
await this.imq.send(this.name, message, rescheduleDelay);
}
});
return this;
}
}
// noinspection JSUnusedGlobalSymbols
/**
* Implements simple scheduled job queue. Job scheduling is optional. It may
* process jobs immediately or after specified delay for particular job.
* It also allows to define max lifetime of the job in a queue, after which
* the job is removed from a queue.
* Supports graceful shutdown, if TERM or SIGINT is sent to the process.
*/
export default class JobQueue<T> extends BaseJobQueue<JobQueue<T>, T>
implements
AnyJobQueueWorker<JobQueue<T>, T>,
AnyJobQueuePublisher<JobQueue<T>, T>
{
/**
* Constructor. Instantiates new JobQueue instance.
*
* @constructor
* @param {JobQueueOptions} options
*/
public constructor(options: JobQueueOptions) {
super(options);
this.imq = IMQ.create(options.name, toIMQOptions(options, this.logger));
}
/**
* Starts processing job queue. Throws if handler is not set before start.
*
* @throws {TypeError}
* @return {Promise<T>} - this queue
*/
public async start(): Promise<JobQueue<T>> {
if (!this.handler) {
throw new TypeError(
'Message handler is not set, can not start job queue!',
);
}
return await super.start();
}
/**
* Pushes new job to this queue. Throws if handler is not set.
*
* @throws {TypeError}
* @param {T} job - job data itself of user defined type
* @param {PushOptions} options - push options, like delay and ttl for job
* @return {JobQueue<T>} - this queue
*/
public push(job: T, options?: PushOptions): JobQueue<T> {
if (!this.handler) {
throw new TypeError(
'Message handler is not set, can not enqueue data!',
);
}
return JobQueuePublisher.prototype.push.call(this, job, options);
}
/**
* Sets up job handler, which is called when the job is popped from this
* queue.
*
* @param {JobQueuePopHandler<T>} handler - job pop handler
* @return {JobQueue<T>} - this queue
*/
public onPop(handler: JobQueuePopHandler<T>): JobQueue<T> {
return JobQueueWorker.prototype.onPop.call(this, handler);
}
}