Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(session): keep every key when session config patches overlap
Yudhi Armyndharis1db1ca3038d9
diff --git a/src/modules/session/session-config.concurrency.spec.ts b/src/modules/session/session-config.concurrency.spec.tsnew file mode 100644index 000000000..9c8df58ca--- /dev/null+++ b/src/modules/session/session-config.concurrency.spec.ts@@ -0,0 +1,85 @@+import { ConflictException } from '@nestjs/common';+import { DataSource } from 'typeorm';+import { Session } from './entities/session.entity';+import { SessionService } from './session.service';++/**+ * PATCH /config merges into the stored blob. Two overlapping requests that each read the same blob+ * before either writes must not have the later write drop the earlier one's key. Run against a real+ * database, because the race lives between the read and the write.+ */+describe('SessionService.updateConfig under concurrent requests', () => {+ let ds: DataSource;+ let service: SessionService;++ beforeAll(async () => {+ ds = new DataSource({ type: 'better-sqlite3', database: ':memory:', entities: [Session], synchronize: true });+ await ds.initialize();+ const attach = { attachTo: (s: Session) => s } as never;+ const unused = {} as never;+ service = new SessionService(+ ds.getRepository(Session),+ unused, // messages+ ds,+ unused, // engine registry+ unused, // watchdog+ attach, // session errors+ attach, // session restrictions+ unused, // presence+ unused, // hooks+ unused, // engine lifecycle+ unused, // lid mappings+ );+ });++ afterAll(async () => {+ await ds.destroy();+ });++ it('keeps every key when two patches overlap', async () => {+ const { id } = await ds.getRepository(Session).save({ name: 'cfg-race', config: { operatorKey: 'keep' } });++ await Promise.all([+ service.updateConfig(id, { autoRejectCalls: true }),+ service.updateConfig(id, { maxReconnectAttempts: 5 }),+ service.updateConfig(id, { reconnectBaseDelay: 9000 }),+ ]);++ const stored = await ds.getRepository(Session).findOneByOrFail({ id });+ expect(stored.config).toEqual({+ operatorKey: 'keep',+ autoRejectCalls: true,+ maxReconnectAttempts: 5,+ reconnectBaseDelay: 9000,+ });+ });++ // The swap compares the stored text exactly, so a row not written by JSON.stringify must still update.+ it('updates a row whose stored text is not in the form this process writes', async () => {+ const { id } = await ds.getRepository(Session).save({ name: 'cfg-spaced', config: {} });+ await ds.query(`UPDATE sessions SET config = '{ "operatorKey" : "keep" }' WHERE id = ?`, [id]);++ await expect(service.updateConfig(id, { autoRejectCalls: true })).resolves.toMatchObject({ autoRejectCalls: true });++ const stored = await ds.getRepository(Session).findOneByOrFail({ id });+ expect(stored.config).toEqual({ operatorKey: 'keep', autoRejectCalls: true });+ });++ // A request that keeps losing the race must not loop for ever.+ it('gives up with 409 when the config keeps changing underneath it', async () => {+ const { id } = await ds.getRepository(Session).save({ name: 'cfg-contended', config: {} });+ const update = jest.spyOn(ds.getRepository(Session), 'update').mockResolvedValue({ affected: 0 } as never);+ try {+ await expect(service.updateConfig(id, { autoRejectCalls: true })).rejects.toBeInstanceOf(ConflictException);+ expect(update).toHaveBeenCalledTimes(5);+ } finally {+ update.mockRestore();+ }+ });++ it('answers 404 for a session that does not exist', async () => {+ await expect(+ service.updateConfig('00000000-0000-4000-8000-000000000000', { autoRejectCalls: true }),+ ).rejects.toMatchObject({ status: 404 });+ });+});diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex b310a4e80..8b641c44e 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -8911,6 +8911,16 @@ describe('SessionService', () => {beforeEach(() => {(repository.update as jest.Mock).mockResolvedValue({ affected: 1 });+ // updateConfig reads the raw column text; serve it from whatever row findOne is mocked to hold.+ const raw = {+ select: () => raw,+ where: () => raw,+ getRawOne: async () => {+ const row = (await (repository.findOne as jest.Mock)()) as Session | null;+ return row ? { config: JSON.stringify(row.config) } : undefined;+ },+ };+ repository.createQueryBuilder = jest.fn().mockReturnValue(raw);});it('reports the documented defaults for a session that has never been configured', async () => {diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex 7c6300bc6..00a2907c6 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -22,6 +22,7 @@ import {DataSource,FindManyOptions,FindOptionsWhere,+ Raw,} from 'typeorm';import { QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity';import { setTimeout } from 'node:timers/promises';@@ -439,24 +440,45 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat* on the DTO rather than papered over by forcing a reconnect nobody asked for.*/async updateConfig(id: string, dto: UpdateSessionConfigDto): Promise<SessionConfigResponseDto> {- const session = await this.findOne(id);- const config = { ...(session.config ?? {}) };-- for (const key of ['autoRejectCalls', 'maxReconnectAttempts', 'reconnectBaseDelay'] as const) {- const value = dto[key];- if (value === undefined) continue;- if (value === null) {- delete config[key];- } else {- config[key] = value;+ // Compare-and-swap on the stored text: the write lands only while the column still holds the blob+ // this request merged into, so two overlapping PATCHes cannot both start from the same blob and+ // have the later write drop the earlier one's keys. A request that lost the race reads again.+ for (let attempt = 1; ; attempt++) {+ // The raw text rather than the parsed entity, so the comparison is exact whatever wrote the row.+ const row = await this.sessionRepository+ .createQueryBuilder('session')+ .select('session.config', 'config')+ .where('session.id = :id', { id })+ .getRawOne<{ config: string | null }>();+ if (!row) {+ throw new NotFoundException(`Session with id '${id}' not found`);+ }+ const stored = row.config;+ const config = { ...((stored ? JSON.parse(stored) : null) as Record<string, unknown> | null) };++ for (const key of ['autoRejectCalls', 'maxReconnectAttempts', 'reconnectBaseDelay'] as const) {+ const value = dto[key];+ if (value === undefined) continue;+ if (value === null) {+ delete config[key];+ } else {+ config[key] = value;+ }}- }- // update() with an explicit object rather than save() on the loaded entity: the entity carries- // runtime-attached fields (lastError, restriction) that no column backs, and save() would try to- // write the whole row back from a snapshot taken before this await.- await this.sessionRepository.update(id, { config: config as QueryDeepPartialEntity<Record<string, unknown>> });- return this.projectConfig(config);+ // update() with an explicit object rather than save() on an entity: only the config column is+ // written, never the rest of the row from a snapshot taken before this await.+ const { affected } = await this.sessionRepository.update(+ { id, config: Raw(column => (stored === null ? `${column} IS NULL` : `${column} = :stored`), { stored }) },+ { config: config as QueryDeepPartialEntity<Record<string, unknown>> },+ );+ if (affected !== 0) {+ return this.projectConfig(config);+ }+ if (attempt >= 5) {+ throw new ConflictException('Session config is being changed by other requests; retry');+ }+ }}async getProxy(id: string): Promise<SessionProxyResponseDto> {