Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(infra): harden the lease carry and state what it trades
Yudhi Armyndharis3f35af73af5c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8c1ccc986..9e1d4bad3 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 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 data import now carries each session's ownership lease by its remaining time instead of its original deadline** — a restore re-applied the deadline unchanged, so one that ran longer than a claim had left committed that claim as expired, including claims held by other nodes whose engines never stopped.- **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 b0f6f8d35..cacb14836 100644--- a/src/modules/infra/infra-data.controller.spec.ts+++ b/src/modules/infra/infra-data.controller.spec.ts@@ -122,11 +122,19 @@ 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 () => {+ it('carries LIVE claims forward by their remaining time, including a peer node’s', async () => {await seedSession('s1');+ await seedSession('s2');+ const dump = await controller.exportData();++ // Seeded AFTER the export on purpose: the sessions importer writes 12 columns and none of them is+ // ownership, so the dump cannot carry these values — and stamping them here keeps the assertion+ // margin free of the export's cost. That margin is consumed by the import preamble and the+ // commit, NOT by the stall below: a late timer moves the committed lease and `Date.now()` by the+ // same amount, so lengthening the sleep buys nothing.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.+ // Scaled down from the real 60s TTL so the test costs a second, not a minute — the transaction+ // outliving the remaining time is the property under test, not the size of either number.const remainingMs = 1_000;await ds.getRepository(Session).update({ id: 's1' },@@ -137,7 +145,19 @@ describe('InfraDataController.importData round-trips export-data (no silent messnodeUrl: 'http://10.0.0.5:2785',},);- const dump = await controller.exportData();+ // A claim this node does NOT own. The import reads every row with a nodeId, so without the carry+ // it commits a live peer's lease as expired — and `lapsedHeldByOthers` excludes only `nodeId =+ // me`, so the importing node's own takeover sweep is what would then adopt a session whose engine+ // never stopped on the peer.+ await ds.getRepository(Session).update(+ { id: 's2' },+ {+ nodeId: 'node-b',+ claimedAt: new Date(readAt),+ leaseExpiresAt: new Date(readAt + remainingMs * 2),+ nodeUrl: 'http://10.0.0.9:2785',+ },+ );// 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@@ -162,14 +182,20 @@ describe('InfraDataController.importData round-trips export-data (no silent messjest.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);+ const own = await ds.getRepository(Session).findOneByOrFail({ id: 's1' });+ const peer = await ds.getRepository(Session).findOneByOrFail({ id: 's2' });+ const ownLease = new Date(own.leaseExpiresAt as unknown as string).getTime();+ const peerLease = new Date(peer.leaseExpiresAt as unknown as string).getTime();++ expect(own.nodeId).toBe('node-a');+ expect(peer.nodeId).toBe('node-b');+ // Both still in the future: they were live when read, so they must be live when written back.+ expect(ownLease).toBeGreaterThan(Date.now());+ expect(peerLease).toBeGreaterThan(Date.now());+ // Carried, not renewed: each keeps its OWN remaining time rather than being reset to a full TTL,+ // so the restore extends nobody's hold and the two do not collapse onto the same deadline.+ expect(ownLease).toBeLessThanOrEqual(Date.now() + remainingMs);+ expect(peerLease).toBeGreaterThan(ownLease);});it('holds the ownership loss-detection token for the whole transaction, and releases it', async () => {diff --git a/src/modules/infra/infra-data.controller.ts b/src/modules/infra/infra-data.controller.tsindex a0c62b57a..57415db3b 100644--- a/src/modules/infra/infra-data.controller.ts+++ b/src/modules/infra/infra-data.controller.ts@@ -72,15 +72,28 @@ async function readSessionOwnership(queryRunner: QueryRunner): Promise<SessionOw** 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.+ *+ * Note the deliberate asymmetry with `claimedAt`, which stays verbatim because it is a historical+ * fact. After a carry the pair therefore no longer spans a single TTL — `leaseExpiresAt - claimedAt`+ * is the TTL plus the restore's duration — so it must not be used to derive a lease age.*/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.+ // Only the two shapes these columns are actually stored in are interpreted, and for text only the+ // UTC form the two writers emit (`DateTransformer.to` and `leaseParam`, both `toISOString()`).+ // Anything else is left alone: rewriting a shape this function does not understand would be worse+ // than not carrying it, because a local-time parse would bake the host's UTC offset into the+ // column permanently — where the old verbatim write merely passed the odd value through.if (!(raw instanceof Date) && typeof raw !== 'string') return raw;+ if (typeof raw === 'string' && !raw.endsWith('Z')) 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);+ // Never earlier than what was read: a backward clock step between the two stamps must not be able+ // to commit an expiry sooner than the row already carried, which would re-create the very problem.+ const carried = new Date(Math.max(now.getTime() + remainingMs, deadline.getTime()));+ // A deadline that is representable but whose carry is not: fall back rather than throw, since the+ // caller routes a throw into `warnings` and every later row in the loop would lose its claim.+ if (!Number.isFinite(carried.getTime())) return raw;return raw instanceof Date ? carried : carried.toISOString();}