umami/lib/db/kafka.js

76 lines
1.6 KiB
JavaScript
Raw Normal View History

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';
export function getKafkaClient() {
if (!process.env.KAFKA_URL) {
return null;
}
const url = new URL(process.env.KAFKA_URL);
const brokers = process.env.KAFKA_BROKER.split(',');
if (url.username.length === 0 && url.password.length === 0) {
return new Kafka({
clientId: 'umami',
brokers: brokers,
2022-08-18 20:07:30 +02:00
connectionTimeout: 3000,
2022-08-25 20:07:47 +02:00
logLevel: logLevel.ERROR,
2022-08-12 18:21:43 +02:00
});
} else {
return new Kafka({
clientId: 'umami',
brokers: brokers,
2022-08-18 20:07:30 +02:00
connectionTimeout: 3000,
2022-08-12 18:21:43 +02:00
ssl: true,
sasl: {
mechanism: 'plain',
username: url.username,
password: url.password,
},
});
}
}
const kafka = global.kafka || getKafkaClient();
2022-08-25 20:07:47 +02:00
let kafkaProducer = null;
2022-08-12 18:21:43 +02:00
2022-08-25 20:07:47 +02:00
(async () => {
kafkaProducer = global.kakfaProducer || (await getKafkaProducer());
if (process.env.NODE_ENV !== 'production') {
global.kafka = kafka;
global.kakfaProducer = kafkaProducer;
}
})();
2022-08-12 18:21:43 +02:00
2022-08-25 20:07:47 +02:00
export { kafka, kafkaProducer };
2022-08-12 18:21:43 +02:00
2022-08-25 20:07:47 +02:00
export async function getKafkaProducer() {
2022-08-12 18:21:43 +02:00
const producer = kafka.producer();
await producer.connect();
2022-08-25 20:07:47 +02:00
return producer;
}
export async function sendKafkaMessage(params, topic) {
await kafkaProducer.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
});
}
export function getDateFormatKafka(date) {
return dateFormat(date, 'UTC:yyyy-mm-dd HH:MM:ss');
}
export function getKafkaService() {
const type = process.env.KAFKA_URL && process.env.KAFKA_URL.split(':')[0];
return type;
}