Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

refactor(integration): drop the SessionModule import in favor of narrower deps

Yudhi Armyndharisebf380bd5eec
diff --git a/src/modules/integration/integration-instance.controller.spec.ts b/src/modules/integration/integration-instance.controller.spec.ts
index aadd5f5bb..b9d80ae74 100644
--- a/src/modules/integration/integration-instance.controller.spec.ts
+++ b/src/modules/integration/integration-instance.controller.spec.ts
@@ -5,12 +5,13 @@ import { PluginLoaderService } from '../../core/plugins/plugin-loader.service';
import { AuditAction } from '../audit/entities/audit-log.entity';
import { AuditService } from '../audit/audit.service';
import { ScopeBindingService } from './scope-binding.service';
-import { SessionService } from '../session/session.service';
+import { Repository } from 'typeorm';
+import { Session } from '../session/entities/session.entity';
import { ApiKey } from '../auth/entities/api-key.entity';
// ScopeBindingService reads session rows only for its boot-time "this scope matches no session"
// warning; provisioning never reaches it, so these tests hand it a resolving stub.
-const sessions = { findOne: jest.fn().mockResolvedValue({ id: 'sess-1' }) } as unknown as SessionService;
+const sessions = { findOne: jest.fn().mockResolvedValue({ id: 'sess-1' }) } as unknown as Repository<Session>;
// The provisioning bridge is what makes a minted instance's config reach the ingress worker: on
// create/patch it mirrors the instance config into the plugin's per-session config and activates the
diff --git a/src/modules/integration/integration-queue-wiring.spec.ts b/src/modules/integration/integration-queue-wiring.spec.ts
index ed2b93fd0..84df55fa4 100644
--- a/src/modules/integration/integration-queue-wiring.spec.ts
+++ b/src/modules/integration/integration-queue-wiring.spec.ts
@@ -77,6 +77,8 @@ describe('IntegrationModule queue wiring (QUEUE_ENABLED conditional)', () => {
require('../../core/plugins/plugins.module') as typeof import('../../core/plugins/plugins.module');
const { AuditService } = require('../audit/audit.service') as typeof import('../audit/audit.service');
const { EventsGateway } = require('../events/events.gateway') as typeof import('../events/events.gateway');
+ const { EngineRegistry } =
+ require('../../engine/engine-registry.service') as typeof import('../../engine/engine-registry.service');
const { QueueModule } = require('../queue/queue.module') as typeof import('../queue/queue.module');
const { QUEUE_NAMES } = require('../queue/queue-names') as typeof import('../queue/queue-names');
/* eslint-enable @typescript-eslint/no-require-imports */
@@ -97,8 +99,12 @@ describe('IntegrationModule queue wiring (QUEUE_ENABLED conditional)', () => {
{ provide: getDataSourceToken('data'), useValue: dataSourceStub },
{ provide: AuditService, useValue: { record: jest.fn() } },
{ provide: EventsGateway, useValue: {} },
+ // IngressService's liveness probe reads this registry (EngineModule is @Global in the real
+ // app, imported once by app.module.ts; this spec never boots that far, so it is stubbed the
+ // same way as the other app-level globals above).
+ { provide: EngineRegistry, useValue: {} },
],
- exports: [getDataSourceToken('data'), AuditService, EventsGateway],
+ exports: [getDataSourceToken('data'), AuditService, EventsGateway, EngineRegistry],
};
const moduleRef = await Test.createTestingModule({
diff --git a/src/modules/integration/integration.module.ts b/src/modules/integration/integration.module.ts
index a5ecf862b..a3bf59a34 100644
--- a/src/modules/integration/integration.module.ts
+++ b/src/modules/integration/integration.module.ts
@@ -16,8 +16,8 @@ import { IntegrationRetentionService } from './integration-retention.service';
import { IntegrationInstanceController } from './integration-instance.controller';
import { ScopeBindingService } from './scope-binding.service';
import { PluginLoaderService } from '../../core/plugins/plugin-loader.service';
-import { SessionModule } from '../session/session.module';
-import { SessionService } from '../session/session.service';
+import { EngineRegistry } from '../../engine/engine-registry.service';
+import { Session } from '../session/entities/session.entity';
import { createLogger } from '../../common/services/logger.service';
/**
@@ -43,8 +43,7 @@ if (process.env.QUEUE_ENABLED === 'true') {
@Module({
imports: [
- SessionModule,
- TypeOrmModule.forFeature([PluginInstance, IngressEvent, IntegrationDeliveryFailure], 'data'),
+ TypeOrmModule.forFeature([PluginInstance, IngressEvent, IntegrationDeliveryFailure, Session], 'data'),
...queueModules,
],
controllers: [IngressController, RedriveController, IntegrationInstanceController],
@@ -64,7 +63,7 @@ if (process.env.QUEUE_ENABLED === 'true') {
PluginLoaderService,
IngressEnqueueService,
getRepositoryToken(IntegrationDeliveryFailure, 'data'),
- SessionService,
+ EngineRegistry,
],
useFactory: (
instances: PluginInstanceService,
@@ -72,7 +71,7 @@ if (process.env.QUEUE_ENABLED === 'true') {
loader: PluginLoaderService,
ingressEnqueue: IngressEnqueueService,
failures: Repository<IntegrationDeliveryFailure>,
- sessions: SessionService,
+ registry: EngineRegistry,
) => {
const dlqLogger = createLogger('IngressEnqueue');
const ingressLogger = createLogger('Ingress');
@@ -84,7 +83,7 @@ if (process.env.QUEUE_ENABLED === 'true') {
// O(1) in-memory liveness probe for the `session-alive` preflight: a Map read + a field read.
// MUST stay cheap — never call engine.initialize() here (that is the slow/blocking path bounded
// separately by the #667/#696 init-timeout). Undefined = no live engine (stopped/deleted).
- sessionStatus: (scope: string) => sessions.getEngine(scope)?.getStatus(),
+ sessionStatus: (scope: string) => registry.get(scope)?.getStatus(),
// Audit sink for preflight rejections (they leave no dedup/DLQ row). The Prometheus counter is
// a separate follow-up (see plan notes); the structured log is the MVP audit surface.
log: (event, meta) => ingressLogger.warn(event, meta),
diff --git a/src/modules/integration/scope-binding.service.spec.ts b/src/modules/integration/scope-binding.service.spec.ts
index 1c5e72582..4def6bfce 100644
--- a/src/modules/integration/scope-binding.service.spec.ts
+++ b/src/modules/integration/scope-binding.service.spec.ts
@@ -1,9 +1,9 @@
-import { NotFoundException } from '@nestjs/common';
+import { Repository } from 'typeorm';
import { ScopeBindingService } from './scope-binding.service';
import { PluginInstanceService } from './plugin-instance.service';
import { PluginLoaderService } from '../../core/plugins/plugin-loader.service';
import { AuditService } from '../audit/audit.service';
-import { SessionService } from '../session/session.service';
+import { Session } from '../session/entities/session.entity';
// The boot-time reconciler re-derives each ENABLED instance's runtime scope binding from the persisted
// plugin_instances rows, so a binding lost at provisioning time (plugin momentarily unloaded) is
@@ -23,8 +23,8 @@ describe('ScopeBindingService.onApplicationBootstrap reconciliation', () => {
} as unknown as PluginLoaderService;
const audit = { logInfo: jest.fn(), logWarn: jest.fn() } as unknown as AuditService;
// Default: every bound scope resolves to a real session row, so the missing-session warning stays
- // quiet unless a test asks for it (SessionService.findOne throws NotFoundException for a gone row).
- const sessions = { findOne: jest.fn().mockResolvedValue({ id: 'sess-1' }) } as unknown as SessionService;
+ // quiet unless a test asks for it (the repository findOne resolves null for a gone row).
+ const sessions = { findOne: jest.fn().mockResolvedValue({ id: 'sess-1' }) } as unknown as Repository<Session>;
return { loader, audit, sessions, setPluginSessionConfig, setPluginSessions, updatePluginConfig };
}
@@ -174,9 +174,7 @@ describe('ScopeBindingService.onApplicationBootstrap reconciliation', () => {
]),
list: jest.fn().mockResolvedValue([]),
} as unknown as PluginInstanceService;
- const sessions = {
- findOne: jest.fn().mockRejectedValue(new NotFoundException("Session with id 'gone-sess' not found")),
- } as unknown as SessionService;
+ const sessions = { findOne: jest.fn().mockResolvedValue(null) } as unknown as Repository<Session>;
const svc = new ScopeBindingService(instances, loader, audit, sessions);
const warn = jest.spyOn(loggerOf(svc), 'warn').mockImplementation(() => undefined);
@@ -221,7 +219,7 @@ describe('ScopeBindingService.onApplicationBootstrap reconciliation', () => {
]),
list: jest.fn().mockResolvedValue([]),
} as unknown as PluginInstanceService;
- const sessions = { findOne: jest.fn().mockRejectedValue(new Error('db down')) } as unknown as SessionService;
+ const sessions = { findOne: jest.fn().mockRejectedValue(new Error('db down')) } as unknown as Repository<Session>;
const svc = new ScopeBindingService(instances, loader, audit, sessions);
const warn = jest.spyOn(loggerOf(svc), 'warn').mockImplementation(() => undefined);
@@ -244,7 +242,7 @@ describe('ScopeBindingService.onApplicationBootstrap reconciliation', () => {
updatePluginConfig: jest.fn(),
} as unknown as PluginLoaderService;
const audit = { logInfo: jest.fn(), logWarn: jest.fn() } as unknown as AuditService;
- const sessionRows = { findOne: jest.fn().mockResolvedValue({ id: 'sess-1' }) } as unknown as SessionService;
+ const sessionRows = { findOne: jest.fn().mockResolvedValue({ id: 'sess-1' }) } as unknown as Repository<Session>;
const wildcard = { pluginId: 'chatwoot', instanceId: 'wild', sessionScope: null, config: {}, enabled: true };
const concrete = { pluginId: 'chatwoot', instanceId: 'conc', sessionScope: 'sess-1', config: {}, enabled: true };
@@ -287,7 +285,7 @@ describe('ScopeBindingService.applyScopeBinding retires an instance without leak
updatePluginConfig: jest.fn(),
} as unknown as PluginLoaderService;
const audit = { logInfo: jest.fn(), logWarn: jest.fn() } as unknown as AuditService;
- const sessions = { findOne: jest.fn().mockResolvedValue({ id: 'sess-1' }) } as unknown as SessionService;
+ const sessions = { findOne: jest.fn().mockResolvedValue({ id: 'sess-1' }) } as unknown as Repository<Session>;
const svc = (rows: unknown[]): ScopeBindingService =>
new ScopeBindingService(
{ list: jest.fn().mockResolvedValue(rows) } as unknown as PluginInstanceService,
diff --git a/src/modules/integration/scope-binding.service.ts b/src/modules/integration/scope-binding.service.ts
index fb9edc60d..47b42dac2 100644
--- a/src/modules/integration/scope-binding.service.ts
+++ b/src/modules/integration/scope-binding.service.ts
@@ -1,8 +1,10 @@
-import { Injectable, NotFoundException, OnApplicationBootstrap } from '@nestjs/common';
+import { Injectable, OnApplicationBootstrap } from '@nestjs/common';
+import { InjectRepository } from '@nestjs/typeorm';
+import { Repository } from 'typeorm';
import { AuditAction } from '../audit/entities/audit-log.entity';
import { AuditService } from '../audit/audit.service';
import { PluginLoaderService } from '../../core/plugins/plugin-loader.service';
-import { SessionService } from '../session/session.service';
+import { Session } from '../session/entities/session.entity';
import { PluginInstanceService } from './plugin-instance.service';
import { PluginInstance } from './entities/plugin-instance.entity';
import { createLogger } from '../../common/services/logger.service';
@@ -22,7 +24,8 @@ export class ScopeBindingService implements OnApplicationBootstrap {
private readonly instances: PluginInstanceService,
private readonly loader: PluginLoaderService,
private readonly audit: AuditService,
- private readonly sessions: SessionService,
+ @InjectRepository(Session, 'data')
+ private readonly sessions: Repository<Session>,
) {}
/**
@@ -92,12 +95,12 @@ export class ScopeBindingService implements OnApplicationBootstrap {
private async warnIfScopeHasNoSession(inst: PluginInstance): Promise<void> {
if (!inst.sessionScope || inst.sessionScope === '*') return;
try {
- await this.sessions.findOne(inst.sessionScope);
- } catch (err) {
- // findOne throws NotFoundException only for a genuinely missing row. Any other failure (a DB
- // hiccup mid-boot) is not evidence the session is gone, and reporting it as gone would send an
- // operator hunting a binding that is in fact fine — so stay quiet rather than cry wolf.
- if (!(err instanceof NotFoundException)) return;
+ // The same row read SessionService.findOne performs ({ where: { id } }), straight through the
+ // repository: a missing row resolves to null instead of throwing NotFoundException, and the
+ // service's runtime-state projection is more than this existence check needs.
+ const session = await this.sessions.findOne({ where: { id: inst.sessionScope } });
+ // A null row (and only a null row) means the session is genuinely missing.
+ if (session) return;
this.logger.warn(
`Plugin instance ${inst.pluginId}:${inst.instanceId} is bound to session '${inst.sessionScope}', which does not exist — it will receive no events until that session is restored or the instance is re-scoped`,
{
@@ -107,6 +110,10 @@ export class ScopeBindingService implements OnApplicationBootstrap {
sessionScope: inst.sessionScope,
},
);
+ } catch {
+ // A failure that throws (a DB hiccup mid-boot) is not evidence the session is gone, and
+ // reporting it as gone would send an operator hunting a binding that is in fact fine — so
+ // stay quiet rather than cry wolf.
}
}