-
Notifications
You must be signed in to change notification settings - Fork 19
/
polling.js
89 lines (72 loc) · 2.01 KB
/
polling.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
'use strict';
const Thing = require('./thing');
const { duration } = require('./values');
const pollDuration = Symbol('pollDuration');
const pollTimer = Symbol('pollTimer');
const maxPollFailures = Symbol('maxpollFailures');
const pollFailures = Symbol('pollFailures');
module.exports = Thing.mixin(Parent => class extends Parent {
constructor(...args) {
super(...args);
this[pollDuration] = 30000;
this.internalPoll = this.internalPoll.bind(this);
this[maxPollFailures] = -1;
this[pollFailures] = 0;
}
updatePollDuration(time) {
time = this[pollDuration] = duration(time).ms;
if(this[pollTimer]) {
clearTimeout(this[pollTimer]);
this[pollTimer] = setTimeout(this.internalPoll, time);
}
}
updateMaxPollFailures(failures) {
this[maxPollFailures] = failures;
}
initCallback() {
return super.initCallback()
.then(() => {
// During initalization a single poll is performed
return this.internalPoll(true);
});
}
destroyCallback() {
return super.destroyCallback()
.then(() => clearTimeout(this[pollTimer]));
}
internalPoll(isInitial=false) {
const time = Date.now();
// Perform poll async - and schedule new poll after it has resolved
return Promise.resolve(this.poll(isInitial))
.catch(ex => {
this.debug('Could not poll:', ex);
return new Error('Polling issue');
})
.then(r => {
// Check if failure
if(r instanceof Error) {
this[pollFailures]++;
if(this[maxPollFailures] > 0 && this[maxPollFailures] <= this[pollFailures]) {
/*
* The maximum number of failures in a row have been
* reached. Destroy this thing.
*/
this.destroy();
}
} else {
this[pollFailures] = 0;
}
// Schedule the next poll
const diff = Date.now() - time;
const d = this[pollDuration];
let nextTime = d - diff;
while(nextTime < 0) {
nextTime += d;
}
this[pollTimer] = setTimeout(this.internalPoll, nextTime);
});
}
poll(isInitial) {
throw new Error('Poll has not been implemented');
}
});