Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(infra): refuse a data import when another transaction holds the connection

Yudhi Armyndharis5cde77d017c8
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2e7c3ba73..e8efec26d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,6 +19,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- **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/openapi.json b/openapi.json
index 9b7a53506..18d48f7cd 100644
--- a/openapi.json
+++ b/openapi.json
@@ -3410,7 +3410,7 @@
"description": "Data imported successfully"
},
"409": {
- "description": "Refused, for one of two reasons: another import is already running (code IMPORT_ALREADY_RUNNING — wait for it, do not retry immediately); or 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. 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)"
}
},
"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.ts
index 7610b6d5e..9a1fa9b10 100644
--- a/src/modules/infra/infra-data.controller.spec.ts
+++ b/src/modules/infra/infra-data.controller.spec.ts
@@ -163,6 +163,42 @@ describe('InfraDataController.importData round-trips export-data (no silent mess
expect(held).toBe(0);
});
+ it('refuses outright when another transaction already holds the connection, before deleting anything', async () => {
+ await seedSession('s1');
+ const dump = await controller.exportData();
+
+ // better-sqlite3 hands out a SINGLETON runner, so an import started while a session create or
+ // delete holds a transaction becomes a SAVEPOINT inside it: its commit issues RELEASE SAVEPOINT,
+ // not COMMIT. The result is genuinely indeterminate — the enclosing transaction may commit (the
+ // replace lands) or roll back (it vanishes) — so detecting it afterwards cannot produce a
+ // truthful answer, and by then every row is already deleted. Refuse before touching anything.
+ const outer = ds.createQueryRunner();
+ await outer.connect();
+ await outer.startTransaction();
+
+ await expect(controller.importData({ tables: dump.tables })).rejects.toMatchObject({ status: 409 });
+
+ // The decisive assertion: nothing was destroyed on the way to the refusal.
+ const survived = await ds.getRepository(Session).findOneBy({ id: 's1' });
+ expect(survived).not.toBeNull();
+
+ await outer.rollbackTransaction();
+ await outer.release();
+ });
+
+ it('runs normally once no other transaction holds the connection', async () => {
+ await seedSession('s1');
+ const dump = await controller.exportData();
+
+ const outer = ds.createQueryRunner();
+ await outer.connect();
+ await outer.startTransaction();
+ await outer.rollbackTransaction();
+ await outer.release();
+
+ await expect(controller.importData({ tables: dump.tables })).resolves.toMatchObject({ imported: true });
+ });
+
it('refuses a second concurrent import instead of letting two share one transaction', async () => {
await seedSession('s1');
const dump = await controller.exportData();
diff --git a/src/modules/infra/infra-data.controller.ts b/src/modules/infra/infra-data.controller.ts
index 482c566f8..8a2172f00 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, for one of two reasons: another import is already running (code IMPORT_ALREADY_RUNNING — wait for it, do not retry immediately); or 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. 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)',
})
async importData(
@Body()
@@ -469,6 +469,29 @@ export class InfraDataController {
try {
const queryRunner = this.dataDataSource.createQueryRunner();
await queryRunner.connect();
+
+ // Refuse BEFORE a single row is deleted, not after. On better-sqlite3 every query runner is a
+ // driver SINGLETON, so if anything else already holds a transaction on this DataSource — a
+ // session create or delete — this import would not get its own: it would become a SAVEPOINT
+ // inside theirs, and commitTransaction() would issue RELEASE SAVEPOINT rather than COMMIT.
+ //
+ // The outcome of that is genuinely indeterminate, which is why detecting it afterwards is not
+ // good enough: if the enclosing transaction commits, the replace lands; if it rolls back, the
+ // replace vanishes. Either way this request cannot report the truth, and it has already
+ // deleted every row — including any the enclosing transaction just wrote. Refusing up front is
+ // the only answer that is both honest and non-destructive. On Postgres each runner gets its own
+ // pooled client, so this is always false there and the check costs nothing.
+ if (queryRunner.isTransactionActive) {
+ throw new ConflictException({
+ statusCode: 409,
+ error: 'Conflict',
+ message:
+ 'Another database transaction is in progress on this connection, so a restore could not be ' +
+ 'made durable. Retry with no other data operation in flight.',
+ code: 'IMPORT_NESTED_TRANSACTION',
+ });
+ }
+
// startTransaction is inside the runner's own try/finally, so a throw from it still releases
// the runner instead of stranding it for the life of the process.
await queryRunner.startTransaction();