-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathpolling-job-queue-strategy.ts
272 lines (247 loc) · 10.1 KB
/
polling-job-queue-strategy.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
import { JobState } from '@vendure/common/lib/generated-types';
import { ID } from '@vendure/common/lib/shared-types';
import { isObject } from '@vendure/common/lib/shared-utils';
import { from, interval, race, Subject, Subscription } from 'rxjs';
import { filter, switchMap, take, throttleTime } from 'rxjs/operators';
import { Logger } from '../config/logger/vendure-logger';
import { InjectableJobQueueStrategy } from './injectable-job-queue-strategy';
import { Job } from './job';
import { QueueNameProcessStorage } from './queue-name-process-storage';
import { JobData } from './types';
/**
* @description
* Defines the backoff strategy used when retrying failed jobs. Returns the delay in
* ms that should pass before the failed job is retried.
*
* @docsCategory JobQueue
* @docsPage types
*/
export type BackoffStrategy = (queueName: string, attemptsMade: number, job: Job) => number;
export interface PollingJobQueueStrategyConfig {
/**
* @description
* How many jobs from a given queue to process concurrently.
*
* @default 1
*/
concurrency?: number;
/**
* @description
* The interval in ms between polling the database for new jobs.
*
* @description 200
*/
pollInterval?: number | ((queueName: string) => number);
/**
* @description
* When a job is added to the JobQueue using `JobQueue.add()`, the calling
* code may specify the number of retries in case of failure. This option allows
* you to override that number and specify your own number of retries based on
* the job being added.
*/
setRetries?: (queueName: string, job: Job) => number;
/**
* @description
* The strategy used to decide how long to wait before retrying a failed job.
*
* @default () => 1000
*/
backoffStrategy?: BackoffStrategy;
}
const STOP_SIGNAL = Symbol('STOP_SIGNAL');
class ActiveQueue<Data extends JobData<Data> = object> {
private timer: any;
private running = false;
private activeJobs: Array<Job<Data>> = [];
private errorNotifier$ = new Subject<[string, string]>();
private queueStopped$ = new Subject<typeof STOP_SIGNAL>();
private subscription: Subscription;
private readonly pollInterval: number;
constructor(
private readonly queueName: string,
private readonly process: (job: Job<Data>) => Promise<any>,
private readonly jobQueueStrategy: PollingJobQueueStrategy,
) {
this.subscription = this.errorNotifier$.pipe(throttleTime(3000)).subscribe(([message, stack]) => {
Logger.error(message);
Logger.debug(stack);
});
this.pollInterval =
typeof this.jobQueueStrategy.pollInterval === 'function'
? this.jobQueueStrategy.pollInterval(queueName)
: this.jobQueueStrategy.pollInterval;
}
start() {
Logger.debug(`Starting JobQueue "${this.queueName}"`);
this.running = true;
const runNextJobs = async () => {
try {
const runningJobsCount = this.activeJobs.length;
for (let i = runningJobsCount; i < this.jobQueueStrategy.concurrency; i++) {
const nextJob = await this.jobQueueStrategy.next(this.queueName);
if (nextJob) {
this.activeJobs.push(nextJob);
await this.jobQueueStrategy.update(nextJob);
const onProgress = (job: Job) => this.jobQueueStrategy.update(job);
nextJob.on('progress', onProgress);
const cancellationSignal$ = interval(this.pollInterval * 5).pipe(
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
switchMap(() => this.jobQueueStrategy.findOne(nextJob.id!)),
filter(job => job?.state === JobState.CANCELLED),
take(1),
);
const stopSignal$ = this.queueStopped$.pipe(take(1));
race(from(this.process(nextJob)), cancellationSignal$, stopSignal$)
.toPromise()
.then(
result => {
if (result === STOP_SIGNAL) {
nextJob.defer();
} else if (result instanceof Job && result.state === JobState.CANCELLED) {
nextJob.cancel();
} else {
nextJob.complete(result);
}
},
err => {
nextJob.fail(err);
},
)
.finally(() => {
if (!this.running && nextJob.state !== JobState.PENDING) {
return;
}
nextJob.off('progress', onProgress);
return this.onFailOrComplete(nextJob);
})
.catch((err: any) => {
Logger.warn(`Error updating job info: ${JSON.stringify(err)}`);
});
}
}
} catch (e: any) {
this.errorNotifier$.next([
`Job queue "${
this.queueName
}" encountered an error (set log level to Debug for trace): ${JSON.stringify(e.message)}`,
e.stack,
]);
}
if (this.running) {
this.timer = setTimeout(runNextJobs, this.pollInterval);
}
};
void runNextJobs();
}
stop(): Promise<void> {
this.running = false;
this.queueStopped$.next(STOP_SIGNAL);
clearTimeout(this.timer);
const start = +new Date();
// Wait for 2 seconds to allow running jobs to complete
const maxTimeout = 2000;
let pollTimer: any;
return new Promise(resolve => {
const pollActiveJobs = async () => {
const timedOut = +new Date() - start > maxTimeout;
if (this.activeJobs.length === 0 || timedOut) {
clearTimeout(pollTimer);
resolve();
} else {
pollTimer = setTimeout(pollActiveJobs, 50);
}
};
void pollActiveJobs();
});
}
private async onFailOrComplete(job: Job<Data>) {
await this.jobQueueStrategy.update(job);
this.removeJobFromActive(job);
}
private removeJobFromActive(job: Job<Data>) {
const index = this.activeJobs.indexOf(job);
this.activeJobs.splice(index, 1);
}
}
/**
* @description
* This class allows easier implementation of {@link JobQueueStrategy} in a polling style.
* Instead of providing {@link JobQueueStrategy} `start()` you should provide a `next` method.
*
* This class should be extended by any strategy which does not support a push-based system
* to notify on new jobs. It is used by the {@link SqlJobQueueStrategy} and {@link InMemoryJobQueueStrategy}.
*
* @docsCategory JobQueue
*/
export abstract class PollingJobQueueStrategy extends InjectableJobQueueStrategy {
public concurrency: number;
public pollInterval: number | ((queueName: string) => number);
public setRetries: (queueName: string, job: Job) => number;
public backOffStrategy?: BackoffStrategy;
private activeQueues = new QueueNameProcessStorage<ActiveQueue<any>>();
constructor(config?: PollingJobQueueStrategyConfig);
constructor(concurrency?: number, pollInterval?: number);
constructor(concurrencyOrConfig?: number | PollingJobQueueStrategyConfig, maybePollInterval?: number) {
super();
if (concurrencyOrConfig && isObject(concurrencyOrConfig)) {
this.concurrency = concurrencyOrConfig.concurrency ?? 1;
this.pollInterval = concurrencyOrConfig.pollInterval ?? 200;
this.backOffStrategy = concurrencyOrConfig.backoffStrategy ?? (() => 1000);
this.setRetries = concurrencyOrConfig.setRetries ?? ((_, job) => job.retries);
} else {
this.concurrency = concurrencyOrConfig ?? 1;
this.pollInterval = maybePollInterval ?? 200;
this.setRetries = (_, job) => job.retries;
}
}
async start<Data extends JobData<Data> = object>(
queueName: string,
process: (job: Job<Data>) => Promise<any>,
) {
if (!this.hasInitialized) {
this.started.set(queueName, process);
return;
}
if (this.activeQueues.has(queueName, process)) {
return;
}
const active = new ActiveQueue<Data>(queueName, process, this);
active.start();
this.activeQueues.set(queueName, process, active);
}
async stop<Data extends JobData<Data> = object>(
queueName: string,
process: (job: Job<Data>) => Promise<any>,
) {
const active = this.activeQueues.getAndDelete(queueName, process);
if (!active) {
return;
}
await active.stop();
}
async cancelJob(jobId: ID): Promise<Job | undefined> {
const job = await this.findOne(jobId);
if (job) {
job.cancel();
await this.update(job);
return job;
}
}
/**
* @description
* Should return the next job in the given queue. The implementation is
* responsible for returning the correct job according to the time of
* creation.
*/
abstract next(queueName: string): Promise<Job | undefined>;
/**
* @description
* Update the job details in the store.
*/
abstract update(job: Job): Promise<void>;
/**
* @description
* Returns a job by its id.
*/
abstract findOne(id: ID): Promise<Job | undefined>;
}