Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(session): give up the engine when the claim is lost

Yudhi Armyndharise455d3e2954a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e588e2f39..c8f926e58 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -25,6 +25,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
Existing rows read as unclaimed, so a single-process deployment behaves exactly as before.
+ A node that loses a claim stops running the session. A lease can lapse while the process itself is
+ healthy — a slow query is enough — and a peer is then free to claim the session, so an engine left
+ running here would be the second one on that WhatsApp account. Renewal is the regular contact with
+ the row, so it is also where the loss is noticed and the local engine is torn down. A failed
+ renewal is explicitly not a loss: the TTL exists to absorb a database blip, and treating a failed
+ query as lost ownership would stop every healthy engine on the node the first time one occurred.
+
Bulk-send batches follow the same ownership. The boot reaper marked every `PROCESSING` batch
`FAILED`, which on a second replica meant declaring a peer's in-flight batches failed while they
were still sending — the caller told the send failed, the messages going out regardless. A batch
diff --git a/docs/13-horizontal-scaling.md b/docs/13-horizontal-scaling.md
index 9606c6bef..fef0df9b5 100644
--- a/docs/13-horizontal-scaling.md
+++ b/docs/13-horizontal-scaling.md
@@ -14,6 +14,12 @@
> does not depend on one. `NODE_ID` names the process; it defaults to the hostname and must
> be stable across restarts.
>
+> A node that loses its claim gives up the engine. A lease can lapse while the process is
+> perfectly healthy — a slow query is enough — after which a peer may legitimately take the
+> session; renewal detects the loss and tears the local engine down, so the account never
+> ends up with two. A failed renewal is deliberately not read as a loss: the TTL is sized to
+> absorb a database blip, and concluding otherwise would stop every healthy engine on the node.
+>
> Bulk-send batches follow the same rule. A batch is only ever driven by the process
> holding its session's engine, so a booting replica now reaps only the batches whose
> sessions it may claim, instead of declaring a peer's in-flight batches FAILED while they
diff --git a/src/modules/session/session-ownership.service.spec.ts b/src/modules/session/session-ownership.service.spec.ts
index caaf78cee..39e97214b 100644
--- a/src/modules/session/session-ownership.service.spec.ts
+++ b/src/modules/session/session-ownership.service.spec.ts
@@ -177,6 +177,80 @@ describe('SessionOwnershipService', () => {
});
});
+ /**
+ * The lease only means something if losing it has a consequence. A node can lose one while
+ * perfectly healthy — a slow query is enough — after which a peer may legitimately claim the
+ * session; an engine left running here would be the second one on that WhatsApp account.
+ */
+ describe('losing a claim', () => {
+ it('reports the sessions a peer has taken, and stops counting them as its own', async () => {
+ const mine = await seed();
+ const taken = await seed();
+ const nodeA = service('node-a');
+ await nodeA.claim(mine.id);
+ await nodeA.claim(taken.id);
+ const lost: string[][] = [];
+ nodeA.onLeaseLoss(ids => void lost.push(ids));
+
+ // The peer took it after node-a's lease lapsed.
+ await sessions.update({ id: taken.id }, { nodeId: 'node-b', leaseExpiresAt: new Date(Date.now() + 60_000) });
+ await nodeA.renew();
+
+ expect(lost).toEqual([[taken.id]]);
+ expect(nodeA.ownedIds()).toEqual([mine.id]);
+ });
+
+ it('says nothing while everything is still held', async () => {
+ const session = await seed();
+ const nodeA = service('node-a');
+ await nodeA.claim(session.id);
+ const lost: string[][] = [];
+ nodeA.onLeaseLoss(ids => void lost.push(ids));
+
+ await nodeA.renew();
+
+ expect(lost).toEqual([]);
+ });
+
+ /**
+ * The property that matters most. Concluding loss from a failed query would tear down every
+ * healthy engine on this node the first time the database hiccuped — far worse than a renewal
+ * arriving late, which the TTL is sized to absorb.
+ */
+ it('treats a database failure as a late renewal, never as lost ownership', async () => {
+ const session = await seed();
+ const nodeA = service('node-a');
+ await nodeA.claim(session.id);
+ const lost: string[][] = [];
+ nodeA.onLeaseLoss(ids => void lost.push(ids));
+ const find = jest.spyOn(sessions, 'find').mockRejectedValue(new Error('connection reset'));
+
+ await expect(nodeA.renew()).resolves.toBeUndefined();
+
+ expect(lost).toEqual([]);
+ expect(nodeA.ownedIds()).toEqual([session.id]);
+ find.mockRestore();
+ });
+
+ /**
+ * Renewal runs on an interval, so a throwing handler would surface as an unhandled rejection
+ * and could take the loop down with it — losing every remaining lease as a consequence of one
+ * failed teardown.
+ */
+ it('survives a handler that throws, and still forgets the lost session', async () => {
+ const session = await seed();
+ const nodeA = service('node-a');
+ await nodeA.claim(session.id);
+ nodeA.onLeaseLoss(() => {
+ throw new Error('teardown exploded');
+ });
+ await sessions.update({ id: session.id }, { nodeId: 'node-b', leaseExpiresAt: new Date(Date.now() + 60_000) });
+
+ await expect(nodeA.renew()).resolves.toBeUndefined();
+ expect(nodeA.ownedIds()).toEqual([]);
+ });
+ });
+
describe('what a booting process may reset', () => {
const now = new Date();
diff --git a/src/modules/session/session-ownership.service.ts b/src/modules/session/session-ownership.service.ts
index d96b18ac4..0d6310c6e 100644
--- a/src/modules/session/session-ownership.service.ts
+++ b/src/modules/session/session-ownership.service.ts
@@ -28,6 +28,8 @@ export class SessionOwnershipService {
private heartbeat?: ReturnType<typeof setInterval>;
/** Sessions this process believes it owns, so the heartbeat knows what to renew. */
private readonly owned = new Set<string>();
+ /** Notified when a renewal proves this process no longer holds sessions it thought it did. */
+ private onLeaseLost?: (sessionIds: string[]) => Promise<unknown> | unknown;
constructor(
@InjectRepository(Session, 'data')
@@ -147,10 +149,29 @@ export class SessionOwnershipService {
this.heartbeat = undefined;
}
- /** Push every held lease out by another TTL. */
+ /**
+ * Register what to do about a session this process has lost.
+ *
+ * Losing a lease is not an abstract bookkeeping event: a peer is now free to claim the session,
+ * and if this process keeps its engine running there are two engines on one WhatsApp account —
+ * the exact outcome the claim exists to prevent. The handler is how the engine gets torn down.
+ */
+ onLeaseLoss(handler: (sessionIds: string[]) => Promise<unknown> | unknown): void {
+ this.onLeaseLost = handler;
+ }
+
+ /**
+ * Push every held lease out by another TTL, and find out whether any were lost.
+ *
+ * A lease can lapse while this process is perfectly healthy — a slow query or a long pause is
+ * enough — after which a peer may legitimately take the session. Renewal is therefore also the
+ * moment to notice, because it is the only regular contact with the row.
+ */
async renew(): Promise<void> {
const ids = [...this.owned];
if (ids.length === 0) return;
+
+ let kept: Set<string>;
try {
await this.sessions
.createQueryBuilder()
@@ -158,13 +179,39 @@ export class SessionOwnershipService {
.set({ leaseExpiresAt: new Date(Date.now() + this.leaseTtlMs) })
.where({ id: In(ids), nodeId: this.nodeId })
.execute();
+ const rows = await this.sessions.find({ where: { id: In(ids), nodeId: this.nodeId }, select: { id: true } });
+ kept = new Set(rows.map(row => row.id));
} catch (error) {
// A failed renewal is survivable — the next tick tries again, and the TTL is long enough to
- // absorb a transient database blip. Throwing here would take down the interval instead.
+ // absorb a transient database blip. Crucially it must NOT be read as having lost anything:
+ // concluding loss from a failed query would tear down every healthy engine on this node the
+ // first time the database hiccuped, which is far worse than a late renewal.
this.logger.warn('Failed to renew session leases', {
nodeId: this.nodeId,
error: error instanceof Error ? error.message : String(error),
});
+ return;
+ }
+
+ const lost = ids.filter(id => !kept.has(id));
+ if (lost.length === 0) return;
+ for (const id of lost) this.owned.delete(id);
+ this.logger.warn(`Lost the claim on ${lost.length} session(s); another node now holds them`, {
+ nodeId: this.nodeId,
+ sessionIds: lost,
+ });
+ try {
+ await this.onLeaseLost?.(lost);
+ } catch (error) {
+ // Renewal is driven by an interval, so a throwing handler would surface as an unhandled
+ // rejection and could stop the loop entirely. The sessions are already out of `owned`, so the
+ // bookkeeping is consistent either way — what a failure here means is that an engine may
+ // still be running for a session this node no longer owns, which is worth an error rather
+ // than a crash.
+ this.logger.error('Failed to release engines for lost sessions', error instanceof Error ? error.stack : '', {
+ nodeId: this.nodeId,
+ sessionIds: lost,
+ });
}
}
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index cd88c106f..b80018d0c 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -125,6 +125,11 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
// The watchdog owns the probe cadence and failure counting; a session it proves dead comes
// back through the same disconnect path an engine-reported drop uses.
this.watchdog.start((id, engine, reason) => this.engineLifecycle.handleEngineDisconnected(id, engine, reason));
+ // A session this node has lost belongs to a peer now, which is free to start its own engine.
+ // Leaving ours running would put two engines on one WhatsApp account — the thing the claim
+ // exists to prevent — so the engine goes down. stopOrphanEngines is the right verb: it tears
+ // down locally and leaves the row alone, because the row is no longer ours to write.
+ this.ownership?.onLeaseLoss(ids => this.engineLifecycle.stopOrphanEngines(ids));
// Renewal runs regardless of auto-start: a session started through the API later is claimed the
// same way and must keep its lease alive.
this.ownership?.startHeartbeat();