2015-12-16 22:57:58 +08:00
|
|
|
'use strict';
|
|
|
|
|
2016-07-07 20:14:46 +08:00
|
|
|
var debug = require('./util/debug')('pubsub:subscriber');
|
|
|
|
var error = require('./util/debug')('pubsub:subscriber:error');
|
2016-07-07 16:44:17 +08:00
|
|
|
|
2016-07-07 20:14:46 +08:00
|
|
|
var DB = 0;
|
|
|
|
var SUBSCRIBE_INTERVAL_IN_MILLISECONDS = 10 * 60 * 1000; // 10 minutes
|
2016-04-05 02:00:18 +08:00
|
|
|
|
2016-07-22 19:47:14 +08:00
|
|
|
function _subscribe(client, channel, queueSeeker, onMessage, callback) {
|
|
|
|
|
|
|
|
client.removeAllListeners('message');
|
|
|
|
client.unsubscribe(channel);
|
|
|
|
client.subscribe(channel);
|
|
|
|
|
|
|
|
client.on('message', function (channel, host) {
|
|
|
|
debug('message received from: ' + channel + ':' + host);
|
|
|
|
onMessage(channel, host);
|
|
|
|
});
|
2016-07-07 16:44:17 +08:00
|
|
|
|
2016-04-05 02:00:18 +08:00
|
|
|
queueSeeker.seek(onMessage, function (err) {
|
|
|
|
if (err) {
|
2016-07-07 20:14:46 +08:00
|
|
|
error(err);
|
2016-04-05 02:00:18 +08:00
|
|
|
|
2016-07-22 19:47:14 +08:00
|
|
|
if (callback) {
|
|
|
|
callback(err);
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
debug('queues found successfully');
|
2016-07-07 16:44:17 +08:00
|
|
|
|
2016-07-22 19:47:14 +08:00
|
|
|
if (callback) {
|
|
|
|
callback();
|
|
|
|
}
|
|
|
|
}
|
2016-04-05 02:00:18 +08:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2016-07-07 20:14:46 +08:00
|
|
|
function JobSubscriber(pool, queueSeeker) {
|
2015-12-29 22:46:04 +08:00
|
|
|
this.channel = 'batch:hosts';
|
2016-07-07 20:14:46 +08:00
|
|
|
this.pool = pool;
|
2016-04-04 22:05:33 +08:00
|
|
|
this.queueSeeker = queueSeeker;
|
2015-12-16 22:57:58 +08:00
|
|
|
}
|
|
|
|
|
2016-04-05 02:00:18 +08:00
|
|
|
module.exports = JobSubscriber;
|
|
|
|
|
2016-07-22 19:47:14 +08:00
|
|
|
JobSubscriber.prototype.subscribe = function (onMessage, callback) {
|
2016-03-31 23:37:35 +08:00
|
|
|
var self = this;
|
|
|
|
|
2016-07-07 20:14:46 +08:00
|
|
|
this.pool.acquire(DB, function (err, client) {
|
|
|
|
if (err) {
|
|
|
|
return error('Error adquiring redis client: ' + err.message);
|
|
|
|
}
|
|
|
|
|
|
|
|
self.client = client;
|
|
|
|
|
|
|
|
self.seekerInterval = setInterval(
|
|
|
|
_subscribe,
|
|
|
|
SUBSCRIBE_INTERVAL_IN_MILLISECONDS,
|
|
|
|
self.client,
|
|
|
|
self.channel,
|
|
|
|
self.queueSeeker,
|
|
|
|
onMessage
|
|
|
|
);
|
2016-07-22 19:47:14 +08:00
|
|
|
|
|
|
|
_subscribe(self.client, self.channel, self.queueSeeker, onMessage, callback);
|
2016-07-07 20:14:46 +08:00
|
|
|
});
|
2016-03-31 23:37:35 +08:00
|
|
|
|
2015-12-16 22:57:58 +08:00
|
|
|
};
|
|
|
|
|
2015-12-23 03:12:10 +08:00
|
|
|
JobSubscriber.prototype.unsubscribe = function () {
|
2016-04-05 02:00:18 +08:00
|
|
|
clearInterval(this.seekerInterval);
|
2016-07-07 20:14:46 +08:00
|
|
|
if (this.client && this.client.connected) {
|
|
|
|
this.client.unsubscribe(this.channel);
|
|
|
|
}
|
2015-12-23 03:12:10 +08:00
|
|
|
};
|