CartoDB-SQL-API/batch/batch.js

76 lines
2.5 KiB
JavaScript
Raw Normal View History

2015-12-09 07:02:08 +08:00
'use strict';
2015-12-23 06:13:33 +08:00
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var JobRunner = require('./job_runner');
var JobQueuePool = require('./job_queue_pool');
var JobQueueConsumer = require('./job_queue_consumer');
var JobSubscriber = require('./job_subscriber');
var UserDatabaseMetadataService = require('./user_database_metadata_service');
2015-12-09 07:02:08 +08:00
function Batch(metadataBackend) {
EventEmitter.call(this);
this.metadataBackend = metadataBackend;
this.jobSubscriber = new JobSubscriber();
this.userDatabaseMetadataService = new UserDatabaseMetadataService(this.metadataBackend);
this.jobRunner = new JobRunner(this.metadataBackend, this.userDatabaseMetadataService);
}
util.inherits(Batch, EventEmitter);
Batch.prototype.start = function () {
var self = this;
2015-12-23 06:13:33 +08:00
var jobRunner = this.jobRunner;
var metadataBackend = this.metadataBackend;
var jobQueuePool = new JobQueuePool();
2015-12-09 07:02:08 +08:00
// subscribe to message exchange broker in order to know what queues are available
this.jobSubscriber.subscribe(function onMessage(channel, host) {
2015-12-23 06:13:33 +08:00
var jobQueueConsumer = jobQueuePool.get(host);
// if queue consumer is not registered yet
if (!jobQueueConsumer) {
// creates new one
2015-12-23 06:13:33 +08:00
jobQueueConsumer = new JobQueueConsumer(metadataBackend, host);
// register it in batch service
2015-12-23 06:13:33 +08:00
jobQueuePool.add(host, jobQueueConsumer);
// while read from queue then perform job
jobQueueConsumer.on('data', function (job_id) {
// limit one job at the same time per queue (queue <1:1> db intance)
jobQueueConsumer.pause();
var job = jobRunner.run(job_id);
job.on('done', function () {
// next job
self.emit('job:done', job_id);
jobQueueConsumer.resume();
});
job.on('error', function (err) {
console.error(err.stack || err);
self.emit('job:failed', job_id);
jobQueueConsumer.resume();
});
})
.on('error', function (err) {
console.error(err.stack || err);
2015-12-23 06:13:33 +08:00
jobQueuePool.remove(host);
})
.on('end', function () {
2015-12-23 06:13:33 +08:00
jobQueuePool.remove(host);
});
}
});
};
Batch.prototype.stop = function () {
this.jobSubscriber.unsubscribe();
2015-12-09 07:02:08 +08:00
};
module.exports = Batch;