import { Kafka, Producer, RecordMetadata } from 'kafkajs'; import { Observable, catchError, from, mergeMap, of } from 'rxjs'; export class LoggerClient { private kafka: Kafka; private kafkaTopic: string; private producer: Producer; private connected = false; private connecting: Promise | null = null; constructor( kafkaBrokers: string[], kafkaClientId: string, kafkaLogTopic: string, ) { this.kafkaTopic = kafkaLogTopic; this.kafka = new Kafka({ brokers: kafkaBrokers, clientId: kafkaClientId }); this.producer = this.kafka.producer(); } private async ensureConnected(): Promise { if (this.connected) return; if (this.connecting) return this.connecting; this.connecting = this.producer .connect() .then(() => { this.connected = true; }) .finally(() => { this.connecting = null; }); return this.connecting; } sendLog(log: any, key?: string): Observable { const messageString = JSON.stringify(log); return from(this.ensureConnected()).pipe( mergeMap(() => from( this.producer.send({ topic: this.kafkaTopic, messages: [{ key, value: messageString }], }), ), ), catchError((err) => { this.connected = false; return of(err); }), ); } async disconnect(): Promise { if (this.connected) { await this.producer.disconnect(); this.connected = false; } } }