Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
perf(baileys): reuse the participant list of a group
Yudhi Armyndharisbacd2fc425b0
diff --git a/.env.example b/.env.exampleindex dead67c00..f2c994861 100644--- a/.env.example+++ b/.env.example@@ -302,6 +302,11 @@ OPENWA_PIDS_LIMIT=2048# it for many sessions or large chat lists. 0 disables the cap. Default 5000.# BAILEYS_CHAT_STATE_CACHE_MAX=5000+# How long, in milliseconds, a Baileys group send reuses the group's participant list instead of querying+# it for every message. A membership or settings event, a reconnect and a write to the group each drop+# the cached list early. 0 queries for every send. Default 300000 (5 minutes).+# BAILEYS_GROUP_METADATA_CACHE_TTL_MS=300000+# Per-session cap on the Baileys message rows kept in the database: the newest N survive and older# rows are pruned after each write. A value that is not a positive integer fails the boot.# BAILEYS_MESSAGE_STORE_LIMIT=5000diff --git a/docker-compose.dev.yml b/docker-compose.dev.ymlindex c3b516ad6..c9b9c763c 100644--- a/docker-compose.dev.yml+++ b/docker-compose.dev.yml@@ -252,6 +252,7 @@ services:- BAILEYS_MESSAGE_STORE_LIMIT=${BAILEYS_MESSAGE_STORE_LIMIT:-}- BAILEYS_SESSION_STORE_MAX_ENTRIES=${BAILEYS_SESSION_STORE_MAX_ENTRIES:-}- BAILEYS_CHAT_STATE_CACHE_MAX=${BAILEYS_CHAT_STATE_CACHE_MAX:-}+ - BAILEYS_GROUP_METADATA_CACHE_TTL_MS=${BAILEYS_GROUP_METADATA_CACHE_TTL_MS:-}- WWEBJS_ONBOARDING_CONTINUE_LABELS=${WWEBJS_ONBOARDING_CONTINUE_LABELS:-}# Default matches the image's ENV (Dockerfile); a blank forward would shadow it and make# puppeteer fall back to a bundled Chromium the image does not ship. compose-parity.spec.tsdiff --git a/docker-compose.yml b/docker-compose.ymlindex 7e4bb94f7..4714b7d7d 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -357,6 +357,7 @@ services:- BAILEYS_MESSAGE_STORE_LIMIT=${BAILEYS_MESSAGE_STORE_LIMIT:-}- BAILEYS_SESSION_STORE_MAX_ENTRIES=${BAILEYS_SESSION_STORE_MAX_ENTRIES:-}- BAILEYS_CHAT_STATE_CACHE_MAX=${BAILEYS_CHAT_STATE_CACHE_MAX:-}+ - BAILEYS_GROUP_METADATA_CACHE_TTL_MS=${BAILEYS_GROUP_METADATA_CACHE_TTL_MS:-}- WWEBJS_ONBOARDING_CONTINUE_LABELS=${WWEBJS_ONBOARDING_CONTINUE_LABELS:-}# Default matches the image's ENV (Dockerfile); a blank forward would shadow it and make# puppeteer fall back to a bundled Chromium the image does not ship. compose-parity.spec.tsdiff --git a/docs/29-engine-capability-matrix.md b/docs/29-engine-capability-matrix.mdindex a062ed8c8..5435afdc8 100644--- a/docs/29-engine-capability-matrix.md+++ b/docs/29-engine-capability-matrix.md@@ -1018,6 +1018,12 @@ adapter boundary — none silently stubs.a revoke while the send still resolves, so sending it would report a deletion that never happened.When the group's member list shows no row the gateway can identify as the account, admin status isunknown and the revoke is still sent.+- **Group sends (baileys) reuse the group's participant list.** Rather than query it for every+ message, the adapter keeps each group's list for `BAILEYS_GROUP_METADATA_CACHE_TTL_MS` (default 5+ minutes; `0` queries for every send). A membership or settings event for the group, a write to it+ through the API, and every reconnect drop the cached list early. A member added without the adapter+ receiving the event gets the group's messages once the entry expires or its client asks for a+ retry. whatsapp-web.js has no counterpart: the page keeps the member list itself.## 29.8 Snapshot summarydiff --git a/src/config/env-precedence.ts b/src/config/env-precedence.tsindex 6974a7254..19b9f3951 100644--- a/src/config/env-precedence.ts+++ b/src/config/env-precedence.ts@@ -214,6 +214,7 @@ export const BLANK_SHADOWED_ENV_KEYS: string[] = ['BAILEYS_MESSAGE_STORE_LIMIT','BAILEYS_SESSION_STORE_MAX_ENTRIES','BAILEYS_CHAT_STATE_CACHE_MAX',+ 'BAILEYS_GROUP_METADATA_CACHE_TTL_MS','WWEBJS_ONBOARDING_CONTINUE_LABELS','SHUTDOWN_DELAY_MS','SIMULATE_TYPING_MAX_MS',diff --git a/src/config/env.validation.ts b/src/config/env.validation.tsindex 0a08f7e19..0c4b0b572 100644--- a/src/config/env.validation.ts+++ b/src/config/env.validation.ts@@ -263,6 +263,7 @@ export function validateEnv(config: EnvConfig): EnvConfig {'MESSAGE_REAPER_GRACE_MS','WEBHOOK_RECONCILE_GRACE_MS','INGRESS_RECONCILE_GRACE_MS',+ 'BAILEYS_GROUP_METADATA_CACHE_TTL_MS', // 0 = no cache; every group send then queries the participant list]) {checkNonNegativeInt(key);}diff --git a/src/engine/adapters/baileys-group-metadata-cache.spec.ts b/src/engine/adapters/baileys-group-metadata-cache.spec.tsnew file mode 100644index 000000000..003a5cd44--- /dev/null+++ b/src/engine/adapters/baileys-group-metadata-cache.spec.ts@@ -0,0 +1,214 @@+import type { GroupMetadata } from '@whiskeysockets/baileys';+import { GroupMetadataCache, groupMetadataCacheTtlMs } from './baileys-group-metadata-cache';++const GROUP = '[email protected]';+const OTHER = '[email protected]';++const group = (id: string, members: string[] = ['[email protected]']): GroupMetadata =>+ ({ id, subject: 'Test', participants: members.map(member => ({ id: member })) }) as unknown as GroupMetadata;++describe('GroupMetadataCache', () => {+ let clock: number;+ const now = (): number => clock;+ const build = (ttlMs = 1000, maxEntries = 256): GroupMetadataCache => new GroupMetadataCache(ttlMs, maxEntries, now);++ beforeEach(() => {+ clock = 1_000_000;+ });++ describe('reading through', () => {+ it('queries once and answers from the cache until the TTL ends', async () => {+ const cache = build();+ const fetch = jest.fn().mockResolvedValue(group(GROUP));++ const first = await cache.read(GROUP, fetch);+ clock += 999;+ const second = await cache.read(GROUP, fetch);++ expect(first).toBe(second);+ expect(fetch).toHaveBeenCalledTimes(1);++ clock += 1;+ await cache.read(GROUP, fetch);+ expect(fetch).toHaveBeenCalledTimes(2);+ });++ it('keeps each group apart', async () => {+ const cache = build();+ const fetch = jest.fn((jid: string) => Promise.resolve(group(jid)));++ await cache.read(GROUP, () => fetch(GROUP));+ await cache.read(OTHER, () => fetch(OTHER));+ await cache.read(GROUP, () => fetch(GROUP));++ expect(fetch).toHaveBeenCalledTimes(2);+ });++ it('lets concurrent reads of one group share a single query', async () => {+ const cache = build();+ let answer!: (metadata: GroupMetadata) => void;+ const fetch = jest.fn(() => new Promise<GroupMetadata>(resolve => (answer = resolve)));++ const reads = [cache.read(GROUP, fetch), cache.read(GROUP, fetch), cache.read(GROUP, fetch)];+ answer(group(GROUP));+ const results = await Promise.all(reads);++ expect(fetch).toHaveBeenCalledTimes(1);+ expect(new Set(results).size).toBe(1);+ });++ it('does not keep a failed query: the error surfaces and the next read asks again', async () => {+ const cache = build();+ const fetch = jest.fn().mockRejectedValueOnce(new Error('rate-overlimit')).mockResolvedValue(group(GROUP));++ await expect(cache.read(GROUP, fetch)).rejects.toThrow('rate-overlimit');+ await expect(cache.read(GROUP, fetch)).resolves.toMatchObject({ id: GROUP });++ expect(fetch).toHaveBeenCalledTimes(2);+ });++ it('answers undefined without querying when the TTL is 0, so Baileys queries on its own', async () => {+ const cache = build(0);+ const fetch = jest.fn().mockResolvedValue(group(GROUP));++ await expect(cache.read(GROUP, fetch)).resolves.toBeUndefined();++ expect(cache.enabled).toBe(false);+ expect(fetch).not.toHaveBeenCalled();+ });+ });++ describe('forgetting', () => {+ it('reads a group again after it is invalidated, and leaves the others', async () => {+ const cache = build();+ const fetch = jest.fn((jid: string) => Promise.resolve(group(jid)));+ await cache.read(GROUP, () => fetch(GROUP));+ await cache.read(OTHER, () => fetch(OTHER));++ cache.invalidate(GROUP);+ await cache.read(GROUP, () => fetch(GROUP));+ await cache.read(OTHER, () => fetch(OTHER));++ expect(fetch.mock.calls.map(([jid]) => jid)).toEqual([GROUP, OTHER, GROUP]);+ });++ it('ignores an invalidation that names no group', () => {+ const cache = build();+ expect(() => cache.invalidate(undefined)).not.toThrow();+ });++ it('does not keep an answer that an invalidation overtook, but still hands it to its callers', async () => {+ const cache = build();+ let answer!: (metadata: GroupMetadata) => void;+ const slow = jest.fn(() => new Promise<GroupMetadata>(resolve => (answer = resolve)));+ const read = cache.read(GROUP, slow);++ cache.invalidate(GROUP); // the membership changed while the query was out+ answer(group(GROUP, ['[email protected]']));++ await expect(read).resolves.toMatchObject({ id: GROUP });+ const fresh = jest.fn().mockResolvedValue(group(GROUP, ['[email protected]', '[email protected]']));+ await cache.read(GROUP, fresh);+ expect(fresh).toHaveBeenCalledTimes(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)));+ let answer!: (metadata: GroupMetadata) => void;+ const inFlight = cache.read(OTHER, () => new Promise<GroupMetadata>(resolve => (answer = resolve)));++ cache.clear();+ answer(group(OTHER));+ await inFlight;++ expect(cache.size).toBe(0);+ });++ it('evicts the least recently used group beyond its capacity', async () => {+ const cache = build(1000, 2);+ const fetch = jest.fn((jid: string) => Promise.resolve(group(jid)));+ const third = '[email protected]';+ await cache.read(GROUP, () => fetch(GROUP));+ await cache.read(OTHER, () => fetch(OTHER));+ await cache.read(GROUP, () => fetch(GROUP)); // GROUP is now the more recent of the two++ await cache.read(third, () => fetch(third)); // pushes OTHER out++ expect(cache.size).toBe(2);+ fetch.mockClear();+ await cache.read(GROUP, () => fetch(GROUP));+ await cache.read(OTHER, () => fetch(OTHER));+ expect(fetch.mock.calls.map(([jid]) => jid)).toEqual([OTHER]);+ });+ });++ describe('groups.update batches', () => {+ it('drops a group whose partial change arrives, and leaves the others', async () => {+ const cache = build();+ const fetch = jest.fn((jid: string) => Promise.resolve(group(jid)));+ await cache.read(GROUP, () => fetch(GROUP));+ await cache.read(OTHER, () => fetch(OTHER));++ cache.applyUpdates([{ id: GROUP, announce: true }]);++ fetch.mockClear();+ await cache.read(GROUP, () => fetch(GROUP));+ await cache.read(OTHER, () => fetch(OTHER));+ expect(fetch.mock.calls.map(([jid]) => jid)).toEqual([GROUP]);+ });++ it('refreshes a cached group from a whole snapshot, restarting its TTL', async () => {+ const cache = build();+ const fetch = jest.fn().mockResolvedValue(group(GROUP, ['[email protected]']));+ await cache.read(GROUP, fetch);+ clock += 900;++ cache.applyUpdates([group(GROUP, ['[email protected]', '[email protected]'])]);+ clock += 900;++ const hit = await cache.read(GROUP, fetch);+ expect(hit?.participants).toHaveLength(2);+ expect(fetch).toHaveBeenCalledTimes(1);+ });++ it('does not add a group nobody has sent to from a snapshot', () => {+ const cache = build();++ cache.applyUpdates([group(GROUP), group(OTHER)]);++ expect(cache.size).toBe(0);+ });++ it('skips entries without an id and tolerates a missing batch', () => {+ const cache = build();+ expect(() => cache.applyUpdates([{ subject: 'no id' }])).not.toThrow();+ expect(() => cache.applyUpdates(undefined)).not.toThrow();+ });+ });+});++describe('groupMetadataCacheTtlMs', () => {+ const KEY = 'BAILEYS_GROUP_METADATA_CACHE_TTL_MS';+ const saved = process.env[KEY];+ afterEach(() => {+ if (saved === undefined) delete process.env[KEY];+ else process.env[KEY] = saved;+ });++ it('defaults to five minutes', () => {+ delete process.env[KEY];+ expect(groupMetadataCacheTtlMs()).toBe(300_000);+ });++ it('takes a configured value, 0 included, and falls back on garbage', () => {+ process.env[KEY] = '60000';+ expect(groupMetadataCacheTtlMs()).toBe(60_000);+ process.env[KEY] = '0';+ expect(groupMetadataCacheTtlMs()).toBe(0);+ process.env[KEY] = '5m';+ expect(groupMetadataCacheTtlMs()).toBe(300_000);+ process.env[KEY] = '';+ expect(groupMetadataCacheTtlMs()).toBe(300_000);+ });+});diff --git a/src/engine/adapters/baileys-group-metadata-cache.ts b/src/engine/adapters/baileys-group-metadata-cache.tsnew file mode 100644index 000000000..ca9e0423d--- /dev/null+++ b/src/engine/adapters/baileys-group-metadata-cache.ts@@ -0,0 +1,131 @@+import type { GroupMetadata } from '@whiskeysockets/baileys';+import { resolveNonNegativeIntEnv } from '../../config/configuration';++/** How long a group's participant list is reused before Baileys reads it again; 0 switches the cache off. */+const DEFAULT_GROUP_METADATA_CACHE_TTL_MS = 5 * 60_000;++/** BAILEYS_GROUP_METADATA_CACHE_TTL_MS, read per session so a restart picks up a change. */+export function groupMetadataCacheTtlMs(): number {+ return resolveNonNegativeIntEnv(process.env.BAILEYS_GROUP_METADATA_CACHE_TTL_MS, DEFAULT_GROUP_METADATA_CACHE_TTL_MS);+}++/** The cached copy of one group's metadata and when it was read. */+interface CachedGroup {+ metadata: GroupMetadata;+ storedAt: number;+}++/**+ * The cache behind Baileys' `cachedGroupMetadata` option, one per session.+ *+ * Without it every group send makes its own query for the group's participant list, which for a busy+ * account is one extra round trip (and one more chance at a throttle) per message, each parsing the+ * whole member list. With it the list is reused for up to `ttlMs`.+ *+ * A stale list costs a delay, not a message: a member added since is left out of the sender-key+ * distribution until its client asks for a retry, which Baileys answers. The entry is dropped on the+ * events that change membership or group settings, the whole cache on every connection change (the+ * events missed while offline never arrive), and it expires on its own after `ttlMs`.+ */+export class GroupMetadataCache {+ private readonly entries = new Map<string, CachedGroup>();+ /** Reads under way, so concurrent sends to one group share a single query. */+ 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,+ private readonly maxEntries = 256,+ private readonly now: () => number = Date.now,+ ) {}++ /** A TTL of 0 switches the cache off: Baileys then queries on its own, as it does without one. */+ get enabled(): boolean {+ return this.ttlMs > 0;+ }++ get size(): number {+ return this.entries.size;+ }++ /** The group's metadata if it was read within the TTL; a hit is marked most recently used. */+ peek(jid: string): GroupMetadata | undefined {+ const cached = this.entries.get(jid);+ if (!cached) return undefined;+ if (this.now() - cached.storedAt >= this.ttlMs) {+ this.entries.delete(jid);+ return undefined;+ }+ this.entries.delete(jid);+ this.entries.set(jid, cached);+ return cached.metadata;+ }++ /**+ * The group's metadata from the cache, or from `fetch` (the query Baileys would have made) when it+ * holds none, remembering the answer. Undefined when the cache is off.+ */+ read(jid: string, fetch: () => Promise<GroupMetadata>): Promise<GroupMetadata | undefined> {+ if (!this.enabled) return Promise.resolve(undefined);+ const hit = this.peek(jid);+ 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);+ return metadata;+ } finally {+ this.overtaken.delete(jid);+ this.inFlight.delete(jid);+ }+ })();+ this.inFlight.set(jid, pending);+ return pending;+ }++ /**+ * Replace the copy of a group that is already cached with metadata that arrived whole. A group nobody+ * has sent to is not added: the cache holds what sends use, not every group the account is in.+ */+ refresh(metadata: GroupMetadata): void {+ if (this.enabled && metadata.id && this.entries.has(metadata.id)) this.store(metadata.id, metadata);+ }++ /** Forget one group: its membership or settings changed, so the next send reads it again. */+ invalidate(jid: string | undefined): void {+ if (!jid) return;+ this.entries.delete(jid);+ if (this.inFlight.has(jid)) this.overtaken.add(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);+ }++ /**+ * Apply a `groups.update` batch. A whole-metadata entry (the result of a full group fetch, which+ * Baileys also emits through this event) refreshes the cached copy; a partial one is a real change to+ * some field, so the group is read again on the next send.+ */+ applyUpdates(updates: ReadonlyArray<Partial<GroupMetadata>> | undefined): void {+ for (const update of updates ?? []) {+ if (!update?.id) continue;+ if (Array.isArray(update.participants)) this.refresh(update as GroupMetadata);+ else this.invalidate(update.id);+ }+ }++ private store(jid: string, metadata: GroupMetadata): void {+ this.entries.delete(jid);+ this.entries.set(jid, { metadata, storedAt: this.now() });+ while (this.entries.size > this.maxEntries) {+ const [oldest] = this.entries.keys();+ this.entries.delete(oldest);+ }+ }+}diff --git a/src/engine/adapters/baileys-groups.ts b/src/engine/adapters/baileys-groups.tsindex b7e05ca59..7803e39fe 100644--- a/src/engine/adapters/baileys-groups.ts+++ b/src/engine/adapters/baileys-groups.ts@@ -37,6 +37,8 @@ export interface BaileysGroupsHost {normalizedSelfJid(): string;/** Learn lid->pn pairs (write-through to the persistent table); no-ops pairs missing either side. */addLidMappings(mappings: { lid?: string; pn?: string }[]): void;+ /** Drop the group's cached metadata, which a group send reuses: its members or settings are changing. */+ forgetGroupMetadata?(groupId: string): void;}/**@@ -176,8 +178,14 @@ export class BaileysGroups {* reads as not-found, so it answers 404 as whatsapp-web.js does rather than a 403 permissions* refusal. The w:g2 group IQs are addressed to the group jid, and a leave names only that group.*/- private groupWrite<T>(groupId: string, operation: string, op: () => Promise<T>): Promise<T> {- return mapServerRefusal(operation, op, refusedStatusCode, () => new GroupNotFoundError(groupId));+ private async groupWrite<T>(groupId: string, operation: string, op: () => Promise<T>): Promise<T> {+ try {+ return await mapServerRefusal(operation, op, refusedStatusCode, () => new GroupNotFoundError(groupId));+ } finally {+ // A group write may change who is in the group and how it sends, confirmed or not, so the next send+ // to it reads the group again instead of reusing the participant list cached before.+ this.host.forgetGroupMetadata?.(groupId);+ }}/** Neutral → engine id fold for participant/mention lists. */diff --git a/src/engine/adapters/baileys-lifecycle.ts b/src/engine/adapters/baileys-lifecycle.tsindex 93082521a..ed9c6623d 100644--- a/src/engine/adapters/baileys-lifecycle.ts+++ b/src/engine/adapters/baileys-lifecycle.ts@@ -17,6 +17,7 @@ import { type createLogger } from '../../common/services/logger.service';import { BaileysAdapterConfig } from '../types/baileys.types';import { useAtomicMultiFileAuthState } from './baileys-auth-store';import { createBaileysLogger } from './baileys-logger';+import { GroupMetadataCache, groupMetadataCacheTtlMs } from './baileys-group-metadata-cache';import { BaileysVersionResolver } from './baileys-version-resolver';import { unappliedPatches, unappliedPatchesMessage } from './engine-patch-status';import {@@ -215,6 +216,12 @@ export class BaileysLifecycle {private lib?: typeof BaileysLib;/** The session proxy's fetch dispatcher, built on first use and closed at teardown. */private dispatcher?: Dispatcher;+ /**+ * The participant lists Baileys reuses for group sends instead of querying one per message. Kept up to+ * date by the group events registered below, dropped with every socket (see dropConnectionState).+ * Public so the groups delegate can forget a group right after it changes its membership.+ */+ readonly groupMetadata = new GroupMetadataCache(groupMetadataCacheTtlMs());constructor(private readonly host: BaileysLifecycleHost) {this.versionResolver = new BaileysVersionResolver({@@ -387,8 +394,12 @@ export class BaileysLifecycle {}}+ // Group changes made while the previous socket was down never reached it, so nothing it cached is+ // trusted by the next one.+ this.groupMetadata.clear();+const fetchDispatcher = this.fetchDispatcher();- const sock = b.default({+ const sock: WASocket = b.default({auth: state,version,browser: BAILEYS_BROWSER,@@ -463,6 +474,11 @@ export class BaileysLifecycle {}return stored.message ?? undefined;},+ // Every group send needs the group's participant list, and without this Baileys queries it for each+ // message. Read through the cache, on a miss with the same query Baileys would have made; a failure+ // surfaces as the send's own, exactly as before. 0 in BAILEYS_GROUP_METADATA_CACHE_TTL_MS switches it+ // off, and Baileys then queries on its own.+ cachedGroupMetadata: jid => this.groupMetadata.read(jid, () => sock.groupMetadata(jid)),logger: baileysLogger,});this.sock = sock;@@ -534,9 +550,20 @@ export class BaileysLifecycle {});this.host.removeChats(ids);});- sock.ev.on('group-participants.update', event => this.host.handleGroupParticipantsUpdate(event));- sock.ev.on('groups.update', updates => this.host.handleGroupsUpdate(updates));- sock.ev.on('groups.upsert', groups => this.host.handleGroupsUpsert(groups));+ // The same events keep the group metadata cache honest: a membership change or a (re)join drops that+ // group, a whole-metadata snapshot refreshes it, and any other change makes it read again.+ sock.ev.on('group-participants.update', event => {+ this.groupMetadata.invalidate(event.id);+ this.host.handleGroupParticipantsUpdate(event);+ });+ sock.ev.on('groups.update', updates => {+ this.groupMetadata.applyUpdates(updates);+ this.host.handleGroupsUpdate(updates);+ });+ sock.ev.on('groups.upsert', groups => {+ for (const group of groups) this.groupMetadata.invalidate(group.id);+ this.host.handleGroupsUpsert(groups);+ });sock.ev.on('group.join-request', event => this.host.handleGroupJoinRequest(event));sock.ev.on('messaging-history.set', history => {// A chunk still arriving means the pull could be absorbed into the next one: wait again.@@ -698,7 +725,7 @@ export class BaileysLifecycle {// the operator stops the other instance, then starts this session again (onError = terminal// + evict in the session service). Auth state is NOT cleared: the link itself is still valid.this.setStatus(EngineStatus.FAILED);- this.host.liveCalls.clear(); // terminal close: dead call handles, like the loggedOut branch above+ this.dropConnectionState(); // terminal close: dead call handles, like the loggedOut branch abovethis.host.getOnError()?.(`${CONNECTION_REPLACED_REASON} — stop the other instance, then start this session again`,);@@ -712,7 +739,7 @@ export class BaileysLifecycle {// 401): this is an account-level refusal, not dead credentials — the operator keeps the auth// files for inspection and can retry manually once the account issue is resolved.this.setStatus(EngineStatus.FAILED);- this.host.liveCalls.clear(); // terminal close: dead call handles, like the loggedOut branch above+ this.dropConnectionState(); // terminal close: dead call handles, like the loggedOut branch abovethis.host.getOnError()?.(`${ACCOUNT_REJECTED_REASON} — the number is likely banned or blocked; reconnecting will not help`,);@@ -891,6 +918,16 @@ export class BaileysLifecycle {}}+ /**+ * What lives and dies with a connection: the cached call handles, which a later rejectCall() must+ * report as not-found rather than act on a dead socket, and the group metadata, whose changes the+ * socket stops reporting once it is gone.+ */+ private dropConnectionState(): void {+ this.host.liveCalls.clear();+ this.groupMetadata.clear();+ }+disconnect(): Promise<void> {this.teardown.abort();if (this.reconnectTimer) {@@ -904,7 +941,7 @@ export class BaileysLifecycle {this.closeFetchDispatcher();// Cached call handles die with the socket — drop them so a later rejectCall() reports// not-found instead of acting on a closed connection.- this.host.liveCalls.clear();+ this.dropConnectionState();this.setStatus(EngineStatus.DISCONNECTED);return Promise.resolve();}@@ -991,7 +1028,7 @@ export class BaileysLifecycle {this.closeFetchDispatcher();// Cached call handles die with the connection — drop them so a later rejectCall() reports// not-found (404) instead of acting on a dead socket (mirrors disconnect/destroy).- this.host.liveCalls.clear();+ this.dropConnectionState();if (this.sock === sourceSock) {this.sock = null;}@@ -1017,7 +1054,7 @@ export class BaileysLifecycle {this.sock = null;// Cached call handles die with the connection — drop them so a later rejectCall() reports// not-found (404) instead of acting on a dead socket (mirrors disconnect/logout/destroy).- this.host.liveCalls.clear();+ this.dropConnectionState();// A message still being processed must not recreate a row of the unlinked account after the wipe below.this.host.fenceStoredWrites();void dead?.end(undefined);@@ -1098,7 +1135,7 @@ export class BaileysLifecycle {void this.sock?.end(undefined);this.sock = null;this.closeFetchDispatcher();- this.host.liveCalls.clear();+ this.dropConnectionState();this.setStatus(EngineStatus.DISCONNECTED);return Promise.resolve();}diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex 06a0698e4..0b186bb41 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -10439,3 +10439,166 @@ describe('BaileysAdapter keeps the message store in step with edits and deletes'});});});++describe('BaileysAdapter group metadata cache', () => {+ const GROUP = '[email protected]';+ const TTL_ENV = 'BAILEYS_GROUP_METADATA_CACHE_TTL_MS';+ const savedTtl = process.env[TTL_ENV];+ const meta = (members: string[]) => ({ id: GROUP, subject: 'G', participants: members.map(id => ({ id })) });++ beforeEach(() => {+ fakeSock.user = { id: '628999:[email protected]', name: 'Me' };+ fakeSock.resetEmitter();+ jest.clearAllMocks();+ delete process.env[TTL_ENV];+ fakeSock.groupMetadata.mockReset().mockResolvedValue(meta(['[email protected]']));+ });+ afterEach(() => {+ jest.useRealTimers();+ if (savedTtl === undefined) delete process.env[TTL_ENV];+ else process.env[TTL_ENV] = savedTtl;+ });++ type SocketConfig = { cachedGroupMetadata: (jid: string) => Promise<unknown> };+ const socketConfig = (): SocketConfig => {+ const make = jest.requireMock<{ default: jest.Mock }>('@whiskeysockets/baileys').default;+ const calls = make.mock.calls as Array<[SocketConfig]>;+ return calls[calls.length - 1][0];+ };+ const ready = async (): Promise<BaileysAdapter> => {+ const adapter = newAdapter();+ await adapter.initialize({});+ fakeSock.fire('connection.update', { connection: 'open' });+ return adapter;+ };++ it('answers a group send from the cache after one query', async () => {+ await ready();+ const { cachedGroupMetadata } = socketConfig();++ const first = await cachedGroupMetadata(GROUP);+ const second = await cachedGroupMetadata(GROUP);++ expect(first).toBe(second);+ expect(fakeSock.groupMetadata).toHaveBeenCalledTimes(1);+ expect(fakeSock.groupMetadata).toHaveBeenCalledWith(GROUP);+ });++ it('lets a failed query surface as the send error and tries again on the next send', async () => {+ await ready();+ const { cachedGroupMetadata } = socketConfig();+ fakeSock.groupMetadata.mockRejectedValueOnce(Object.assign(new Error('rate-overlimit'), { data: 429 }));++ await expect(cachedGroupMetadata(GROUP)).rejects.toThrow('rate-overlimit');+ await expect(cachedGroupMetadata(GROUP)).resolves.toMatchObject({ id: GROUP });+ expect(fakeSock.groupMetadata).toHaveBeenCalledTimes(2);+ });++ it('is off when the TTL is 0: the option answers nothing, so Baileys queries on its own', async () => {+ process.env[TTL_ENV] = '0';+ await ready();++ await expect(socketConfig().cachedGroupMetadata(GROUP)).resolves.toBeUndefined();+ expect(fakeSock.groupMetadata).not.toHaveBeenCalled();+ });++ it.each([+ ['a participant is added or removed', 'group-participants.update', { id: GROUP, action: 'add', participants: [] }],+ ['the group changes a setting', 'groups.update', [{ id: GROUP, announce: true }]],+ ['the account is added to the group again', 'groups.upsert', [{ id: GROUP, participants: [] }]],+ ])('reads the group again after %s', async (_label, event, payload) => {+ await ready();+ const { cachedGroupMetadata } = socketConfig();+ await cachedGroupMetadata(GROUP);++ fakeSock.fire(event, payload);+ await cachedGroupMetadata(GROUP);++ expect(fakeSock.groupMetadata).toHaveBeenCalledTimes(2);+ });++ it('refreshes a cached group from a whole snapshot without another query', async () => {+ await ready();+ const { cachedGroupMetadata } = socketConfig();+ await cachedGroupMetadata(GROUP);++ fakeSock.fire('groups.update', [meta(['[email protected]', '[email protected]'])]);+ const refreshed = (await cachedGroupMetadata(GROUP)) as { participants: unknown[] };++ expect(refreshed.participants).toHaveLength(2);+ expect(fakeSock.groupMetadata).toHaveBeenCalledTimes(1);+ });++ it('still reports the group events to consumers while it keeps the cache', async () => {+ const onGroupEvent = jest.fn();+ const adapter = newAdapter();+ await adapter.initialize({ onGroupEvent });+ fakeSock.fire('connection.update', { connection: 'open' });++ fakeSock.fire('group-participants.update', {+ id: GROUP,+ action: 'add',+ participants: ['[email protected]'],+ });++ expect(onGroupEvent).toHaveBeenCalledWith(expect.objectContaining({ kind: 'join', groupId: GROUP }));+ });++ it.each([+ ['addParticipants', (a: BaileysAdapter) => a.addParticipants(GROUP, ['[email protected]'])],+ ['removeParticipants', (a: BaileysAdapter) => a.removeParticipants(GROUP, ['[email protected]'])],+ ['leaveGroup', (a: BaileysAdapter) => a.leaveGroup(GROUP)],+ ])('reads the group again after %s, whether or not WhatsApp has reported the change yet', async (_label, write) => {+ const adapter = await ready();+ const { cachedGroupMetadata } = socketConfig();+ await cachedGroupMetadata(GROUP);++ await write(adapter);+ await cachedGroupMetadata(GROUP);++ expect(fakeSock.groupMetadata).toHaveBeenCalledTimes(2);+ });++ it('forgets a group when its write fails too, since the outcome may be partial', async () => {+ const adapter = await ready();+ const { cachedGroupMetadata } = socketConfig();+ await cachedGroupMetadata(GROUP);+ fakeSock.groupLeave.mockRejectedValueOnce(new Error('connection closed'));++ await expect(adapter.leaveGroup(GROUP)).rejects.toThrow();+ await cachedGroupMetadata(GROUP);++ expect(fakeSock.groupMetadata).toHaveBeenCalledTimes(2);+ });++ it('starts every new socket with an empty cache', async () => {+ const adapter = await ready();+ await socketConfig().cachedGroupMetadata(GROUP);++ // A transient drop: the lifecycle builds a fresh socket without going through a teardown.+ jest.useFakeTimers();+ fakeSock.fire('connection.update', {+ connection: 'close',+ lastDisconnect: { error: { output: { statusCode: 515 } } },+ });+ await jest.runAllTimersAsync();+ await socketConfig().cachedGroupMetadata(GROUP);++ expect(fakeSock.groupMetadata).toHaveBeenCalledTimes(2);+ await adapter.destroy();+ });++ it.each([+ ['disconnect', (a: BaileysAdapter) => a.disconnect()],+ ['destroy', (a: BaileysAdapter) => a.destroy()],+ ])('empties the cache on %s', async (_label, tearDown) => {+ const adapter = await ready();+ const { cachedGroupMetadata } = socketConfig();+ await cachedGroupMetadata(GROUP);++ await tearDown(adapter);+ await cachedGroupMetadata(GROUP);++ expect(fakeSock.groupMetadata).toHaveBeenCalledTimes(2);+ });+});diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.tsindex 0bfe39f8f..4d529b299 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -171,6 +171,7 @@ export class BaileysAdapter implements IWhatsAppEngine {ensureReady: () => this.ensureReady(),toEngineJid: jid => this.sessionStore.toEngineJid(jid),chatJid: chatId => this.sessionStore.chatJid(chatId),+ forgetGroupMetadata: groupId => this.lifecycle.groupMetadata.invalidate(groupId),getEphemeralExpiration: chatId => this.sessionStore.getEphemeralExpiration(chatId),getStoredMessage: messageId => this.config.messageStore?.getMessage(this.config.dbSessionId, messageId),getStoredMessages: messageIds => this.config.messageStore?.getMessages(this.config.dbSessionId, messageIds),