Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(engine): tolerate absent parent session in Baileys message store (#319) (#320)

Yudhi Armyndharisf2664389bc0e
diff --git a/src/engine/adapters/baileys-message-store.service.spec.ts b/src/engine/adapters/baileys-message-store.service.spec.ts
index 9c894dc65..701e314a8 100644
--- a/src/engine/adapters/baileys-message-store.service.spec.ts
+++ b/src/engine/adapters/baileys-message-store.service.spec.ts
@@ -90,9 +90,12 @@ describe('BaileysMessageStoreService', () => {
const s = new BaileysMessageStoreService(repo);
// Insert 6 messages via put() — each call sets createdAt: new Date(), so even within the
- // same wall-clock second the stored values carry millisecond precision.
+ // same wall-clock second the stored values carry millisecond precision. A 2ms gap guarantees
+ // each createdAt is a distinct millisecond, so the (createdAt, id) eviction order is
+ // deterministic and the survivor assertions below don't race the random-UUID tiebreaker.
for (let i = 1; i <= 6; i++) {
await s.put('s_c1', msg(`C${i}`));
+ await new Promise(r => setTimeout(r, 2));
}
const count = await repo.count({ where: { sessionId: 's_c1' } });
@@ -151,6 +154,25 @@ describe('BaileysMessageStoreService', () => {
expect(await s.getMessage('s2', 'T4')).not.toBeNull();
});
+ // Issue #319 — an orphaned adapter (its session was deleted/recreated during reconnect
+ // churn) keeps receiving messages.upsert and calls put() under a sessionId that no longer
+ // has a parent row. The FK then fails (SQLITE_CONSTRAINT in prod) on EVERY message, the
+ // store stays empty, and reply/forward/react/delete-by-id can never resolve the message.
+ // put() must tolerate the absent parent — skip the write instead of throwing per message.
+ it('skips persisting (no throw) when the parent session row is absent (orphaned adapter; #319)', async () => {
+ await ds.query('PRAGMA foreign_keys = ON'); // faithfully reproduce production FK enforcement
+ // No seedSession('orphan') — the parent is gone.
+ await expect(service.put('orphan', msg('M1'))).resolves.toBeUndefined();
+ expect(await repo.count({ where: { sessionId: 'orphan' } })).toBe(0);
+ });
+
+ it('still rethrows a non-FK persistence error (does not swallow real failures)', async () => {
+ await seedSession('s1');
+ const boom = Object.assign(new Error('disk full'), { code: 'SQLITE_FULL' });
+ jest.spyOn(repo, 'upsert').mockRejectedValueOnce(boom);
+ await expect(service.put('s1', msg('M1'))).rejects.toThrow('disk full');
+ });
+
it('clearSession removes only that session', async () => {
await seedSession('s1');
await seedSession('s2');
diff --git a/src/engine/adapters/baileys-message-store.service.ts b/src/engine/adapters/baileys-message-store.service.ts
index 0f6caf773..5c0db5583 100644
--- a/src/engine/adapters/baileys-message-store.service.ts
+++ b/src/engine/adapters/baileys-message-store.service.ts
@@ -5,14 +5,38 @@ import type * as BaileysLib from '@whiskeysockets/baileys';
import type { WAMessage } from '@whiskeysockets/baileys';
import { BaileysStoredMessage } from './baileys-stored-message.entity';
import { BaileysMessageStore } from '../types/baileys.types';
+import { createLogger } from '../../common/services/logger.service';
function positiveIntFromEnv(name: string, fallback: number): number {
const parsed = Number.parseInt(process.env[name] ?? '', 10);
return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback;
}
+/**
+ * True when a write failed because the parent `sessions` row is absent (a foreign-key violation),
+ * as opposed to any other persistence error. Covers SQLite (`SQLITE_CONSTRAINT[_FOREIGNKEY]`) and
+ * Postgres (`23503`). TypeORM wraps the driver error in a QueryFailedError, so check both the
+ * wrapper and `driverError`.
+ */
+function isMissingParentSessionError(err: unknown): boolean {
+ const e = err as { code?: string; driverError?: { code?: string }; message?: string };
+ const code = e?.driverError?.code ?? e?.code;
+ if (code === '23503') {
+ return true; // Postgres foreign_key_violation
+ }
+ const message = e?.message ?? '';
+ if (typeof code === 'string' && code.startsWith('SQLITE_CONSTRAINT')) {
+ return code === 'SQLITE_CONSTRAINT_FOREIGNKEY' || /FOREIGN KEY/i.test(message);
+ }
+ return /FOREIGN KEY constraint failed/i.test(message);
+}
+
@Injectable()
export class BaileysMessageStoreService implements BaileysMessageStore {
+ private readonly logger = createLogger('BaileysMessageStore');
+ /** Sessions already warned about a missing parent row — keeps the orphan log to once per session. */
+ private readonly orphanWarnedSessions = new Set<string>();
+
/** Lazily loaded @whiskeysockets/baileys module (ESM-only; loaded on first use, not at boot). */
private baileysLib?: typeof BaileysLib;
@@ -38,10 +62,28 @@ export class BaileysMessageStoreService implements BaileysMessageStore {
// second-precision (e.g. '…:11') while the JS Date bound serializes as '…:11.000', and SQLite
// string-compares '…:11' < '…:11.000' = TRUE, causing every same-second row to be over-evicted
// and the store to be wiped to ~0 (C1).
- await this.repo.upsert({ sessionId, waMessageId, serializedMessage, createdAt: new Date() }, [
- 'sessionId',
- 'waMessageId',
- ]);
+ try {
+ await this.repo.upsert({ sessionId, waMessageId, serializedMessage, createdAt: new Date() }, [
+ 'sessionId',
+ 'waMessageId',
+ ]);
+ } catch (err) {
+ if (isMissingParentSessionError(err)) {
+ // Orphaned adapter: the sessions row was deleted/recreated (reconnect churn) while this
+ // adapter kept emitting messages.upsert. There is no valid parent to store under, so drop
+ // the write instead of throwing the FK error on every message (#319). Warn once per session
+ // so the orphan stays visible without per-message log noise.
+ if (!this.orphanWarnedSessions.has(sessionId)) {
+ this.orphanWarnedSessions.add(sessionId);
+ this.logger.warn(
+ `No parent session row for "${sessionId}" — skipping Baileys message store (orphaned/recreated session). ` +
+ `reply/forward/react/delete-by-id will be unavailable for messages received under this id.`,
+ );
+ }
+ return;
+ }
+ throw err; // a genuine persistence failure — let the adapter's catch surface it
+ }
await this.enforceLimit(sessionId);
}