Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(infra): identify the retryable import refusal by a code, not by absence
Yudhi Armyndharis26d9b7fe4266
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex eade90ab5..32cb7fd04 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -19,7 +19,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed-- **A refused data import no longer offers a retry that stops live engines** — the dashboard read the `409` status rather than its machine code, so a refusal that only asks the operator to wait presented a confirm whose OK re-ran the replace-all with `stopOrphans=true`.+- **A refused data import no longer offers a retry that stops live engines** — the one refusal whose retry is destructive now carries `IMPORT_WOULD_ORPHAN_ENGINES` and the dashboard matches it positively, so a refusal that only asks the operator to wait can no longer present a confirm whose OK re-runs the replace-all with `stopOrphans=true`.- **A data import is refused with `409` when another transaction holds the connection** — on SQLite it would otherwise nest inside that transaction and commit into it rather than to disk, so a restore reported as successful could vanish with that transaction's rollback.- **A second data import while one is running is now refused with `409`** — on SQLite both shared a single transaction, so the second one's rollback discarded a restore the first had already reported as successful.- **A replace-all data import no longer disturbs the engines it left running** — the restore dropped each session's ownership lease and, on SQLite, the heartbeat could read the half-applied transaction, so a renewal concluded the claim was lost and tore down engines that had never stopped.diff --git a/dashboard/src/hooks/useDataBackup.ts b/dashboard/src/hooks/useDataBackup.tsindex fc2caac0d..bc7dcdf1e 100644--- a/dashboard/src/hooks/useDataBackup.ts+++ b/dashboard/src/hooks/useDataBackup.ts@@ -45,12 +45,12 @@ export function useDataBackup(): DataBackup {// POST the replace-all restore and fold the backend's orphan-engine contract into the UI. The route// answers 409 for several different reasons and they need opposite handling, so branch on the- // machine code, never on the status alone: a coded refusal (IMPORT_ALREADY_RUNNING, another restore- // in flight; IMPORT_NESTED_TRANSACTION, another transaction holds the connection) leaves nothing to- // decide, and retrying it with stopOrphans would run a second destructive replace the operator- // never asked for. The orphan case does have a decision — live engines exist for sessions- // the backup would remove — and its preferred retry is stopOrphans=true, which stops them inside- // the request, so that one is offered as a confirm. force=true is deliberately not offered (the api+ // machine code, never on the status alone. Only IMPORT_WOULD_ORPHAN_ENGINES is a decision — live+ // engines exist for sessions the backup would remove — and its preferred retry is stopOrphans=true,+ // which stops them inside the request, so that one is offered as a confirm. Every other 409 leaves+ // nothing to decide (another restore in flight, another transaction holding the connection), and+ // retrying one with stopOrphans would run a second destructive replace the operator never asked+ // for. force=true is deliberately not offered (the api// client does not even send it): it leaves the engines running until a restart.const runImport = async (tables: Record<string, unknown[]>, stopOrphans = false): Promise<void> => {try {diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.tsindex 8cce30447..872e7e516 100644--- a/dashboard/src/services/api.ts+++ b/dashboard/src/services/api.ts@@ -1073,12 +1073,12 @@ export const infraApi = {counts: Record<string, number>;}>('/infra/export-data'),// 200 contract includes the orphan-engine reconciliation result (restartRequired / notices /- // stopped+failed ids). 409 has several causes and the error's `code` distinguishes them: a coded- // refusal is a "not now" with nothing to retry (IMPORT_ALREADY_RUNNING, another restore is in- // flight; IMPORT_NESTED_TRANSACTION, another transaction holds the connection), while the- // code-less orphan case (live engines exist for sessions the backup would remove; the message- // lists them) is the one the caller retries with stopOrphans=true to stop those engines inside- // the request. force is+ // stopped+failed ids). 409 has several causes and the error's `code` distinguishes them:+ // IMPORT_WOULD_ORPHAN_ENGINES (live engines exist for sessions the backup would remove; the+ // message lists them) is the only one the caller retries with stopOrphans=true to stop those+ // engines inside the request. IMPORT_ALREADY_RUNNING (another restore is in flight) and+ // IMPORT_NESTED_TRANSACTION (another transaction holds the connection) leave nothing to retry.+ // force is// deliberately NOT exposed: it leaves the engines writing into the restored tables until a// restart — the window stopOrphans exists to close.importData: (tables: Record<string, unknown[]>, options?: { stopOrphans?: boolean }) =>diff --git a/dashboard/src/utils/importRefusal.test.ts b/dashboard/src/utils/importRefusal.test.tsindex 9273d2c5d..f1abfe1c4 100644--- a/dashboard/src/utils/importRefusal.test.ts+++ b/dashboard/src/utils/importRefusal.test.ts@@ -8,7 +8,7 @@ import { shouldOfferStopOrphansRetry } from './importRefusal.ts';// acknowledgement and ran a second full replace nobody asked for.test('offers the retry for the orphan-engine refusal, which is a real decision', () => {- assert.equal(shouldOfferStopOrphansRetry(409, undefined, false), true);+ assert.equal(shouldOfferStopOrphansRetry(409, 'IMPORT_WOULD_ORPHAN_ENGINES', false), true);});test('never offers the retry when another import is already running', () => {@@ -16,7 +16,14 @@ test('never offers the retry when another import is already running', () => {});test('does not loop: a 409 on the retry itself is not offered again', () => {- assert.equal(shouldOfferStopOrphansRetry(409, undefined, true), false);+ assert.equal(shouldOfferStopOrphansRetry(409, 'IMPORT_WOULD_ORPHAN_ENGINES', true), false);+});++test('a 409 carrying no code at all does not open the destructive confirm', () => {+ // Not hypothetical: a reverse proxy, a gateway error page or a body that never parsed all arrive+ // with no code, and the api client then synthesises the message as "HTTP 409". Identifying the+ // destructive case by the ABSENCE of a code would offer to tear down live engines for those.+ assert.equal(shouldOfferStopOrphansRetry(409, undefined, false), false);});test('leaves every other status alone', () => {@@ -34,3 +41,7 @@ test('an unknown future 409 code does not get the destructive retry', () => {// safe default is to withhold a retry that stops live engines and replaces every table again.assert.equal(shouldOfferStopOrphansRetry(409, 'SOME_FUTURE_CODE', false), false);});++test('only the 409 status can offer it, whatever the code says', () => {+ assert.equal(shouldOfferStopOrphansRetry(500, 'IMPORT_WOULD_ORPHAN_ENGINES', false), false);+});diff --git a/dashboard/src/utils/importRefusal.ts b/dashboard/src/utils/importRefusal.tsindex 672c9caee..577f6b797 100644--- a/dashboard/src/utils/importRefusal.ts+++ b/dashboard/src/utils/importRefusal.ts@@ -1,16 +1,20 @@/*** POST /infra/import-data answers 409 for unrelated reasons, and they need opposite handling.*- * The orphan case is a DECISION: live engines exist for sessions the backup would remove, and the- * documented retry is `stopOrphans=true`, which stops them inside the request. Offering that as a- * confirm is right — and it is the only refusal the endpoint throws without a machine `code`.+ * Exactly one of them is a DECISION the operator can act on: live engines exist for sessions the+ * backup would remove, and the documented retry is `stopOrphans=true`, which stops them inside the+ * request. That retry is destructive, so it is offered only for `IMPORT_WOULD_ORPHAN_ENGINES` —+ * matched POSITIVELY. The other refusals are "not now" answers (another restore is in flight,+ * another transaction holds the connection) where the only useful response is to wait and retry+ * unchanged; offering them the retry would run a second replace-all the operator never asked for,+ * from a dialog whose message says wait.*- * Every coded refusal is a "not now" instead: another restore is in flight, or another transaction- * holds the connection. The caller can only wait and retry unchanged. Retrying one with- * `stopOrphans` would run a second destructive replace-all the operator never asked for — tearing- * down live engines — from a dialog whose message says wait. So the presence of a code, not the- * status, decides; an unrecognised code withholds the retry, which costs the operator nothing- * because the refusal is still shown as an error toast carrying the server's own message.+ * Matching positively rather than excluding known codes is load-bearing. A 409 with no code is the+ * DEFAULT state, not evidence of the orphan case: a reverse proxy, a gateway error page or a body+ * that never parsed all produce one, and so would any refusal added later by an author who does not+ * know a destructive confirm keys on this. Withholding costs nothing — the refusal is still shown+ * as an error toast carrying the server's own message. The backend pins its half of this contract+ * in the infra-data controller spec.*/export function shouldOfferStopOrphansRetry(status: number | undefined,@@ -20,5 +24,5 @@ export function shouldOfferStopOrphansRetry(if (status !== 409) return false;// A 409 on the retry itself (an engine started mid-import) must not loop.if (alreadyRetriedWithStopOrphans) return false;- return code === undefined;+ return code === 'IMPORT_WOULD_ORPHAN_ENGINES';}diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex cb027ac3f..4b4c7b4f5 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -5158,7 +5158,7 @@ Because that pre-flight runs _before_ the transaction, its teardown is not coverInside 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 error+**Errors:** `401` · `403` · `409` refused, with the reason in `code` — `IMPORT_WOULD_ORPHAN_ENGINES` (live engines exist for sessions the backup does not contain; retry with `stopOrphans` or `force`), `IMPORT_ALREADY_RUNNING` (another import is running; wait for it), `IMPORT_NESTED_TRANSACTION` (another database transaction holds the connection; retry with nothing else in flight) · `500` `tables` missing/null or unrecoverable DB error---diff --git a/openapi.json b/openapi.jsonindex 18d48f7cd..acb38ee36 100644--- a/openapi.json+++ b/openapi.json@@ -3410,7 +3410,7 @@"description": "Data imported successfully"},"409": {- "description": "Refused. code IMPORT_ALREADY_RUNNING: another import is running — wait for it. code IMPORT_NESTED_TRANSACTION: another database transaction holds this connection, so a restore could not be made durable — retry with nothing else in flight. Otherwise: 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)"+ "description": "Refused, with the reason in `code`. IMPORT_ALREADY_RUNNING: another import is running — wait for it. IMPORT_NESTED_TRANSACTION: another database transaction holds this connection, so a restore could not be made durable — retry with nothing else in flight. IMPORT_WOULD_ORPHAN_ENGINES: 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. Only the last of these is retryable with stopOrphans; the others leave nothing to decide"}},"summary": "Import data to Data DB (replaces existing data)",diff --git a/src/modules/infra/infra-data.controller.spec.ts b/src/modules/infra/infra-data.controller.spec.tsindex 9a1fa9b10..9500fde7f 100644--- a/src/modules/infra/infra-data.controller.spec.ts+++ b/src/modules/infra/infra-data.controller.spec.ts@@ -176,7 +176,11 @@ describe('InfraDataController.importData round-trips export-data (no silent messawait outer.connect();await outer.startTransaction();- await expect(controller.importData({ tables: dump.tables })).rejects.toMatchObject({ status: 409 });+ const refusal = await controller.importData({ tables: dump.tables }).catch((e: unknown) => e);+ expect((refusal as ConflictException).getStatus()).toBe(409);+ // The dashboard decides whether to offer the destructive stop-orphans retry by matching this+ // code positively, so which code this refusal carries is a cross-tier contract, not a detail.+ expect((refusal as ConflictException).getResponse()).toMatchObject({ code: 'IMPORT_NESTED_TRANSACTION' });// The decisive assertion: nothing was destroyed on the way to the refusal.const survived = await ds.getRepository(Session).findOneBy({ id: 's1' });@@ -215,7 +219,9 @@ describe('InfraDataController.importData round-trips export-data (no silent messconst first = controller.importData({ tables: dump.tables });const second = controller.importData({ tables: dump.tables });- await expect(second).rejects.toMatchObject({ status: 409 });+ const refusal = await second.catch((e: unknown) => e);+ expect((refusal as ConflictException).getStatus()).toBe(409);+ expect((refusal as ConflictException).getResponse()).toMatchObject({ code: 'IMPORT_ALREADY_RUNNING' });await expect(first).resolves.toMatchObject({ imported: true });});@@ -1301,6 +1307,11 @@ describe('InfraDataController.importData status_updates + runtime reconciliationexpect(err).toBeInstanceOf(ConflictException);expect((err as ConflictException).getStatus()).toBe(409);expect((err as ConflictException).message).toContain('ghost');+ // This is the ONLY refusal on this route whose documented retry (stopOrphans=true) is a real+ // decision the operator can act on, and it is the only one the dashboard may offer a destructive+ // retry for. It carries its own code so that identification is positive: an unrecognised code and+ // a 409 that never reached this method both fail closed instead of opening the confirm.+ expect((err as ConflictException).getResponse()).toMatchObject({ code: 'IMPORT_WOULD_ORPHAN_ENGINES' });expect(await ds.getRepository(Session).count()).toBe(1); // nothing deleted// With force: the restore proceeds and the response tells the operator a restart is requireddiff --git a/src/modules/infra/infra-data.controller.ts b/src/modules/infra/infra-data.controller.tsindex 8a2172f00..192cbb7a5 100644--- a/src/modules/infra/infra-data.controller.ts+++ b/src/modules/infra/infra-data.controller.ts@@ -288,7 +288,7 @@ export class InfraDataController {@ApiResponse({status: 409,description:- 'Refused. code IMPORT_ALREADY_RUNNING: another import is running — wait for it. code IMPORT_NESTED_TRANSACTION: another database transaction holds this connection, so a restore could not be made durable — retry with nothing else in flight. Otherwise: 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)',+ 'Refused, with the reason in `code`. IMPORT_ALREADY_RUNNING: another import is running — wait for it. IMPORT_NESTED_TRANSACTION: another database transaction holds this connection, so a restore could not be made durable — retry with nothing else in flight. IMPORT_WOULD_ORPHAN_ENGINES: 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. Only the last of these is retryable with stopOrphans; the others leave nothing to decide',})async importData(@Body()@@ -422,12 +422,21 @@ export class InfraDataController {);}} else if (orphanedEngines.length > 0 && !data.force) {- throw new ConflictException(- `Import would orphan ${orphanedEngines.length} running engine(s) for session(s) ` ++ // Carries a code like the other two refusals, and for a stronger reason: this is the ONLY 409+ // on this route whose documented retry (stopOrphans=true) is destructive — it stops live+ // engines — and the dashboard decides whether to offer that retry by matching this code. Were+ // it identified by the ABSENCE of a code instead, every unrecognised 409 (a proxy's, a body+ // that never parsed) would open a confirm whose OK tears down engines and replaces every table.+ throw new ConflictException({+ statusCode: 409,+ error: 'Conflict',+ message:+ `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).`,- );+ code: 'IMPORT_WOULD_ORPHAN_ENGINES',+ });} else if (orphanedEngines.length > 0 && data.force) {// Legacy escape hatch: proceed and leave the engines running until restart.restartRequired = true;