Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
test(session): give the lifecycle fences and status broadcaster direct specs
Yudhi Armyndharisb3ed6cc1581e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 76f09b960..6759861bf 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- The lifecycle fences (teardown chaining, fail-closed 409, identity-checked initial-status waits, force-destroy eviction) and the status broadcaster (persist-then-mirror, transition de-dup, clear-on-delete) carry their own unit specs instead of being reachable only through the session-service suite's white-box pokes.- Follow-ups: the transient-launch classifier rejects every HttpException up front (the 504 no-retry no longer rests on message wording) and recognizes ECONNRESET; the sendTemplate 404 description names only the template; import-status normalization comments and the parity-fence failure messages state their exact scope.- GET /contacts/:id/phone keeps its documented 400/409 answers (not-started, not-ready) and nulls only genuine lookup failures, logging them at debug; the boundary swallow had absorbed the deliberate errors too.- A transient session-launch failure (dead page at initialize, a database hiccup) gets one bounded retry that keeps the claim held; adopt and boot auto-start used to release the claim and leave the session down until a restart.diff --git a/src/modules/session/session-lifecycle-fences.spec.ts b/src/modules/session/session-lifecycle-fences.spec.tsnew file mode 100644index 000000000..872f10ceb--- /dev/null+++ b/src/modules/session/session-lifecycle-fences.spec.ts@@ -0,0 +1,174 @@+import { ConflictException } from '@nestjs/common';+import { EngineRegistry } from '../../engine/engine-registry.service';+import { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';+import { SessionLifecycleFences } from './session-lifecycle-fences';++/**+ * Direct invariant coverage for the credential-teardown / initial-status fences. Until now these+ * semantics were pinned only through the session-service suite's white-box pokes on the lifecycle's+ * fields; these specs name the invariants (INV-8's fence, the fail-closed 409, the settlement+ * chaining, the identity-checked removals) against the unit itself.+ */+describe('SessionLifecycleFences', () => {+ const engine = (over: Partial<IWhatsAppEngine> = {}): IWhatsAppEngine => over as IWhatsAppEngine;++ const makeFences = () => {+ const engines = new EngineRegistry();+ const pendingTeardowns = new Map<string, Promise<void>>();+ const pendingInitialStatuses = new Map<string, { engine: IWhatsAppEngine; promise: Promise<void> }>();+ const fences = new SessionLifecycleFences({+ engines,+ pendingTeardowns,+ pendingInitialStatuses,+ logger: console as never,+ });+ return { fences, engines, pendingTeardowns, pendingInitialStatuses };+ };++ describe('teardownEngineSafely', () => {+ it('resolves true when the teardown completes', async () => {+ const { fences } = makeFences();+ const destroy = jest.fn().mockResolvedValue(undefined);+ await expect(fences.teardownEngineSafely('s1', engine({ destroy }), e => e.destroy(), 'destroy')).resolves.toBe(+ true,+ );+ expect(destroy).toHaveBeenCalledTimes(1);+ });++ it('resolves false (never rejects) when the teardown throws, so the caller can reconcile the map anyway', async () => {+ const { fences } = makeFences();+ const destroy = jest.fn().mockRejectedValue(new Error('Target closed'));+ await expect(fences.teardownEngineSafely('s1', engine({ destroy }), e => e.destroy(), 'destroy')).resolves.toBe(+ false,+ );+ });++ it('tracks the RAW logout promise under the session NAME before racing the deadline', async () => {+ const { fences, pendingTeardowns } = makeFences();+ let settle!: () => void;+ const logout = jest.fn().mockImplementation(() => new Promise<void>(resolve => (settle = resolve)));+ const pending = fences.teardownEngineSafely('s1', engine({ logout }), e => e.logout(), 'logout', 'main');+ expect(pendingTeardowns.has('main')).toBe(true);+ settle();+ await expect(pending).resolves.toBe(true);+ });+ });++ describe('trackPendingCredentialTeardown', () => {+ it('chains a concurrent teardown onto the previous entry instead of overwriting it', async () => {+ const { fences, pendingTeardowns } = makeFences();+ let settleFirst!: () => void;+ const first = new Promise<void>(resolve => (settleFirst = resolve));+ fences.trackPendingCredentialTeardown('main', first);++ let settleSecond!: () => void;+ const second = new Promise<void>(resolve => (settleSecond = resolve));+ fences.trackPendingCredentialTeardown('main', second);++ // The FIRST settling alone must not drop the entry: the second teardown is still in flight.+ settleFirst();+ await Promise.resolve();+ await Promise.resolve();+ expect(pendingTeardowns.has('main')).toBe(true);++ settleSecond();+ await pendingTeardowns.get('main');+ await Promise.resolve();+ await Promise.resolve();+ await Promise.resolve();+ expect(pendingTeardowns.has('main')).toBe(false);+ });++ it('never rejects the tracked entry even when the raw teardown rejects', async () => {+ const { fences, pendingTeardowns } = makeFences();+ fences.trackPendingCredentialTeardown('main', Promise.reject(new Error('rm failed')));+ await expect(pendingTeardowns.get('main')).resolves.toBeUndefined();+ });+ });++ describe('awaitPendingTeardown (fail-closed fence, INV-8)', () => {+ it('is a no-op when nothing is pending under the name', async () => {+ const { fences } = makeFences();+ await expect(fences.awaitPendingTeardown('main')).resolves.toBeUndefined();+ });++ it('resolves once the tracked teardown settles', async () => {+ const { fences } = makeFences();+ let settle!: () => void;+ fences.trackPendingCredentialTeardown('main', new Promise<void>(resolve => (settle = resolve)));+ settle();+ await expect(fences.awaitPendingTeardown('main')).resolves.toBeUndefined();+ });++ it('refuses with the retryable 409 SESSION_NAME_TEARDOWN_PENDING when the bound is exhausted', async () => {+ const { fences, pendingTeardowns } = makeFences();+ jest.useFakeTimers();+ try {+ fences.trackPendingCredentialTeardown('main', new Promise<void>(() => undefined));+ const waiting = fences.awaitPendingTeardown('main');+ jest.advanceTimersByTime(10_001);+ await expect(waiting).rejects.toMatchObject({+ status: 409,+ response: { code: 'SESSION_NAME_TEARDOWN_PENDING' },+ });+ expect(ConflictException).toBeDefined();+ // Fail closed: the entry survives so a retry after settlement can proceed.+ expect(pendingTeardowns.has('main')).toBe(true);+ } finally {+ jest.useRealTimers();+ }+ });+ });++ describe('awaitInitialStatus (control action stays the final persisted owner)', () => {+ it('awaits ONLY the captured engine entry, never a replacement', async () => {+ const { fences, pendingInitialStatuses } = makeFences();+ const engineA = engine();+ const engineB = engine();+ let settleA!: () => void;+ const promiseA = new Promise<void>(resolve => (settleA = resolve));+ pendingInitialStatuses.set('s1', { engine: engineA, promise: promiseA });++ const waiting = fences.awaitInitialStatus('s1', engineB);+ // engineB's await must NOT wait on engineA's promise: it settles immediately.+ await expect(waiting).resolves.toBeUndefined();++ // And the entry for A is untouched by B's call.+ expect(pendingInitialStatuses.get('s1')?.engine).toBe(engineA);+ settleA();+ });++ it('awaits the captured engine entry when identities match', async () => {+ const { fences, pendingInitialStatuses } = makeFences();+ const engineA = engine();+ let settle!: () => void;+ pendingInitialStatuses.set('s1', { engine: engineA, promise: new Promise<void>(resolve => (settle = resolve)) });++ let settled = false;+ const waiting = fences.awaitInitialStatus('s1', engineA).then(() => (settled = true));+ await Promise.resolve();+ expect(settled).toBe(false);+ settle();+ await waiting;+ expect(settled).toBe(true);+ });+ });++ describe('evictAndForceDestroy', () => {+ it('removes the engine from the registry and force-destroys (never graceful destroy)', async () => {+ const { fences, engines } = makeFences();+ const forceDestroy = jest.fn().mockResolvedValue(undefined);+ const destroy = jest.fn().mockResolvedValue(undefined);+ const e = engine({ forceDestroy, destroy });+ engines.set('s1', e);++ fences.evictAndForceDestroy('s1', e);++ expect(engines.has('s1')).toBe(false);+ await Promise.resolve();+ await Promise.resolve();+ expect(forceDestroy).toHaveBeenCalledTimes(1);+ expect(destroy).not.toHaveBeenCalled();+ });+ });+});diff --git a/src/modules/session/session-status-broadcaster.spec.ts b/src/modules/session/session-status-broadcaster.spec.tsnew file mode 100644index 000000000..63c417bd5--- /dev/null+++ b/src/modules/session/session-status-broadcaster.spec.ts@@ -0,0 +1,73 @@+import { Repository } from 'typeorm';+import { Session, SessionStatus } from './entities/session.entity';+import { SessionStatusBroadcaster } from './session-status-broadcaster';++/**+ * Direct coverage for the session-status fan-out: persist first, then mirror to WS and webhooks,+ * de-duped per status value (some engines signal one transition via BOTH onStateChanged and a+ * dedicated callback). Until now pinned only through the session-service suite's white-box pokes on+ * the lifecycle's lastDispatchedStatus alias.+ */+describe('SessionStatusBroadcaster', () => {+ const make = () => {+ const update = jest.fn().mockResolvedValue({ affected: 1 });+ const repository = { update } as unknown as Repository<Session>;+ const emitSessionStatus = jest.fn();+ const dispatch = jest.fn().mockResolvedValue(undefined);+ const broadcaster = new SessionStatusBroadcaster({+ sessionRepository: repository,+ eventsGateway: { emitSessionStatus } as never,+ webhookService: { dispatch } as never,+ logger: console as never,+ });+ return { broadcaster, update, emitSessionStatus, dispatch };+ };++ it('persists the status BEFORE mirroring it (the row is the source of truth)', async () => {+ const { broadcaster, update, emitSessionStatus } = make();+ await broadcaster.updateStatus('s1', SessionStatus.READY);+ expect(update).toHaveBeenCalledWith('s1', { status: SessionStatus.READY });+ expect(emitSessionStatus).toHaveBeenCalledWith('s1', SessionStatus.READY);+ });++ it('mirrors to WS and dispatches the session.status webhook on a transition', async () => {+ const { broadcaster, emitSessionStatus, dispatch } = make();+ await broadcaster.updateStatus('s1', SessionStatus.QR_READY);+ expect(emitSessionStatus).toHaveBeenCalledTimes(1);+ expect(dispatch).toHaveBeenCalledWith('s1', 'session.status', {+ sessionId: 's1',+ status: SessionStatus.QR_READY,+ });+ });++ it('de-dups the SAME status signalled twice (onStateChanged + a dedicated callback)', async () => {+ const { broadcaster, emitSessionStatus, dispatch } = make();+ await broadcaster.updateStatus('s1', SessionStatus.READY);+ await broadcaster.updateStatus('s1', SessionStatus.READY);+ expect(emitSessionStatus).toHaveBeenCalledTimes(1);+ expect(dispatch).toHaveBeenCalledTimes(1);+ });++ it('re-emits when the status actually CHANGES back and forth', async () => {+ const { broadcaster, emitSessionStatus } = make();+ await broadcaster.updateStatus('s1', SessionStatus.READY);+ await broadcaster.updateStatus('s1', SessionStatus.DISCONNECTED);+ await broadcaster.updateStatus('s1', SessionStatus.READY);+ expect(emitSessionStatus).toHaveBeenCalledTimes(3);+ });++ it('persists EVERY call even when the mirror is de-duped (the row is not the mirror)', async () => {+ const { broadcaster, update } = make();+ await broadcaster.updateStatus('s1', SessionStatus.READY);+ await broadcaster.updateStatus('s1', SessionStatus.READY);+ expect(update).toHaveBeenCalledTimes(2);+ });++ it('clear() drops the de-dup entry so the same status re-emits after a delete-cycle', async () => {+ const { broadcaster, emitSessionStatus } = make();+ await broadcaster.updateStatus('s1', SessionStatus.READY);+ broadcaster.clear('s1');+ await broadcaster.updateStatus('s1', SessionStatus.READY);+ expect(emitSessionStatus).toHaveBeenCalledTimes(2);+ });+});