Skip to content

Commit

Permalink
[service-utils] fix: crash if Kafka connects more than once (#6387)
Browse files Browse the repository at this point in the history
  • Loading branch information
arcoraven authored Mar 1, 2025
1 parent 879148f commit 0c0d837
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 6 deletions.
5 changes: 5 additions & 0 deletions .changeset/gentle-readers-bet.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@thirdweb-dev/service-utils": patch
---

[service-utils] Add connect promise so it only connects once
18 changes: 12 additions & 6 deletions packages/service-utils/src/node/kafka.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@ export interface KafkaProducerSendOptions {
*/
export class KafkaProducer {
private producer: KafkaJS.Producer;
private isConnected = false;
// Use a promise to ensure `connect()` is called at most once.
private connectPromise?: Promise<void>;

constructor(options: {
/**
Expand Down Expand Up @@ -68,10 +69,17 @@ export class KafkaProducer {

/**
* Connects the producer. Can be called explicitly at the start of your service, or will be called automatically when sending messages.
*
* A cached promise is used so this function is safe to call more than once and concurrently.
*/
async connect() {
await this.producer.connect();
this.isConnected = true;
if (!this.connectPromise) {
this.connectPromise = this.producer.connect().catch((err) => {
this.connectPromise = undefined;
throw err;
});
}
await this.connectPromise;
}

/**
Expand All @@ -88,9 +96,7 @@ export class KafkaProducer {
topic: string,
messages: Record<string, unknown>[],
): Promise<void> {
if (!this.isConnected) {
await this.connect();
}
await this.connect();

await this.producer.send({
topic,
Expand Down

0 comments on commit 0c0d837

Please sign in to comment.