Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[service-utils] fix: crash if Kafka connects more than once #6387

Merged
merged 1 commit into from
Mar 1, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading