Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): apply a revoke or edit that beats the message row

Yudhi Armyndharis6f0eedc1ee2b
diff --git a/src/modules/session/message-projector.service.spec.ts b/src/modules/session/message-projector.service.spec.ts
index b208732b9..431300abe 100644
--- a/src/modules/session/message-projector.service.spec.ts
+++ b/src/modules/session/message-projector.service.spec.ts
@@ -532,6 +532,91 @@ describe('MessageProjector (inbound projection)', () => {
expect(projector.inFlightInbound('other-session', 'wamid.1')).toBeUndefined();
});
+ // The row is inserted only after the message:received chain, so a revoke or edit landing while
+ // it runs updates nothing, and the insert would then write the content the sender took back.
+ describe('a revoke or edit that lands while message:received is still running', () => {
+ let releaseHook: () => void;
+ const received = async (engine: IWhatsAppEngine): Promise<void> => {
+ const gate = new Promise<void>(resolve => (releaseHook = resolve));
+ hookManager.execute.mockImplementationOnce(async (_event: string, data: unknown) => {
+ await gate;
+ return { continue: true, data };
+ });
+ projector.handleInboundMessage(SESSION_ID, engine, makeIncoming());
+ await new Promise(resolve => setImmediate(resolve));
+ };
+ const drain = async (): Promise<void> => {
+ for (let i = 0; i < 5; i++) await new Promise(resolve => setImmediate(resolve));
+ };
+ /** The update calls issued after the row was inserted, as [where, change]. */
+ const updatesAfterInsert = (): unknown[] => {
+ const insertedAt = messageRepository.insert.mock.invocationCallOrder[0];
+ return messageRepository.update.mock.calls.filter(
+ (_call, i) => messageRepository.update.mock.invocationCallOrder[i] > insertedAt,
+ );
+ };
+ const where = { sessionId: SESSION_ID, waMessageId: 'wamid.1' };
+
+ beforeEach(() => {
+ Object.assign(eventsGateway, { emitMessageEdited: jest.fn() });
+ });
+
+ it('empties the row once it is written', async () => {
+ const engine = makeEngine();
+ engines.set(SESSION_ID, engine);
+ await received(engine);
+
+ projector.handleMessageRevoked(SESSION_ID, engine, { id: 'wamid.1', body: '', type: 'revoked' } as never);
+ expect(messageRepository.update).toHaveBeenCalledWith(where, { body: '', type: 'revoked' });
+ expect(webhookService.dispatch).toHaveBeenCalledWith(SESSION_ID, 'message.revoked', expect.anything());
+ releaseHook();
+ await drain();
+
+ expect(messageRepository.insert).toHaveBeenCalledTimes(1);
+ expect(updatesAfterInsert()).toEqual([[where, { body: '', type: 'revoked' }]]);
+ });
+
+ it('writes the latest edit onto the row once it is written', async () => {
+ const engine = makeEngine();
+ engines.set(SESSION_ID, engine);
+ await received(engine);
+
+ projector.applyMessageEditQueued(SESSION_ID, { messageId: 'wamid.1', body: 'first fix' } as never);
+ projector.applyMessageEditQueued(SESSION_ID, { messageId: 'wamid.1', body: 'second fix' } as never);
+ await drain();
+ releaseHook();
+ await drain();
+
+ expect(updatesAfterInsert()).toEqual([[where, { body: 'second fix' }]]);
+ expect(webhookService.dispatch).toHaveBeenCalledWith(SESSION_ID, 'message.edited', expect.anything());
+ });
+
+ it('lets a revoke win over an edit', async () => {
+ const engine = makeEngine();
+ engines.set(SESSION_ID, engine);
+ await received(engine);
+
+ projector.handleMessageRevoked(SESSION_ID, engine, { id: 'wamid.1' } as never);
+ projector.applyMessageEditQueued(SESSION_ID, { messageId: 'wamid.1', body: 'late fix' } as never);
+ await drain();
+ releaseHook();
+ await drain();
+
+ expect(updatesAfterInsert()).toEqual([[where, { body: '', type: 'revoked' }]]);
+ });
+
+ it('changes nothing after the insert when no revoke or edit arrived', async () => {
+ const engine = makeEngine();
+ engines.set(SESSION_ID, engine);
+ await received(engine);
+ releaseHook();
+ await drain();
+
+ expect(messageRepository.insert).toHaveBeenCalledTimes(1);
+ expect(updatesAfterInsert()).toEqual([]);
+ });
+ });
+
it('routes a status broadcast to the status store instead of the message table', async () => {
const engine = makeEngine();
engines.set(SESSION_ID, engine);
diff --git a/src/modules/session/message-projector.service.ts b/src/modules/session/message-projector.service.ts
index 299133f97..da57aa756 100644
--- a/src/modules/session/message-projector.service.ts
+++ b/src/modules/session/message-projector.service.ts
@@ -87,8 +87,13 @@ export class MessageProjector {
});
// Inbound messages whose `message:received` chain is running, by `${sessionId}:${waMessageId}`. The
- // row is written only after the chain, so a handler that quotes the message reads it from here.
- private readonly inboundInFlight = new Map<string, { message: InboundMessageData }>();
+ // row is written only after the chain, so a handler that quotes the message reads it from here, and
+ // a revoke or edit landing meanwhile finds no row to update: it is recorded here and applied once
+ // the row is written (see applyChangesMadeInFlight).
+ private readonly inboundInFlight = new Map<
+ string,
+ { message: InboundMessageData; revoked?: boolean; editedBody?: string }
+ >();
// Reaction/edit applies, extracted to a plain collaborator. It shares this instance's
// messageMutations queue, so the public enqueue path and the queued applies serialize on one chain.
@@ -143,8 +148,10 @@ export class MessageProjector {
// Convert IncomingMessage to plain object for dispatch
const messageData = { ...message };
// Tracks the chain's current copy, so a quote taken mid-chain carries an earlier handler's rewrite.
- const inFlight = { message: messageData };
const inFlightKey = `${id}:${message.id}`;
+ // A re-fire of the same id keeps a change recorded against the chain it replaces.
+ const { revoked, editedBody } = this.inboundInFlight.get(inFlightKey) ?? {};
+ const inFlight = { message: messageData, revoked, editedBody };
this.inboundInFlight.set(inFlightKey, inFlight);
// Execute hook for message received - plugins can modify or stop processing
@@ -349,6 +356,7 @@ export class MessageProjector {
const result = await this.messageRepository.insert(dbMessage as unknown as QueryDeepPartialEntity<Message>);
Object.assign(dbMessage, result.identifiers[0] ?? {}, result.generatedMaps?.[0] ?? {});
persisted = true;
+ this.applyChangesMadeInFlight(id, incoming.id);
} catch (err) {
if (isUniqueViolation(err)) {
isNewMessage = false;
@@ -362,6 +370,25 @@ export class MessageProjector {
return { dbMessage, persisted };
}
+ /**
+ * Write a revoke or edit that arrived while the message's `message:received` chain ran onto the row
+ * that chain just inserted: its own UPDATE matched no row then. Queued on the message's mutation
+ * chain, so it lands after any edit already queued, and a revoke wins over an edit. A change arriving
+ * after the insert finds the row itself.
+ */
+ private applyChangesMadeInFlight(id: string, waMessageId: string): void {
+ const pending = waMessageId ? this.inboundInFlight.get(`${id}:${waMessageId}`) : undefined;
+ if (!pending?.revoked && pending?.editedBody === undefined) return;
+ this.enqueueMessageMutation(id, waMessageId, async () => {
+ const change = pending.revoked ? { body: '', type: 'revoked' } : { body: pending.editedBody };
+ try {
+ await this.messageRepository.update({ sessionId: id, waMessageId }, change);
+ } catch (err) {
+ this.logger.error(`Failed to apply a revoke or edit to message ${waMessageId}`, String(err));
+ }
+ });
+ }
+
/** Fan an accepted inbound message out: `message:persisted` plugin hook, webhook, websocket emit. */
private dispatchInboundMessage(id: string, finalMessage: InboundMessageData, outcome: InboundPersistOutcome): void {
const { dbMessage, persisted } = outcome;
@@ -619,6 +646,8 @@ export class MessageProjector {
// `message.id` is the revocation notification, which never matches a stored row.
// `revokedId` falls back to `id` (Baileys, where the two are the same).
const revokedWaMessageId = message.revokedId ?? message.id;
+ const inFlight = this.inboundInFlight.get(`${id}:${revokedWaMessageId}`);
+ if (inFlight) inFlight.revoked = true;
void this.messageRepository
.update({ sessionId: id, waMessageId: revokedWaMessageId }, { body: '', type: 'revoked' })
.catch(err => {
@@ -646,6 +675,8 @@ export class MessageProjector {
/** Edit apply, queued on the per-message mutation chain — see MessageMutationProjector. */
applyMessageEditQueued(id: string, message: EditedMessage): void {
+ const inFlight = this.inboundInFlight.get(`${id}:${message.messageId}`);
+ if (inFlight) inFlight.editedBody = message.body;
this.mutationProjector.applyMessageEditQueued(id, message);
}