2022-08-25 20:07:47 +02:00
|
|
|
import { Kafka, logLevel } from 'kafkajs';
|
2022-08-12 18:21:43 +02:00
|
|
|
import dateFormat from 'dateformat';
|
2022-08-28 06:38:35 +02:00
|
|
|
import debug from 'debug';
|
|
|
|
import { KAFKA, KAFKA_PRODUCER } from 'lib/db';
|
2022-08-12 18:21:43 +02:00
|
|
|
|
2022-08-28 06:38:35 +02:00
|
|
|
const log = debug('kafka');
|
|
|
|
|
|
|
|
function getClient() {
|
|
|
|
if (!process.env.KAFKA_URL || !process.env.KAFKA_BROKER) {
|
2022-08-12 18:21:43 +02:00
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
2022-08-28 06:38:35 +02:00
|
|
|
const { username, password } = new URL(process.env.KAFKA_URL);
|
2022-08-12 18:21:43 +02:00
|
|
|
const brokers = process.env.KAFKA_BROKER.split(',');
|
|
|
|
|
2022-08-28 06:38:35 +02:00
|
|
|
const ssl =
|
|
|
|
username && password
|
|
|
|
? {
|
|
|
|
ssl: true,
|
|
|
|
sasl: {
|
|
|
|
mechanism: 'plain',
|
|
|
|
username,
|
|
|
|
password,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
: {};
|
2022-08-12 18:21:43 +02:00
|
|
|
|
2022-08-28 06:38:35 +02:00
|
|
|
const client = new Kafka({
|
|
|
|
clientId: 'umami',
|
|
|
|
brokers: brokers,
|
|
|
|
connectionTimeout: 3000,
|
|
|
|
logLevel: logLevel.ERROR,
|
|
|
|
...ssl,
|
|
|
|
});
|
2022-08-25 20:07:47 +02:00
|
|
|
|
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
2022-08-28 06:38:35 +02:00
|
|
|
global[KAFKA] = client;
|
2022-08-25 20:07:47 +02:00
|
|
|
}
|
2022-08-12 18:21:43 +02:00
|
|
|
|
2022-08-28 06:38:35 +02:00
|
|
|
return client;
|
|
|
|
}
|
2022-08-12 18:21:43 +02:00
|
|
|
|
2022-08-26 07:43:22 +02:00
|
|
|
async function getProducer() {
|
2022-08-12 18:21:43 +02:00
|
|
|
const producer = kafka.producer();
|
|
|
|
await producer.connect();
|
|
|
|
|
2022-08-28 06:38:35 +02:00
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
|
|
global[KAFKA_PRODUCER] = producer;
|
|
|
|
}
|
|
|
|
|
2022-08-25 20:07:47 +02:00
|
|
|
return producer;
|
|
|
|
}
|
|
|
|
|
2022-08-26 07:43:22 +02:00
|
|
|
function getDateFormat(date) {
|
2022-08-26 07:04:32 +02:00
|
|
|
return dateFormat(date, 'UTC:yyyy-mm-dd HH:MM:ss');
|
|
|
|
}
|
|
|
|
|
2022-08-26 07:43:22 +02:00
|
|
|
async function sendMessage(params, topic) {
|
2022-08-28 06:38:35 +02:00
|
|
|
await producer.send({
|
2022-08-12 18:21:43 +02:00
|
|
|
topic,
|
|
|
|
messages: [
|
|
|
|
{
|
|
|
|
key: 'key',
|
|
|
|
value: JSON.stringify(params),
|
|
|
|
},
|
|
|
|
],
|
2022-08-25 20:07:47 +02:00
|
|
|
acks: 0,
|
2022-08-12 18:21:43 +02:00
|
|
|
});
|
|
|
|
}
|
2022-08-26 07:43:22 +02:00
|
|
|
|
2022-08-28 06:38:35 +02:00
|
|
|
// Initialization
|
|
|
|
let kafka;
|
|
|
|
let producer;
|
|
|
|
|
|
|
|
(async () => {
|
|
|
|
kafka = global[KAFKA] || getClient();
|
|
|
|
producer = global[KAFKA_PRODUCER] || (await getProducer());
|
|
|
|
})();
|
|
|
|
|
2022-08-26 07:43:22 +02:00
|
|
|
export default {
|
2022-08-28 06:38:35 +02:00
|
|
|
client: kafka,
|
|
|
|
producer: producer,
|
|
|
|
log,
|
2022-08-26 07:43:22 +02:00
|
|
|
getDateFormat,
|
|
|
|
sendMessage,
|
|
|
|
};
|