Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(messages): keep a bulk send's media when the echo wins the persist race
Yudhi Armyndharis29317779d780
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f47ff9eb5..2fbe36fdf 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -23,6 +23,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- **A bulk media send lost its attachment when the engine echo won the persist race** — the batch write collided on `UNIQUE(sessionId, waMessageId)` and was swallowed into a warning, leaving only the echo's row, which on a Baileys API send carries a media-less marker; it now merges onto that row like the single-send path already did.+- **Three shared status descriptions said the wrong thing on the routes that borrowed them** — `send-text`'s `501` is specifically a caller-supplied `customLinkPreview`, which only Baileys accepts, not a wholesale gap in the engine; `POST /channels/subscribe` takes an invite code and no channel id, so its `404` is an unresolvable invite; and the `400` on six send routes named the unreachable recipient as though it were the only cause, while omitting body validation and an inactive session, and cited a `404` meaning that four of those six routes do not declare.- **Four contract corrections from a review of this cycle's own work** — the `409` description said the session had no engine when the guard actually fires on an engine that exists but is not `ready` (an unstarted session answers `400`); `send-bulk` declared a `409` it cannot produce, since the batch drains after the handler has answered `202`; the nine catalog and status routes declared that `409` but not the `404` their own service throws for an unstarted session; and the logout example showed a null `pushName` and `connectedAt` beside a populated `lastActive`, though logout clears only `phone`.diff --git a/src/modules/message/bulk-message.service.ts b/src/modules/message/bulk-message.service.tsindex 2675b8016..579df560d 100644--- a/src/modules/message/bulk-message.service.ts+++ b/src/modules/message/bulk-message.service.ts@@ -702,6 +702,8 @@ export class BulkMessageService implements OnApplicationBootstrap {: undefined,});} catch (error) {+ // Losing the dedup race to the own-send echo is no longer an error here — saveOutgoingMessage+ // merges onto the echo's row. Anything reaching this point is a real persistence fault.this.logger.warn(`Batch message persisted-after-send failed: ${String(error)}`);}}diff --git a/src/modules/message/message.service.spec.ts b/src/modules/message/message.service.spec.tsindex 6f41a54ec..533484887 100644--- a/src/modules/message/message.service.spec.ts+++ b/src/modules/message/message.service.spec.ts@@ -1482,6 +1482,64 @@ describe('MessageService', () => {});});+ // The bulk path persists AFTER the send with the engine id already known, so it races the own-send+ // echo on UNIQUE(sessionId, waMessageId). Losing that race used to drop the batch's media payload.+ describe('saveOutgoingMessage vs the own-send echo (dedup race)', () => {+ const uniqueViolation = new Error('UNIQUE constraint failed: messages.sessionId, messages.waMessageId');+ const bulkRow = {+ waMessageId: 'wa-bulk-1',+ chatId: '[email protected]',+ type: 'image',+ status: MessageStatus.SENT,+ timestamp: 1706868000,+ metadata: { media: { mimetype: 'image/png', data: 'QUJD', filename: 'a.png' } },+ };++ it('merges the media payload onto the echo row instead of losing it', async () => {+ (repository.save as jest.Mock).mockRejectedValueOnce(uniqueViolation);+ (repository.findOne as jest.Mock).mockResolvedValueOnce({ id: 'echo-row', ...bulkRow });++ const saved = await service.saveOutgoingMessage('sess-1', bulkRow);++ expect(repository.update).toHaveBeenCalledWith(+ { sessionId: 'sess-1', waMessageId: 'wa-bulk-1' },+ expect.objectContaining({+ status: MessageStatus.SENT,+ timestamp: 1706868000,+ metadata: bulkRow.metadata,+ }),+ );+ expect(saved).toEqual(expect.objectContaining({ id: 'echo-row' }));+ });++ it('leaves the echo row metadata alone when this write carries none', async () => {+ (repository.save as jest.Mock).mockRejectedValueOnce(uniqueViolation);+ (repository.findOne as jest.Mock).mockResolvedValueOnce({ id: 'echo-row' });++ await service.saveOutgoingMessage('sess-1', { ...bulkRow, type: 'text', metadata: undefined });++ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access+ const patch = (repository.update as jest.Mock).mock.calls[0]?.[1] as Record<string, unknown>;+ expect(patch).not.toHaveProperty('metadata');+ });++ it('rethrows a transient (non-unique) persist error', async () => {+ (repository.save as jest.Mock).mockRejectedValueOnce(new Error('SQLITE_BUSY: database is locked'));++ await expect(service.saveOutgoingMessage('sess-1', bulkRow)).rejects.toThrow('SQLITE_BUSY');+ expect(repository.update).not.toHaveBeenCalled();+ });++ it('rethrows when there is no engine id to merge onto', async () => {+ (repository.save as jest.Mock).mockRejectedValueOnce(uniqueViolation);++ await expect(service.saveOutgoingMessage('sess-1', { chatId: '[email protected]', type: 'text' })).rejects.toThrow(+ uniqueViolation,+ );+ expect(repository.update).not.toHaveBeenCalled();+ });+ });+describe('persistSentState vs the own-send echo (dedup race)', () => {it('merges state onto the echo row, then drops the redundant PENDING row', async () => {// The engine's message_create echo (onMessageCreate) won the insert race, so the SENT-state savediff --git a/src/modules/message/message.service.ts b/src/modules/message/message.service.tsindex 05b69cf0a..289d34ea5 100644--- a/src/modules/message/message.service.ts+++ b/src/modules/message/message.service.ts@@ -615,6 +615,12 @@ export class MessageService {* Save outgoing message to database.* When called before sending, creates a record with PENDING status; bulk send reuses this after a* successful send (status SENT) so batch messages are persisted like single sends.+ *+ * A caller that already knows the engine id races the own-send echo on+ * UNIQUE(sessionId, waMessageId) — only the bulk path does today, since every single send persists+ * its PENDING row before the id exists. Losing that race merges onto the echo's row rather than+ * failing, mirroring `persistSentState`: the echo carries only what the engine reported (for a+ * Baileys API send, a media-less marker), so dropping this write would lose the media payload.*/async saveOutgoingMessage(sessionId: string,@@ -648,7 +654,22 @@ export class MessageService {status: data.status ?? MessageStatus.PENDING,metadata: data.metadata,});- const saved = await this.messageRepository.save(message);+ const saved = await this.messageRepository.save(message).catch(async (err: unknown) => {+ const waMessageId = message.waMessageId;+ if (!waMessageId || !isUniqueConstraintError(err)) throw err;+ const patch: QueryDeepPartialEntity<Message> = {+ status: message.status,+ timestamp: message.timestamp,+ };+ // Only when this write actually carries metadata: a text item must not blank the echo's.+ if (message.metadata) {+ patch.metadata = message.metadata as QueryDeepPartialEntity<Record<string, unknown>>;+ }+ await this.messageRepository.update({ sessionId, waMessageId }, patch);+ const surviving = await this.messageRepository.findOne({ where: { sessionId, waMessageId } });+ if (!surviving) throw err;+ return surviving;+ });this.emitPersisted(sessionId, saved);return saved;}