Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): drop a session's claim generation when its claim ends

Yudhi Armyndharisff330e3933fd
diff --git a/src/modules/session/session-ownership.service.spec.ts b/src/modules/session/session-ownership.service.spec.ts
index 1b2e0f0e4..1ae083370 100644
--- a/src/modules/session/session-ownership.service.spec.ts
+++ b/src/modules/session/session-ownership.service.spec.ts
@@ -223,6 +223,24 @@ describe('SessionOwnershipService', () => {
expect((await sessions.findOneByOrFail({ id: one.id })).nodeId).toBeNull();
expect((await sessions.findOneByOrFail({ id: two.id })).nodeId).toBeNull();
});
+
+ // Per-session bookkeeping must end with the claim, or create/delete churn grows it forever.
+ it('keeps no per-session state once a claim ends by release, shutdown or loss', async () => {
+ const [one, two, three] = [await seed(), await seed(), await seed()];
+ const nodeA = service('node-a');
+ const claimGen = (nodeA as unknown as { claimGen: Map<string, number> }).claimGen;
+ await nodeA.claim(one.id);
+ await nodeA.claim(two.id);
+ await nodeA.claim(three.id);
+
+ await nodeA.release(one.id);
+ await sessions.update({ id: two.id }, { nodeId: 'node-b', leaseExpiresAt: new Date(Date.now() + 60_000) });
+ await nodeA.renew();
+ expect([...claimGen.keys()]).toEqual([three.id]);
+
+ await nodeA.releaseAll();
+ expect(claimGen.size).toBe(0);
+ });
});
describe('releasing a lapsed foreign claim', () => {
diff --git a/src/modules/session/session-ownership.service.ts b/src/modules/session/session-ownership.service.ts
index aa1d00821..ddd2f8047 100644
--- a/src/modules/session/session-ownership.service.ts
+++ b/src/modules/session/session-ownership.service.ts
@@ -41,8 +41,13 @@ 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>();
- /** Bumped on every claim and release, so renew() can tell a claim it read from one replaced since. */
+ /**
+ * A fresh value from claimSeq on every claim, dropped when the claim ends, so renew() can tell a
+ * claim it read from one replaced since. One sequence for all sessions: a per-session counter
+ * restarting after a release could repeat the value a tick had read.
+ */
private readonly claimGen = new Map<string, number>();
+ private claimSeq = 0;
/** Notified when a renewal proves this process no longer holds sessions it thought it did. */
private onLeaseLost?: (sessionIds: string[]) => Promise<void> | void;
/** Notified when this process takes a session over from a node whose lease lapsed. See onAdoption. */
@@ -158,7 +163,7 @@ export class SessionOwnershipService {
const claimed = (result.affected ?? 0) > 0;
if (claimed) {
this.owned.add(sessionId);
- this.bumpClaimGen(sessionId);
+ this.claimGen.set(sessionId, ++this.claimSeq);
this.lastSeenLease.set(sessionId, leaseExpiresAt.getTime());
// A released row (nodeId NULL) is not an adoption: its holder may still be finishing its own
// batches, and failing them under it would leave two writers on one batch row.
@@ -184,7 +189,7 @@ export class SessionOwnershipService {
async release(sessionId: string): Promise<void> {
const now = new Date();
this.owned.delete(sessionId);
- this.bumpClaimGen(sessionId);
+ this.claimGen.delete(sessionId);
const cleared = { nodeId: null, claimedAt: null, leaseExpiresAt: null, nodeUrl: null };
// Its own claim first, in one statement as before. Only when that matched nothing is a lapsed
// claim of another node cleared, and that is a takeover like a claim: the dead holder's
@@ -210,14 +215,11 @@ export class SessionOwnershipService {
if ((lapsed.affected ?? 0) > 0) this.followAdoption(sessionId);
}
- private bumpClaimGen(sessionId: string): void {
- this.claimGen.set(sessionId, (this.claimGen.get(sessionId) ?? 0) + 1);
- }
-
/** Release everything this process holds, on the way down. */
async releaseAll(): Promise<void> {
const ids = [...this.owned];
this.owned.clear();
+ this.claimGen.clear();
if (ids.length === 0) return;
await this.sessions
.createQueryBuilder()
@@ -379,7 +381,10 @@ export class SessionOwnershipService {
// in between: neither was taken by a peer.
const lost = held.filter(id => !kept.has(id) && this.owned.has(id) && this.claimGen.get(id) === heldGen.get(id));
if (lost.length === 0) return;
- for (const id of lost) this.owned.delete(id);
+ for (const id of lost) {
+ this.owned.delete(id);
+ this.claimGen.delete(id);
+ }
this.logger.warn(`Lost the claim on ${lost.length} session(s); another node now holds them`, {
nodeId: this.nodeId,
sessionIds: lost,