Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(engine): retry a failed wwebjs lid report on the next send

Yudhi Armyndharisd96a57885426
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index dab1d734d..37353222e 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -5695,6 +5695,50 @@ describe('LID mapping persistence to LidMappingStore (#583 R3)', () => {
readyWithStore({ getNumberId, sendMessage }, makeStore(remember)).sendTextMessage('[email protected]', 'hi'),
).resolves.toBeDefined();
});
+
+ it.each(['resolves false', 'rejects'])(
+ 'reports the pair again with the next send when the mapping write %s, without probing again',
+ async failure => {
+ const remember = jest.fn().mockResolvedValue(true);
+ if (failure === 'rejects') remember.mockRejectedValueOnce(new Error('db down'));
+ else remember.mockResolvedValueOnce(false);
+ const getNumberId = jest.fn().mockResolvedValue({ _serialized: '555000111@lid' });
+ const sendMessage = jest.fn<Promise<typeof sentMessage>, [string, ...unknown[]]>().mockResolvedValue(sentMessage);
+ const adapter = readyWithStore({ getNumberId, sendMessage }, makeStore(remember));
+
+ await adapter.sendTextMessage('[email protected]', 'first');
+ await adapter.sendTextMessage('[email protected]', 'second');
+ await adapter.sendTextMessage('[email protected]', 'third');
+
+ expect(getNumberId).toHaveBeenCalledTimes(1);
+ expect(remember).toHaveBeenCalledTimes(2);
+ expect(remember).toHaveBeenNthCalledWith(2, '555000111', '628111', 's1');
+ expect(sendMessage.mock.calls.map(call => call[0])).toEqual(['555000111@lid', '555000111@lid', '555000111@lid']);
+ },
+ );
+
+ it('does not report a newer resolution again when an older mapping write fails late', async () => {
+ let settleOlder!: (stored: boolean) => void;
+ const getNumberId = jest
+ .fn()
+ .mockResolvedValueOnce({ _serialized: '555000111@lid' })
+ .mockResolvedValueOnce({ _serialized: '555000222@lid' });
+ const remember = jest
+ .fn()
+ .mockReturnValueOnce(new Promise<boolean>(resolve => (settleOlder = resolve)))
+ .mockResolvedValue(true);
+ const sendMessage = jest.fn<Promise<typeof sentMessage>, [string, ...unknown[]]>().mockResolvedValue(sentMessage);
+ const adapter = readyWithStore({ getNumberId, sendMessage }, makeStore(remember));
+
+ await Promise.all([adapter.sendTextMessage('[email protected]', 'a'), adapter.sendTextMessage('[email protected]', 'b')]);
+ settleOlder(false);
+ await new Promise(resolve => setImmediate(resolve));
+ await adapter.sendTextMessage('[email protected]', 'c');
+
+ expect(getNumberId).toHaveBeenCalledTimes(2);
+ expect(remember).toHaveBeenCalledTimes(2);
+ expect(sendMessage.mock.calls[2][0]).toBe('555000222@lid');
+ });
});
describe('extractWwebjsCall (call_log → { video, missed }, salvaged from #494)', () => {
diff --git a/src/engine/adapters/wwebjs-messaging.ts b/src/engine/adapters/wwebjs-messaging.ts
index c33f5ab9e..89b8bb318 100644
--- a/src/engine/adapters/wwebjs-messaging.ts
+++ b/src/engine/adapters/wwebjs-messaging.ts
@@ -399,6 +399,9 @@ export class WwebjsMessaging {
// Unbounded Map, bounded in practice by distinct recipients per session; add an LRU only if a
// session ever addresses a truly unbounded set of fresh numbers.
private readonly resolvedSendIds = new Map<string, string>();
+ // The `<phone>@c.us` keys of the cache above whose `@lid` the mapping store has not taken (its write failed):
+ // the next send reports the pair again, so a failed write costs one more write, not a fresh probe.
+ private readonly unreportedLids = new Set<string>();
/**
* Resolve an individual (`@c.us`) recipient to the id whatsapp-web.js will accept. WhatsApp has
@@ -416,20 +419,14 @@ export class WwebjsMessaging {
}
const cached = this.resolvedSendIds.get(chatId);
if (cached) {
+ if (this.unreportedLids.delete(chatId)) this.reportLid(chatId, cached);
return cached;
}
try {
const wid = await this.host.getNumberId(chatId);
if (wid) {
this.resolvedSendIds.set(chatId, wid);
- if (wid.endsWith('@lid')) {
- // Persist the learned phone -> lid so the message read-path (resolveJidCandidates) can
- // bridge this contact's `@c.us` and `@lid` rows on a pure whatsapp-web.js deployment
- // (#583 R3). Fire-and-forget: resolution (and the send) must never block/fail on the write.
- void this.host.config.lidMappingStore
- ?.remember(userPart(wid), userPart(chatId), this.host.config.sessionId)
- ?.catch(() => {});
- }
+ if (wid.endsWith('@lid')) this.reportLid(chatId, wid);
return wid;
}
return chatId;
@@ -438,6 +435,23 @@ export class WwebjsMessaging {
}
}
+ /**
+ * Persist a learned phone -> lid so the message read-path (resolveJidCandidates) can bridge this contact's
+ * `@c.us` and `@lid` rows on a pure whatsapp-web.js deployment (#583 R3). Fire-and-forget: resolution (and
+ * the send) must never block/fail on the write. A write the store reports failed (it resolves false, or
+ * rejects) is marked for the next send, unless a newer resolution has replaced this one meanwhile.
+ */
+ private reportLid(chatId: string, wid: string): void {
+ const failed = (): void => {
+ if (this.resolvedSendIds.get(chatId) === wid) this.unreportedLids.add(chatId);
+ };
+ void this.host.config.lidMappingStore
+ ?.remember(userPart(wid), userPart(chatId), this.host.config.sessionId)
+ ?.then(stored => {
+ if (stored === false) failed();
+ }, failed);
+ }
+
/**
* The send options that attach a quote, or nothing at all when the caller asked for none.
*
@@ -500,6 +514,7 @@ export class WwebjsMessaging {
throw toCapturedPageError(err);
}
this.resolvedSendIds.delete(chatId);
+ this.unreportedLids.delete(chatId);
const fresh = await this.resolveSendId(chatId);
// Same gap as above, and before the comparison: a lookup that failed because the session went away
// answers the unresolved id, which would read as an unreachable recipient.