@tsed/bullmq 7.49.0 → 7.51.0

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.
@@ -1,4 +1,5 @@
1
1
  import { Job } from "bullmq";
2
2
  export interface JobMethods<DataType = unknown, ReturnType = unknown> {
3
3
  handle(payload: DataType, job: Job<DataType, ReturnType>): ReturnType | Promise<ReturnType>;
4
+ jobId?(payload: DataType): string | Promise<string>;
4
5
  }
@@ -7,7 +7,8 @@ export declare class JobDispatcher {
7
7
  private readonly injector;
8
8
  constructor(injector: InjectorService);
9
9
  dispatch<T extends JobMethods>(job: Type<T>, payload?: Parameters<T["handle"]>[0], options?: JobsOptions): Promise<BullMQJob>;
10
- dispatch<T = any>(job: JobDispatcherOptions, payload?: T, options?: JobsOptions): Promise<BullMQJob>;
11
- dispatch<T = any>(job: string, payload?: T, options?: JobsOptions): Promise<BullMQJob>;
10
+ dispatch<P = unknown>(job: JobDispatcherOptions, payload?: P, options?: JobsOptions): Promise<BullMQJob>;
11
+ dispatch<P = unknown>(job: string, payload?: P, options?: JobsOptions): Promise<BullMQJob>;
12
12
  private resolveDispatchArgs;
13
+ private retrieveJobOptionsFromClassBasedJob;
13
14
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tsed/bullmq",
3
- "version": "7.49.0",
3
+ "version": "7.51.0",
4
4
  "private": false,
5
5
  "description": "BullMQ integration for Ts.ED",
6
6
  "keywords": [
@@ -29,11 +29,11 @@
29
29
  "tslib": "2.5.0"
30
30
  },
31
31
  "devDependencies": {
32
- "@tsed/common": "7.49.0",
33
- "@tsed/core": "7.49.0",
34
- "@tsed/di": "7.49.0",
32
+ "@tsed/common": "7.51.0",
33
+ "@tsed/core": "7.51.0",
34
+ "@tsed/di": "7.51.0",
35
35
  "@tsed/eslint": "7.44.1",
36
- "@tsed/schema": "7.49.0",
36
+ "@tsed/schema": "7.51.0",
37
37
  "@tsed/typescript": "7.44.1",
38
38
  "bullmq": "^4.12.3",
39
39
  "eslint": "^8.12.0",
package/jest.config.js DELETED
@@ -1,11 +0,0 @@
1
- module.exports = {
2
- ...require("@tsed/jest-config"),
3
- coverageThreshold: {
4
- global: {
5
- branches: 89.58,
6
- functions: 100,
7
- lines: 100,
8
- statements: 100
9
- }
10
- }
11
- };
@@ -1,381 +0,0 @@
1
- import {PlatformTest} from "@tsed/common";
2
- import {catchAsyncError} from "@tsed/core";
3
- import {Queue, Worker} from "bullmq";
4
- import {anything, instance, mock, verify, when} from "ts-mockito";
5
-
6
- import "./BullMQModule";
7
- import {BullMQModule} from "./BullMQModule";
8
- import {type BullMQConfig} from "./config/config";
9
- import {JobMethods} from "./contracts";
10
- import {FallbackJobController, JobController} from "./decorators";
11
- import {JobDispatcher} from "./dispatchers";
12
-
13
- const queueConstructorSpy = jest.fn();
14
- const workerConstructorSpy = jest.fn();
15
-
16
- jest.mock("bullmq", () => {
17
- return {
18
- Queue: class {
19
- constructor(...args: any[]) {
20
- queueConstructorSpy(...args);
21
- }
22
- close() {}
23
- },
24
- Worker: class {
25
- constructor(...args: any[]) {
26
- workerConstructorSpy(...args);
27
- }
28
- close() {}
29
- }
30
- };
31
- });
32
-
33
- @JobController("cron", "default", {
34
- repeat: {
35
- pattern: "* * * * *"
36
- }
37
- })
38
- class CustomCronJob implements JobMethods {
39
- handle() {}
40
- }
41
-
42
- @JobController("regular", "default")
43
- class RegularJob {
44
- handle() {}
45
- }
46
-
47
- describe("BullMQModule", () => {
48
- let dispatcher: JobDispatcher;
49
-
50
- beforeEach(() => {
51
- dispatcher = mock(JobDispatcher);
52
- when(dispatcher.dispatch(CustomCronJob)).thenResolve();
53
- });
54
-
55
- afterEach(PlatformTest.reset);
56
-
57
- describe("configuration", () => {
58
- beforeEach(() => {
59
- queueConstructorSpy.mockClear();
60
- workerConstructorSpy.mockClear();
61
- });
62
-
63
- describe("merges config correctly", () => {
64
- beforeEach(async () => {
65
- await PlatformTest.create({
66
- bullmq: {
67
- queues: ["default", "special"],
68
- connection: {
69
- connectionName: "defaultConnectionName"
70
- },
71
- defaultQueueOptions: {
72
- defaultJobOptions: {
73
- delay: 100
74
- },
75
- blockingConnection: true
76
- },
77
- queueOptions: {
78
- special: {
79
- connection: {
80
- connectionName: "specialConnectionName"
81
- },
82
- defaultJobOptions: {
83
- attempts: 9
84
- }
85
- }
86
- },
87
- defaultWorkerOptions: {
88
- connection: {
89
- connectTimeout: 123
90
- },
91
- concurrency: 50
92
- },
93
- workerOptions: {
94
- special: {
95
- concurrency: 1,
96
- lockDuration: 2
97
- }
98
- }
99
- },
100
- imports: [
101
- {
102
- token: JobDispatcher,
103
- use: instance(dispatcher)
104
- }
105
- ]
106
- });
107
- });
108
-
109
- it("queue", () => {
110
- expect(queueConstructorSpy).toHaveBeenCalledTimes(2);
111
-
112
- expect(queueConstructorSpy).toHaveBeenNthCalledWith(1, "default", {
113
- connection: {
114
- connectionName: "defaultConnectionName"
115
- },
116
- defaultJobOptions: {
117
- delay: 100
118
- },
119
- blockingConnection: true
120
- });
121
-
122
- expect(queueConstructorSpy).toHaveBeenNthCalledWith(2, "special", {
123
- connection: {
124
- connectionName: "specialConnectionName"
125
- },
126
- defaultJobOptions: {
127
- attempts: 9,
128
- delay: 100
129
- },
130
- blockingConnection: true
131
- });
132
- });
133
-
134
- it("worker", () => {
135
- expect(workerConstructorSpy).toHaveBeenCalledTimes(2);
136
-
137
- expect(workerConstructorSpy).toHaveBeenNthCalledWith(1, "default", expect.any(Function), {
138
- connection: {
139
- connectTimeout: 123
140
- },
141
- concurrency: 50
142
- });
143
-
144
- expect(workerConstructorSpy).toHaveBeenNthCalledWith(2, "special", expect.any(Function), {
145
- connection: {
146
- connectTimeout: 123
147
- },
148
- concurrency: 1,
149
- lockDuration: 2
150
- });
151
- });
152
- });
153
-
154
- describe("disableWorker", () => {
155
- const config = {
156
- queues: ["default", "foo", "bar"],
157
- connection: {},
158
- disableWorker: true
159
- } as BullMQConfig;
160
-
161
- beforeEach(async () => {
162
- await PlatformTest.create({
163
- bullmq: config,
164
- imports: [
165
- {
166
- token: JobDispatcher,
167
- use: instance(dispatcher)
168
- }
169
- ]
170
- });
171
- });
172
-
173
- it("should not create any workers", () => {
174
- expect(workerConstructorSpy).toHaveBeenCalledTimes(0);
175
- });
176
- });
177
-
178
- describe("without", () => {
179
- it("skips initialization", async () => {
180
- await PlatformTest.create({
181
- imports: [
182
- {
183
- token: JobDispatcher,
184
- use: instance(dispatcher)
185
- }
186
- ]
187
- });
188
-
189
- expect(queueConstructorSpy).not.toHaveBeenCalled();
190
- verify(dispatcher.dispatch(anything())).never();
191
- });
192
- });
193
- });
194
-
195
- describe("functionality", () => {
196
- const config = {
197
- queues: ["default", "foo", "bar"],
198
- connection: {},
199
- workerQueues: ["default", "foo"]
200
- } as BullMQConfig;
201
-
202
- beforeEach(async () => {
203
- await PlatformTest.create({
204
- bullmq: config,
205
- imports: [
206
- {
207
- token: JobDispatcher,
208
- use: instance(dispatcher)
209
- }
210
- ]
211
- });
212
- });
213
-
214
- describe("cronjobs", () => {
215
- it("should dispatch cron jobs automatically", () => {
216
- verify(dispatcher.dispatch(CustomCronJob)).once();
217
- });
218
- });
219
-
220
- describe("queues", () => {
221
- it("should get default", () => {
222
- const instance = PlatformTest.get<Queue>("bullmq.queue.default");
223
-
224
- expect(instance).toBeInstanceOf(Queue);
225
- });
226
-
227
- it.each(config.queues)("should register queue(%s)", (queue) => {
228
- const instance = PlatformTest.get<Queue>(`bullmq.queue.${queue}`);
229
-
230
- expect(instance).toBeInstanceOf(Queue);
231
- });
232
-
233
- it("should not allow direct injection of the queue", () => {
234
- expect(PlatformTest.get(Queue)).not.toBeInstanceOf(Queue);
235
- });
236
- });
237
-
238
- describe("workers", () => {
239
- it("should get default", () => {
240
- const instance = PlatformTest.get<Worker>("bullmq.worker.default");
241
-
242
- expect(instance).toBeInstanceOf(Worker);
243
- });
244
-
245
- it.each(config.workerQueues)("should register worker(%s)", (queue) => {
246
- const instance = PlatformTest.get<Worker>(`bullmq.worker.${queue}`);
247
-
248
- expect(instance).toBeInstanceOf(Worker);
249
- });
250
-
251
- it("should not register unspecified worker queue", () => {
252
- expect(PlatformTest.get("bullmq.worker.bar")).toBeUndefined();
253
- });
254
-
255
- it("should not allow direct injection of the worker", () => {
256
- expect(PlatformTest.get(Worker)).not.toBeInstanceOf(Worker);
257
- });
258
-
259
- it("should run worker and execute processor", async () => {
260
- const bullMQModule = PlatformTest.get<BullMQModule>(BullMQModule);
261
- const worker = PlatformTest.get<JobMethods>("bullmq.job.default.regular");
262
- const job = {
263
- name: "regular",
264
- queueName: "default",
265
- data: {test: "test"}
266
- };
267
-
268
- jest.spyOn(worker, "handle").mockResolvedValueOnce(undefined as never);
269
-
270
- await (bullMQModule as any).onProcess(job);
271
-
272
- expect(worker.handle).toHaveBeenCalledWith({test: "test"}, job);
273
- });
274
-
275
- it("should log warning when the worker doesn't exists", async () => {
276
- const bullMQModule = PlatformTest.get<BullMQModule>(BullMQModule);
277
-
278
- jest.spyOn(PlatformTest.injector.logger, "warn");
279
-
280
- const job = {
281
- name: "regular",
282
- queueName: "toto",
283
- data: {test: "test"}
284
- };
285
-
286
- await (bullMQModule as any).onProcess(job);
287
-
288
- expect(PlatformTest.injector.logger.warn).toHaveBeenCalledWith({
289
- event: "BULLMQ_JOB_NOT_FOUND",
290
- message: "Job regular toto not found"
291
- });
292
- });
293
-
294
- it("should run worker, execute processor and handle error", async () => {
295
- const bullMQModule = PlatformTest.get<BullMQModule>(BullMQModule);
296
- const worker = PlatformTest.get<JobMethods>("bullmq.job.default.regular");
297
- const job = {
298
- name: "regular",
299
- queueName: "default",
300
- data: {test: "test"}
301
- };
302
-
303
- jest.spyOn(PlatformTest.injector.logger, "error");
304
-
305
- jest.spyOn(worker, "handle").mockRejectedValue(new Error("error") as never);
306
-
307
- const error = await catchAsyncError(() => (bullMQModule as any).onProcess(job));
308
-
309
- expect(worker.handle).toHaveBeenCalledWith({test: "test"}, job);
310
- expect(PlatformTest.injector.logger.error).toHaveBeenCalledWith({
311
- duration: expect.any(Number),
312
- event: "BULLMQ_JOB_ERROR",
313
- message: "error",
314
- reqId: expect.any(String),
315
- stack: expect.any(String),
316
- time: expect.any(Object)
317
- });
318
- expect(error?.message).toEqual("error");
319
- });
320
- });
321
- });
322
-
323
- describe("with fallback controller", () => {
324
- beforeEach(async () => {
325
- @FallbackJobController("foo")
326
- class FooFallbackController {
327
- handle() {}
328
- }
329
-
330
- @FallbackJobController()
331
- class FallbackController {
332
- handle() {}
333
- }
334
-
335
- await PlatformTest.create({
336
- bullmq: {
337
- queues: ["default", "foo"],
338
- connection: {}
339
- },
340
- imports: [
341
- {
342
- token: JobDispatcher,
343
- use: instance(dispatcher)
344
- }
345
- ]
346
- });
347
- });
348
-
349
- it("should run queue specific fallback job controller", async () => {
350
- const bullMQModule = PlatformTest.get<BullMQModule>(BullMQModule);
351
- const worker = PlatformTest.get<JobMethods>("bullmq.fallback-job.foo");
352
- const job = {
353
- name: "unknown-name",
354
- queueName: "foo",
355
- data: {test: "test"}
356
- };
357
-
358
- jest.spyOn(worker, "handle").mockResolvedValueOnce(undefined as never);
359
-
360
- await (bullMQModule as any).onProcess(job);
361
-
362
- expect(worker.handle).toHaveBeenCalledWith({test: "test"}, job);
363
- });
364
-
365
- it("should run overall fallback job controller", async () => {
366
- const bullMQModule = PlatformTest.get<BullMQModule>(BullMQModule);
367
- const worker = PlatformTest.get<JobMethods>("bullmq.fallback-job");
368
- const job = {
369
- name: "unknown-name",
370
- queueName: "default",
371
- data: {test: "123"}
372
- };
373
-
374
- jest.spyOn(worker, "handle").mockResolvedValueOnce(undefined as never);
375
-
376
- await (bullMQModule as any).onProcess(job);
377
-
378
- expect(worker.handle).toHaveBeenCalledWith({test: "123"}, job);
379
- });
380
- });
381
- });
@@ -1,122 +0,0 @@
1
- import {BeforeInit, DIContext, runInContext} from "@tsed/common";
2
- import {Constant, InjectorService, Module} from "@tsed/di";
3
- import {deepMerge} from "@tsed/core";
4
- import {getComputedType} from "@tsed/schema";
5
- import {Job, Queue, type QueueOptions, Worker, type WorkerOptions} from "bullmq";
6
- import {v4} from "uuid";
7
- import {BullMQConfig} from "./config/config";
8
- import {JobMethods} from "./contracts";
9
- import {JobDispatcher} from "./dispatchers";
10
-
11
- @Module()
12
- export class BullMQModule implements BeforeInit {
13
- @Constant("bullmq")
14
- private readonly bullmq: BullMQConfig;
15
-
16
- constructor(private readonly injector: InjectorService, private readonly dispatcher: JobDispatcher) {}
17
-
18
- $beforeInit() {
19
- if (!this.bullmq) {
20
- return;
21
- }
22
-
23
- if (!this.bullmq.disableWorker) {
24
- this.buildWorkers();
25
- }
26
- this.buildQueues();
27
-
28
- this.injector.getMany<JobMethods>("bullmq:cron").map((job) => this.dispatcher.dispatch(getComputedType(job)));
29
- }
30
-
31
- private buildQueues() {
32
- this.bullmq.queues.forEach((queue) => {
33
- const ops = deepMerge<QueueOptions, QueueOptions>(
34
- {
35
- connection: this.bullmq.connection,
36
- defaultJobOptions: this.bullmq.defaultJobOptions,
37
- ...this.bullmq.defaultQueueOptions
38
- },
39
- this.bullmq.queueOptions?.[queue]
40
- )!;
41
-
42
- this.injector
43
- .add(`bullmq.queue.${queue}`, {
44
- type: "bullmq:queue",
45
- useValue: new Queue(queue, ops),
46
- hooks: {
47
- $onDestroy: (queue) => queue.close()
48
- }
49
- })
50
- .invoke<Queue>(`bullmq.queue.${queue}`);
51
- });
52
- }
53
-
54
- private buildWorkers() {
55
- (this.bullmq.workerQueues ?? this.bullmq.queues).forEach((queue) => {
56
- const ops = deepMerge<WorkerOptions, WorkerOptions>(
57
- {
58
- connection: this.bullmq.connection,
59
- ...this.bullmq.defaultWorkerOptions
60
- },
61
- this.bullmq.workerOptions?.[queue]
62
- )!;
63
-
64
- this.injector
65
- .add(`bullmq.worker.${queue}`, {
66
- type: "bullmq:worker",
67
- useValue: new Worker(queue, this.onProcess.bind(this), ops),
68
- hooks: {
69
- $onDestroy: (worker) => worker.close()
70
- }
71
- })
72
- .invoke<Worker>(`bullmq.worker.${queue}`);
73
- });
74
- }
75
-
76
- private getJob(name: string, queueName: string) {
77
- const job = this.injector.get<JobMethods>(`bullmq.job.${queueName}.${name}`);
78
- if (job) {
79
- return job;
80
- }
81
-
82
- const fallbackJobForQueue = this.injector.get(`bullmq.fallback-job.${queueName}`);
83
- if (fallbackJobForQueue) {
84
- return fallbackJobForQueue;
85
- }
86
-
87
- return this.injector.get("bullmq.fallback-job");
88
- }
89
-
90
- private async onProcess(job: Job) {
91
- const jobService = this.getJob(job.name, job.queueName);
92
-
93
- if (!jobService) {
94
- this.injector.logger.warn({
95
- event: "BULLMQ_JOB_NOT_FOUND",
96
- message: `Job ${job.name} ${job.queueName} not found`
97
- });
98
- return;
99
- }
100
-
101
- const $ctx = new DIContext({
102
- injector: this.injector,
103
- logger: this.injector.logger,
104
- id: job.id || v4().split("-").join("")
105
- });
106
-
107
- $ctx.set("BULLMQ_JOB", job);
108
-
109
- try {
110
- return await runInContext($ctx, () => jobService.handle(job.data, job));
111
- } catch (er) {
112
- $ctx.logger.error({
113
- event: "BULLMQ_JOB_ERROR",
114
- message: er.message,
115
- stack: er.stack
116
- });
117
- throw er;
118
- } finally {
119
- await $ctx.destroy();
120
- }
121
- }
122
- }
@@ -1,64 +0,0 @@
1
- import type {ConnectionOptions, DefaultJobOptions, QueueOptions, WorkerOptions} from "bullmq";
2
-
3
- export type BullMQConfig = {
4
- /**
5
- * Specify queue name's to create
6
- */
7
- queues: string[];
8
-
9
- /**
10
- * Default connection to use for queue's and worker's
11
- */
12
- connection: ConnectionOptions;
13
-
14
- /**
15
- * @deprecated Use defaultQueueOptions instead. Will be removed in the next major release
16
- */
17
- defaultJobOptions?: DefaultJobOptions;
18
-
19
- /**
20
- * Default queue options which are applied to every queue
21
- *
22
- * Can be extended/overridden by `queueOptions`
23
- */
24
- defaultQueueOptions?: QueueOptions;
25
-
26
- /**
27
- * Specify additional queue options by queue name
28
- */
29
- queueOptions?: Record<string, QueueOptions>;
30
-
31
- /**
32
- * Disable the creation of any worker.
33
- *
34
- * All other worker configuration will be ignored
35
- */
36
- disableWorker?: boolean;
37
-
38
- /**
39
- * Specify for which queues to start a worker for.
40
- *
41
- * Defaultly for every queue added in the `queues` parameter
42
- */
43
- workerQueues?: string[];
44
-
45
- /**
46
- * Default worker options which are applied to every worker
47
- *
48
- * Can be extended/overridden by `workerOptions`
49
- */
50
- defaultWorkerOptions?: WorkerOptions;
51
-
52
- /**
53
- * Specify additional worker options by queue name
54
- */
55
- workerOptions?: Record<string, WorkerOptions>;
56
- };
57
-
58
- declare global {
59
- namespace TsED {
60
- interface Configuration {
61
- bullmq?: BullMQConfig;
62
- }
63
- }
64
- }
@@ -1,5 +0,0 @@
1
- import {Job} from "bullmq";
2
-
3
- export interface JobMethods<DataType = unknown, ReturnType = unknown> {
4
- handle(payload: DataType, job: Job<DataType, ReturnType>): ReturnType | Promise<ReturnType>;
5
- }
@@ -1,7 +0,0 @@
1
- import {JobsOptions} from "bullmq";
2
-
3
- export type JobStore = {
4
- name: string;
5
- queue: string;
6
- opts: JobsOptions;
7
- };
@@ -1,6 +0,0 @@
1
- /**
2
- * @file Automatically generated by barrelsby.
3
- */
4
-
5
- export * from "./JobMethods";
6
- export * from "./JobStore";