Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(infra): report the orphan teardown a rolled-back import already performed
Yudhi Armyndharisb2696d992fab
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1ad98b4cb..7435e9170 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -76,6 +76,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- **A rolled-back `POST /api/infra/import-data` no longer denies the engines it already stopped.** The+ orphan pre-flight runs *before* the transaction opens, and `stopOrphans: true` really destroys those+ engines there — a teardown the rollback cannot undo. Both rollback branches nevertheless returned a+ hardcoded `restartRequired: false` with three empty orphan arrays, so an operator who hit a per-row+ warning read "nothing was stopped, no restart needed" while their sessions were in fact down. They+ now report what actually happened, exactly as the success path already did.++ `restartRequired` on that path narrows to the one thing a rollback cannot undo: a **failed** teardown,+ which may have left a Chromium/socket alive. A cleanly stopped orphan leaves its session row intact+ (restart it with `POST /sessions/{id}/start`), and an engine `force` left running was never orphaned+ after all, because the data that would have orphaned it was not replaced. The response shape is+ unchanged and `openapi.json` is untouched — only the values were wrong.+- **A missing dashboard asset returns 404 instead of the SPA shell.** `ServeStaticModule`'s built-infallback answered *every* unmatched GET with `index.html`, so a mistyped or stale `<script src>`came back `200 text/html` and the browser reported a JavaScript syntax error from parsing the HTMLdiff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex f650b0fa5..6738680c4 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -4371,6 +4371,8 @@ Replace all Data DB rows with the supplied export. **Destructive and transaction**Orphan-engine pre-flight.** Before the transaction opens, any running engine whose session id is absent from `tables.sessions` is an orphan (the replace would delete its DB row, leaving an unstoppable engine writing into freshly restored tables). Default behaviour is to refuse with `409` listing those ids; `stopOrphans: true` stops them in-request and proceeds; `force: true` proceeds and leaves them running until restart.+Because that pre-flight runs *before* the transaction, its teardown is not covered by the rollback. A response with `imported:false` therefore still reports the engines it really stopped, and `restartRequired` on that path means only that a teardown **failed** — a cleanly stopped orphan leaves its session row intact (restart it with `POST /sessions/{id}/start`), and an engine `force` left running was never orphaned after all, since the data that would have orphaned it was not replaced.+Inside the transaction every migration table is emptied. `webhooks` and `sessions` are DELETEd directly, so a missing table there fails the restore; the other 11 go through a tolerant helper where a *genuinely missing* table is skipped. Any other DELETE failure propagates to the rollback. Rows are then re-inserted, sessions first. JSON object/array fields are auto-stringified before insert, and the Postgres-form `$N` placeholders are rewritten for SQLite. Two guards return `imported:false` after a rollback: any `warnings`, and a payload that restores **zero** rows in total (a wrong/empty backup would otherwise commit a silent wipe — the response then carries `Backup contained no rows to restore; refused to replace existing data. Check the file.`). On commit the lid→phone mirror is reloaded from the restored rows.**Errors:** `401` · `403` · `409` live engines exist for sessions the backup does not contain (retry with `stopOrphans` or `force`) · `500` `tables` missing/null or unrecoverable DB errordiff --git a/src/modules/infra/infra.controller.spec.ts b/src/modules/infra/infra.controller.spec.tsindex a4a6320c6..57404ca92 100644--- a/src/modules/infra/infra.controller.spec.ts+++ b/src/modules/infra/infra.controller.spec.ts@@ -2623,6 +2623,60 @@ describe('InfraController.importData status_updates + runtime reconciliation', (expect(res.orphanedEngines).toEqual(['ghost']);});+ it('still reports the engines it already stopped when the import rolls back', async () => {+ // The pre-flight teardown runs BEFORE the transaction opens and cannot be rolled back with it.+ // An operator reading imported:false plus empty orphan arrays would conclude nothing happened,+ // while their sessions are actually down.+ await seedSession('s1');+ const stopOrphanEngines = jest.fn().mockResolvedValue({ stopped: ['ghost'], notRunning: [], failed: [] });+ const controller = build({+ sessionService: { getActiveSessionIds: () => ['ghost'], stopOrphanEngines },+ });+ const dump = await controller.exportData();++ // A message row missing the non-null from/to fails mid-import and forces the all-or-nothing rollback.+ const res = await controller.importData({+ tables: {+ ...dump.tables,+ messages: [+ { id: 'mX', sessionId: 's1', chatId: 'c', type: 'text', direction: 'incoming', status: 'sent' },+ ] as never,+ },+ stopOrphans: true,+ });++ expect(res.imported).toBe(false); // the DB really did roll back+ expect(stopOrphanEngines).toHaveBeenCalledWith(['ghost']); // ...but the teardown really did happen+ expect(res.stoppedOrphanEngines).toEqual(['ghost']);+ expect(res.orphanedEngines).toEqual(['ghost']);+ expect(res.restartRequired).toBe(false); // sessions survive the rollback; restart them via the API+ });++ it('flags restartRequired on a rolled-back import whose orphan teardown failed', async () => {+ // The failed teardown is the one irreversible thing a rollback cannot undo: the Chromium/socket+ // may still be alive, so this must stay true even though no data changed.+ await seedSession('s1');+ const stopOrphanEngines = jest.fn().mockResolvedValue({ stopped: [], notRunning: [], failed: ['ghost'] });+ const controller = build({+ sessionService: { getActiveSessionIds: () => ['ghost'], stopOrphanEngines },+ });+ const dump = await controller.exportData();++ const res = await controller.importData({+ tables: {+ ...dump.tables,+ messages: [+ { id: 'mX', sessionId: 's1', chatId: 'c', type: 'text', direction: 'incoming', status: 'sent' },+ ] as never,+ },+ stopOrphans: true,+ });++ expect(res.imported).toBe(false);+ expect(res.restartRequired).toBe(true);+ expect(res.failedOrphanEngines).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'] });diff --git a/src/modules/infra/infra.controller.ts b/src/modules/infra/infra.controller.tsindex b22156181..14bd1b608 100644--- a/src/modules/infra/infra.controller.ts+++ b/src/modules/infra/infra.controller.ts@@ -1407,6 +1407,23 @@ export class InfraController implements OnApplicationBootstrap {restartRequired = true;}+ // What the rollback branches below must report about the engines. The transaction can be rolled+ // back; the orphan teardown above CANNOT — it ran before the transaction opened and those engines+ // are already destroyed. Reporting empty arrays there would tell an operator nothing happened+ // while their sessions are down.+ //+ // restartRequired narrows to the one thing a rollback cannot undo: a FAILED teardown may have left+ // a Chromium/socket alive. The two other pre-flight outcomes do not survive the rollback as+ // restart-worthy — a cleanly stopped orphan leaves its session row intact (restart it through+ // POST /sessions/:id/start), and an engine the force path left running was never orphaned after+ // all, because the data it would have been orphaned by is gone.+ const engineStateAfterRollback = {+ restartRequired: failedOrphanEngines.length > 0,+ orphanedEngines,+ stoppedOrphanEngines,+ failedOrphanEngines,+ };+const queryRunner = this.dataDataSource.createQueryRunner();await queryRunner.connect();await queryRunner.startTransaction();@@ -1886,10 +1903,7 @@ export class InfraController implements OnApplicationBootstrap {counts,warnings,notices,- restartRequired: false,- orphanedEngines: [],- stoppedOrphanEngines: [],- failedOrphanEngines: [],+ ...engineStateAfterRollback,};}@@ -1903,10 +1917,7 @@ export class InfraController implements OnApplicationBootstrap {counts,warnings: ['Backup contained no rows to restore; refused to replace existing data. Check the file.'],notices,- restartRequired: false,- orphanedEngines: [],- stoppedOrphanEngines: [],- failedOrphanEngines: [],+ ...engineStateAfterRollback,};}