/
queue-scheduler.ts
169 lines (147 loc) · 4.71 KB
/
queue-scheduler.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
import { QueueSchedulerOptions } from '../interfaces';
import { array2obj } from '../utils';
import { QueueBase } from './';
import { Scripts } from './scripts';
import IORedis = require('ioredis');
const MAX_TIMEOUT_MS = Math.pow(2, 31) - 1; // 32 bit signed
/**
* This class is just used for some automatic bookkeeping of the queue,
* such as updating the delay set as well as moving stalled jobs back
* to the waiting list.
*
* Jobs are checked for stallness once every "visibility window" seconds.
* Jobs are then marked as candidates for being stalled, in the next check,
* the candidates are marked as stalled and moved to wait.
* Workers need to clean the candidate list with the jobs that they are working
* on, failing to update the list results in the job ending being stalled.
*
* This class requires a dedicated redis connection, and at least one is needed
* to be running at a given time, otherwise delays, stalled jobs, retries, repeatable
* jobs, etc, will not work correctly or at all.
*
*/
export class QueueScheduler extends QueueBase {
private nextTimestamp = Number.MAX_VALUE;
private isBlocked = false;
constructor(protected name: string, opts: QueueSchedulerOptions = {}) {
super(name, { maxStalledCount: 1, stalledInterval: 30000, ...opts });
this.run().catch(this.emit.bind(this));
}
private async run() {
const client = await this.waitUntilReady();
const key = this.keys.delay;
const opts = this.opts as QueueSchedulerOptions;
const delaySet = await this.updateDelaySet(Date.now());
const [nextTimestamp] = delaySet;
let streamLastId = delaySet[1] || '0-0';
if (nextTimestamp) {
this.nextTimestamp = nextTimestamp;
}
while (!this.closing) {
// Check if at least the min stalled check time has passed.
await this.moveStalledJobsToWait();
// Listen to the delay event stream from lastDelayStreamTimestamp
// Can we use XGROUPS to reduce redundancy?
const nextDelay = this.nextTimestamp - Date.now();
const blockTime = Math.round(
Math.min(opts.stalledInterval, Math.max(nextDelay, 0)),
);
const data = await this.readDelayedData(
client,
key,
streamLastId,
blockTime,
);
if (data && data[0]) {
const stream = data[0];
const events = stream[1];
for (let i = 0; i < events.length; i++) {
streamLastId = events[i][0];
const args = array2obj(events[i][1]);
const nextTimestamp: number = parseInt(args.nextTimestamp);
if (nextTimestamp < this.nextTimestamp) {
this.nextTimestamp = nextTimestamp;
}
}
//
// We trim to a length of 100, which should be a very safe value
// for all kind of scenarios.
//
if (!this.closing) {
await client.xtrim(key, 'MAXLEN', '~', 100);
}
}
const now = Date.now();
const delay = this.nextTimestamp - now;
if (delay <= 0) {
const [nextTimestamp, id] = await this.updateDelaySet(now);
if (nextTimestamp) {
this.nextTimestamp = nextTimestamp / 4096;
streamLastId = id;
} else {
this.nextTimestamp = Number.MAX_VALUE;
}
}
}
}
private async readDelayedData(
client: IORedis.Redis,
key: string,
streamLastId: string,
blockTime: number,
) {
if (!this.closing) {
let data;
if (blockTime) {
try {
this.isBlocked = true;
data = await client.xread(
'BLOCK',
blockTime,
'STREAMS',
key,
streamLastId,
);
} catch (err) {
// We can ignore closed connection errors
if (err.message !== 'Connection is closed.') {
throw err;
}
} finally {
this.isBlocked = false;
}
} else {
data = await client.xread('STREAMS', key, streamLastId);
}
return data;
}
}
private async updateDelaySet(timestamp: number) {
if (!this.closing) {
return Scripts.updateDelaySet(this, timestamp);
}
return [0, 0];
}
private async moveStalledJobsToWait() {
if (!this.closing) {
const [failed, stalled] = await Scripts.moveStalledJobsToWait(this);
failed.forEach((jobId: string) =>
this.emit(
'failed',
jobId,
new Error('job stalled more than allowable limit'),
'active',
),
);
stalled.forEach((jobId: string) => this.emit('stalled', jobId, 'active'));
}
}
async close() {
if (this.isBlocked) {
this.closing = this.disconnect();
} else {
await super.close();
}
return this.closing;
}
}