Skip to content

Commit

Permalink
Update Producer.ts
Browse files Browse the repository at this point in the history
  • Loading branch information
ashish-egov authored Jul 30, 2024
1 parent e86a4dc commit 348888c
Showing 1 changed file with 13 additions and 19 deletions.
32 changes: 13 additions & 19 deletions utilities/project-factory/src/server/kafka/Producer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,39 +12,33 @@ const kafkaClient = new KafkaClient({
// Creating a new Kafka producer instance using the Kafka client
const producer = new Producer(kafkaClient, { partitionerType: 2 }); // Using partitioner type 2

// Function to check broker availability
// Function to send a test message to check broker availability
const checkBrokerAvailability = () => {
kafkaClient.loadMetadataForTopics([], (err, data) => {
const payloads = [
{
topic: config.kafka.KAFKA_TEST_TOPIC,
messages: JSON.stringify({ message: 'Test message to check broker availability' }),
},
];

producer.send(payloads, (err, data) => {
if (err) {
if (err.message && err.message.toLowerCase().includes('broker not available')) {
logger.error('Broker not available. Shutting down the service.');
shutdownGracefully();
} else {
logger.error('Error checking broker availability:', err);
logger.error('Error sending test message:', err);
}
} else {
logger.info('Broker is available:', data);
logger.info('Test message sent successfully:', data);
}
});
};

// Event listener for 'ready' event, indicating that the client is ready to check broker availability
kafkaClient.on('ready', () => {
logger.info('Kafka client is ready'); // Log message indicating client is ready
checkBrokerAvailability(); // Check broker availability
});

// Event listener for 'ready' event, indicating that the producer is ready to send messages
producer.on('ready', () => {
logger.info('Producer is ready'); // Log message indicating producer is ready
checkBrokerAvailability();
});

// Event listener for 'error' event, indicating that the client encountered an error
kafkaClient.on('error', (err) => {
logger.error('Kafka client is in error state'); // Log message indicating client is in error state
console.error(err.stack || err); // Log the error stack or message
shutdownGracefully();
checkBrokerAvailability(); // Check broker availability by sending a test message
});

// Event listener for 'error' event, indicating that the producer encountered an error
Expand All @@ -54,4 +48,4 @@ producer.on('error', (err) => {
shutdownGracefully();
});

export { producer }; // Exporting the producer instance for external use
export { producer }; // Exporting the producer instance for external use

0 comments on commit 348888c

Please sign in to comment.