Skip to content

Commit

Permalink
Avoid potential racing condition
Browse files Browse the repository at this point in the history
  • Loading branch information
kibertoad committed Feb 23, 2024
1 parent c3553b0 commit 513659b
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
15 changes: 12 additions & 3 deletions packages/sns/lib/sns/AbstractSnsService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,13 @@ export abstract class AbstractSnsService<
// @ts-ignore
public topicArn: string

private isInitted: boolean
private initPromise?: Promise<void>

constructor(dependencies: DependenciesType, options: SNSOptionsType) {
super(dependencies, options)

this.isInitted = false
this.snsClient = dependencies.snsClient
}

Expand All @@ -98,6 +102,7 @@ export abstract class AbstractSnsService<

const initResult = await initSns(this.snsClient, this.locatorConfig, this.creationConfig)
this.topicArn = initResult.topicArn
this.isInitted = true
}

// eslint-disable-next-line @typescript-eslint/require-await
Expand All @@ -108,9 +113,13 @@ export abstract class AbstractSnsService<
messageSchema: ZodSchema<MessagePayloadType>,
options: SNSMessageOptions = {},
): Promise<void> {
if (this.topicArn === undefined) {
// Lazy loading
await this.init()
// If it's not initted yet, do the lazy init
if (!this.isInitted) {
// avoid multiple concurrent inits
if (!this.initPromise) {
this.initPromise = this.init()
}
await this.initPromise
}

try {
Expand Down
15 changes: 12 additions & 3 deletions packages/sqs/lib/sqs/AbstractSqsService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,13 @@ export abstract class AbstractSqsService<
// @ts-ignore
public queueArn: string

private isInitted: boolean
private initPromise?: Promise<void>

constructor(dependencies: DependenciesType, options: SQSOptionsType) {
super(dependencies, options)

this.isInitted = false
this.sqsClient = dependencies.sqsClient
}

Expand All @@ -72,16 +76,21 @@ export abstract class AbstractSqsService<
this.queueArn = queueArn
this.queueUrl = queueUrl
this.queueName = queueName
this.isInitted = true
}

protected async internalPublish(
message: MessagePayloadType,
messageSchema: ZodSchema<MessagePayloadType>,
options: SQSMessageOptions = {},
): Promise<void> {
if (!this.queueArn) {
// Lazy loading
await this.init()
// If it's not initted yet, do the lazy init
if (!this.isInitted) {
// avoid multiple concurrent inits
if (!this.initPromise) {
this.initPromise = this.init()
}
await this.initPromise
}

try {
Expand Down

0 comments on commit 513659b

Please sign in to comment.