Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

refactor(session): extract KeyedMutationQueue

Yudhi Armyndharisf922471a5eec
diff --git a/src/common/utils/keyed-mutation-queue.spec.ts b/src/common/utils/keyed-mutation-queue.spec.ts
new file mode 100644
index 000000000..25744afb4
--- /dev/null
+++ b/src/common/utils/keyed-mutation-queue.spec.ts
@@ -0,0 +1,132 @@
+import { KeyedMutationQueue } from './keyed-mutation-queue';
+
+/**
+ * Lets queued chains drain. Cycles through the macrotask queue as well as microtasks, so work
+ * deferred with setImmediate settles too.
+ */
+const drain = async (): Promise<void> => {
+ for (let i = 0; i < 5; i++) await new Promise(resolve => setImmediate(resolve));
+};
+
+describe('KeyedMutationQueue', () => {
+ it('runs queued work', async () => {
+ const queue = new KeyedMutationQueue();
+ const work = jest.fn().mockResolvedValue(undefined);
+
+ queue.enqueue('k', work);
+ await drain();
+
+ expect(work).toHaveBeenCalledTimes(1);
+ });
+
+ it('serializes work for the same key in arrival order', async () => {
+ const queue = new KeyedMutationQueue();
+ const order: string[] = [];
+ const slow = () =>
+ new Promise<void>(resolve => {
+ setImmediate(() => {
+ order.push('first');
+ resolve();
+ });
+ });
+
+ queue.enqueue('k', slow);
+ queue.enqueue('k', () => {
+ order.push('second');
+ return Promise.resolve();
+ });
+ await drain();
+
+ // Without chaining, the synchronous second would land before the deferred first.
+ expect(order).toEqual(['first', 'second']);
+ });
+
+ it('does not serialize across different keys', async () => {
+ const queue = new KeyedMutationQueue();
+ let releaseA: () => void = () => {};
+ const blocked = new Promise<void>(resolve => {
+ releaseA = resolve;
+ });
+ const bDone = jest.fn().mockResolvedValue(undefined);
+
+ queue.enqueue('a', () => blocked);
+ queue.enqueue('b', bDone);
+ await drain();
+
+ // 'b' must not wait on the still-pending 'a'.
+ expect(bDone).toHaveBeenCalledTimes(1);
+ releaseA();
+ await drain();
+ });
+
+ it('isolates a failure so later work on the same key still runs', async () => {
+ const queue = new KeyedMutationQueue();
+ const after = jest.fn().mockResolvedValue(undefined);
+
+ queue.enqueue('k', () => Promise.reject(new Error('boom')));
+ queue.enqueue('k', after);
+ await drain();
+
+ expect(after).toHaveBeenCalledTimes(1);
+ });
+
+ it('reports an unexpected failure to the handler with its key', async () => {
+ const onUnexpectedError = jest.fn();
+ const queue = new KeyedMutationQueue(onUnexpectedError);
+ const err = new Error('boom');
+
+ queue.enqueue('k', () => Promise.reject(err));
+ await drain();
+
+ expect(onUnexpectedError).toHaveBeenCalledWith('k', err);
+ });
+
+ it('never leaks a rejected fire-and-forget promise', async () => {
+ const unhandled = jest.fn();
+ process.on('unhandledRejection', unhandled);
+ const queue = new KeyedMutationQueue();
+
+ queue.enqueue('k', () => Promise.reject(new Error('boom')));
+ await drain();
+
+ process.off('unhandledRejection', unhandled);
+ expect(unhandled).not.toHaveBeenCalled();
+ });
+
+ it('reclaims the chain once it drains, so memory does not grow per entity touched', async () => {
+ const queue = new KeyedMutationQueue();
+
+ queue.enqueue('k', () => Promise.resolve());
+ expect(queue.size).toBe(1);
+ await drain();
+
+ expect(queue.size).toBe(0);
+ });
+
+ it('reclaims a chain that ended in failure', async () => {
+ const queue = new KeyedMutationQueue();
+
+ queue.enqueue('k', () => Promise.reject(new Error('boom')));
+ await drain();
+
+ expect(queue.size).toBe(0);
+ });
+
+ it('keeps the chain while later work is still pending', async () => {
+ const queue = new KeyedMutationQueue();
+ let release: () => void = () => {};
+ const blocked = new Promise<void>(resolve => {
+ release = resolve;
+ });
+
+ queue.enqueue('k', () => Promise.resolve());
+ queue.enqueue('k', () => blocked);
+ await drain();
+
+ // The first chain settled but must not evict the entry the second one replaced it with.
+ expect(queue.size).toBe(1);
+ release();
+ await drain();
+ expect(queue.size).toBe(0);
+ });
+});
diff --git a/src/common/utils/keyed-mutation-queue.ts b/src/common/utils/keyed-mutation-queue.ts
new file mode 100644
index 000000000..c2b8998ca
--- /dev/null
+++ b/src/common/utils/keyed-mutation-queue.ts
@@ -0,0 +1,44 @@
+/**
+ * Serializes async work per key, so concurrent mutations of the same entity apply in arrival order.
+ *
+ * Extracted from SessionService, where it existed to keep stored-message mutations ordered:
+ * reactions perform a read-modify-write and rapid edits must remain latest-write-wins, and sharing
+ * one chain per message also preserves order when different mutation kinds for the same message
+ * arrive together.
+ *
+ * There is nothing session-specific about it — it is a keyed promise chain — so it lives on its own
+ * where its failure-isolation and memory-reclamation behaviour can be tested directly, rather than
+ * through engine callbacks.
+ */
+export class KeyedMutationQueue {
+ private readonly chains = new Map<string, Promise<void>>();
+
+ /**
+ * @param onUnexpectedError Last-resort handler. Callers' work functions are expected to do their
+ * own contextual error handling; this exists so a future one cannot leak a rejected
+ * fire-and-forget promise or permanently block the key's later mutations.
+ */
+ constructor(private readonly onUnexpectedError: (key: string, err: unknown) => void = () => {}) {}
+
+ /** Queue work for `key`. A failed operation is isolated so later work on the same key still runs. */
+ enqueue(key: string, work: () => Promise<void>): void {
+ const prior = this.chains.get(key) ?? Promise.resolve();
+ const next = prior
+ .catch(() => undefined)
+ .then(work)
+ .catch(err => this.onUnexpectedError(key, err));
+ this.chains.set(key, next);
+ // Reclaim the entry once the chain drains, but only if no later work replaced it — otherwise a
+ // long-lived process would accumulate one settled promise per entity touched.
+ void next.finally(() => {
+ if (this.chains.get(key) === next) {
+ this.chains.delete(key);
+ }
+ });
+ }
+
+ /** Number of keys with in-flight work. Exposed for tests and diagnostics. */
+ get size(): number {
+ return this.chains.size;
+ }
+}
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index aa72fdc1c..d532d4185 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -25,6 +25,7 @@ import { Template } from '../template/entities/template.entity';
import { BaileysStoredMessage } from '../../engine/adapters/baileys-stored-message.entity';
import { EngineFactory } from '../../engine/engine.factory';
import { EngineRegistry } from '../../engine/engine-registry.service';
+import type { KeyedMutationQueue } from '../../common/utils/keyed-mutation-queue';
import { SessionLidResolver } from './session-lid-resolver.service';
import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';
import { EventsGateway } from '../events/events.gateway';
@@ -2913,7 +2914,7 @@ describe('SessionService', () => {
for (let i = 0; i < 3; i++) await flush();
- const chains = (service as unknown as { messageMutationChains: Map<string, unknown> }).messageMutationChains;
+ const chains = (service as unknown as { messageMutations: KeyedMutationQueue }).messageMutations;
expect(chains.size).toBe(0);
});
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index fce28e2a0..5c271e905 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -24,6 +24,7 @@ import { BaileysStoredMessage } from '../../engine/adapters/baileys-stored-messa
import { CreateSessionDto } from './dto';
import { EngineFactory } from '../../engine/engine.factory';
import { EngineRegistry } from '../../engine/engine-registry.service';
+import { KeyedMutationQueue } from '../../common/utils/keyed-mutation-queue';
import { decideReconnect, clampReconnectDelay, type ReconnectAttemptState } from './reconnect-policy';
import { SessionLidResolver } from './session-lid-resolver.service';
import { resolveAuthTimeoutMs } from '../../engine/adapters/whatsapp-web-js.adapter';
@@ -211,7 +212,12 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
// Serializes stored-message mutations per `${sessionId}:${waMessageId}`. Reactions perform a
// read-modify-write and rapid edits must remain latest-write-wins; sharing one chain also preserves
// order when different mutation kinds for the same message arrive together.
- private messageMutationChains: Map<string, Promise<void>> = new Map();
+ private readonly messageMutations = new KeyedMutationQueue((key, err) => {
+ // Both current mutation implementations contain their own contextual error handling. Keep a
+ // final guard here so a future implementation cannot leak a rejected fire-and-forget promise
+ // or permanently block the message's later mutations.
+ this.logger.error(`Unexpected failure applying message mutation: ${key}`, String(err));
+ });
// Destructive credential-teardown promises (logout rms of the session's on-disk WhatsApp auth
// dir), keyed by session NAME — the on-disk auth-dir key (EngineFactory.wwjsAuthDir/baileysAuthDir
@@ -1916,23 +1922,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
/** Queue a message-scoped mutation. A failed operation is isolated so later events still run. */
private enqueueMessageMutation(id: string, messageId: string, work: () => Promise<void>): void {
- const key = `${id}:${messageId}`;
- const prior = this.messageMutationChains.get(key) ?? Promise.resolve();
- const next = prior
- .catch(() => undefined)
- .then(work)
- .catch(err => {
- // Both current mutation implementations contain their own contextual error handling. Keep a
- // final guard here so a future implementation cannot leak a rejected fire-and-forget promise
- // or permanently block the message's later mutations.
- this.logger.error(`Unexpected failure applying message mutation: ${messageId}`, String(err));
- });
- this.messageMutationChains.set(key, next);
- void next.finally(() => {
- if (this.messageMutationChains.get(key) === next) {
- this.messageMutationChains.delete(key);
- }
- });
+ this.messageMutations.enqueue(`${id}:${messageId}`, work);
}
/** Persist an edit before notifying consumers, while still surfacing the occurrence if storage fails. */