Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(infra): make data export/import complete, crash-safe, and runtime-reconciled (#927)

Yudhi Armyndharisa374dc7397fe
diff --git a/openapi.json b/openapi.json
index 6cc285e44..b4d6b56fa 100644
--- a/openapi.json
+++ b/openapi.json
@@ -2642,6 +2642,14 @@
"schema": {
"type": "object",
"properties": {
+ "force": {
+ "type": "boolean",
+ "description": "Allow the replace to proceed even while engines are running for sessions the backup does not contain (they keep running until restart; see restartRequired). Prefer stopOrphans, which closes that window inside this request instead."
+ },
+ "stopOrphans": {
+ "type": "boolean",
+ "description": "Stop the running engines for sessions the backup does not contain, inside this request and before the replace runs. Supersedes force for the orphan case: with stopOrphans the engines no longer need a process restart to reconcile, so restartRequired stays false on the success path."
+ },
"tables": {
"type": "object",
"properties": {
@@ -2656,6 +2664,9 @@
},
"messageBatches": {
"type": "array"
+ },
+ "statusUpdates": {
+ "type": "array"
}
}
}
@@ -2667,6 +2678,9 @@
"responses": {
"200": {
"description": "Data imported successfully"
+ },
+ "409": {
+ "description": "Refused: live engines exist for sessions the backup would remove (retry with stopOrphans=true to stop them in-request, or force=true to proceed and restart after)"
}
},
"summary": "Import data to Data DB (replaces existing data)",
diff --git a/src/common/storage/storage.service.spec.ts b/src/common/storage/storage.service.spec.ts
index bd940de3c..8b325339c 100644
--- a/src/common/storage/storage.service.spec.ts
+++ b/src/common/storage/storage.service.spec.ts
@@ -226,6 +226,35 @@ describe('StorageService import resource caps (decompression-bomb defense)', ()
});
});
+describe('StorageService import stream error handling (request fails, process survives)', () => {
+ let baseDir: string;
+ let service: StorageService;
+
+ beforeEach(() => {
+ ({ service, baseDir } = makeLocalService());
+ });
+
+ afterEach(() => {
+ fs.rmSync(baseDir, { recursive: true, force: true });
+ });
+
+ it("rejects on a non-gzip input instead of crashing on gunzip's unhandled error event", async () => {
+ // zlib emits 'error' on the gunzip stream for a corrupt/non-gzip payload; pipe() does not forward
+ // it, so without a listener on gunzip this would take down the whole process.
+ const notGzip = Readable.from([Buffer.from('this is definitely not a gzip stream')]);
+ await expect(service.importFromStream(notGzip)).rejects.toThrow();
+ });
+
+ it('rejects when the input stream itself errors mid-read', async () => {
+ const failing = new Readable({
+ read() {
+ this.destroy(new Error('read boom'));
+ },
+ });
+ await expect(service.importFromStream(failing)).rejects.toThrow(/read boom/);
+ });
+});
+
describe('StorageService local traversal (async + bounded)', () => {
let baseDir: string;
let service: StorageService;
diff --git a/src/common/storage/storage.service.ts b/src/common/storage/storage.service.ts
index 039fce736..2c5e5131e 100644
--- a/src/common/storage/storage.service.ts
+++ b/src/common/storage/storage.service.ts
@@ -315,8 +315,23 @@ export class StorageService {
if (settled) return;
settled = true;
extract.destroy();
+ gunzip.destroy();
+ // Destroying the input mid-pipe stops the source; without an error arg it emits no 'error'.
+ inputStream.destroy();
reject(err);
};
+ // Every stream in the pipeline needs an 'error' listener: an EventEmitter with none CRASHES the
+ // process on error. pipe() does not forward errors, so a corrupt gzip (zlib error on gunzip) or
+ // an input read failure (disk I/O, file replaced mid-read) would otherwise kill the server
+ // mid-request instead of failing the import.
+ gunzip.on('error', (err: Error) => {
+ this.logger.error('Import failed (gzip)', String(err));
+ fail(err);
+ });
+ inputStream.on('error', (err: Error) => {
+ this.logger.error('Import failed (input)', String(err));
+ fail(err);
+ });
extract.on('entry', (header, stream, next) => {
if (settled) {
diff --git a/src/engine/identity/lid-mapping-store.service.ts b/src/engine/identity/lid-mapping-store.service.ts
index fb3f1345a..21cc26e8b 100644
--- a/src/engine/identity/lid-mapping-store.service.ts
+++ b/src/engine/identity/lid-mapping-store.service.ts
@@ -54,8 +54,21 @@ export class LidMappingStoreService implements LidMappingStore, OnModuleInit {
}
async onModuleInit(): Promise<void> {
+ await this.reload();
+ }
+
+ /**
+ * (Re)load the in-memory mirror from the table. Called on boot, and by the infra data import after
+ * a committed full-replace restore — the mirror is otherwise write-through only, so restored rows
+ * would never reach it and entries the restore removed would stay resolvable until the next start.
+ * Never throws: a missing table (migration not yet applied) or a read error must not block boot or
+ * fail the import — resolution falls back to engine re-resolution until the table is readable.
+ */
+ async reload(): Promise<void> {
try {
const rows = await this.repo.find();
+ this.lidToPhone.clear();
+ this.phoneToLids.clear();
for (const row of rows) {
this.index(row.lid, row.phone);
}
@@ -63,8 +76,6 @@ export class LidMappingStoreService implements LidMappingStore, OnModuleInit {
`Loaded ${rows.length} lid->phone mappings into cache${this.maxCachedLids ? ` (cap ${this.maxCachedLids})` : ''}`,
);
} catch (err) {
- // A missing table (migration not yet applied) or a read error must not block boot: resolution
- // falls back to the per-session in-memory map until the table is available.
this.logger.warn(`Could not preload lid->phone mappings: ${err instanceof Error ? err.message : String(err)}`);
}
}
diff --git a/src/modules/infra/infra.controller.spec.ts b/src/modules/infra/infra.controller.spec.ts
index 1b68c4f3d..cdc00b765 100644
--- a/src/modules/infra/infra.controller.spec.ts
+++ b/src/modules/infra/infra.controller.spec.ts
@@ -28,6 +28,7 @@ jest.mock('fs', () => {
});
import { DataSource, QueryFailedError } from 'typeorm';
+import { ConflictException } from '@nestjs/common';
import { InfraController } from './infra.controller';
import { REQUIRED_ROLE_KEY } from '../auth/decorators/auth.decorators';
import { ApiKeyRole } from '../auth/entities/api-key.entity';
@@ -43,6 +44,7 @@ import { ConversationMapping } from '../integration/entities/conversation-mappin
import { IngressEvent } from '../integration/entities/ingress-event.entity';
import { WebhookDeliveryFailure } from '../webhook/entities/webhook-delivery-failure.entity';
import { IntegrationDeliveryFailure } from '../integration/entities/integration-delivery-failure.entity';
+import { StatusUpdate } from '../status-store/entities/status-update.entity';
import { AuditAction } from '../audit/entities/audit-log.entity';
describe('InfraController access control (Vuln 2)', () => {
@@ -1333,3 +1335,391 @@ describe('InfraController C002 audit trail — import emits only on a committed
expect(actions).not.toContain(AuditAction.INFRA_DATA_IMPORTED);
});
});
+
+describe('InfraController.exportData optional-table strictness', () => {
+ const cfg = { get: (key: string, def?: unknown) => (key === 'dataDatabase.type' ? 'sqlite' : def) };
+ const build = (query: jest.Mock) =>
+ new InfraController(
+ cfg as never,
+ {} as never,
+ { query } as never,
+ {} as never,
+ {} as never,
+ {} as never,
+ {} as never,
+ {} as never,
+ );
+
+ it('rethrows a non-missing-table error (lock/IO/timeout) instead of reporting a partial export as complete', async () => {
+ // A lock on ONE optional table must fail the whole export: silently exporting without that table
+ // produces a backup the import then treats as authoritative, DELETing the table's existing rows.
+ const query = jest.fn((sql: string) =>
+ sql === 'SELECT * FROM messages'
+ ? Promise.reject(new Error('SQLITE_BUSY: database is locked'))
+ : Promise.resolve([]),
+ );
+ await expect(build(query).exportData()).rejects.toThrow(/database is locked/);
+ });
+
+ it('tolerates a genuinely absent optional table — and marks it in skippedTables', async () => {
+ const missing = Object.assign(new Error('no such table: messages'), { name: 'SqliteError' });
+ const query = jest.fn((sql: string) =>
+ sql === 'SELECT * FROM messages' ? Promise.reject(missing) : Promise.resolve([]),
+ );
+ const dump = await build(query).exportData();
+ expect(dump.counts.messages).toBe(0);
+ expect(dump.tables.messages).toEqual([]);
+ expect(dump.skippedTables).toContain('messages');
+ // Every other table still exported (all empty here, none skipped).
+ expect(dump.skippedTables).toEqual(['messages']);
+ });
+
+ it('strips the Postgres generated body_ts tsvector from exported message rows', async () => {
+ // Postgres' STORED generated FTS column rides along in `SELECT *`; it is an index artifact, not
+ // payload, and must not be serialized into a (dialect-neutral) backup.
+ const messageRow = {
+ id: 'm1',
+ sessionId: 's1',
+ waMessageId: 'WA1',
+ chatId: 'c1',
+ chatName: null,
+ author: null,
+ from: 'a',
+ to: 'b',
+ body: 'hello',
+ type: 'text',
+ direction: 'incoming',
+ timestamp: 1700000000,
+ metadata: null,
+ status: 'delivered',
+ createdAt: '2026-01-01T00:00:00.000Z',
+ body_ts: "'hello'",
+ };
+ const query = jest.fn((sql: string) => Promise.resolve(sql === 'SELECT * FROM messages' ? [messageRow] : []));
+ const dump = await build(query).exportData();
+ expect(dump.tables.messages).toHaveLength(1);
+ expect(dump.tables.messages[0]).not.toHaveProperty('body_ts');
+ expect(dump.tables.messages[0].body).toBe('hello');
+ });
+});
+
+describe('InfraController.importData status_updates + runtime reconciliation', () => {
+ let ds: DataSource;
+ const cfg = { get: (key: string, def?: unknown) => (key === 'dataDatabase.type' ? 'sqlite' : def) };
+
+ // Positional constructor: (config, mainDs, dataDs, engineFactory, dockerService, cacheService,
+ // storageService, shutdownService, webhookQueue?, auditService?, sessionService?, lidMappingStore?).
+ const build = (opts: { sessionService?: unknown; lidMappingStore?: unknown } = {}) =>
+ new InfraController(
+ cfg as never,
+ {} as never,
+ ds,
+ {} as never,
+ {} as never,
+ {} as never,
+ {} as never,
+ {} as never,
+ undefined as never,
+ undefined,
+ opts.sessionService as never,
+ opts.lidMappingStore as never,
+ );
+
+ beforeEach(async () => {
+ ds = new DataSource({
+ type: 'better-sqlite3',
+ database: ':memory:',
+ entities: [
+ Session,
+ Webhook,
+ Message,
+ MessageBatch,
+ Template,
+ BaileysStoredMessage,
+ LidMapping,
+ PluginInstance,
+ ConversationMapping,
+ IngressEvent,
+ WebhookDeliveryFailure,
+ IntegrationDeliveryFailure,
+ StatusUpdate,
+ ],
+ synchronize: true,
+ });
+ await ds.initialize();
+ });
+
+ afterEach(async () => {
+ await ds.destroy();
+ });
+
+ const seedSession = (id: string) =>
+ ds.getRepository(Session).save(
+ ds.getRepository(Session).create({
+ id,
+ name: `session-${id}`,
+ status: SessionStatus.READY,
+ phone: null,
+ pushName: null,
+ config: {},
+ proxyUrl: null,
+ proxyType: null,
+ connectedAt: null,
+ lastActiveAt: null,
+ }),
+ );
+
+ it('exports and restores status_updates (the table the docs promise is covered)', async () => {
+ await seedSession('s1');
+ const statusRepo = ds.getRepository(StatusUpdate);
+ await statusRepo.save(
+ statusRepo.create({
+ id: 'su1',
+ sessionId: 's1',
+ contactJid: '[email protected]',
+ contactName: 'Alice',
+ contactPushName: 'alice',
+ waStatusId: 'false_status@broadcast_ABC',
+ type: 'text',
+ caption: 'on vacation',
+ mediaOmitted: true,
+ omitReason: 'over_cap',
+ backgroundColor: '#FF0000',
+ font: 2,
+ postedAt: 1750000000000,
+ expiresAt: 1750086400000,
+ }),
+ );
+
+ const controller = build();
+ const dump = await controller.exportData();
+ expect(dump.counts.statusUpdates).toBe(1);
+ expect(dump.skippedTables).toEqual([]);
+
+ await statusRepo.clear();
+ const res = await controller.importData({ tables: dump.tables });
+
+ expect(res.warnings).toEqual([]);
+ expect(res.imported).toBe(true);
+ expect(res.counts.statusUpdates).toBe(1);
+ const restored = await statusRepo.findOneByOrFail({ id: 'su1' });
+ expect(restored.waStatusId).toBe('false_status@broadcast_ABC');
+ expect(restored.caption).toBe('on vacation');
+ expect(restored.mediaOmitted).toBe(true); // boolean survives the 0/1 round-trip
+ expect(restored.omitReason).toBe('over_cap');
+ expect(restored.font).toBe(2);
+ expect(restored.postedAt).toBe(1750000000000);
+ expect(restored.expiresAt).toBe(1750086400000);
+ });
+
+ it('tolerates body_ts on imported message rows (backup made before the strip)', async () => {
+ await seedSession('s1');
+ const res = await build().importData({
+ tables: {
+ sessions: [
+ {
+ id: 's1',
+ name: 'session-s1',
+ status: 'ready',
+ config: '{}',
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:00:00.000Z',
+ },
+ ] as never,
+ messages: [
+ {
+ id: 'm1',
+ sessionId: 's1',
+ waMessageId: 'WA1',
+ chatId: 'c1',
+ from: 'a',
+ to: 'b',
+ body: 'hello',
+ type: 'text',
+ direction: 'incoming',
+ status: 'delivered',
+ createdAt: '2026-01-01T00:00:00.000Z',
+ body_ts: "'hello'", // legacy Postgres export artifact — must be ignored, not fail
+ },
+ ] as never,
+ },
+ });
+ expect(res.imported).toBe(true);
+ expect(res.warnings).toEqual([]);
+ expect((await ds.getRepository(Message).findOneByOrFail({ id: 'm1' })).body).toBe('hello');
+ });
+
+ it('reloads the in-memory lid mappings after a committed restore', async () => {
+ await seedSession('s1');
+ const lidMappingStore = { reload: jest.fn().mockResolvedValue(undefined) };
+ const controller = build({ lidMappingStore });
+ const dump = await controller.exportData();
+ const res = await controller.importData({ tables: dump.tables });
+ expect(res.imported).toBe(true);
+ expect(lidMappingStore.reload).toHaveBeenCalledTimes(1);
+ });
+
+ it('does NOT reload lid mappings when the import is refused (nothing committed)', async () => {
+ await seedSession('s1');
+ const lidMappingStore = { reload: jest.fn().mockResolvedValue(undefined) };
+ const res = await build({ lidMappingStore }).importData({ tables: {} });
+ expect(res.imported).toBe(false);
+ expect(lidMappingStore.reload).not.toHaveBeenCalled();
+ });
+
+ it('409s when a live engine would be orphaned by the replace — unless force=true', async () => {
+ await seedSession('s1');
+ const controller = build({ sessionService: { getActiveSessionIds: () => ['ghost'] } });
+ const dump = await controller.exportData(); // backup contains only s1, not the running 'ghost'
+
+ // Without force: 409 Conflict, and the destructive replace never started.
+ const err = await controller.importData({ tables: dump.tables }).catch((e: unknown) => e);
+ expect(err).toBeInstanceOf(ConflictException);
+ expect((err as ConflictException).getStatus()).toBe(409);
+ expect((err as ConflictException).message).toContain('ghost');
+ expect(await ds.getRepository(Session).count()).toBe(1); // nothing deleted
+
+ // With force: the restore proceeds and the response tells the operator a restart is required
+ // to stop the orphaned engine.
+ const res = await controller.importData({ tables: dump.tables, force: true });
+ expect(res.imported).toBe(true);
+ expect(res.restartRequired).toBe(true);
+ expect(res.orphanedEngines).toEqual(['ghost']);
+ });
+
+ it('reports restartRequired:false when no live engine is orphaned', async () => {
+ await seedSession('s1');
+ const controller = build({ sessionService: { getActiveSessionIds: () => ['s1'] } });
+ const dump = await controller.exportData();
+ const res = await controller.importData({ tables: dump.tables });
+ expect(res.imported).toBe(true);
+ expect(res.restartRequired).toBe(false);
+ expect(res.orphanedEngines).toEqual([]);
+ });
+
+ it('stopOrphans=true stops the orphan engines inside the request and keeps restartRequired:false', async () => {
+ await seedSession('s1');
+ const stopOrphanEngines = jest.fn().mockResolvedValue({ stopped: ['ghost'], notRunning: [], failed: [] });
+ const controller = build({
+ sessionService: { getActiveSessionIds: () => ['ghost'], stopOrphanEngines },
+ });
+ const dump = await controller.exportData(); // backup contains only s1, not 'ghost'
+
+ const res = await controller.importData({ tables: dump.tables, stopOrphans: true });
+
+ // The orphan engines were stopped (called once with exactly the orphan ids) and the import
+ // proceeded without requiring a restart — the whole point of stopOrphans vs force.
+ expect(stopOrphanEngines).toHaveBeenCalledWith(['ghost']);
+ expect(stopOrphanEngines).toHaveBeenCalledTimes(1);
+ expect(res.imported).toBe(true);
+ expect(res.restartRequired).toBe(false);
+ expect(res.stoppedOrphanEngines).toEqual(['ghost']);
+ expect(res.failedOrphanEngines).toEqual([]);
+ expect(res.orphanedEngines).toEqual(['ghost']);
+ });
+
+ it('stopOrphans=true surfaces a teardown failure as restartRequired:true + a warning (Map reconciled regardless)', async () => {
+ await seedSession('s1');
+ const stopOrphanEngines = jest.fn().mockResolvedValue({ stopped: ['g1'], notRunning: [], failed: ['g2'] });
+ const controller = build({
+ sessionService: { getActiveSessionIds: () => ['g1', 'g2'], stopOrphanEngines },
+ });
+ const dump = await controller.exportData();
+
+ const res = await controller.importData({ tables: dump.tables, stopOrphans: true });
+
+ expect(res.imported).toBe(true);
+ expect(res.restartRequired).toBe(true);
+ expect(res.failedOrphanEngines).toEqual(['g2']);
+ expect(res.stoppedOrphanEngines).toEqual(['g1']);
+ expect(res.notices.some(w => w.includes('g2') && w.includes('restart'))).toBe(true);
+ });
+
+ it('stopOrphans=true reports notRunning orphans (still initializing) as a warning', async () => {
+ await seedSession('s1');
+ const stopOrphanEngines = jest.fn().mockResolvedValue({ stopped: ['g1'], notRunning: ['g-init'], failed: [] });
+ const controller = build({
+ sessionService: { getActiveSessionIds: () => ['g1', 'g-init'], stopOrphanEngines },
+ });
+ const dump = await controller.exportData();
+
+ const res = await controller.importData({ tables: dump.tables, stopOrphans: true });
+
+ expect(res.imported).toBe(true);
+ expect(res.restartRequired).toBe(false);
+ expect(res.notices.some(w => w.includes('g-init') && w.includes('initializing'))).toBe(true);
+ });
+
+ it('stopOrphans=true is a no-op when there is no sessionService wired', async () => {
+ // Some stripped-down module shapes may not import SessionModule; the controller must not throw
+ // when stopOrphans is requested but the service is unavailable — it falls back to refuse/force.
+ await seedSession('s1');
+ const controller = build({}); // no sessionService
+ const dump = await controller.exportData();
+
+ // Without sessionService there are no active ids to detect, so no orphan, no 409 — the import
+ // proceeds normally. (This matches the @Optional() wiring; the gate only engages when the
+ // service is present.)
+ const res = await controller.importData({ tables: dump.tables, stopOrphans: true });
+ expect(res.imported).toBe(true);
+ expect(res.stoppedOrphanEngines).toEqual([]);
+ });
+});
+
+describe('InfraController storage stream failures surface as request errors, not process crashes', () => {
+ it('importStorage maps an archive/stream failure to a 400 with the real reason', async () => {
+ const cwdSpy = jest.spyOn(process, 'cwd').mockReturnValue('/srv/openwa');
+ (fs.existsSync as jest.Mock).mockImplementation((p: string) => p === '/srv/openwa/data/exports/bad.tar.gz');
+ try {
+ const storage = {
+ importFromStream: jest.fn().mockRejectedValue(new Error('incorrect header check')),
+ getCurrentStorageType: () => 'local',
+ };
+ const controller = new InfraController(
+ {} as never,
+ {} as never,
+ {} as never,
+ {} as never,
+ {} as never,
+ {} as never,
+ storage as never,
+ {} as never,
+ );
+ const err = await controller.importStorage({ filePath: 'data/exports/bad.tar.gz' }).catch((e: unknown) => e);
+ expect(err).toBeInstanceOf(BadRequestException);
+ expect((err as BadRequestException).message).toContain('incorrect header check');
+ } finally {
+ cwdSpy.mockRestore();
+ (fs.existsSync as jest.Mock).mockReturnValue(false);
+ }
+ });
+
+ it('exportStorage rejects (and the process lives) when the export source stream errors', async () => {
+ const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-export-err-'));
+ const cwdSpy = jest.spyOn(process, 'cwd').mockReturnValue(cwd);
+ try {
+ // pipe() never forwards source errors: without a listener on the source this would be an
+ // unhandled 'error' event and kill the process instead of failing the request.
+ const errStream = new Readable({
+ read() {
+ this.destroy(new Error('archive boom'));
+ },
+ });
+ const storage = { createExportStream: jest.fn().mockResolvedValue(errStream) };
+ const controller = new InfraController(
+ {} as never,
+ {} as never,
+ {} as never,
+ {} as never,
+ {} as never,
+ {} as never,
+ storage as never,
+ {} as never,
+ );
+ await expect(controller.exportStorage()).rejects.toThrow(/archive boom/);
+ } finally {
+ cwdSpy.mockRestore();
+ fs.rmSync(cwd, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/src/modules/infra/infra.controller.ts b/src/modules/infra/infra.controller.ts
index ca2e507b2..af8817c4f 100644
--- a/src/modules/infra/infra.controller.ts
+++ b/src/modules/infra/infra.controller.ts
@@ -5,6 +5,7 @@ import {
Post,
Body,
BadRequestException,
+ ConflictException,
HttpException,
HttpCode,
HttpStatus,
@@ -33,6 +34,8 @@ import { createLogger } from '../../common/services/logger.service';
import { isMissingTableError } from '../../common/utils/db-errors';
import { AuditService } from '../audit/audit.service';
import { AuditAction } from '../audit/entities/audit-log.entity';
+import { SessionService } from '../session/session.service';
+import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';
import { ImportStorageDto } from './dto/import-storage.dto';
import * as fs from 'fs';
import * as path from 'path';
@@ -313,6 +316,12 @@ interface MessageRow {
metadata: string | Record<string, unknown> | null;
status: string;
createdAt: string;
+ /**
+ * Postgres-only STORED generated tsvector (FTS). Present in `SELECT *` rows read from a Postgres
+ * source (and in backups made before it was stripped) but never a real payload column: export drops
+ * it, and the import's explicit column list ignores it. Declared so both directions type-check.
+ */
+ body_ts?: unknown;
}
interface MessageBatchRow {
@@ -427,6 +436,28 @@ interface IntegrationDeliveryFailureRow {
createdAt: string;
}
+// status_updates has no FK to sessions (plain columns), so the import's `DELETE FROM sessions` never
+// clears it — it must be exported + re-inserted explicitly like lid_mappings. postedAt/expiresAt are
+// bigint epoch-ms: raw queries bypass the entity transformer, so Postgres returns them as strings.
+interface StatusUpdateRow {
+ id: string;
+ sessionId: string;
+ contactJid: string;
+ contactName: string | null;
+ contactPushName: string | null;
+ waStatusId: string;
+ type: string;
+ caption: string | null;
+ mediaPath: string | null;
+ mediaMimetype: string | null;
+ mediaOmitted: boolean | number;
+ omitReason: string | null;
+ backgroundColor: string | null;
+ font: number | null;
+ postedAt: number | string;
+ expiresAt: number | string;
+}
+
interface MigrationTables {
sessions: SessionRow[];
webhooks: WebhookRow[];
@@ -440,6 +471,7 @@ interface MigrationTables {
ingressEvents: IngressEventRow[];
webhookDeliveryFailures: WebhookDeliveryFailureRow[];
integrationDeliveryFailures: IntegrationDeliveryFailureRow[];
+ statusUpdates: StatusUpdateRow[];
}
// Saved infrastructure config returned to the dashboard form for hydration. Secret
@@ -497,6 +529,13 @@ export class InfraController {
// call site then makes emission a no-op there instead of forcing every test to wire a mock.
@Optional()
private readonly auditService?: AuditService,
+ // Post-import runtime reconciliation (see importData). Same trailing-@Optional convention as
+ // auditService: provided by the app (InfraModule imports SessionModule; EngineModule is @Global),
+ // omitted by direct-construction unit tests, and every use is `?.`-guarded.
+ @Optional()
+ private readonly sessionService?: SessionService,
+ @Optional()
+ private readonly lidMappingStore?: LidMappingStoreService,
) {}
/** Bound the DB liveness probe so a hung connection can't stall the status read. */
@@ -1095,89 +1134,55 @@ export class InfraController {
ingressEvents: number;
webhookDeliveryFailures: number;
integrationDeliveryFailures: number;
+ statusUpdates: number;
};
+ /** Optional tables that were skipped because they genuinely do not exist in this DB (older schema). */
+ skippedTables: string[];
}> {
// Get all entities from Data DB
const sessions = await this.dataDataSource.query<SessionRow[]>('SELECT * FROM sessions');
const webhooks = await this.dataDataSource.query<WebhookRow[]>('SELECT * FROM webhooks');
- // These tables may not exist yet (older DB) or be empty.
- let messages: MessageRow[] = [];
- let messageBatches: MessageBatchRow[] = [];
- let templates: TemplateRow[] = [];
- let baileysStoredMessages: BaileysStoredMessageRow[] = [];
- let lidMappings: LidMappingRow[] = [];
- let pluginInstances: PluginInstanceRow[] = [];
- let conversationMappings: ConversationMappingRow[] = [];
- let ingressEvents: IngressEventRow[] = [];
- let webhookDeliveryFailures: WebhookDeliveryFailureRow[] = [];
- let integrationDeliveryFailures: IntegrationDeliveryFailureRow[] = [];
-
- try {
- messages = await this.dataDataSource.query<MessageRow[]>('SELECT * FROM messages');
- } catch (error) {
- this.logger.debug('Messages table not available for export', { error: String(error) });
- }
-
- try {
- messageBatches = await this.dataDataSource.query<MessageBatchRow[]>('SELECT * FROM message_batches');
- } catch (error) {
- this.logger.debug('Message batches table not available for export', { error: String(error) });
- }
-
- try {
- templates = await this.dataDataSource.query<TemplateRow[]>('SELECT * FROM templates');
- } catch (error) {
- this.logger.debug('Templates table not available for export', { error: String(error) });
- }
-
- try {
- baileysStoredMessages = await this.dataDataSource.query<BaileysStoredMessageRow[]>(
- 'SELECT * FROM baileys_stored_messages',
- );
- } catch (error) {
- this.logger.debug('Baileys stored messages table not available for export', { error: String(error) });
- }
+ // The tables below may legitimately not exist yet (created by migrations an older DB has not run).
+ // Only a GENUINE missing-table error (isMissingTableError) may be tolerated — anything else (lock,
+ // I/O, timeout, aborted connection) must FAIL the export. The old blind `catch { debug-log }`
+ // pattern reported those as "table is empty", producing a 200 "complete" backup that was actually
+ // partial — which the import then treated as authoritative and DELETEd the missing tables' rows.
+ // A skipped table is surfaced in `skippedTables` (and logged as a warning) so an operator can tell
+ // "not migrated yet" apart from "exported empty".
+ const skippedTables: string[] = [];
+ const queryOptionalTable = async <T>(table: string): Promise<T[]> => {
+ try {
+ return await this.dataDataSource.query<T[]>(`SELECT * FROM ${table}`);
+ } catch (error) {
+ if (!isMissingTableError(error)) throw error;
+ skippedTables.push(table);
+ this.logger.warn('Optional table does not exist in this DB; exporting without it', { table });
+ return [];
+ }
+ };
- try {
- lidMappings = await this.dataDataSource.query<LidMappingRow[]>('SELECT * FROM lid_mappings');
- } catch (error) {
- this.logger.debug('Lid mappings table not available for export', { error: String(error) });
+ const messages = await queryOptionalTable<MessageRow>('messages');
+ // Postgres carries a STORED generated tsvector column `body_ts` (FTS) that `SELECT *` picks up.
+ // It is a server-maintained index artifact, not payload: strip it so backups stay dialect-neutral
+ // (and small). The import's explicit column list already ignores it in older archives.
+ for (const row of messages) {
+ delete row.body_ts;
}
-
+ const messageBatches = await queryOptionalTable<MessageBatchRow>('message_batches');
+ const templates = await queryOptionalTable<TemplateRow>('templates');
+ const baileysStoredMessages = await queryOptionalTable<BaileysStoredMessageRow>('baileys_stored_messages');
+ const lidMappings = await queryOptionalTable<LidMappingRow>('lid_mappings');
// Integration Fabric + both DLQs were added after the original migration set; tolerate a genuinely
// absent table (older DB) like the tables above rather than 500-ing the whole export.
- try {
- pluginInstances = await this.dataDataSource.query<PluginInstanceRow[]>('SELECT * FROM plugin_instances');
- } catch (error) {
- this.logger.debug('plugin_instances table not available for export', { error: String(error) });
- }
- try {
- conversationMappings = await this.dataDataSource.query<ConversationMappingRow[]>(
- 'SELECT * FROM conversation_mappings',
- );
- } catch (error) {
- this.logger.debug('conversation_mappings table not available for export', { error: String(error) });
- }
- try {
- ingressEvents = await this.dataDataSource.query<IngressEventRow[]>('SELECT * FROM ingress_events');
- } catch (error) {
- this.logger.debug('ingress_events table not available for export', { error: String(error) });
- }
- try {
- webhookDeliveryFailures = await this.dataDataSource.query<WebhookDeliveryFailureRow[]>(
- 'SELECT * FROM webhook_delivery_failures',
- );
- } catch (error) {
- this.logger.debug('webhook_delivery_failures table not available for export', { error: String(error) });
- }
- try {
- integrationDeliveryFailures = await this.dataDataSource.query<IntegrationDeliveryFailureRow[]>(
- 'SELECT * FROM integration_delivery_failures',
- );
- } catch (error) {
- this.logger.debug('integration_delivery_failures table not available for export', { error: String(error) });
- }
+ const pluginInstances = await queryOptionalTable<PluginInstanceRow>('plugin_instances');
+ const conversationMappings = await queryOptionalTable<ConversationMappingRow>('conversation_mappings');
+ const ingressEvents = await queryOptionalTable<IngressEventRow>('ingress_events');
+ const webhookDeliveryFailures = await queryOptionalTable<WebhookDeliveryFailureRow>('webhook_delivery_failures');
+ const integrationDeliveryFailures = await queryOptionalTable<IntegrationDeliveryFailureRow>(
+ 'integration_delivery_failures',
+ );
+ const statusUpdates = await queryOptionalTable<StatusUpdateRow>('status_updates');
const counts = {
sessions: sessions.length,
@@ -1192,6 +1197,7 @@ export class InfraController {
ingressEvents: ingressEvents.length,
webhookDeliveryFailures: webhookDeliveryFailures.length,
integrationDeliveryFailures: integrationDeliveryFailures.length,
+ statusUpdates: statusUpdates.length,
};
// Audit the full-DB export: this payload carries webhook + plugin-instance secrets, so WHO pulled
@@ -1215,8 +1221,10 @@ export class InfraController {
ingressEvents,
webhookDeliveryFailures,
integrationDeliveryFailures,
+ statusUpdates,
},
counts,
+ skippedTables,
};
}
@@ -1229,6 +1237,16 @@ export class InfraController {
schema: {
type: 'object',
properties: {
+ force: {
+ type: 'boolean',
+ description:
+ 'Allow the replace to proceed even while engines are running for sessions the backup does not contain (they keep running until restart; see restartRequired). Prefer stopOrphans, which closes that window inside this request instead.',
+ },
+ stopOrphans: {
+ type: 'boolean',
+ description:
+ 'Stop the running engines for sessions the backup does not contain, inside this request and before the replace runs. Supersedes force for the orphan case: with stopOrphans the engines no longer need a process restart to reconcile, so restartRequired stays false on the success path.',
+ },
tables: {
type: 'object',
properties: {
@@ -1236,16 +1254,31 @@ export class InfraController {
webhooks: { type: 'array' },
messages: { type: 'array' },
messageBatches: { type: 'array' },
+ statusUpdates: { type: 'array' },
},
},
},
},
})
@ApiResponse({ status: 200, description: 'Data imported successfully' })
+ @ApiResponse({
+ status: 409,
+ description:
+ 'Refused: live engines exist for sessions the backup would remove (retry with stopOrphans=true to stop them in-request, or force=true to proceed and restart after)',
+ })
async importData(
@Body()
data: {
tables: Partial<MigrationTables>;
+ force?: boolean;
+ /**
+ * Stop the running engines for sessions the backup does not contain, inside this request and
+ * before the replace runs (best-effort, time-bounded per engine). Supersedes force=true for the
+ * orphan case: with stopOrphans the engines no longer need a process restart to reconcile, so
+ * restartRequired stays false on the success path. Without it the pre-existing behavior holds —
+ * refuse with 409, or proceed with force=true and leave the engines running until restart.
+ */
+ stopOrphans?: boolean;
},
): Promise<{
imported: boolean;
@@ -1262,10 +1295,89 @@ export class InfraController {
ingressEvents: number;
webhookDeliveryFailures: number;
integrationDeliveryFailures: number;
+ statusUpdates: number;
};
warnings: string[];
+ /**
+ * Non-fatal operator-facing messages (e.g. orphan-engine reconciliation details). Distinct from
+ * warnings: notices never cause a rollback, while warnings make the replace-rollback gate fire.
+ */
+ notices: string[];
+ /** True when live engines were left pointing at sessions this restore removed — restart to stop them. */
+ restartRequired: boolean;
+ /** Session ids with a running engine that the restored data no longer contains. */
+ orphanedEngines: string[];
+ /** Orphan engines stopped inside this request (only populated when stopOrphans=true was passed). */
+ stoppedOrphanEngines: string[];
+ /** Orphan engines whose teardown threw or timed out (Map reconciled regardless; investigate). */
+ failedOrphanEngines: string[];
}> {
const warnings: string[] = [];
+
+ // Runtime reconciliation, part 1 (pre-flight): the replace below DELETES every session not in the
+ // backup, but an engine started for such a session keeps running as an unstoppable zombie (the
+ // session service keys engines by session id, and every stop path goes through the now-missing DB
+ // row) whose inbound messages land in tables that were just replaced. Three operator-chosen paths:
+ // - default: refuse with 409 listing the orphan ids;
+ // - force=true: proceed and leave the engines running until process restart (restartRequired=true);
+ // - stopOrphans=true: stop each orphan engine inside this request (best-effort, time-bounded,
+ // isolated per engine) and then proceed — restartRequired stays false on the success path.
+ // stopOrphans is preferred over force for the orphan case: a force restore that silently leaves
+ // engines writing into the freshly replaced tables for an unbounded time is the corruption this
+ // gate exists to prevent, so the explicit-stop path closes that window instead of relying on the
+ // operator to restart promptly.
+ const importedSessionIds = new Set((data.tables.sessions ?? []).map(s => s.id));
+ const orphanedEngines = (this.sessionService?.getActiveSessionIds() ?? []).filter(
+ id => !importedSessionIds.has(id),
+ );
+
+ let stoppedOrphanEngines: string[] = [];
+ let failedOrphanEngines: string[] = [];
+ let restartRequired = false;
+
+ // notices collect non-fatal operator-facing messages (orphan-engine reconciliation details) that
+ // must NOT trip the warnings→rollback gate further down. warnings is reserved for per-row import
+ // failures that make the replace partial and therefore require a rollback.
+ const notices: string[] = [];
+
+ if (orphanedEngines.length > 0 && data.stopOrphans && this.sessionService) {
+ // Stop the orphans inside this request, BEFORE the transaction opens. destroyEngineSafely's
+ // per-engine 10s deadline bounds the worst case (a stuck Chromium cannot wedge the import); the
+ // engines are reconciled from the Map regardless of teardown outcome.
+ const result = await this.sessionService.stopOrphanEngines(orphanedEngines);
+ stoppedOrphanEngines = result.stopped;
+ failedOrphanEngines = result.failed;
+ if (failedOrphanEngines.length > 0) {
+ // Teardown failed for at least one orphan. The Map entry is removed regardless (see
+ // stopOrphanEngines), so the engine no longer holds a concurrency slot — but its underlying
+ // Chromium/socket may still be alive and writing into restored tables. Surface the ids and
+ // flag restartRequired so the operator does not read a clean response as "engines stopped".
+ restartRequired = true;
+ notices.push(
+ `Teardown failed for ${failedOrphanEngines.length} orphan engine(s): ${failedOrphanEngines.join(', ')} ` +
+ `(removed from the engine registry; a process restart guarantees cleanup).`,
+ );
+ }
+ // Engines still mid-initialization (no Map entry yet) are reported in notRunning: their start()
+ // self-aborts via the stop mark, but they are not counted as stopped here.
+ if (result.notRunning.length > 0) {
+ notices.push(
+ `${result.notRunning.length} orphan session(s) had no live engine yet (still initializing): ` +
+ `${result.notRunning.join(', ')} — their start() will self-abort.`,
+ );
+ }
+ } else if (orphanedEngines.length > 0 && !data.force) {
+ throw new ConflictException(
+ `Import would orphan ${orphanedEngines.length} running engine(s) for session(s) ` +
+ `${orphanedEngines.join(', ')} that the backup does not contain. Stop them first, retry with ` +
+ `stopOrphans=true (stops them inside this request), or retry with force=true ` +
+ `(a server restart is then required to stop the orphaned engines).`,
+ );
+ } else if (orphanedEngines.length > 0 && data.force) {
+ // Legacy escape hatch: proceed and leave the engines running until restart.
+ restartRequired = true;
+ }
+
const queryRunner = this.dataDataSource.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
@@ -1313,6 +1425,8 @@ export class InfraController {
await clearTable('ingress_events');
await clearTable('webhook_delivery_failures');
await clearTable('integration_delivery_failures');
+ // status_updates has no FK to sessions; clear it explicitly so the replace is complete.
+ await clearTable('status_updates');
await queryRunner.query('DELETE FROM sessions');
// Import sessions first
@@ -1672,6 +1786,40 @@ export class InfraController {
}
}
+ // Import status updates (24h-TTL status/story store; sessionId is non-FK provenance)
+ let statusUpdatesCount = 0;
+ if (data.tables.statusUpdates?.length) {
+ for (const su of data.tables.statusUpdates) {
+ try {
+ await insert(
+ `INSERT INTO status_updates (id, "sessionId", "contactJid", "contactName", "contactPushName", "waStatusId", type, caption, "mediaPath", "mediaMimetype", "mediaOmitted", "omitReason", "backgroundColor", font, "postedAt", "expiresAt")
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16)`,
+ [
+ su.id,
+ su.sessionId,
+ su.contactJid,
+ su.contactName ?? null,
+ su.contactPushName ?? null,
+ su.waStatusId,
+ su.type,
+ su.caption ?? null,
+ su.mediaPath ?? null,
+ su.mediaMimetype ?? null,
+ su.mediaOmitted ?? false,
+ su.omitReason ?? null,
+ su.backgroundColor ?? null,
+ su.font ?? null,
+ su.postedAt,
+ su.expiresAt,
+ ],
+ );
+ statusUpdatesCount++;
+ } catch (err) {
+ warnings.push(`Failed to import status update ${su.id}: ${err}`);
+ }
+ }
+ }
+
const counts = {
sessions: sessionsCount,
webhooks: webhooksCount,
@@ -1685,6 +1833,7 @@ export class InfraController {
ingressEvents: ingressEventsCount,
webhookDeliveryFailures: webhookDeliveryFailuresCount,
integrationDeliveryFailures: integrationDeliveryFailuresCount,
+ statusUpdates: statusUpdatesCount,
};
// "Replace all data" must be all-or-nothing: the import already DELETEd every row, so if any
@@ -1693,7 +1842,16 @@ export class InfraController {
// message history could silently vanish on a SQLite->Postgres migration.
if (warnings.length > 0) {
await queryRunner.rollbackTransaction();
- return { imported: false, counts, warnings };
+ return {
+ imported: false,
+ counts,
+ warnings,
+ notices,
+ restartRequired: false,
+ orphanedEngines: [],
+ stoppedOrphanEngines: [],
+ failedOrphanEngines: [],
+ };
}
// A wrong/empty/garbage backup file restores zero rows but the DELETE already ran — committing
@@ -1705,18 +1863,41 @@ export class InfraController {
imported: false,
counts,
warnings: ['Backup contained no rows to restore; refused to replace existing data. Check the file.'],
+ notices,
+ restartRequired: false,
+ orphanedEngines: [],
+ stoppedOrphanEngines: [],
+ failedOrphanEngines: [],
};
}
await queryRunner.commitTransaction();
+ // Runtime reconciliation, part 2 (post-commit): the in-memory lid->phone mirror was warmed from
+ // the OLD lid_mappings rows and is write-through only, so the just-restored table would never
+ // reach it — resolution would keep serving stale entries (and miss restored ones) until the next
+ // process start. Reload from the new DB contents. Best-effort: a miss falls back to engine
+ // re-resolution, so a reload failure degrades instead of failing the (already committed) import.
+ await this.lidMappingStore?.reload();
+
// Audit the destructive replace-all restore, only on the committed-success path (the rollback /
// refused-empty branches above return without emitting, since no data actually changed). Any
// warnings would have taken the rollback branch, so warnings.length is always 0 here — record
// only the per-table counts.
await this.auditService?.logInfo(AuditAction.INFRA_DATA_IMPORTED, { metadata: { counts } });
- return { imported: true, counts, warnings };
+ // restartRequired was computed in the pre-flight: true only when orphans were left running
+ // (force=true legacy path) or when stopOrphans teardown failed for at least one engine.
+ return {
+ imported: true,
+ counts,
+ warnings,
+ notices,
+ restartRequired,
+ orphanedEngines,
+ stoppedOrphanEngines,
+ failedOrphanEngines,
+ };
} catch (error) {
await queryRunner.rollbackTransaction();
throw error;
@@ -1773,6 +1954,13 @@ export class InfraController {
await new Promise<void>((resolve, reject) => {
writeStream.on('finish', resolve);
writeStream.on('error', reject);
+ // pipe() does NOT forward source errors: an archiver/gzip failure surfaces as an 'error' event on
+ // the source stream, which without a listener crashes the process. Fail the request instead and
+ // tear down the sink so its fd isn't held open waiting for a 'finish' that never comes.
+ stream.on('error', (err: Error) => {
+ writeStream.destroy();
+ reject(err);
+ });
});
// Sweep the throwaway archive so repeated exports don't accumulate on the data volume.
@@ -1822,7 +2010,17 @@ export class InfraController {
}
const readStream = fs.createReadStream(resolved);
- const count = await this.storageService.importFromStream(readStream);
+ // importFromStream rejects on archive/gzip/read failures (its streams carry error listeners, so a
+ // bad file fails the request instead of crashing the process on an unhandled 'error' event). The
+ // failures that reach here are almost always a problem with the caller-supplied file (not a gzip,
+ // not a tar, unreadable, over the resource caps), so surface them as a 400 with the real reason
+ // rather than an opaque 500.
+ let count: number;
+ try {
+ count = await this.storageService.importFromStream(readStream);
+ } catch (error) {
+ throw new BadRequestException(`Storage import failed: ${error instanceof Error ? error.message : String(error)}`);
+ }
const storageType = this.storageService.getCurrentStorageType();
// Audit the bulk media-import (files written into the active storage backend).
diff --git a/src/modules/infra/infra.module.ts b/src/modules/infra/infra.module.ts
index 9a8a6068f..6f0f37b04 100644
--- a/src/modules/infra/infra.module.ts
+++ b/src/modules/infra/infra.module.ts
@@ -2,6 +2,7 @@ import { Module, DynamicModule, Type } from '@nestjs/common';
import { InfraController } from './infra.controller';
import { EngineModule } from '../../engine/engine.module';
import { DockerModule } from '../docker';
+import { SessionModule } from '../session/session.module';
// Only import QueueModule if explicitly enabled to avoid Redis connection errors. It registers and
// exports the webhook queue, which the controller injects (@Optional) to report live job counts.
@@ -13,7 +14,9 @@ if (process.env.QUEUE_ENABLED === 'true') {
}
@Module({
- imports: [EngineModule, DockerModule, ...queueModules],
+ // SessionModule gives the controller the live-engine registry for the import pre-flight orphan
+ // check. Its own imports (WebhookModule, StatusStoreModule) never point back here — no cycle.
+ imports: [EngineModule, DockerModule, SessionModule, ...queueModules],
controllers: [InfraController],
})
export class InfraModule {}
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index 64c54be6b..229bd90ad 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -312,6 +312,85 @@ describe('SessionService', () => {
});
});
+ // ── stopOrphanEngines (infra import path) ─────────────────────────
+ describe('stopOrphanEngines', () => {
+ const enginesOf = () => (service as unknown as { engines: Map<string, unknown> }).engines;
+ const stoppingOf = () => (service as unknown as { stoppingSessions: Set<string> }).stoppingSessions;
+
+ it('stops each running orphan engine, reconciles the map, and reports stopped', async () => {
+ const g1 = { destroy: jest.fn().mockResolvedValue(undefined) };
+ const g2 = { destroy: jest.fn().mockResolvedValue(undefined) };
+ enginesOf().set('g1', g1);
+ enginesOf().set('g2', g2);
+
+ const result = await service.stopOrphanEngines(['g1', 'g2']);
+
+ expect(g1.destroy).toHaveBeenCalledTimes(1);
+ expect(g2.destroy).toHaveBeenCalledTimes(1);
+ expect(enginesOf().has('g1')).toBe(false);
+ expect(enginesOf().has('g2')).toBe(false);
+ expect(result.stopped.sort()).toEqual(['g1', 'g2']);
+ expect(result.notRunning).toEqual([]);
+ expect(result.failed).toEqual([]);
+ // The stop mark blocks a late reconnect from resurrecting either id mid-teardown.
+ expect(stoppingOf().has('g1')).toBe(true);
+ expect(stoppingOf().has('g2')).toBe(true);
+ });
+
+ it('reports an id without a live engine as notRunning (still initializing — start() self-aborts via the mark)', async () => {
+ const g1 = { destroy: jest.fn().mockResolvedValue(undefined) };
+ enginesOf().set('g1', g1);
+ // 'g-init' is in the requested list but has no Map entry.
+
+ const result = await service.stopOrphanEngines(['g1', 'g-init']);
+
+ expect(result.stopped).toEqual(['g1']);
+ expect(result.notRunning).toEqual(['g-init']);
+ expect(result.failed).toEqual([]);
+ expect(stoppingOf().has('g-init')).toBe(true); // still marked so start() aborts
+ });
+
+ it('isolates a failing destroy(): teardown is best-effort so both engines are reconciled from the map', async () => {
+ // destroyEngineSafely delegates to teardownEngineSafely, which isolates + time-bounds failures and
+ // never throws — a stuck destroy() therefore cannot stall the batch or poison other orphans. The
+ // engine is removed from the Map regardless of teardown outcome (it stops holding a slot).
+ const good = { destroy: jest.fn().mockResolvedValue(undefined) };
+ const bad = { destroy: jest.fn().mockRejectedValue(new Error('stuck chromium')) };
+ enginesOf().set('good', good);
+ enginesOf().set('bad', bad);
+
+ const result = await service.stopOrphanEngines(['good', 'bad']);
+
+ expect(good.destroy).toHaveBeenCalledTimes(1);
+ expect(bad.destroy).toHaveBeenCalledTimes(1);
+ // Map reconciled for both regardless of teardown outcome — neither holds a concurrency slot.
+ expect(enginesOf().has('good')).toBe(false);
+ expect(enginesOf().has('bad')).toBe(false);
+ expect(result.failed).toEqual([]); // teardown failures are isolated, not surfaced as failed
+ expect(result.stopped.sort()).toEqual(['bad', 'good']);
+ });
+
+ it('is a bounded no-op for an empty id list', async () => {
+ const result = await service.stopOrphanEngines([]);
+ expect(result).toEqual({ stopped: [], notRunning: [], failed: [] });
+ });
+
+ it('cancels an in-flight reconnect for each orphan before teardown', async () => {
+ const engine = { destroy: jest.fn().mockResolvedValue(undefined) };
+ enginesOf().set('g1', engine);
+ const reconnectStates = (
+ service as unknown as {
+ reconnectStates: Map<string, unknown>;
+ }
+ ).reconnectStates;
+ reconnectStates.set('g1', { timer: null }); // exercise the cancelReconnect path
+
+ await service.stopOrphanEngines(['g1']);
+
+ expect(reconnectStates.has('g1')).toBe(false);
+ });
+ });
+
// ── create ────────────────────────────────────────────────────────
describe('create', () => {
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index 1a8150912..e7f620eed 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -2356,6 +2356,73 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
return this.engines.has(id);
}
+ /**
+ * Ids of every session with a live engine — including ones mid-initialization (their engine is not
+ * in `engines` yet but will register when start() completes). The infra import pre-flight uses this
+ * to refuse a full-replace restore that would orphan a running engine.
+ */
+ getActiveSessionIds(): string[] {
+ return [...new Set([...this.engines.keys(), ...this.initializingSessions])];
+ }
+
+ /**
+ * Stop the engines for the given session ids WITHOUT touching the sessions DB row (the caller,
+ * the infra import path, is about to DELETE that row as part of a full replace). This is the one
+ * stop path that bypasses findOne()/stop()/delete() — every other path keys through the row, so an
+ * engine orphaned by a restore was previously unstoppable until process restart.
+ *
+ * Each id is handled in isolation and time-bounded: a stuck Chromium/socket on one orphan can
+ * neither stall nor abort the others, and the whole call is bounded by teardownEngineSafely's
+ * per-engine 10s deadline. The mark + reconnect-cancel happen first so an in-flight reconnect
+ * cannot resurrect the id while teardown runs. Engines that are mid-initialization (no entry in
+ * `engines` yet) are marked but cannot be torn down here — their start() will see the stop mark
+ * via its existing guard and self-abort; the caller learns about them in `notRunning`.
+ *
+ * Always resolves. Best-effort: a `failed` entry means teardown threw or timed out, and the engine
+ * is removed from the Map regardless so it stops holding a concurrency slot.
+ */
+ async stopOrphanEngines(
+ sessionIds: string[],
+ ): Promise<{ stopped: string[]; notRunning: string[]; failed: string[] }> {
+ const stopped: string[] = [];
+ const notRunning: string[] = [];
+ const failed: string[] = [];
+
+ if (sessionIds.length === 0) return { stopped, notRunning, failed };
+
+ await Promise.allSettled(
+ sessionIds.map(async id => {
+ // Mark + cancel BEFORE teardown so a late reconnect cannot resurrect the id mid-teardown.
+ this.stoppingSessions.add(id);
+ this.cancelReconnect(id);
+
+ const engine = this.engines.get(id);
+ if (!engine) {
+ // Either never started, or still inside initializeEngine (no Map entry yet). The stop mark
+ // above is what aborts the initializing case via start()'s existing guard.
+ notRunning.push(id);
+ return;
+ }
+ try {
+ await this.destroyEngineSafely(id, engine);
+ if (this.isLiveEngine(id, engine)) this.engines.delete(id);
+ stopped.push(id);
+ } catch (err) {
+ // destroyEngineSafely never throws today (it isolates via teardownEngineSafely), but defend
+ // against a future change so a single orphan cannot abort the batch.
+ this.logger.error(`Failed to stop orphan engine for session ${id}`, String(err), {
+ sessionId: id,
+ action: 'stop_orphan_failed',
+ });
+ if (this.isLiveEngine(id, engine)) this.engines.delete(id);
+ failed.push(id);
+ }
+ }),
+ );
+
+ return { stopped, notRunning, failed };
+ }
+
private delay(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}