Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(db): save a row that may conflict without a transaction of its own
Yudhi Armyndharis53f28094b426
diff --git a/src/modules/message/bulk-message.service.ts b/src/modules/message/bulk-message.service.tsindex a923ca307..3638f8a36 100644--- a/src/modules/message/bulk-message.service.ts+++ b/src/modules/message/bulk-message.service.ts@@ -375,7 +375,9 @@ export class BulkMessageService implements OnModuleInit, OnApplicationBootstrap,// them, so a burst cannot all observe the same stale count and overshoot the ceiling.this.inFlightBatches++;try {- await this.batchRepository.save(batch);+ // No transaction of its own: on SQLite's single shared connection the rollback of the unique+ // violation handled below would also discard what other callers wrote while it was open.+ await this.batchRepository.save(batch, { transaction: false });} catch (error) {this.inFlightBatches--;this.processingBatches.delete(batch.id);diff --git a/src/modules/message/message-send.service.spec.ts b/src/modules/message/message-send.service.spec.tsindex c2ee7a8b1..e5eff2727 100644--- a/src/modules/message/message-send.service.spec.ts+++ b/src/modules/message/message-send.service.spec.ts@@ -1327,6 +1327,7 @@ describe('MessageSendService', () => {button: { id: 'yes', text: 'Sim' },},}),+ { transaction: false },);});diff --git a/src/modules/message/message-send.service.ts b/src/modules/message/message-send.service.tsindex ebbb16da5..50b2753b4 100644--- a/src/modules/message/message-send.service.ts+++ b/src/modules/message/message-send.service.ts@@ -714,7 +714,10 @@ export class MessageSendService {status: data.status ?? MessageStatus.PENDING,metadata: quotedMessage ? { ...data.metadata, quotedMessage } : data.metadata,});- const saved = await this.messageRepository.save(message).catch(async (err: unknown) => {+ // No transaction of its own: the unique violation handled below is routine (the own-send echo wins the+ // race), and on SQLite's single shared connection its rollback would discard what other callers wrote+ // while it was open, after they were told it was stored.+ const saved = await this.messageRepository.save(message, { transaction: false }).catch(async (err: unknown) => {const waMessageId = message.waMessageId;if (!waMessageId || !isUniqueViolation(err)) throw err;// No `status` here on purpose. The row this collides with is the own-send echo's, inserted@@ -813,7 +816,8 @@ export class MessageSendService {message.status = MessageStatus.SENT;message.timestamp = result.timestamp;try {- await this.messageRepository.save(message);+ // No transaction of its own, for the reason given at the first save of this message.+ await this.messageRepository.save(message, { transaction: false });// Reconcile the earlier PENDING emission with the finalized row (#906).this.emitPersisted(message.sessionId, message);} catch (persistError) {diff --git a/src/modules/status-store/status-store.service.spec.ts b/src/modules/status-store/status-store.service.spec.tsindex 3d1e745ba..a41f1fb76 100644--- a/src/modules/status-store/status-store.service.spec.ts+++ b/src/modules/status-store/status-store.service.spec.ts@@ -45,6 +45,44 @@ describe('StatusStoreService (ingest / list / getMedia)', () => {fs.rmSync(baseDir, { recursive: true, force: true });});+ // SQLite serves every repository from one connection, so a transaction a save opens is shared with the+ // writes made while it is open, and the rollback of a duplicate's unique violation would undo them too,+ // after ingest had reported them created and the status.received webhook had gone out.+ it('keeps a row written while a duplicate that lost the unique-key race is refused', async () => {+ const status = (waStatusId: string) => ({+ waStatusId,+ contactJid: '[email protected]',+ type: 'text' as const,+ caption: waStatusId,+ postedAt: Date.now(),+ });+ await service.ingest('sess-race', status('dup'));+ // The racing ingest read before the winner wrote, so it goes on to the insert that must be refused.+ jest.spyOn(repository, 'findOne').mockResolvedValueOnce(null);+ let concurrent: Promise<unknown> | undefined;+ ds.subscribers.push({+ listenTo: () => StatusUpdate,+ beforeInsert: event => {+ if ((event.entity as StatusUpdate).waStatusId === 'dup' && !concurrent) {+ const other = status('other');+ concurrent = repository.insert({+ ...other,+ sessionId: 'sess-race',+ expiresAt: other.postedAt + 24 * 60 * 60 * 1000,+ mediaOmitted: false,+ });+ }+ },+ });++ const { created } = await service.ingest('sess-race', status('dup'));+ await concurrent;++ expect(created).toBe(false);+ const stored = (await repository.find({ where: { sessionId: 'sess-race' } })).map(row => row.waStatusId).sort();+ expect(stored).toEqual(['dup', 'other']);+ });+it('ingest writes a text row with expiresAt = postedAt + 24h, flagged as created', async () => {const postedAt = Date.now();const { row, created } = await service.ingest('sess', {diff --git a/src/modules/status-store/status-store.service.ts b/src/modules/status-store/status-store.service.tsindex 4be46847e..bfca25f84 100644--- a/src/modules/status-store/status-store.service.ts+++ b/src/modules/status-store/status-store.service.ts@@ -139,7 +139,10 @@ export class StatusStoreService implements OnModuleInit, OnModuleDestroy {let saved: StatusUpdate;try {- saved = await this.repository.save(row);+ // Without a transaction: a single-row save() wraps itself in one, and on SQLite's single shared+ // connection the rollback of the unique violation expected below also discards the rows other callers+ // wrote while it was open, after they were reported stored.+ saved = await this.repository.save(row, { transaction: false });} catch (error) {// The unique (sessionId, waStatusId) index is the idempotency backstop for a concurrent ingest// of the same status racing past the findOne check above; on a unique-constraint violation thediff --git a/src/modules/template/template.service.spec.ts b/src/modules/template/template.service.spec.tsindex 4a1156992..84584b563 100644--- a/src/modules/template/template.service.spec.ts+++ b/src/modules/template/template.service.spec.ts@@ -190,6 +190,7 @@ describe('TemplateService', () => {expect(repository.save).toHaveBeenCalledWith(expect.objectContaining({ body: 'Updated body', name: template.name }),+ { transaction: false },);});diff --git a/src/modules/template/template.service.ts b/src/modules/template/template.service.tsindex abfcc96ac..2e976900b 100644--- a/src/modules/template/template.service.ts+++ b/src/modules/template/template.service.ts@@ -33,7 +33,9 @@ export class TemplateService {});try {- const saved = await this.templateRepository.save(template);+ // No transaction of its own: on SQLite's single shared connection the rollback of the unique+ // violation handled below would also discard what other callers wrote while it was open.+ const saved = await this.templateRepository.save(template, { transaction: false });this.logger.log('Template created', { sessionId, templateId: saved.id, name: saved.name });return saved;} catch (err) {@@ -102,7 +104,9 @@ export class TemplateService {if (dto.footer !== undefined) template.footer = dto.footer;try {- return await this.templateRepository.save(template);+ // No transaction of its own: on SQLite's single shared connection the rollback of the unique+ // violation handled below would also discard what other callers wrote while it was open.+ return await this.templateRepository.save(template, { transaction: false });} catch (err) {if (isUniqueViolation(err)) {throw new ConflictException(`A template named '${template.name}' already exists for this session`);