Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

refactor(session): extract SessionLidResolver

Yudhi Armyndharisce480d41d4f8
diff --git a/src/modules/session/logout-teardown-race.spec.ts b/src/modules/session/logout-teardown-race.spec.ts
index 0efc13704..8833a5f92 100644
--- a/src/modules/session/logout-teardown-race.spec.ts
+++ b/src/modules/session/logout-teardown-race.spec.ts
@@ -8,6 +8,7 @@ import { Session, SessionStatus } from './entities/session.entity';
import { Message } from '../message/entities/message.entity';
import { EngineFactory } from '../../engine/engine.factory';
import { EngineRegistry } from '../../engine/engine-registry.service';
+import { SessionLidResolver } from './session-lid-resolver.service';
import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';
import { EventsGateway } from '../events/events.gateway';
import { WebhookService } from '../webhook/webhook.service';
@@ -92,6 +93,7 @@ describe('SessionService logout() name-scoped teardown fence', () => {
{ provide: EngineFactory, useValue: engineFactory },
// Real registry: this suite asserts on engine map state across the teardown fence.
EngineRegistry,
+ SessionLidResolver,
{
provide: EventsGateway,
useValue: { emitSessionStatus: jest.fn(), emitSessionDisconnected: jest.fn(), emitQRCode: jest.fn() },
diff --git a/src/modules/session/session-lid-resolver.service.spec.ts b/src/modules/session/session-lid-resolver.service.spec.ts
new file mode 100644
index 000000000..ebfd811a6
--- /dev/null
+++ b/src/modules/session/session-lid-resolver.service.spec.ts
@@ -0,0 +1,108 @@
+import { SessionLidResolver } from './session-lid-resolver.service';
+import { EngineRegistry } from '../../engine/engine-registry.service';
+import type { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';
+import type { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';
+
+describe('SessionLidResolver', () => {
+ let engines: EngineRegistry;
+ let resolveContactPhone: jest.Mock;
+ let remember: jest.Mock;
+ let resolver: SessionLidResolver;
+
+ beforeEach(() => {
+ engines = new EngineRegistry();
+ resolveContactPhone = jest.fn().mockResolvedValue('628111222333');
+ engines.set('s1', { resolveContactPhone } as unknown as IWhatsAppEngine);
+ remember = jest.fn().mockResolvedValue(undefined);
+ resolver = new SessionLidResolver(engines, { remember } as unknown as LidMappingStoreService);
+ });
+
+ it('resolves a phone through the engine', async () => {
+ await expect(resolver.resolveSenderPhone('s1', '111@lid')).resolves.toBe('628111222333');
+ expect(resolveContactPhone).toHaveBeenCalledWith('111@lid');
+ });
+
+ it('caches a hit so a chatty sender is queried once', async () => {
+ await resolver.resolveSenderPhone('s1', '111@lid');
+ await resolver.resolveSenderPhone('s1', '111@lid');
+
+ expect(resolveContactPhone).toHaveBeenCalledTimes(1);
+ });
+
+ it('caches a miss too, so an unmapped sender does not re-query every message', async () => {
+ resolveContactPhone.mockResolvedValue(null);
+
+ await expect(resolver.resolveSenderPhone('s1', '404@lid')).resolves.toBeNull();
+ await expect(resolver.resolveSenderPhone('s1', '404@lid')).resolves.toBeNull();
+
+ expect(resolveContactPhone).toHaveBeenCalledTimes(1);
+ });
+
+ it('keys the cache per session, so two sessions resolve independently', async () => {
+ engines.set('s2', { resolveContactPhone } as unknown as IWhatsAppEngine);
+
+ await resolver.resolveSenderPhone('s1', '111@lid');
+ await resolver.resolveSenderPhone('s2', '111@lid');
+
+ expect(resolveContactPhone).toHaveBeenCalledTimes(2);
+ });
+
+ it('returns null (never throws) when the engine rejects', async () => {
+ resolveContactPhone.mockRejectedValue(new Error('socket closed'));
+
+ await expect(resolver.resolveSenderPhone('s1', '111@lid')).resolves.toBeNull();
+ });
+
+ it('returns null when the session has no live engine', async () => {
+ await expect(resolver.resolveSenderPhone('not-started', '111@lid')).resolves.toBeNull();
+ });
+
+ it('persists a real resolution to the shared lid mapping store', async () => {
+ await resolver.resolveSenderPhone('s1', '111@lid');
+
+ expect(remember).toHaveBeenCalledWith('111', '628111222333', 's1');
+ });
+
+ it('does not persist a miss', async () => {
+ resolveContactPhone.mockResolvedValue(null);
+
+ await resolver.resolveSenderPhone('s1', '404@lid');
+
+ expect(remember).not.toHaveBeenCalled();
+ });
+
+ it('never rejects when the mapping store write fails (fire-and-forget)', async () => {
+ remember.mockRejectedValue(new Error('db down'));
+
+ await expect(resolver.resolveSenderPhone('s1', '111@lid')).resolves.toBe('628111222333');
+ });
+
+ it('works without a mapping store at all (optional dependency)', async () => {
+ const bare = new SessionLidResolver(engines);
+
+ await expect(bare.resolveSenderPhone('s1', '111@lid')).resolves.toBe('628111222333');
+ });
+
+ it('evicts the oldest entry once the cache is full, bounding memory', async () => {
+ const max = 5000;
+ // Fill past the cap; the first key inserted must be the one evicted (FIFO).
+ for (let i = 0; i < max; i++) {
+ resolveContactPhone.mockResolvedValue(`phone-${i}`);
+ await resolver.resolveSenderPhone('s1', `${i}@lid`);
+ }
+ expect(resolveContactPhone).toHaveBeenCalledTimes(max);
+
+ // One more insert evicts the oldest ('0@lid').
+ resolveContactPhone.mockResolvedValue('phone-new');
+ await resolver.resolveSenderPhone('s1', 'new@lid');
+
+ // The evicted key must be re-queried; a still-cached one must not be.
+ resolveContactPhone.mockClear();
+ await resolver.resolveSenderPhone('s1', '0@lid');
+ expect(resolveContactPhone).toHaveBeenCalledTimes(1);
+
+ resolveContactPhone.mockClear();
+ await resolver.resolveSenderPhone('s1', `${max - 1}@lid`);
+ expect(resolveContactPhone).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/modules/session/session-lid-resolver.service.ts b/src/modules/session/session-lid-resolver.service.ts
new file mode 100644
index 000000000..fb17d103c
--- /dev/null
+++ b/src/modules/session/session-lid-resolver.service.ts
@@ -0,0 +1,65 @@
+import { Injectable, Optional } from '@nestjs/common';
+import { EngineRegistry } from '../../engine/engine-registry.service';
+import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';
+import { userPart } from '../../engine/identity/wa-id';
+
+/**
+ * Resolves a privacy-id sender (`@lid`) to a phone number for inline attachment on incoming
+ * messages (#263).
+ *
+ * Split out of SessionService because it is a self-contained read-through cache over the engine: it
+ * has no lifecycle state, cannot fail the message path, and its only collaborators are the engine
+ * registry and the shared lid<->phone table. Keeping it here means the eviction policy and the
+ * fire-and-forget persistence are testable without standing up the whole session lifecycle.
+ */
+@Injectable()
+export class SessionLidResolver {
+ /**
+ * Bounded cache keyed `${sessionId}:${lid}`. Caches misses (null) too, so a chatty unmapped sender
+ * isn't re-queried on every message (which also reduces engine rate-limit pressure). Best-effort
+ * feature, so staleness is acceptable.
+ */
+ private readonly cache = new Map<string, string | null>();
+ private static readonly CACHE_MAX = 5000;
+
+ constructor(
+ private readonly engines: EngineRegistry,
+ // Shared lid<->phone table (global). Used to persist an inbound @lid sender's resolved phone so
+ // an inbound-only migrated contact's `@lid` and `@c.us` rows bridge in the read-path (#583 R3 Ph2).
+ @Optional()
+ private readonly lidMappingStore?: LidMappingStoreService,
+ ) {}
+
+ /**
+ * Best-effort resolution, cached per session (incl. misses). Never throws — returns null on any
+ * failure or when the engine isn't available. Gated by the caller on `RESOLVE_LID_TO_PHONE`.
+ */
+ async resolveSenderPhone(sessionId: string, contactId: string): Promise<string | null> {
+ const key = `${sessionId}:${contactId}`;
+ const cached = this.cache.get(key);
+ if (cached !== undefined) {
+ return cached;
+ }
+ let phone: string | null;
+ try {
+ phone = (await this.engines.get(sessionId)?.resolveContactPhone(contactId)) ?? null;
+ } catch {
+ phone = null;
+ }
+ // Bounded FIFO eviction: Map preserves insertion order, so the first key is the oldest.
+ if (this.cache.size >= SessionLidResolver.CACHE_MAX) {
+ for (const oldest of this.cache.keys()) {
+ this.cache.delete(oldest);
+ break;
+ }
+ }
+ this.cache.set(key, phone);
+ // Persist a real @lid -> phone resolution so the read-path can bridge this contact's `@lid` and
+ // `@c.us` rows even when the operator never sent to them (#583 R3 Phase 2). Reuses the resolution
+ // above — no extra network call — and is fire-and-forget so dispatch never blocks/fails on it.
+ if (phone) {
+ void this.lidMappingStore?.remember(userPart(contactId), phone, sessionId)?.catch(() => {});
+ }
+ return phone;
+ }
+}
diff --git a/src/modules/session/session.module.ts b/src/modules/session/session.module.ts
index ea67c464b..063217211 100644
--- a/src/modules/session/session.module.ts
+++ b/src/modules/session/session.module.ts
@@ -3,6 +3,7 @@ import { TypeOrmModule } from '@nestjs/typeorm';
import { Session } from './entities/session.entity';
import { Message } from '../message/entities/message.entity';
import { SessionService } from './session.service';
+import { SessionLidResolver } from './session-lid-resolver.service';
import { SessionController } from './session.controller';
import { WebhookModule } from '../webhook/webhook.module';
import { StatusStoreModule } from '../status-store/status-store.module';
@@ -12,7 +13,7 @@ import { StatusStoreModule } from '../status-store/status-store.module';
// one-directional — no forwardRef() needed.
imports: [TypeOrmModule.forFeature([Session, Message], 'data'), WebhookModule, StatusStoreModule],
controllers: [SessionController],
- providers: [SessionService],
+ providers: [SessionService, SessionLidResolver],
exports: [SessionService],
})
export class SessionModule {}
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index 001e92698..aa72fdc1c 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -25,6 +25,7 @@ import { Template } from '../template/entities/template.entity';
import { BaileysStoredMessage } from '../../engine/adapters/baileys-stored-message.entity';
import { EngineFactory } from '../../engine/engine.factory';
import { EngineRegistry } from '../../engine/engine-registry.service';
+import { SessionLidResolver } from './session-lid-resolver.service';
import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';
import { EventsGateway } from '../events/events.gateway';
import { WebhookService } from '../webhook/webhook.service';
@@ -202,6 +203,7 @@ describe('SessionService', () => {
// and writes on every lifecycle path, and the identity semantics (isLive/deleteIfLive) are
// exactly what the stale-callback tests below exercise. Its own unit tests cover it directly.
EngineRegistry,
+ SessionLidResolver,
{ provide: EventsGateway, useValue: eventsGateway },
{ provide: WebhookService, useValue: webhookService },
{ provide: HookManager, useValue: hookManager },
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index 14938abcc..bd32079fc 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -24,9 +24,8 @@ import { BaileysStoredMessage } from '../../engine/adapters/baileys-stored-messa
import { CreateSessionDto } from './dto';
import { EngineFactory } from '../../engine/engine.factory';
import { EngineRegistry } from '../../engine/engine-registry.service';
+import { SessionLidResolver } from './session-lid-resolver.service';
import { resolveAuthTimeoutMs } from '../../engine/adapters/whatsapp-web-js.adapter';
-import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';
-import { userPart } from '../../engine/identity/wa-id';
import { paginate, ListOptions, resolveListWindow } from '../../common/utils/paginate';
import { isUniqueConstraintError } from '../../common/utils/unique-constraint.util';
import { resolveFeatureFlags } from '../../config/feature-flags';
@@ -196,11 +195,6 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
private get engines(): EngineRegistry {
return this.engineRegistry;
}
- // Bounded cache for inline @lid -> phone resolution (#263), keyed `${sessionId}:${lid}`. Caches
- // misses (null) too, so a chatty unmapped sender isn't re-queried on every message (which also
- // reduces engine rate-limit pressure). Best-effort feature, so staleness is acceptable.
- private readonly lidPhoneCache = new Map<string, string | null>();
- private static readonly LID_PHONE_CACHE_MAX = 5000;
// Transient, human-readable reason for the most recent terminal engine failure,
// keyed by session id. Surfaced on read so the dashboard can explain a FAILED
// status; cleared when the session re-initializes or becomes ready.
@@ -286,16 +280,13 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
private readonly dataSource: DataSource,
private readonly engineFactory: EngineFactory,
private readonly engineRegistry: EngineRegistry,
+ private readonly lidResolver: SessionLidResolver,
private readonly eventsGateway: EventsGateway,
private readonly webhookService: WebhookService,
private readonly hookManager: HookManager,
private readonly statusStore: StatusStoreService,
@Optional()
private readonly configService?: ConfigService,
- // Shared lid<->phone table (global). Used to persist an inbound @lid sender's resolved phone so
- // an inbound-only migrated contact's `@lid` and `@c.us` rows bridge in the read-path (#583 R3 Ph2).
- @Optional()
- private readonly lidMappingStore?: LidMappingStoreService,
// Draining flag (set on a termination signal or an admin restart). Used to suppress a mid-shutdown
// reconnect that would launch a fresh Chromium racing onModuleDestroy's teardown. @Optional so the
// service degrades to today's behaviour if it is ever constructed without the (global) LoggerModule.
@@ -1326,7 +1317,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
// attaches senderPhone (digits or null) before persist/dispatch so webhook/ws consumers
// get it in a single pass. Only for privacy-id senders, so no lookup for normal numbers.
if (resolveFeatureFlags(this.configService).resolveLidToPhone && incoming.isLidSender && !incoming.fromMe) {
- incoming.senderPhone = await this.resolveSenderPhone(id, incoming.author ?? incoming.from);
+ incoming.senderPhone = await this.lidResolver.resolveSenderPhone(id, incoming.author ?? incoming.from);
}
const metadata: Record<string, unknown> = {};
@@ -2694,40 +2685,6 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
return this.engines.get(id);
}
- /**
- * Best-effort resolution of a privacy-id sender (`@lid`) to a phone number for inline attachment on
- * incoming messages (#263). Cached per session (incl. misses). Never throws — returns null on any
- * failure or when the engine isn't available. Gated by the caller on `RESOLVE_LID_TO_PHONE`.
- */
- private async resolveSenderPhone(sessionId: string, contactId: string): Promise<string | null> {
- const key = `${sessionId}:${contactId}`;
- const cached = this.lidPhoneCache.get(key);
- if (cached !== undefined) {
- return cached;
- }
- let phone: string | null;
- try {
- phone = (await this.getEngine(sessionId)?.resolveContactPhone(contactId)) ?? null;
- } catch {
- phone = null;
- }
- // Bounded FIFO eviction: Map preserves insertion order, so the first key is the oldest.
- if (this.lidPhoneCache.size >= SessionService.LID_PHONE_CACHE_MAX) {
- for (const oldest of this.lidPhoneCache.keys()) {
- this.lidPhoneCache.delete(oldest);
- break;
- }
- }
- this.lidPhoneCache.set(key, phone);
- // Persist a real @lid -> phone resolution so the read-path can bridge this contact's `@lid` and
- // `@c.us` rows even when the operator never sent to them (#583 R3 Phase 2). Reuses the resolution
- // above — no extra network call — and is fire-and-forget so dispatch never blocks/fails on it.
- if (phone) {
- void this.lidMappingStore?.remember(userPart(contactId), phone, sessionId)?.catch(() => {});
- }
- return phone;
- }
-
async getGroups(
id: string,
opts: ListOptions = {},