Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(baileys): start a new group read after a reset

Yudhi Armyndharisbc6642a16556
diff --git a/src/engine/adapters/baileys-group-metadata-cache.spec.ts b/src/engine/adapters/baileys-group-metadata-cache.spec.ts
index 003a5cd44..383d6e5d6 100644
--- a/src/engine/adapters/baileys-group-metadata-cache.spec.ts
+++ b/src/engine/adapters/baileys-group-metadata-cache.spec.ts
@@ -112,6 +112,34 @@ describe('GroupMetadataCache', () => {
expect(fresh).toHaveBeenCalledTimes(1);
});
+ // A query out on a socket that has been replaced may never be answered, so a read that follows the
+ // change has to ask again rather than wait on it, and the old answer must leave the new read alone.
+ it.each([
+ ['an invalidation', (cache: GroupMetadataCache) => cache.invalidate(GROUP)],
+ ['a clear', (cache: GroupMetadataCache) => cache.clear()],
+ ])('asks again for a read that follows %s while a query is out', async (_label, forget) => {
+ const cache = build();
+ let answerOld!: (metadata: GroupMetadata) => void;
+ const old = cache.read(GROUP, () => new Promise<GroupMetadata>(resolve => (answerOld = resolve)));
+
+ forget(cache);
+ let answerNew!: (metadata: GroupMetadata) => void;
+ const fresh = jest.fn(() => new Promise<GroupMetadata>(resolve => (answerNew = resolve)));
+ const next = cache.read(GROUP, fresh);
+ expect(fresh).toHaveBeenCalledTimes(1);
+
+ answerOld(group(GROUP, ['[email protected]']));
+ await old;
+ expect(cache.size).toBe(0); // the old answer is not kept
+ const joiner = jest.fn();
+ void cache.read(GROUP, joiner);
+ expect(joiner).not.toHaveBeenCalled(); // and it did not release the new query's slot
+
+ answerNew(group(GROUP, ['[email protected]', '[email protected]']));
+ await expect(next).resolves.toMatchObject({ participants: [{}, {}] });
+ expect(cache.size).toBe(1);
+ });
+
it('clears every group, and an answer in flight is not kept either', async () => {
const cache = build();
await cache.read(GROUP, () => Promise.resolve(group(GROUP)));
diff --git a/src/engine/adapters/baileys-group-metadata-cache.ts b/src/engine/adapters/baileys-group-metadata-cache.ts
index ca9e0423d..0d1a09fb1 100644
--- a/src/engine/adapters/baileys-group-metadata-cache.ts
+++ b/src/engine/adapters/baileys-group-metadata-cache.ts
@@ -29,10 +29,12 @@ interface CachedGroup {
*/
export class GroupMetadataCache {
private readonly entries = new Map<string, CachedGroup>();
- /** Reads under way, so concurrent sends to one group share a single query. */
+ /**
+ * Reads under way, so concurrent sends to one group share a single query. A read that an invalidation
+ * or a clear overtook is dropped from here: its answer still reaches the callers that joined it, but
+ * it is not kept and no later read waits on it.
+ */
private readonly inFlight = new Map<string, Promise<GroupMetadata>>();
- /** In-flight reads that an invalidation overtook: their answer is returned but not kept. */
- private readonly overtaken = new Set<string>();
constructor(
private readonly ttlMs: number,
@@ -72,16 +74,22 @@ export class GroupMetadataCache {
if (hit) return Promise.resolve(hit);
const joined = this.inFlight.get(jid);
if (joined) return joined;
- const pending = (async (): Promise<GroupMetadata> => {
- try {
- const metadata = await fetch();
- if (!this.overtaken.has(jid)) this.store(jid, metadata);
+ // Gives up the group's slot and says whether this read still held it: an invalidation or a clear takes it away.
+ const settle = (): boolean => {
+ const held = this.inFlight.get(jid) === pending;
+ if (held) this.inFlight.delete(jid);
+ return held;
+ };
+ const pending: Promise<GroupMetadata> = fetch().then(
+ metadata => {
+ if (settle()) this.store(jid, metadata);
return metadata;
- } finally {
- this.overtaken.delete(jid);
- this.inFlight.delete(jid);
- }
- })();
+ },
+ (error: unknown) => {
+ settle();
+ throw error;
+ },
+ );
this.inFlight.set(jid, pending);
return pending;
}
@@ -98,13 +106,13 @@ export class GroupMetadataCache {
invalidate(jid: string | undefined): void {
if (!jid) return;
this.entries.delete(jid);
- if (this.inFlight.has(jid)) this.overtaken.add(jid);
+ this.inFlight.delete(jid);
}
/** Forget everything, for a connection change or a teardown. */
clear(): void {
this.entries.clear();
- for (const jid of this.inFlight.keys()) this.overtaken.add(jid);
+ this.inFlight.clear();
}
/**
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index 0b186bb41..a21b522fa 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -10588,6 +10588,24 @@ describe('BaileysAdapter group metadata cache', () => {
await adapter.destroy();
});
+ it('asks a new socket for a group whose query never came back on the previous one', async () => {
+ const adapter = await ready();
+ // A socket ended on a silent connection loss leaves a query still out on it unanswered.
+ fakeSock.groupMetadata.mockReturnValueOnce(new Promise(() => undefined));
+ void socketConfig().cachedGroupMetadata(GROUP);
+
+ jest.useFakeTimers();
+ fakeSock.fire('connection.update', {
+ connection: 'close',
+ lastDisconnect: { error: { output: { statusCode: 515 } } },
+ });
+ await jest.runAllTimersAsync();
+ void socketConfig().cachedGroupMetadata(GROUP);
+
+ expect(fakeSock.groupMetadata).toHaveBeenCalledTimes(2);
+ await adapter.destroy();
+ });
+
it.each([
['disconnect', (a: BaileysAdapter) => a.disconnect()],
['destroy', (a: BaileysAdapter) => a.destroy()],