-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy path2-timeouts.js
128 lines (111 loc) · 2.78 KB
/
2-timeouts.js
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
'use strict';
class Queue {
constructor(concurrency) {
this.concurrency = concurrency;
this.count = 0;
this.waiting = [];
this.onProcess = null;
this.onDone = null;
this.onSuccess = null;
this.onFailure = null;
this.onDrain = null;
this.waitTimeout = Infinity;
this.processTimeout = Infinity;
}
static channels(concurrency) {
return new Queue(concurrency);
}
wait(msec) {
this.waitTimeout = msec;
return this;
}
timeout(msec) {
this.processTimeout = msec;
return this;
}
add(task) {
const hasChannel = this.count < this.concurrency;
if (hasChannel) return void this.next(task);
this.waiting.push({ task, start: Date.now() });
}
next(task) {
this.count++;
let timer = null;
let finished = false;
const { processTimeout, onProcess } = this;
const finish = (error, res) => {
if (finished) return;
finished = true;
if (timer) clearTimeout(timer);
this.count--;
this.finish(error, res);
if (this.waiting.length > 0) this.takeNext();
};
if (processTimeout !== Infinity) {
timer = setTimeout(() => {
timer = null;
const error = new Error('Process timed out');
finish(error, task);
}, processTimeout);
}
onProcess(task, finish);
}
takeNext() {
const { waiting, waitTimeout } = this;
const { task, start } = waiting.shift();
if (waitTimeout !== Infinity) {
const delay = Date.now() - start;
if (delay > waitTimeout) {
const error = new Error('Waiting timed out');
this.finish(error, task);
if (waiting.length > 0) this.takeNext();
return;
}
}
this.next(task);
}
finish(error, res) {
const { onFailure, onSuccess, onDone, onDrain } = this;
if (error) {
if (onFailure) onFailure(error, res);
} else if (onSuccess) {
onSuccess(res);
}
if (onDone) onDone(error, res);
if (this.count === 0 && onDrain) onDrain();
}
process(listener) {
this.onProcess = listener;
return this;
}
done(listener) {
this.onDone = listener;
return this;
}
success(listener) {
this.onSuccess = listener;
return this;
}
failure(listener) {
this.onFailure = listener;
return this;
}
drain(listener) {
this.onDrain = listener;
return this;
}
}
// Usage
const job = (task, next) => {
setTimeout(next, task.interval, null, task);
};
const queue = Queue.channels(3)
.wait(4000)
.timeout(5000)
.process(job)
.success((task) => void console.log(`Success: ${task.name}`))
.failure((error, task) => void console.log(`Failure: ${error} ${task.name}`))
.drain(() => void console.log('Queue drain'));
for (let i = 0; i < 10; i++) {
queue.add({ name: `Task${i}`, interval: i * 1000 });
}