Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): refuse a start at the cap before claiming the lease

Yudhi Armyndharisb232cbc6dc31
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index 9c2a970a4..00987f83f 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -1424,6 +1424,62 @@ describe('SessionService', () => {
expect(ownership.release).toHaveBeenCalledWith('sess-uuid-1');
});
+ // The engine's own cap check runs after the claim, and its refusal releases the claim to no node:
+ // a row nobody holds is never adopted by a peer, so the session stayed down until a reboot.
+ it('start() at MAX_CONCURRENT_SESSIONS refuses before claiming, leaving the lease for a peer', async () => {
+ const ownership = withOwnership();
+ (configService.get as jest.Mock).mockImplementation(<T>(key: string, def?: T): T | number =>
+ key === 'sessions.maxConcurrent' ? 1 : (def as T),
+ );
+ jest.spyOn(lifecycle, 'startSlotHolders').mockReturnValue(new Set(['other']));
+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());
+ const engineStart = jest.spyOn(lifecycle, 'start');
+
+ await expect(service.start('sess-uuid-1')).rejects.toThrow('Maximum concurrent sessions reached (1)');
+
+ expect(ownership.claim).not.toHaveBeenCalled();
+ expect(ownership.release).not.toHaveBeenCalled();
+ expect(engineStart).not.toHaveBeenCalled();
+ });
+
+ 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 =>
+ key === 'sessions.maxConcurrent' ? 1 : (def as T),
+ );
+ jest.spyOn(lifecycle, 'startSlotHolders').mockReturnValue(new Set(['other']));
+ (repository.findOne as jest.Mock).mockResolvedValue(null);
+
+ await expect(service.start('missing')).rejects.toBeInstanceOf(NotFoundException);
+ });
+
+ it('start() at MAX_CONCURRENT_SESSIONS still answers 409 for a session a live peer holds', async () => {
+ const ownership = withOwnership();
+ ownership.isHeldByOtherNode.mockResolvedValue(true);
+ (configService.get as jest.Mock).mockImplementation(<T>(key: string, def?: T): T | number =>
+ key === 'sessions.maxConcurrent' ? 1 : (def as T),
+ );
+ jest.spyOn(lifecycle, 'startSlotHolders').mockReturnValue(new Set(['other']));
+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());
+
+ await expect(service.start('sess-uuid-1')).rejects.toBeInstanceOf(ConflictException);
+ expect(ownership.claim).not.toHaveBeenCalled();
+ expect(ownership.release).not.toHaveBeenCalled();
+ });
+
+ it('start() does not count its own running engine against the cap', async () => {
+ const ownership = withOwnership();
+ (configService.get as jest.Mock).mockImplementation(<T>(key: string, def?: T): T | number =>
+ key === 'sessions.maxConcurrent' ? 1 : (def as T),
+ );
+ jest.spyOn(lifecycle, 'startSlotHolders').mockReturnValue(new Set(['sess-uuid-1']));
+ jest.spyOn(lifecycle, 'start').mockRejectedValue(new BadRequestException('Session is already started'));
+ jest.spyOn(lifecycle, 'isEngineActive').mockReturnValue(true);
+
+ await expect(service.start('sess-uuid-1')).rejects.toThrow('Session is already started');
+ expect(ownership.claim).toHaveBeenCalledWith('sess-uuid-1');
+ });
+
it('start() keeps the claim when the refusal means the engine genuinely runs here', async () => {
const ownership = withOwnership();
jest.spyOn(lifecycle, 'start').mockRejectedValue(new BadRequestException('Session is already started'));
@@ -8661,6 +8717,38 @@ describe('SessionService', () => {
}
});
+ // Each start past the cap is refused anyway; launching on would only log one failure per row.
+ it('stops at MAX_CONCURRENT_SESSIONS and leaves the remaining sessions alone', async () => {
+ process.env.AUTO_START_SESSIONS = 'true';
+ (configService.get as jest.Mock).mockImplementation(<T>(key: string, def?: T): T | number =>
+ key === 'sessions.maxConcurrent' ? 1 : (def as T),
+ );
+ (repository.find as jest.Mock).mockResolvedValue([
+ { id: 'a', name: 'A' },
+ { id: 'b', name: 'B' },
+ ]);
+ const slots = jest.spyOn(lifecycle, 'startSlotHolders').mockReturnValue(new Set());
+ const startSpy = jest.spyOn(service, 'start').mockImplementation((id: string) => {
+ slots.mockReturnValue(new Set([id]));
+ return Promise.resolve(undefined as never);
+ });
+ const logger = (service as unknown as { logger: { error: jest.Mock } }).logger;
+ const logError = jest.spyOn(logger, 'error');
+
+ jest.useFakeTimers();
+ try {
+ service.onApplicationBootstrap();
+ await jest.advanceTimersByTimeAsync(AUTOSTART_THROTTLE_MS);
+ await autoStartRun();
+
+ expect(startSpy).toHaveBeenCalledTimes(1);
+ expect(startSpy).toHaveBeenCalledWith('a');
+ expect(logError).not.toHaveBeenCalled();
+ } finally {
+ jest.useRealTimers();
+ }
+ });
+
it('reports a session stopped after the scan as skipped, not as a failed start', async () => {
process.env.AUTO_START_SESSIONS = 'true';
(repository.find as jest.Mock).mockResolvedValue([{ id: 'a', name: 'A' }]);
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index 9adb698e4..06cc05d95 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -42,7 +42,11 @@ import { SessionLivenessWatchdog } from './session-liveness-watchdog.service';
import { SessionErrorStore } from './session-error-store.service';
import { SessionRestrictionStore } from './session-restriction-store.service';
import { PresenceStore, type ChatPresence } from './presence-store.service';
-import { SessionEngineLifecycle, resolveReconnectConfig } from './session-engine-lifecycle.service';
+import {
+ SessionEngineLifecycle,
+ resolveMaxConcurrentSessions,
+ resolveReconnectConfig,
+} from './session-engine-lifecycle.service';
import { SessionOwnershipService } from './session-ownership.service';
import { paginate, ListOptions, resolveListWindow } from '../../common/utils/paginate';
import { isTransientDbError, isUniqueViolation } from '../../common/utils/db-errors';
@@ -265,6 +269,15 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
});
return;
}
+ // Every start past the cap is refused, so going on would only log one failure per row.
+ const max = resolveMaxConcurrentSessions(this.configService);
+ if (max !== null && !this.hasStartCapacity(max)) {
+ this.logger.log(
+ `Auto-start stopped at ${i} of ${sessions.length} session(s): MAX_CONCURRENT_SESSIONS reached`,
+ { action: 'auto_start_capacity_reached', max },
+ );
+ return;
+ }
const session = sessions[i];
try {
await this.start(session.id);
@@ -580,6 +593,23 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
* the engine start refuses them a row still marked stopped when it reads it.
*/
async start(id: string, { explicit = false }: { explicit?: boolean } = {}): Promise<Session> {
+ // 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.
+ 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})`);
+ }
+ }
// 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))) {