forked from fwang7/node-red-contrib-kafka-node
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathkafka-batch-runner.js
54 lines (49 loc) · 1.49 KB
/
kafka-batch-runner.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
const async = require('async');
const kafka = require('kafka-node');
const LinkedList = require('./linked-list');
const ConsumerGroup = kafka.ConsumerGroup;
function KafkaBatchRunner(node, options, topics, config) {
function debug(...rest) {
if (config.debug) {
console.log(rest);
}
}
const messageBuffer = new LinkedList();
const consumerGroup = new ConsumerGroup(options, topics);
function run(callback) {
// Emit each message in the message buffer.
async.timesSeries(messageBuffer.length, (n, next) => {
node.send({
payload: messageBuffer.pop(),
cb: next,
});
}, doneProcessing);
function doneProcessing(err) {
if (err) {
debug('An error has occured while processing a message. Quitting. Error = ', err);
process.exit(1);
}
callback();
}
}
consumerGroup.on('message', (msg) => {
debug('Received message. Adding it to the buffer -', msg);
messageBuffer.add(msg);
});
consumerGroup.on('done', () => {
debug('Done one fetch request. Pausing the stream.');
consumerGroup.pause();
run(() => {
debug('Done processing one batch. Commiting now.');
consumerGroup.commit(true, (err) => {
if (err) {
debug('Error occured while commiting a batch. Quitting. Error =', err);
process.exit(1);
}
debug('Done processing records. Resuming the stream');
consumerGroup.resume();
});
});
});
}
module.exports = KafkaBatchRunner;