Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(session): hold the start slot while the lease claim is awaited
Yudhi Armyndharis4277748146bb
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex 00987f83f..f384b2e27 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -1442,6 +1442,85 @@ describe('SessionService', () => {expect(engineStart).not.toHaveBeenCalled();});+ // Both starts passed the cap check while neither had reached the engine yet, so the second+ // claimed its lapsed lease, met the engine's own cap refusal, and released the lease to no node.+ it('start() racing another start for the last slot refuses before claiming', async () => {+ const ownership = withOwnership();+ (configService.get as jest.Mock).mockImplementation(<T>(key: string, def?: T): T | number =>+ key === 'sessions.maxConcurrent' ? 2 : (def as T),+ );+ jest.spyOn(lifecycle, 'startSlotHolders').mockImplementation(() => new Set(['other']));+ jest.spyOn(lifecycle, 'isEngineActive').mockReturnValue(false);+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());+ let finishClaim = (): void => undefined;+ ownership.claim.mockImplementationOnce(+ () => new Promise<boolean>(resolve => (finishClaim = () => resolve(true))),+ );+ // The first start reaches the engine first and takes the slot there.+ jest+ .spyOn(lifecycle, 'start')+ .mockImplementation(id =>+ id === 'first'+ ? Promise.resolve(createMockSession())+ : Promise.reject(new BadRequestException('Maximum concurrent sessions reached (2)')),+ );++ const first = service.start('first');+ await expect(service.start('second')).rejects.toThrow('Maximum concurrent sessions reached (2)');+ expect(ownership.claim).not.toHaveBeenCalledWith('second');+ expect(ownership.release).not.toHaveBeenCalledWith('second');++ finishClaim();+ await first;+ });++ it('start() refused as a duplicate keeps the slot the first start of that id holds', async () => {+ const ownership = withOwnership();+ (configService.get as jest.Mock).mockImplementation(<T>(key: string, def?: T): T | number =>+ key === 'sessions.maxConcurrent' ? 2 : (def as T),+ );+ jest.spyOn(lifecycle, 'startSlotHolders').mockImplementation(() => new Set(['other']));+ jest.spyOn(lifecycle, 'isEngineActive').mockReturnValue(false);+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());+ let finishClaim = (): void => undefined;+ ownership.claim.mockImplementationOnce(+ () => new Promise<boolean>(resolve => (finishClaim = () => resolve(true))),+ );+ jest+ .spyOn(lifecycle, 'start')+ .mockRejectedValueOnce(new BadRequestException('Session is already starting'))+ .mockResolvedValue(createMockSession());++ const first = service.start('first');+ await expect(service.start('first')).rejects.toThrow('Session is already starting');+ await expect(service.start('second')).rejects.toThrow('Maximum concurrent sessions reached (2)');+ expect(ownership.claim).not.toHaveBeenCalledWith('second');++ finishClaim();+ await first;+ });++ // Boot auto-start and the takeover sweep stop at the first false answer, so a start whose claim+ // then fails must not read as a used slot while that claim is awaited.+ it('hasStartCapacity() does not count a start whose claim is still awaited', async () => {+ const ownership = withOwnership();+ (configService.get as jest.Mock).mockImplementation(<T>(key: string, def?: T): T | number =>+ key === 'sessions.maxConcurrent' ? 2 : (def as T),+ );+ jest.spyOn(lifecycle, 'startSlotHolders').mockImplementation(() => new Set(['other']));+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());+ let finishClaim = (): void => undefined;+ ownership.claim.mockImplementationOnce(+ () => new Promise<boolean>(resolve => (finishClaim = () => resolve(false))),+ );++ const first = service.start('first');+ expect(service.hasStartCapacity(2)).toBe(true);++ finishClaim();+ await expect(first).rejects.toThrow(ConflictException);+ });+it('start() at MAX_CONCURRENT_SESSIONS still answers 404 for an unknown id', async () => {withOwnership();(configService.get as jest.Mock).mockImplementation(<T>(key: string, def?: T): T | number =>diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex 06cc05d95..7a048286e 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -133,6 +133,12 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat* after it began from a mark left over by an earlier stop, which start() clears by design.*/private readonly stopRequests = new Map<string, number>();+ /**+ * Starts past start()'s cap check, held until they return. That check counts them with the+ * engine's slot holders, so two starts at the last free slot cannot both pass it while their claims+ * are awaited. hasStartCapacity() does not: a held start whose claim then fails never used a slot.+ */+ private readonly startReservations = new Set<string>();constructor(@InjectRepository(Session, 'data')@@ -596,20 +602,33 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat// At the cap, refused before the claim: the engine's own cap check runs after it, and its// refusal releases the claim to no node. A row nobody holds is never adopted by a peer, while a// lapsed lease left where it is gets taken over by one with room. The engine check stays the- // authoritative one; this only keeps a refusal off the lease.+ // authoritative one; this only keeps a refusal off the lease. A start that passes holds its slot+ // until it returns, so a concurrent start cannot pass on the same free slot during the claim.const max = resolveMaxConcurrentSessions(this.configService);- if (this.ownership && max !== null) {- const holders = this.engineLifecycle.startSlotHolders();- holders.delete(id);- if (holders.size >= max) {- // Same answer the failed claim below would give, so the cap does not mask a 404 or a 409.- await this.findOne(id);- if (await this.ownership.isHeldByOtherNode(id)) {- throw new ConflictException(`Session ${id} is running on another node`);- }- throw new BadRequestException(`Maximum concurrent sessions reached (${max})`);+ if (!this.ownership || max === null) {+ return this.claimAndStart(id, explicit);+ }+ const holders = this.startSlotsInUse();+ holders.delete(id);+ if (holders.size >= max) {+ // Same answer the failed claim below would give, so the cap does not mask a 404 or a 409.+ await this.findOne(id);+ if (await this.ownership.isHeldByOtherNode(id)) {+ throw new ConflictException(`Session ${id} is running on another node`);}+ throw new BadRequestException(`Maximum concurrent sessions reached (${max})`);}+ // A duplicate start of the same id leaves the reservation to the start that made it.+ const reserved = !this.startReservations.has(id);+ this.startReservations.add(id);+ try {+ return await this.claimAndStart(id, explicit);+ } finally {+ if (reserved) this.startReservations.delete(id);+ }+ }++ private async claimAndStart(id: string, explicit: boolean): Promise<Session> {// Claimed before the engine is launched, never after: launching first and discovering the// session belongs elsewhere would already have opened a second connection to the account.if (this.ownership && !(await this.ownership.claim(id))) {@@ -1134,11 +1153,15 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatreturn this.engines.activeIds();}- /** Whether this node has a MAX_CONCURRENT_SESSIONS slot free, counted exactly as the start path counts it. */+ /** Whether this node has a MAX_CONCURRENT_SESSIONS slot free, counted exactly as the engine's cap check counts it. */hasStartCapacity(max: number): boolean {return this.engineLifecycle.startSlotHolders().size < max;}+ private startSlotsInUse(): Set<string> {+ return new Set([...this.engineLifecycle.startSlotHolders(), ...this.startReservations]);+ }+/*** Stop engines for session ids whose DB row is about to be replaced by an infra import.* Owned by the lifecycle service; see SessionEngineLifecycle.stopOrphanEngines().