-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworker.js
127 lines (96 loc) · 2.86 KB
/
worker.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
var EventEmitter = require('events').EventEmitter;
var Worker = module.exports = function (id, queue, limit, fn) {
EventEmitter.call(this);
this.id = id;
this.queue = queue;
this.limit = limit;
this.interval = null;
this.last_ping = 0;
this.fn = fn;
this.paused = false;
this.workingInstances = 0;
queue.on('change', this._onChange.bind(this));
};
Worker.prototype = Object.create(EventEmitter.prototype);
Worker.prototype._onChange = function () {
this.last_ping = new Date().getTime();
this.wakeUp();
};
Worker.prototype.wakeUp = function () {
if (!this.interval && !this.paused) {
this.interval = setInterval(this._run.bind(this), 300 + Math.random() * 100 - 50);
this.emit('wakeup');
}
return this;
};
Worker.prototype.goToSleep = function () {
clearInterval(this.interval);
this.interval = null;
this.emit('sleep');
};
Worker.prototype.pause = function () {
this.paused = true;
};
Worker.prototype.resume = function () {
this.paused = false;
};
Worker.prototype._threadEnter = function () {
this.workingInstances++;
this.emit('load', this.workingInstances, this.limit);
};
Worker.prototype._threadExit = function () {
this.workingInstances--;
this.emit('load', this.workingInstances, this.limit);
};
Worker.prototype._run = function () {
var self = this;
if (self.workingInstances < self.limit && !self.paused) {
self._threadEnter();
self.queue.getInactiveJobs(function (err, docs) {
if (err) {
console.log(err);
return self._threadExit();
}
if (docs.length === 0) {
if (self.last_ping < Date.now() - 5000) {
self.goToSleep();
}
return self._threadExit();
}
var _loop = function () {
if (self.paused) {
return self._threadExit();
}
var doc = docs.shift();
if (!doc) {
return self._threadExit();
}
self.queue.tryJob(self.id, doc, function (err, res) {
if (err) {
return _loop();
}
self.fn(res.id, function (err) {
if (!self.queue.jobExists(res.id)) {
throw new Error('Callback called for unknown job. The callback should not be called more than once.');
}
if (err) {
return self.queue.setJobState(res.id, 'failed', function (err) {
if (err) return self._threadExit();
self.queue.finishJob(res.id, function (err) {
return self._threadExit();
});
});
}
self.queue.setJobState(res.id, 'complete', function (err) {
if (err) return self._threadExit();
self.queue.finishJob(res.id, function (err) {
return self._threadExit();
});
});
});
});
};
_loop();
});
}
};