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

fix(channel-web) prevent mapping error #1814

Merged
merged 1 commit into from
Feb 23, 2024
Merged
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
27 changes: 26 additions & 1 deletion modules/channel-web/src/backend/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ export default class WebchatDb {
// Prevents issues when switching between different Messaging servers
// TODO: Remove this check once the 'web_user_map' table is removed
if (!(await this.checkUserExist(botId, userMapping.userId))) {
this.bp.logger.info(`No user found for visitor ${visitorId} in the current mapping, reseting mapping`)
await this.deleteMappingFromVisitor(botId, visitorId)
await createUserAndMapping()
}
Expand Down Expand Up @@ -105,11 +106,31 @@ export default class WebchatDb {
}
}

async waitForLock(lockName: string, durationMs: number, run: number = 0): Promise<sdk.RedisLock> {
const lock = this.bp.distributed.acquireLock(lockName, durationMs)

if (!lock) {
if (run > durationMs / 100) {
throw new Error(`Timeout acquiring lock '${lockName}'`)
}

await new Promise(resolve => setTimeout(resolve, 100))
return this.waitForLock(lockName, durationMs, run + 1)
}

return lock
}

async createUserMapping(botId: string, visitorId: string, userId: string): Promise<UserMapping> {
let mapping: UserMapping | undefined = { botId, visitorId, userId }

let lock: sdk.RedisLock
try {
try {
// Lock prevent issues when multiple endpoints are trying
// to map the user at the same time
const lockName = `create_user_mapping_${botId}_${visitorId}`
lock = await this.waitForLock(lockName, ms('5s'))

await this.knex('web_user_map').insert(mapping)
this.cacheByVisitor.set(`${botId}_${visitorId}`, mapping)
} catch (err) {
Expand All @@ -124,6 +145,10 @@ export default class WebchatDb {
.forBot(botId)
.attachError(err)
.error(`An error occurred while creating a user mapping for user ${userId} and visitor ${visitorId}.`)
} finally {
if (lock) {
lock.unlock()
}
}

return mapping
Expand Down
Loading