Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(infra): carry a session lease across an import by its remaining time
Yudhi Armyndharis71230e9eed48
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 32cb7fd04..8c1ccc986 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 long data import no longer expires the session claims it restores** — the ownership lease was written back with its original deadline, so a restore that ran longer than the lease had left committed an expiry that had already passed while the owning node was still recorded and still running the engine.- **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.diff --git a/src/modules/infra/infra-data.controller.spec.ts b/src/modules/infra/infra-data.controller.spec.tsindex cb1e469f1..b0f6f8d35 100644--- a/src/modules/infra/infra-data.controller.spec.ts+++ b/src/modules/infra/infra-data.controller.spec.ts@@ -90,8 +90,12 @@ describe('InfraDataController.importData round-trips export-data (no silent messit('keeps the session ownership lease across a replace, and never takes it from the payload', async () => {await seedSession('s1');- const claimedAt = new Date('2026-08-06T10:00:00.000Z');- const leaseExpiresAt = new Date('2026-08-06T10:05:00.000Z');+ // Seeded far in the past ON PURPOSE, so the claim is unambiguously LAPSED whatever day the suite+ // runs: a lapsed claim must survive verbatim, because shifting it would resurrect a dead node's+ // hold on the session. (The previous fixture used a same-day stamp, so whether this exercised the+ // lapsed or the live path depended on the wall clock.) The live path is covered below.+ const claimedAt = new Date('2020-01-01T10:00:00.000Z');+ const leaseExpiresAt = new Date('2020-01-01T10:05:00.000Z');// A live claim held by THIS node, exactly as SessionOwnershipService would have written it.await ds.getRepository(Session)@@ -118,6 +122,56 @@ describe('InfraDataController.importData round-trips export-data (no silent messexpect(new Date(restored.leaseExpiresAt as unknown as string).toISOString()).toBe(leaseExpiresAt.toISOString());});+ it('carries a LIVE claim forward by its remaining time, not by its original expiry stamp', async () => {+ await seedSession('s1');+ const readAt = Date.now();+ // A live claim whose remaining time the transaction below deliberately outlives. Scaled down from+ // the real 60s TTL so the test costs a second, not a minute — the ordering is what matters.+ const remainingMs = 1_000;+ await ds.getRepository(Session).update(+ { id: 's1' },+ {+ nodeId: 'node-a',+ claimedAt: new Date(readAt),+ leaseExpiresAt: new Date(readAt + remainingMs),+ nodeUrl: 'http://10.0.0.5:2785',+ },+ );+ const dump = await controller.exportData();++ // Hold the transaction open past the original expiry, the way a large restore does. Re-binding+ // the stamp verbatim would then commit a lease this request already knows has expired: nodeId+ // still names the live owner, so the row reads as an adoptable orphan to a peer's takeover sweep+ // — a lapse manufactured by the restore, on a claim it observed live moments earlier.+ const realCreate = ds.createQueryRunner.bind(ds);+ let stalled = false;+ jest.spyOn(ds, 'createQueryRunner').mockImplementation(() => {+ const runner = realCreate();+ const realQuery = runner.query.bind(runner) as (...args: unknown[]) => Promise<unknown>;+ runner.query = (async (...args: unknown[]): Promise<unknown> => {+ if (!stalled && typeof args[0] === 'string' && args[0].startsWith('DELETE FROM sessions')) {+ stalled = true;+ await new Promise(resolve => setTimeout(resolve, remainingMs * 1.5));+ }+ return realQuery(...args);+ }) as typeof runner.query;+ return runner;+ });++ const res = await controller.importData({ tables: dump.tables });+ jest.restoreAllMocks();+ expect(res.imported).toBe(true);++ const restored = await ds.getRepository(Session).findOneByOrFail({ id: 's1' });+ const committed = new Date(restored.leaseExpiresAt as unknown as string).getTime();+ expect(restored.nodeId).toBe('node-a');+ // Still in the future: the claim was live when read, so it must be live when written back.+ expect(committed).toBeGreaterThan(Date.now());+ // Carried, not renewed: the remaining time is preserved rather than reset to a full TTL, so the+ // restore cannot extend anyone's hold — least of all a peer's.+ expect(committed).toBeLessThanOrEqual(Date.now() + remainingMs);+ });+it('holds the ownership loss-detection token for the whole transaction, and releases it', async () => {await seedSession('s1');const dump = await controller.exportData();@@ -1495,9 +1549,9 @@ describe('restoreSessionOwnership', () => {// Swallowing it would be worse than the bug: on PostgreSQL a failed statement aborts the// transaction, so the COMMIT that followed would execute as a ROLLBACK and the endpoint would// report a fully discarded import as a success.- await expect(restoreSessionOwnership([claim], () => Promise.reject(new Error('db went away')))).rejects.toThrow(- 'db went away',- );+ await expect(+ restoreSessionOwnership([claim], () => Promise.reject(new Error('db went away')), new Date()),+ ).rejects.toThrow('db went away');});it('does nothing when there is no ownership to carry', async () => {@@ -1507,8 +1561,8 @@ describe('restoreSessionOwnership', () => {return Promise.resolve();};- await restoreSessionOwnership(null, insert);- await restoreSessionOwnership([], insert);+ await restoreSessionOwnership(null, insert, new Date());+ await restoreSessionOwnership([], insert, new Date());expect(calls).toEqual([]);});@@ -1522,12 +1576,54 @@ describe('restoreSessionOwnership', () => {return Promise.resolve();};- await restoreSessionOwnership([claim], insert);+ await restoreSessionOwnership([claim], insert, new Date());+ // 'l' is not a parseable deadline, so it is written back untouched: a value this function cannot+ // interpret is not one it may rewrite.expect(bound).toEqual([['node-a', 'c', 'l', 'u', 's1']]);expect(statements[0]).toContain('UPDATE sessions SET "nodeId"');expect(statements[0]).toContain('"claimedAt"');expect(statements[0]).toContain('"leaseExpiresAt"');expect(statements[0]).toContain('"nodeUrl"');});++ // The lease is a DEADLINE, and the transaction re-applying it can outlive what the deadline has+ // left. These three cases pin which way each kind of claim moves.+ const bindLease = async (leaseExpiresAt: unknown, readAt: Date, now: Date): Promise<unknown> => {+ const bound: unknown[][] = [];+ await restoreSessionOwnership(+ [{ id: 's1', nodeId: 'node-a', claimedAt: 'c', leaseExpiresAt, nodeUrl: 'u' }],+ (_sql, params) => {+ bound.push(params);+ return Promise.resolve();+ },+ readAt,+ now,+ );+ return bound[0][2];+ };++ it('carries a live claim by its remaining time, so a long import cannot expire it', async () => {+ const readAt = new Date('2026-08-06T10:00:00.000Z');+ const commitAt = new Date('2026-08-06T10:02:00.000Z'); // a two-minute restore+ // 30s left when read → 30s left when written, not an expiry two minutes in the past.+ expect(await bindLease('2026-08-06T10:00:30.000Z', readAt, commitAt)).toBe('2026-08-06T10:02:30.000Z');+ });++ it('leaves an already-lapsed claim exactly where it was, so a dead node stays dead', async () => {+ const readAt = new Date('2026-08-06T10:00:00.000Z');+ const commitAt = new Date('2026-08-06T10:02:00.000Z');+ // Shifting this one would resurrect a crashed peer's hold on the session.+ expect(await bindLease('2026-08-06T09:59:00.000Z', readAt, commitAt)).toBe('2026-08-06T09:59:00.000Z');+ });++ it('preserves the stored shape — Date in, Date out (Postgres); text in, text out (SQLite)', async () => {+ const readAt = new Date('2026-08-06T10:00:00.000Z');+ const commitAt = new Date('2026-08-06T10:02:00.000Z');+ const asDate = await bindLease(new Date('2026-08-06T10:00:30.000Z'), readAt, commitAt);+ expect(asDate).toBeInstanceOf(Date);+ expect((asDate as Date).toISOString()).toBe('2026-08-06T10:02:30.000Z');+ expect(typeof (await bindLease('2026-08-06T10:00:30.000Z', readAt, commitAt))).toBe('string');+ expect(await bindLease(null, readAt, commitAt)).toBeNull();+ });});diff --git a/src/modules/infra/infra-data.controller.ts b/src/modules/infra/infra-data.controller.tsindex f5f55e994..a0c62b57a 100644--- a/src/modules/infra/infra-data.controller.ts+++ b/src/modules/infra/infra-data.controller.ts@@ -59,10 +59,37 @@ async function readSessionOwnership(queryRunner: QueryRunner): Promise<SessionOw}/**- * Re-apply the claims verbatim for ids present in both the pre-import database and the restored set.- * Values are re-bound exactly as they were read (ISO text on SQLite, Date on Postgres) rather than- * reconstructed, and go through the caller's `insert` so the `$N`→`?` rewrite applies on SQLite. An- * id the backup did not restore simply matches no row.+ * Carry a lease across the transaction by its REMAINING time rather than its absolute stamp.+ *+ * The stamp is a deadline, and the transaction that re-applies it can run for longer than the+ * deadline has left. Writing it back unchanged therefore commits an expiry this request already knows+ * has passed, while `nodeId` still names the owner whose engine never stopped — a lapse manufactured+ * by the restore, on a claim it observed live moments earlier.+ *+ * A claim that was ALREADY lapsed when read is re-bound untouched: shifting that one would resurrect+ * a dead node's hold, which is the property the verbatim write was protecting. So is anything+ * unparseable — a value this function does not understand is not one it should rewrite.+ *+ * The stored shape is preserved (ISO text on SQLite, Date on Postgres) because these values go back+ * through raw SQL, bypassing the column transformer that would otherwise normalise them.+ */+function carryLease(raw: unknown, readAt: Date, now: Date): unknown {+ // Only the two shapes these columns are actually stored in are interpreted; anything else is a+ // value this function does not understand, and so not one it may rewrite.+ if (!(raw instanceof Date) && typeof raw !== 'string') return raw;+ const deadline = raw instanceof Date ? raw : new Date(raw);+ const remainingMs = deadline.getTime() - readAt.getTime();+ if (Number.isNaN(remainingMs) || remainingMs <= 0) return raw;+ const carried = new Date(now.getTime() + remainingMs);+ return raw instanceof Date ? carried : carried.toISOString();+}++/**+ * Re-apply the claims for ids present in both the pre-import database and the restored set.+ * `nodeId`/`claimedAt`/`nodeUrl` are re-bound exactly as they were read rather than reconstructed;+ * only the lease deadline is carried forward (see {@link carryLease}). They go through the caller's+ * `insert` so the `$N`→`?` rewrite applies on SQLite. An id the backup did not restore simply+ * matches no row.** Errors are NOT swallowed. On PostgreSQL a failed statement aborts the transaction, and the COMMIT* that followed would silently execute as a ROLLBACK — reporting a fully-discarded import as a@@ -72,12 +99,14 @@ async function readSessionOwnership(queryRunner: QueryRunner): Promise<SessionOwexport async function restoreSessionOwnership(preserved: SessionOwnershipRow[] | null,insert: (text: string, params: unknown[]) => Promise<unknown>,+ readAt: Date,+ now: Date = new Date(),): Promise<void> {if (!preserved?.length) return;for (const row of preserved) {await insert('UPDATE sessions SET "nodeId" = $1, "claimedAt" = $2, "leaseExpiresAt" = $3, "nodeUrl" = $4 WHERE id = $5',- [row.nodeId, row.claimedAt, row.leaseExpiresAt, row.nodeUrl, row.id],+ [row.nodeId, row.claimedAt, carryLease(row.leaseExpiresAt, readAt, now), row.nodeUrl, row.id],);}}@@ -567,6 +596,9 @@ export class InfraDataController {// deadlock on Postgres) and tolerate the columns being absent, so a database whose ownership// migration has been rolled back still imports.const preservedOwnership = await readSessionOwnership(queryRunner);+ // Stamped AFTER the read, so the remaining lease time carried forward later is measured from+ // the latest moment these values are known to have been true — never longer than they were.+ const ownershipReadAt = new Date();await queryRunner.query('DELETE FROM sessions');@@ -606,7 +638,7 @@ export class InfraDataController {// execute as a ROLLBACK and the endpoint would report a fully discarded import as a success,// with per-table counts, to an operator restoring after data loss.try {- await restoreSessionOwnership(preservedOwnership, insert);+ await restoreSessionOwnership(preservedOwnership, insert, ownershipReadAt);} catch (error) {warnings.push(`Failed to restore session ownership: ${error instanceof Error ? error.message : String(error)}`,