-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
87 lines (73 loc) · 2.17 KB
/
app.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
/**
* application entry point
*/
global.Promise = require('bluebird')
const config = require('config')
const healthcheck = require('topcoder-healthcheck-dropin')
const Kafka = require('no-kafka')
const helper = require('./src/common/helper')
const logger = require('./src/common/logger')
const KafkaHandlerService = require('./src/services/KafkaHandlerService')
// start Kafka consumer
logger.info('=== start kafka consumer ===')
const kafka_options = helper.getKafkaOptions()
const consumer = new Kafka.GroupConsumer(kafka_options)
// data handler
const dataHandler = (messageSet, topic, partition) =>
Promise.each(messageSet, (m) => {
const message = m.message.value.toString('utf8')
logger.info(
`Handle kafka event message; Topic: ${topic}; Partition: ${partition}; Offset: ${m.offset}; Message: ${message}.`
)
let messageJSON
try {
messageJSON = JSON.parse(message)
} catch (error) {
logger.error('Invalid message JSON.')
logger.error(error)
return
}
logger.debug(JSON.stringify(messageJSON))
return KafkaHandlerService.handle(messageJSON)
.then(() => { })
.catch((err) => {
logger.error('logging full error')
logger.logFullError(err)
})
.finally(() => {
logger.info('committing offset')
consumer.commitOffset({ topic, partition, offset: m.offset })
})
})
// check if there is kafka connection alive
function check() {
if (
!consumer.client.initialBrokers &&
!consumer.client.initialBrokers.length
) {
return false
}
let connected = true
consumer.client.initialBrokers.forEach((conn) => {
logger.debug(`url ${conn.server()} - connected=${conn.connected}`)
connected = conn.connected & connected
})
return connected
}
consumer
.init([
{
subscriptions: [config.KAFKA_AUTOPILOT_NOTIFICATIONS_TOPIC, config.KAFKA_RATING_SERVICE_TOPIC],
handler: dataHandler
}
])
// consume configured topics
.then(() => {
logger.info('initilized.....')
healthcheck.init([check])
logger.debug('consumer initialized successfully')
})
.catch(logger.logFullError)
module.exports = {
kafkaConsumer: consumer
}