Skip to content

Commit bb831d5

Browse files
committed
refactor: optimize retry loop and robustify cache error handling
1 parent cb41e65 commit bb831d5

File tree

2 files changed

+15
-2
lines changed

2 files changed

+15
-2
lines changed

src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1653,6 +1653,7 @@ export class BaileysStartupService extends ChannelStartupService {
16531653

16541654
let retries = 0;
16551655
const maxRetries = 3;
1656+
const retryDelay = 500; // 500ms delay to avoid blocking for too long
16561657

16571658
while (retries < maxRetries) {
16581659
const messages = (await this.prismaRepository.$queryRaw`
@@ -1669,7 +1670,7 @@ export class BaileysStartupService extends ChannelStartupService {
16691670

16701671
retries++;
16711672
if (retries < maxRetries) {
1672-
await delay(2000);
1673+
await delay(retryDelay);
16731674
}
16741675
}
16751676

@@ -1679,6 +1680,13 @@ export class BaileysStartupService extends ChannelStartupService {
16791680
);
16801681
continue;
16811682
}
1683+
1684+
// Sync the incoming key.remoteJid with the stored one.
1685+
// This mutation is safe and necessary because Baileys events might use LIDs while we store Phone JIDs (or vice versa).
1686+
// Normalizing ensuring downstream logic uses the identifier that exists in our database.
1687+
if (findMessage?.key?.remoteJid && key.remoteJid !== findMessage.key.remoteJid) {
1688+
key.remoteJid = findMessage.key.remoteJid;
1689+
}
16821690
if (findMessage?.key?.remoteJid && findMessage.key.remoteJid !== key.remoteJid) {
16831691
this.logger.verbose(
16841692
`Updating key.remoteJid from ${key.remoteJid} to ${findMessage.key.remoteJid} based on stored message`,

src/utils/onWhatsappCache.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { prismaRepository } from '@api/server.module';
22
import { configService, Database } from '@config/env.config';
33
import { Logger } from '@config/logger.config';
4+
import { Prisma } from '@prisma/client';
45
import dayjs from 'dayjs';
56

67
const logger = new Logger('OnWhatsappCache');
@@ -170,7 +171,11 @@ export async function saveOnWhatsappCache(data: ISaveOnWhatsappCacheParams[]) {
170171
});
171172
} catch (error: any) {
172173
// Check for unique constraint violation (Prisma error code P2002)
173-
if (error.code === 'P2002' && error.meta?.target?.includes('remoteJid')) {
174+
if (
175+
error instanceof Prisma.PrismaClientKnownRequestError &&
176+
error.code === 'P2002' &&
177+
(error.meta?.target as string[])?.includes('remoteJid')
178+
) {
174179
logger.verbose(
175180
`[saveOnWhatsappCache] Race condition detected for ${remoteJid}, updating existing record instead.`,
176181
);

0 commit comments

Comments
 (0)