/
framework.ts
202 lines (179 loc) 路 5.34 KB
/
framework.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
import {
BaseFramework,
extend,
IMidwayBootstrapOptions,
Framework,
getClassMetadata,
listModule,
Utils,
MidwayInvokeForbiddenError,
ILogger,
Logger,
} from '@midwayjs/core';
import {
Application,
Context,
IProcessor,
IQueue,
IQueueManager,
} from './interface';
import { Job, JobOptions, QueueOptions } from 'bull';
import Bull = require('bull');
import { BULL_PROCESSOR_KEY } from './constants';
export class BullQueue extends Bull implements IQueue<Job> {
constructor(queueName: string, queueOptions: QueueOptions) {
super(queueName, queueOptions);
}
public async runJob(data: any, options?: JobOptions): Promise<Job> {
return this.add(data || {}, options) as unknown as Job;
}
public getQueueName(): string {
return this.name;
}
}
@Framework()
export class BullFramework
extends BaseFramework<Application, Context, any>
implements IQueueManager<BullQueue, Job>
{
private bullDefaultQueueConfig: Bull.QueueOptions;
private bullDefaultConcurrency: number;
private bullClearRepeatJobWhenStart: boolean;
private queueMap: Map<string, BullQueue> = new Map();
@Logger('bullLogger')
protected bullLogger: ILogger;
async applicationInitialize(options: IMidwayBootstrapOptions) {
this.app = {} as any;
}
public loadConfig() {
this.bullDefaultQueueConfig = this.configService.getConfiguration(
'bull.defaultQueueOptions'
);
this.bullDefaultConcurrency = this.configService.getConfiguration(
'bull.defaultConcurrency'
);
this.bullClearRepeatJobWhenStart = this.configService.getConfiguration(
'bull.clearRepeatJobWhenStart'
);
}
configure() {
return this.configService.getConfiguration('bull');
}
getFrameworkName(): string {
return 'bull';
}
async run() {
const processorModules = listModule(BULL_PROCESSOR_KEY);
for (const mod of processorModules) {
const options = getClassMetadata(BULL_PROCESSOR_KEY, mod) as {
queueName: string;
concurrency: number;
jobOptions?: JobOptions;
queueOptions?: QueueOptions;
};
const { repeat, delay, ...otherOptions } = options.jobOptions ?? {};
const queueOptions = options.queueOptions ?? {};
const currentQueue = this.ensureQueue(options.queueName, {
...queueOptions,
defaultJobOptions: otherOptions,
});
// clear old repeat job when start
if (this.bullClearRepeatJobWhenStart) {
const jobs = await currentQueue.getRepeatableJobs();
for (const job of jobs) {
await currentQueue.removeRepeatableByKey(job.key);
}
}
await this.addProcessor(mod, options.queueName, options.concurrency);
if (options.jobOptions?.repeat) {
await this.runJob(options.queueName, {}, options.jobOptions);
}
}
}
protected async beforeStop() {
// loop queueMap and stop all queue
for (const queue of this.queueMap.values()) {
await queue.close();
}
}
public createQueue(name: string, queueOptions: QueueOptions = {}) {
const queue = new BullQueue(
name,
extend(true, {}, this.bullDefaultQueueConfig, queueOptions)
);
this.queueMap.set(name, queue);
queue.on('error', err => {
this.bullLogger.error(err);
});
return queue;
}
public getQueue(name: string) {
return this.queueMap.get(name);
}
public ensureQueue(name: string, queueOptions: QueueOptions = {}) {
if (!this.queueMap.has(name)) {
this.createQueue(name, queueOptions);
}
return this.queueMap.get(name);
}
public getQueueList() {
return Array.from(this.queueMap.values());
}
public async addProcessor(
processor: new (...args) => IProcessor,
queueName: string | BullQueue,
concurrency?: number
) {
const queue =
typeof queueName === 'string' ? this.queueMap.get(queueName) : queueName;
queue.process(concurrency ?? this.bullDefaultConcurrency, async job => {
const ctx = this.app.createAnonymousContext({
jobId: job.id,
job,
from: processor,
});
try {
ctx.logger.info(`start process job ${job.id} from ${processor.name}`);
const isPassed = await this.app
.getFramework()
.runGuard(ctx, processor, 'execute');
if (!isPassed) {
throw new MidwayInvokeForbiddenError('execute', processor);
}
const service = await ctx.requestContext.getAsync<IProcessor>(
processor as any
);
const fn = await this.applyMiddleware(async ctx => {
return await Utils.toAsyncFunction(service.execute.bind(service))(
job.data,
job
);
});
const result = await Promise.resolve(await fn(ctx));
ctx.logger.info(
`complete process job ${job.id} from ${processor.name}`
);
return result;
} catch (err) {
ctx.logger.error(err);
return Promise.reject(err);
}
});
}
public async runJob(
queueName: string,
jobData: any,
options?: JobOptions
): Promise<Job | undefined> {
const queue = this.queueMap.get(queueName);
if (queue) {
return await queue.runJob(jobData, options);
}
}
public async getJob(queueName: string, jobName: string): Promise<Job> {
const queue = this.queueMap.get(queueName);
if (queue) {
return queue.getJob(jobName);
}
}
}