Skip to content

Commit 703826c

Browse files
committed
refactor(whatsapp): extract group metadata cache owner
1 parent 9402598 commit 703826c

6 files changed

Lines changed: 535 additions & 350 deletions

File tree

‎extensions/whatsapp/src/auto-reply/monitor.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,14 +27,14 @@ import {
2727
type ManagedWhatsAppListener,
2828
} from "../connection-controller.js";
2929
import { resolveWhatsAppInboundPolicy } from "../inbound-policy.js";
30-
import { normalizeWebInboundMessage } from "../inbound/message-aliases.js";
3130
import {
32-
attachWebInboxToSocket,
3331
readWhatsAppBaileysCacheEntry,
3432
type WhatsAppBaileysGroupMetadataCache,
3533
type WhatsAppBaileysMessageCache,
36-
type WhatsAppGroupMetadataCache,
37-
} from "../inbound/monitor.js";
34+
} from "../inbound/baileys-cache.js";
35+
import type { WhatsAppGroupMetadataCache } from "../inbound/group-metadata-cache.js";
36+
import { normalizeWebInboundMessage } from "../inbound/message-aliases.js";
37+
import { attachWebInboxToSocket } from "../inbound/monitor.js";
3838
import type { WebInboundMessageInput } from "../inbound/types.js";
3939
import {
4040
newConnectionId,
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
// Whatsapp plugin module implements bounded Baileys cache behavior.
2+
import type { GroupMetadata, proto } from "baileys";
3+
4+
const WHATSAPP_BAILEYS_CACHE_MAX_ENTRIES = 500;
5+
6+
export type WhatsAppBaileysCacheEntry<T> = {
7+
expiresAt: number;
8+
value: T;
9+
};
10+
11+
export type WhatsAppBaileysMessageCache = Map<string, WhatsAppBaileysCacheEntry<proto.IMessage>>;
12+
13+
export type WhatsAppBaileysGroupMetadataCache = Map<
14+
string,
15+
WhatsAppBaileysCacheEntry<GroupMetadata>
16+
>;
17+
18+
export function rememberWhatsAppBaileysCacheEntry<T>(
19+
cache: Map<string, WhatsAppBaileysCacheEntry<T>> | undefined,
20+
key: string,
21+
value: T,
22+
ttlMs: number,
23+
): void {
24+
if (!cache) {
25+
return;
26+
}
27+
if (cache.has(key)) {
28+
cache.delete(key);
29+
}
30+
cache.set(key, {
31+
expiresAt: Date.now() + ttlMs,
32+
value,
33+
});
34+
while (cache.size > WHATSAPP_BAILEYS_CACHE_MAX_ENTRIES) {
35+
const oldest = cache.keys().next();
36+
if (oldest.done) {
37+
break;
38+
}
39+
cache.delete(oldest.value);
40+
}
41+
}
42+
43+
export function readWhatsAppBaileysCacheEntry<T>(
44+
cache: Map<string, WhatsAppBaileysCacheEntry<T>>,
45+
key: string,
46+
): T | undefined {
47+
const entry = cache.get(key);
48+
if (!entry) {
49+
return undefined;
50+
}
51+
if (entry.expiresAt <= Date.now()) {
52+
cache.delete(key);
53+
return undefined;
54+
}
55+
cache.delete(key);
56+
cache.set(key, entry);
57+
return entry.value;
58+
}
Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,150 @@
1+
// Whatsapp tests cover the group metadata cache owner.
2+
import { EventEmitter } from "node:events";
3+
import type { GroupMetadata, WASocket } from "baileys";
4+
import { afterEach, describe, expect, it, vi } from "vitest";
5+
import type { WhatsAppBaileysGroupMetadataCache } from "./baileys-cache.js";
6+
import {
7+
createWhatsAppGroupMetadataCacheOwner,
8+
type WhatsAppGroupMetadataCache,
9+
} from "./group-metadata-cache.js";
10+
11+
function createGroupMetadata(params: {
12+
id: string;
13+
subject?: string;
14+
participantId?: string;
15+
}): GroupMetadata {
16+
return {
17+
id: params.id,
18+
subject: params.subject ?? params.id,
19+
participants: params.participantId ? [{ id: params.participantId }] : [],
20+
} as GroupMetadata;
21+
}
22+
23+
function createSocket(params?: {
24+
groupMetadata?: (jid: string) => Promise<GroupMetadata>;
25+
groupFetchAllParticipating?: () => Promise<Record<string, GroupMetadata>>;
26+
}) {
27+
const ev = new EventEmitter();
28+
const sock = {
29+
ev,
30+
groupMetadata: vi.fn(
31+
params?.groupMetadata ??
32+
(async (jid: string) => createGroupMetadata({ id: jid, subject: "Fetched group" })),
33+
),
34+
groupFetchAllParticipating: vi.fn(params?.groupFetchAllParticipating ?? (async () => ({}))),
35+
} as unknown as WASocket;
36+
return { ev, sock };
37+
}
38+
39+
function createOwner(params: {
40+
sock: WASocket;
41+
reconnectCache?: WhatsAppGroupMetadataCache;
42+
baileysCache?: WhatsAppBaileysGroupMetadataCache;
43+
}) {
44+
return createWhatsAppGroupMetadataCacheOwner({
45+
sock: params.sock,
46+
getCurrentSock: () => params.sock,
47+
resolveInboundJid: async (jid) => jid?.replace("@s.whatsapp.net", "") ?? null,
48+
reconnectCache: params.reconnectCache,
49+
baileysCache: params.baileysCache,
50+
logVerbose: vi.fn(),
51+
logHydrationWarning: vi.fn(),
52+
});
53+
}
54+
55+
afterEach(() => {
56+
vi.useRealTimers();
57+
});
58+
59+
describe("WhatsApp group metadata cache owner", () => {
60+
it("owns fetched metadata, reconnect fallback, and Baileys participant data", async () => {
61+
const metadata = createGroupMetadata({
62+
63+
subject: "Project room",
64+
participantId: "[email protected]",
65+
});
66+
const { sock } = createSocket({ groupMetadata: async () => metadata });
67+
const reconnectCache: WhatsAppGroupMetadataCache = new Map();
68+
const baileysCache: WhatsAppBaileysGroupMetadataCache = new Map();
69+
const owner = createOwner({ sock, reconnectCache, baileysCache });
70+
71+
owner.start();
72+
const result = await owner.get(metadata.id);
73+
74+
expect(result).toMatchObject({
75+
subject: "Project room",
76+
participants: ["15550001111"],
77+
});
78+
expect(reconnectCache.get(metadata.id)?.subject).toBe("Project room");
79+
expect(baileysCache.get(metadata.id)?.value.participants).toHaveLength(1);
80+
owner.close();
81+
});
82+
83+
it("does not republish metadata invalidated while hydration is pending", async () => {
84+
let resolveHydration: ((groups: Record<string, GroupMetadata>) => void) | undefined;
85+
const hydration = new Promise<Record<string, GroupMetadata>>((resolve) => {
86+
resolveHydration = resolve;
87+
});
88+
const { ev, sock } = createSocket({
89+
groupFetchAllParticipating: async () => await hydration,
90+
});
91+
const reconnectCache: WhatsAppGroupMetadataCache = new Map();
92+
const baileysCache: WhatsAppBaileysGroupMetadataCache = new Map();
93+
const owner = createOwner({ sock, reconnectCache, baileysCache });
94+
95+
owner.start();
96+
ev.emit("groups.update", [{ id: "[email protected]" }]);
97+
resolveHydration?.({
98+
"[email protected]": createGroupMetadata({ id: "[email protected]", subject: "Stale group" }),
99+
});
100+
await vi.waitFor(() => {
101+
expect(sock.groupFetchAllParticipating).toHaveBeenCalledOnce();
102+
});
103+
await Promise.resolve();
104+
105+
expect(reconnectCache.has("[email protected]")).toBe(false);
106+
expect(baileysCache.has("[email protected]")).toBe(false);
107+
owner.close();
108+
});
109+
110+
it("bounds reconnect metadata and detaches group listeners on close", () => {
111+
const { ev, sock } = createSocket();
112+
const reconnectCache: WhatsAppGroupMetadataCache = new Map();
113+
const owner = createOwner({ sock, reconnectCache });
114+
115+
owner.start();
116+
for (let index = 0; index < 501; index += 1) {
117+
const id = `${index}@g.us`;
118+
ev.emit("groups.upsert", [createGroupMetadata({ id })]);
119+
}
120+
121+
expect(reconnectCache.size).toBe(500);
122+
expect(reconnectCache.has("[email protected]")).toBe(false);
123+
expect(ev.listenerCount("groups.upsert")).toBe(1);
124+
expect(ev.listenerCount("groups.update")).toBe(1);
125+
expect(ev.listenerCount("group-participants.update")).toBe(1);
126+
127+
owner.close();
128+
129+
expect(ev.listenerCount("groups.upsert")).toBe(0);
130+
expect(ev.listenerCount("groups.update")).toBe(0);
131+
expect(ev.listenerCount("group-participants.update")).toBe(0);
132+
});
133+
134+
it("expires local metadata before fetching it again", async () => {
135+
vi.useFakeTimers();
136+
vi.setSystemTime(new Date("2026-07-29T00:00:00Z"));
137+
const { sock } = createSocket();
138+
const owner = createOwner({ sock });
139+
140+
await owner.get("[email protected]");
141+
await owner.get("[email protected]");
142+
expect(sock.groupMetadata).toHaveBeenCalledTimes(1);
143+
144+
vi.advanceTimersByTime(5 * 60 * 1000 + 1);
145+
await owner.get("[email protected]");
146+
147+
expect(sock.groupMetadata).toHaveBeenCalledTimes(2);
148+
owner.close();
149+
});
150+
});

0 commit comments

Comments
 (0)