Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(message): preserve media across metadata updates
Yudhi Armyndharisb6054f2d6f29
diff --git a/src/modules/chat-media/chat-media-archive.service.spec.ts b/src/modules/chat-media/chat-media-archive.service.spec.tsindex 792476d89..8f28b733c 100644--- a/src/modules/chat-media/chat-media-archive.service.spec.ts+++ b/src/modules/chat-media/chat-media-archive.service.spec.ts@@ -9,6 +9,11 @@ jest.mock('archiver', () => ({ default: jest.fn() }));import { StorageService } from '../../common/storage/storage.service';import { Message, MessageDirection, MessageStatus } from '../message/entities/message.entity';import { ChatMediaArchiveService, CHAT_MEDIA_PREFIX } from './chat-media-archive.service';+import { MessageMutationProjector } from '../session/message-mutation-projector';+import { KeyedMutationQueue } from '../../common/utils/keyed-mutation-queue';+import { MessageSendService } from '../message/message-send.service';+import { EngineRegistry } from '../../engine/engine-registry.service';+import { updateMessageMetadata } from '../message/message-metadata';/** A ConfigService stub that returns each call's default unless overridden by `overrides`. */function fakeConfigService(overrides: Record<string, unknown> = {}): ConfigService {@@ -74,6 +79,139 @@ describe('ChatMediaArchiveService', () => {});describe('archive', () => {+ it('updates null metadata and never restores metadata after a concurrent revoke', async () => {+ const row = await saveRow();+ expect(await updateMessageMetadata(repository, { id: row.id }, () => ({ keep: 1 }))).toEqual({ keep: 1 });+ const update = repository.update.bind(repository);+ jest.spyOn(repository, 'update').mockImplementationOnce(async (where, patch) => {+ await update({ id: row.id }, { type: 'revoked', metadata: {} });+ return update(where, patch);+ });+ expect(await updateMessageMetadata(repository, { id: row.id }, current => ({ ...current, stale: 1 }))).toBeNull();+ expect((await repository.findOneByOrFail({ id: row.id })).metadata).toEqual({});+ });++ it('bounds metadata retries when another writer wins every update', async () => {+ const row = await saveRow();+ const update = jest.spyOn(repository, 'update').mockResolvedValue({ affected: 0, raw: [], generatedMaps: [] });+ await expect(updateMessageMetadata(repository, { id: row.id }, () => ({ keep: 1 }))).rejects.toThrow(+ 'Message metadata changed repeatedly',+ );+ expect(update).toHaveBeenCalledTimes(3);+ expect((await repository.findOneByOrFail({ id: row.id })).metadata).toBeNull();+ });+ it('enforces the byte cap even when supplied sizeBytes is too small', async () => {+ const row = await saveRow({ mimetype: 'image/png', data: PNG.toString('base64'), sizeBytes: 1 });+ expect(await enabled({ 'chatMedia.maxBytes': 1 }).archive(row)).toBeNull();+ expect((await repository.findOneByOrFail({ id: row.id })).mediaPath).toBeNull();+ });+ it.each(['bulk', 'single'])('keeps an archived echo when the %s send writer merges later', async mode => {+ const media = { mimetype: 'image/png', data: PNG.toString('base64') };+ const row = await saveRow(media, { direction: MessageDirection.OUTGOING });+ await enabled({ 'chatMedia.inlineMode': 'archive' }).archive(row);+ const engines = new EngineRegistry();+ engines.set('sess-1', {+ sendImageMessage: () => Promise.resolve({ id: row.waMessageId, timestamp: 1 }),+ } as never);+ const sender = new MessageSendService(+ repository,+ { findOne: () => Promise.resolve({ phone: '628111' }) } as never,+ engines,+ { execute: (_event: string, data: unknown) => Promise.resolve({ continue: true, data }) } as never,+ {} as never,+ { assertSendAllowed: () => Promise.resolve(), recordSendSuccess: () => undefined } as never,+ fakeConfigService({ 'features.simulateTyping': false }),+ );+ if (mode === 'bulk') {+ await sender.saveOutgoingMessage('sess-1', {+ waMessageId: row.waMessageId,+ chatId: row.chatId,+ type: 'image',+ status: MessageStatus.SENT,+ metadata: { media },+ });+ } else {+ await sender.sendImage('sess-1', { chatId: row.chatId, base64: media.data, mimetype: media.mimetype });+ }+ const stored = await repository.findOneByOrFail({ id: row.id });+ expect(stored.mediaPath).toBeTruthy();+ expect(stored.metadata).toEqual({+ media: { mimetype: 'image/png', omitted: true, archived: true, sizeBytes: PNG.length },+ });+ expect(await repository.count()).toBe(1);+ });++ it('keeps archived media when a reaction read preceded archive publication', async () => {+ const row = await saveRow({ mimetype: 'image/png', data: PNG.toString('base64') });+ const archive = enabled({ 'chatMedia.inlineMode': 'archive' });+ const update = repository.update.bind(repository);+ let published = false;+ jest.spyOn(repository, 'update').mockImplementation(async (where, patch) => {+ if (patch.metadata && !published) {+ published = true;+ await archive.archive(row);+ }+ return update(where, patch);+ });+ const mutations = new KeyedMutationQueue();+ const projector = new MessageMutationProjector(+ repository,+ { emitMessageReaction: jest.fn() } as never,+ { dispatch: jest.fn().mockResolvedValue(undefined) } as never,+ mutations,+ { error: jest.fn() } as never,+ );+ projector.applyReactionQueued('sess-1', {+ messageId: row.waMessageId,+ chatId: row.chatId,+ senderId: '[email protected]',+ reaction: 'ok',+ });+ while (mutations.size) await new Promise(resolve => setImmediate(resolve));+ const stored = await repository.findOneByOrFail({ id: row.id });+ expect(stored.mediaPath).toBeTruthy();+ expect(stored.metadata).toEqual({+ media: { mimetype: 'image/png', omitted: true, archived: true, sizeBytes: PNG.length },+ reactions: { '[email protected]': 'ok' },+ });+ });++ it.each(['bulk', 'single'])('preserves sent bytes after a failed %s echo merge', async mode => {+ const row = await saveRow(undefined, { direction: MessageDirection.OUTGOING });+ const engines = new EngineRegistry();+ engines.set('sess-1', {+ sendImageMessage: () => Promise.resolve({ id: row.waMessageId, timestamp: 1 }),+ } as never);+ const sender = new MessageSendService(+ repository,+ { findOne: () => Promise.resolve({ phone: '628111' }) } as never,+ engines,+ { execute: (_event: string, data: unknown) => Promise.resolve({ continue: true, data }) } as never,+ {} as never,+ { assertSendAllowed: () => Promise.resolve(), recordSendSuccess: () => undefined } as never,+ fakeConfigService({ 'features.simulateTyping': false }),+ );+ jest.spyOn(repository, 'update').mockRejectedValueOnce(new Error('SQLITE_BUSY'));+ const media = { mimetype: 'image/png', data: PNG.toString('base64') };+ if (mode === 'bulk') {+ await sender.saveOutgoingMessage('sess-1', {+ waMessageId: row.waMessageId,+ chatId: row.chatId,+ type: 'image',+ status: MessageStatus.SENT,+ metadata: { media },+ });+ } else {+ await sender.sendImage('sess-1', { chatId: row.chatId, base64: media.data, mimetype: media.mimetype });+ }+ const retained = await repository.findOneByOrFail({ sessionId: 'sess-1', waMessageId: IsNull() });+ expect(retained.status).toBe(MessageStatus.SENT);+ expect(retained.metadata.media).toEqual(media);+ expect(await repository.count()).toBe(2);+ expect(await enabled({ 'chatMedia.inlineMode': 'archive' }).archive(retained)).toBeNull();+ expect((await repository.findOneByOrFail({ id: retained.id })).metadata.media).toEqual(media);+ });+it('writes the blob and points the row at it, under the chat-media prefix', async () => {const row = await saveRow({ mimetype: 'image/png', data: PNG.toString('base64') });diff --git a/src/modules/chat-media/chat-media-archive.service.ts b/src/modules/chat-media/chat-media-archive.service.tsindex 191ddd102..47e9a6a5e 100644--- a/src/modules/chat-media/chat-media-archive.service.ts+++ b/src/modules/chat-media/chat-media-archive.service.ts@@ -153,7 +153,8 @@ export class ChatMediaArchiveService implements OnModuleInit, OnModuleDestroy {if (MEDIA_URL_POINTER.test(media.data)) return null;const maxBytes = this.configService.get<number>('chatMedia.maxBytes', DEFAULT_ARCHIVE_MAX_BYTES);- const sizeBytes = media.sizeBytes ?? Buffer.byteLength(media.data, 'base64');+ // Measure decoded bytes; a plugin or imported row may supply an incorrect sizeBytes.+ const sizeBytes = Buffer.byteLength(media.data, 'base64');if (sizeBytes > maxBytes) return null;// A random key rather than the WhatsApp message id: message ids are engine-controlled strings@@ -179,11 +180,12 @@ export class ChatMediaArchiveService implements OnModuleInit, OnModuleDestroy {if (!stored.equals(bytes)) throw new Error('Archived media did not read back intact');const current = await this.repository.findOne({where: { id: row.id, mediaPath: IsNull(), type: Not('revoked') },- select: { id: true, metadata: true },+ select: { id: true, metadata: true, waMessageId: true },});const metadata = current?.metadata;const currentMedia = (metadata as { media?: InlineMedia } | null | undefined)?.media;- if (!currentMedia?.data || currentMedia.data !== media.data) {+ // The media route needs a WhatsApp id. An id-less send must keep its inline bytes.+ if (!current?.waMessageId || !currentMedia?.data || currentMedia.data !== media.data) {await this.storageService.deleteFile(key).catch(() => undefined);return null;}diff --git a/src/modules/message/entities/message.entity.ts b/src/modules/message/entities/message.entity.tsindex 307c95f52..50ac33d62 100644--- a/src/modules/message/entities/message.entity.ts+++ b/src/modules/message/entities/message.entity.ts@@ -101,7 +101,7 @@ export class Message {* Storage key of this message's archived media, or null when nothing was archived — which is the* case for every row written while `CHAT_MEDIA_ARCHIVE_ENABLED` is off (the default), for non-media* messages, and for media above the archive cap. Independent of the inline base64 copy in- * `metadata.media`, which is unaffected by archiving.+ * `metadata.media`, which stays inline by default and is replaced after verification in archive mode.*/// Partial index for the chat-media orphan sweep's per-chunk `mediaPath IN (...)` lookup. NULL for// every un-archived row (archiving is opt-in), so the WHERE clause keeps the index to rows thatdiff --git a/src/modules/message/message-metadata.ts b/src/modules/message/message-metadata.tsnew file mode 100644index 000000000..baa172c43--- /dev/null+++ b/src/modules/message/message-metadata.ts@@ -0,0 +1,38 @@+import { IsNull, Not, Raw, type FindOptionsWhere, type Repository } from 'typeorm';+import { Message } from './entities/message.entity';+import type { QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity';++/** Apply a metadata change to the current row without restoring a concurrent archive or revoke. */+export async function updateMessageMetadata(+ repository: Repository<Message>,+ where: FindOptionsWhere<Message>,+ change: (metadata: Record<string, unknown>) => Record<string, unknown>,+): Promise<Record<string, unknown> | null> {+ const target = { ...where, type: Not('revoked') };+ for (let attempt = 0; attempt < 3; attempt++) {+ const row = await repository.findOne({ where: target });+ if (!row) return null;+ const snapshot = row.metadata;+ const metadata = change({ ...snapshot });+ const result = await repository.update(+ {+ ...target,+ metadata:+ snapshot == null ? IsNull() : Raw(column => `${column} = :snapshot`, { snapshot: JSON.stringify(snapshot) }),+ },+ { metadata: metadata as QueryDeepPartialEntity<Record<string, unknown>> },+ );+ if (result.affected) return metadata;+ // Another metadata writer won. Read its result before applying this change again.+ }+ throw new Error('Message metadata changed repeatedly during update');+}++/** An already archived echo keeps its media marker when the REST writer supplies inline bytes. */+export function mergeSentMetadata(+ current: Record<string, unknown>,+ incoming: Record<string, unknown>,+): Record<string, unknown> {+ const media = current.media as { archived?: boolean; omitted?: boolean } | undefined;+ return { ...current, ...incoming, ...(media?.archived && media.omitted ? { media } : {}) };+}diff --git a/src/modules/message/message-send.service.spec.ts b/src/modules/message/message-send.service.spec.tsindex 4c384eadf..938ed8fc6 100644--- a/src/modules/message/message-send.service.spec.ts+++ b/src/modules/message/message-send.service.spec.ts@@ -1569,14 +1569,13 @@ describe('MessageSendService', () => {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 });+ (repository.findOne as jest.Mock).mockResolvedValue({ 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({ sessionId: 'sess-1', waMessageId: 'wa-bulk-1' }),expect.objectContaining({- timestamp: 1706868000,metadata: bulkRow.metadata,}),);@@ -1631,6 +1630,23 @@ describe('MessageSendService', () => {});describe('persistSentState vs the own-send echo (dedup race)', () => {+ it('retains the sent media row when merging onto the echo fails', async () => {+ (repository.save as jest.Mock)+ .mockImplementationOnce(msg => Promise.resolve(msg))+ .mockRejectedValueOnce(new Error('UNIQUE constraint failed: messages.sessionId, messages.waMessageId'));+ (repository.findOne as jest.Mock).mockResolvedValue({ id: 'echo-row', metadata: {} });+ (repository.update as jest.Mock).mockRejectedValueOnce(new Error('SQLITE_BUSY'));++ const result = await service.sendImage('sess-1', { chatId: '[email protected]', base64: 'QUJD', mimetype: 'image/png' });++ expect(result.messageId).toBe('wa-msg-1');+ expect(mockEngine.sendImageMessage).toHaveBeenCalledTimes(1);+ expect(repository.delete).not.toHaveBeenCalled();+ expect(repository.update).toHaveBeenCalledWith(+ { id: 'msg-uuid-1', status: MessageStatus.PENDING },+ { status: MessageStatus.SENT, timestamp: 1706868000 },+ );+ });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 save// collides on UNIQUE(sessionId, waMessageId). The echo row carries only what the engine reported@@ -1664,6 +1680,7 @@ describe('MessageSendService', () => {(repository.save as jest.Mock).mockImplementationOnce(msg => Promise.resolve(msg)).mockRejectedValueOnce(new Error('UNIQUE constraint failed: messages.sessionId, messages.waMessageId'));+ (repository.findOne as jest.Mock).mockResolvedValue({ id: 'echo-row', metadata: {} });await service.sendImage('sess-1', { chatId: '[email protected]', base64: 'QUJD', mimetype: 'image/png' });diff --git a/src/modules/message/message-send.service.ts b/src/modules/message/message-send.service.tsindex 3fd595dee..a4956a8f6 100644--- a/src/modules/message/message-send.service.ts+++ b/src/modules/message/message-send.service.ts@@ -1,6 +1,7 @@import { Injectable, BadRequestException, Optional } from '@nestjs/common';import { ConfigService } from '@nestjs/config';import { markEngineSendFailure } from '../../common/errors/engine-send-failure';+import { mergeSentMetadata, updateMessageMetadata } from './message-metadata';import { InjectRepository } from '@nestjs/typeorm';import { In, Repository, QueryDeepPartialEntity } from 'typeorm';import { SessionService } from '../session/session.service';@@ -719,10 +720,23 @@ export class MessageSendService {};// Only when this write actually carries metadata worth merging: a text item must not blank// the echo's, and a URL pointer must not replace bytes the engine already downloaded.- if (message.metadata && !isUrlPointerMetadata(message.metadata)) {- patch.metadata = message.metadata as QueryDeepPartialEntity<Record<string, unknown>>;+ const metadata = message.metadata;+ if (metadata && !isUrlPointerMetadata(metadata)) {+ try {+ await updateMessageMetadata(this.messageRepository, { sessionId, waMessageId }, current =>+ mergeSentMetadata(current, metadata),+ );+ } catch (error) {+ if (message.status !== MessageStatus.SENT) throw error;+ this.logger.warn(`Merging sent metadata onto the echo row failed (id=${waMessageId})`, {+ error: error instanceof Error ? error.message : String(error),+ });+ // The bulk engine has already sent this item. Keep its media in an id-less SENT row+ // when the echo cannot accept it, instead of losing the only payload-bearing copy.+ return this.messageRepository.save(this.messageRepository.create({ ...message, waMessageId: undefined }));+ }}- await this.messageRepository.update({ sessionId, waMessageId }, patch);+ if (message.timestamp !== undefined) await this.messageRepository.update({ sessionId, waMessageId }, patch);const surviving = await this.messageRepository.findOne({ where: { sessionId, waMessageId } });if (!surviving) throw err;return surviving;@@ -813,8 +827,36 @@ export class MessageSendService {// first has advanced it further. Writing SENT here would undo that. See the sibling merge// in saveOutgoingMessage.const patch: QueryDeepPartialEntity<Message> = { timestamp: result.timestamp };- if (message.metadata && !isUrlPointerMetadata(message.metadata)) {- patch.metadata = message.metadata as QueryDeepPartialEntity<Record<string, unknown>>;+ const metadata = message.metadata;+ let metadataMerged = true;+ if (metadata && !isUrlPointerMetadata(metadata)) {+ await updateMessageMetadata(+ this.messageRepository,+ { sessionId: message.sessionId, waMessageId: result.id },+ current => mergeSentMetadata(current, metadata),+ ).catch(err => {+ metadataMerged = false;+ this.logger.warn(`Merging media onto the echo-persisted row failed (id=${result.id})`, {+ error: err instanceof Error ? err.message : String(err),+ });+ });+ }+ if (!metadataMerged) {+ // Keep the payload-bearing row when the echo merge fails. Mark it SENT without the+ // conflicting engine id so the pending reaper cannot strip successfully sent media.+ await this.messageRepository+ .update(+ { id: message.id, status: MessageStatus.PENDING },+ { status: MessageStatus.SENT, timestamp: result.timestamp },+ )+ .catch(err =>+ this.logger.warn(`Preserving the sent media row failed (id=${message.id})`, {+ error: err instanceof Error ? err.message : String(err),+ }),+ );+ const retained = await this.messageRepository.findOne({ where: { id: message.id } }).catch(() => null);+ if (retained) this.emitPersisted(message.sessionId, retained);+ return { messageId: result.id, timestamp: result.timestamp };}await this.messageRepository.update({ sessionId: message.sessionId, waMessageId: result.id }, patch)diff --git a/src/modules/session/message-mutation-projector.ts b/src/modules/session/message-mutation-projector.tsindex dd18236f2..606338773 100644--- a/src/modules/session/message-mutation-projector.ts+++ b/src/modules/session/message-mutation-projector.ts@@ -1,11 +1,11 @@import { Not, Repository } from 'typeorm';-import { QueryDeepPartialEntity } from 'typeorm';import { Message } from '../message/entities/message.entity';import { KeyedMutationQueue } from '../../common/utils/keyed-mutation-queue';import { LoggerService } from '../../common/services/logger.service';import { EventsGateway } from '../events/events.gateway';import { WebhookService } from '../webhook/webhook.service';import { ReactionEvent, EditedMessage } from '../../engine/interfaces/whatsapp-engine.interface';+import { updateMessageMetadata } from '../message/message-metadata';/*** Applies stored-message mutations — reactions, inbound edits, REST outbound-edit echoes — behind@@ -55,33 +55,21 @@ export class MessageMutationProjector {// A revoked row reads as absent, like the edit paths: a reaction that lands after the delete must// not write a reactions map back onto the cleared metadata.- const msg = await this.messageRepository.findOne({- where: { sessionId: id, waMessageId: event.messageId, type: Not('revoked') },- });-// The stored copy is best-effort — a message is absent whenever it was never persisted (an// ephemeral one under STORE_EPHEMERAL_MESSAGES=false, or one that arrived before the session// went live) — but the notification is not: `message.reaction` is a declared webhook event and// the dashboard stream is the point of it, the same contract handleMessageRevoked states.- let reactions: Record<string, string> | undefined;- if (msg) {- const metadata = msg.metadata || {};- reactions = (metadata.reactions as Record<string, string>) || {};- if (!event.reaction) {- delete reactions[event.senderId];- } else {- reactions[event.senderId] = event.reaction;- }- metadata.reactions = reactions;- // Scoped update of ONLY the metadata column. A full-row save(msg) would re-persist the `status`- // read at findOne time, clobbering a concurrent ack UPDATE (SENT→DELIVERED/READ) that committed in- // the window between this findOne and the write — the mutation chain serializes reaction-vs-reaction- // but NOT reaction-vs-ack, so scoping the write to metadata is what keeps delivery state monotonic- // (#220). Other metadata fields are carried through untouched (they were read into `metadata`).- await this.messageRepository.update({ sessionId: id, waMessageId: event.messageId }, {- metadata,- } as QueryDeepPartialEntity<Message>);- }+ const metadata = await updateMessageMetadata(+ this.messageRepository,+ { sessionId: id, waMessageId: event.messageId },+ current => {+ const reactions = { ...(current.reactions as Record<string, string> | undefined) };+ if (!event.reaction) delete reactions[event.senderId];+ else reactions[event.senderId] = event.reaction;+ return { ...current, reactions };+ },+ );+ const reactions = metadata?.reactions as Record<string, string> | undefined;// `reactions` is the post-apply snapshot of EVERY reaction on the message and consumers REPLACE// their copy with it, so this one reaction must not stand in for the whole set — that would readdiff --git a/src/modules/session/message-projector.service.spec.ts b/src/modules/session/message-projector.service.spec.tsindex c0b0742e7..69d478b4a 100644--- a/src/modules/session/message-projector.service.spec.ts+++ b/src/modules/session/message-projector.service.spec.ts@@ -203,7 +203,12 @@ describe('MessageProjector', () => {const payload = dispatchPayload(webhookService.dispatch);expect(payload.reactions).toEqual({ '[email protected]': '❤️', '[email protected]': '👍' });expect(messageRepository.update).toHaveBeenCalledWith(- { sessionId: 's1', waMessageId: 'WA1' },+ expect.objectContaining({+ sessionId: 's1',+ waMessageId: 'WA1',+ type: Not('revoked'),+ metadata: expect.anything() as unknown,+ }),{ metadata: { reactions: { '[email protected]': '❤️', '[email protected]': '👍' } } },);});@@ -1094,10 +1099,18 @@ describe('MessageProjector (inbound projection)', () => {const { releaseA } = await echoWaitingBehindA();projector.applyReactionQueued(SESSION_ID, { messageId: 'S', senderId: '[email protected]', reaction: 'ok' } as never);projector.applyReactionQueued(SESSION_ID, { messageId: 'S', senderId: '[email protected]', reaction: '' } as never);+ messageRepository.update.mockImplementation(() =>+ Promise.resolve({ affected: inserted().includes('S') ? 1 : 0 }),+ );releaseA();await flush();- expect(updatesAfterS()).toEqual([[whereS, { metadata: { keep: 1, reactions: { '[email protected]': 'ok' } } }]]);+ expect(updatesAfterS()).toEqual([+ [+ expect.objectContaining({ ...whereS, type: Not('revoked'), metadata: expect.anything() as unknown }),+ { metadata: { keep: 1, reactions: { '[email protected]': 'ok' } } },+ ],+ ]);expect(emitMessageReaction).toHaveBeenCalledTimes(2);});});diff --git a/src/modules/session/message-projector.service.ts b/src/modules/session/message-projector.service.tsindex 410d70378..bc7e6c7d9 100644--- a/src/modules/session/message-projector.service.ts+++ b/src/modules/session/message-projector.service.ts@@ -10,6 +10,7 @@ import { KeyedMutationQueue } from '../../common/utils/keyed-mutation-queue';import { SessionLidResolver } from './session-lid-resolver.service';import { buildMessageMetadata, storableWaMessageId } from './message-row.mapper';import { MessageMutationProjector } from './message-mutation-projector';+import { updateMessageMetadata } from '../message/message-metadata';import { persistHistoryMessages } from './message-history-projector';import { isTransientDbError, isUniqueViolation } from '../../common/utils/db-errors';import { resolveFeatureFlags } from '../../config/feature-flags';@@ -515,16 +516,14 @@ export class MessageProjector {/** Merge reactions into the row's metadata, withdrawing a sender's on ''. Must run on the mutation chain. */private async storeReactions(id: string, waMessageId: string, changes: Record<string, string>): Promise<void> {- const row = await this.messageRepository.findOne({ where: { sessionId: id, waMessageId } });- if (!row) return;- const metadata = row.metadata ?? {};- const reactions = { ...(metadata.reactions as Record<string, string> | undefined) };- for (const [sender, reaction] of Object.entries(changes)) {- if (reaction) reactions[sender] = reaction;- else delete reactions[sender];- }- // Only the metadata column, so a concurrent ack UPDATE is not overwritten.- await this.messageRepository.update({ sessionId: id, waMessageId }, { metadata: { ...metadata, reactions } });+ await updateMessageMetadata(this.messageRepository, { sessionId: id, waMessageId }, metadata => {+ const reactions = { ...(metadata.reactions as Record<string, string> | undefined) };+ for (const [sender, reaction] of Object.entries(changes)) {+ if (reaction) reactions[sender] = reaction;+ else delete reactions[sender];+ }+ return { ...metadata, reactions };+ });}/**diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex 681661f4b..f45eedcd7 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -5925,7 +5925,7 @@ describe('SessionService', () => {expect(messageRepository.save).not.toHaveBeenCalled();expect(messageRepository.update).toHaveBeenCalledWith(- { sessionId: 'sess-uuid-1', waMessageId: 'wa-1' },+ expect.objectContaining({ sessionId: 'sess-uuid-1', waMessageId: 'wa-1' }),{ metadata: { reactions: { alice: '👍' } } },);});diff --git a/src/modules/webhook/webhook-recovery.pg.spec.ts b/src/modules/webhook/webhook-recovery.pg.spec.tsindex ee54f05de..36253b380 100644--- a/src/modules/webhook/webhook-recovery.pg.spec.ts+++ b/src/modules/webhook/webhook-recovery.pg.spec.ts@@ -12,6 +12,7 @@ import { recordWebhookDeliveryFailure } from './utils/record-delivery-failure';import { DeduplicateTerminalWebhookFailures1787200000000 } from '../../database/migrations/1787200000000-DeduplicateTerminalWebhookFailures';import { ChatMediaArchiveService } from '../chat-media/chat-media-archive.service';import type { StorageService } from '../../common/storage/storage.service';+import { mergeSentMetadata, updateMessageMetadata } from '../message/message-metadata';jest.mock('archiver', () => ({ default: jest.fn() }));const describePostgres = process.env.DATABASE_TYPE === 'postgres' ? describe : describe.skip;@@ -204,6 +205,25 @@ describePostgres('webhook and media recovery on PostgreSQL', () => {archived: true,omitted: true,});+ await updateMessageMetadata(repository, { id: first.id }, current =>+ mergeSentMetadata(current, { ...metadata, quotedMessage: { id: 'quoted' } }),+ );+ const archived = (await repository.findOneByOrFail({ id: first.id })).metadata;+ expect(archived.media).toMatchObject({ archived: true, omitted: true });+ expect(archived.quotedMessage).toEqual({ id: 'quoted' });+ const update = repository.update.bind(repository);+ jest.spyOn(repository, 'update').mockImplementationOnce(async (where, patch) => {+ await update({ id: first.id }, { metadata: { ...archived, reactions: { a: 'first' } } });+ return update(where, patch);+ });+ await updateMessageMetadata(repository, { id: first.id }, current => ({+ ...current,+ reactions: { ...(current.reactions as Record<string, string>), b: 'second' },+ }));+ expect((await repository.findOneByOrFail({ id: first.id })).metadata).toMatchObject({+ media: { archived: true, omitted: true },+ reactions: { a: 'first', b: 'second' },+ });const raced = await repository.save({ ...base, waMessageId: 'race' });const find = repository.findOne.bind(repository);jest.spyOn(repository, 'findOne').mockImplementationOnce(async options => {