Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(infra): re-key name-keyed chat states restored by import-data

Yudhi Armyndharis15e3f691673f
diff --git a/src/database/migrations/1786500000000-ReKeyChatStatesBySessionId.ts b/src/database/migrations/1786500000000-ReKeyChatStatesBySessionId.ts
index 67cccc106..2d1a92937 100644
--- a/src/database/migrations/1786500000000-ReKeyChatStatesBySessionId.ts
+++ b/src/database/migrations/1786500000000-ReKeyChatStatesBySessionId.ts
@@ -19,24 +19,33 @@ export class ReKeyChatStatesBySessionId1786500000000 implements MigrationInterfa
public async up(queryRunner: QueryRunner): Promise<void> {
if (!(await queryRunner.hasTable('chat_states'))) return;
- await queryRunner.query(this.rekey('name', 'id'));
+ await queryRunner.query(ReKeyChatStatesBySessionId1786500000000.rekey('name', 'id'));
}
public async down(queryRunner: QueryRunner): Promise<void> {
if (!(await queryRunner.hasTable('chat_states'))) return;
- await queryRunner.query(this.rekey('id', 'name'));
+ await queryRunner.query(ReKeyChatStatesBySessionId1786500000000.rekey('id', 'name'));
}
/**
* Correlated-subquery UPDATE rather than `UPDATE ... FROM`, which SQLite and PostgreSQL spell
* differently.
+ *
+ * Static, not a module-level export: TypeORM loads every exported function in this directory as a
+ * migration class. Also run by import-data, whose archive may predate this re-key; that caller sets
+ * `skipAlreadyKeyed` so a row already keyed by an existing session's `to` value is left alone even
+ * when some other session's `from` value happens to equal it.
*/
- private rekey(from: 'name' | 'id', to: 'name' | 'id'): string {
+ static rekey(from: 'name' | 'id', to: 'name' | 'id', opts: { skipAlreadyKeyed?: boolean } = {}): string {
const target = `(SELECT s."${to}" FROM sessions s WHERE s."${from}" = chat_states."sessionId")`;
+ const alreadyKeyed = opts.skipAlreadyKeyed
+ ? `
+ AND NOT EXISTS (SELECT 1 FROM sessions s2 WHERE s2."${to}" = chat_states."sessionId")`
+ : '';
return `UPDATE chat_states SET "sessionId" = ${target}
WHERE EXISTS (SELECT 1 FROM sessions s WHERE s."${from}" = chat_states."sessionId")
AND NOT EXISTS (
SELECT 1 FROM chat_states c WHERE c."chatId" = chat_states."chatId" AND c."sessionId" = ${target}
- )`;
+ )${alreadyKeyed}`;
}
}
diff --git a/src/modules/infra/infra-data.controller.spec.ts b/src/modules/infra/infra-data.controller.spec.ts
index 24912ca41..6ef989f49 100644
--- a/src/modules/infra/infra-data.controller.spec.ts
+++ b/src/modules/infra/infra-data.controller.spec.ts
@@ -1847,6 +1847,51 @@ describe('InfraDataController.importData status_updates + runtime reconciliation
await expect(repo.findOneByOrFail({ id: 'held' })).resolves.toMatchObject({ status: SessionStatus.READY });
});
+ // Archives taken before 0.23.5 key chat_states by session name; the re-key migration has already
+ // run on the target, so the import has to apply it to the restored rows itself.
+ const chatStateRow = (sessionId: string, updatedAt: unknown) => ({
+ sessionId,
+ chatId: '[email protected]',
+ muteEndTime: null,
+ archived: false,
+ pinned: true,
+ updatedAt,
+ });
+ const storedChatStates = () =>
+ ds.query<Array<{ sessionId: string; chatId: string }>>(
+ 'SELECT "sessionId", "chatId" FROM chat_states ORDER BY "sessionId"',
+ );
+
+ it('re-keys a chat state row restored from a name-keyed archive onto its session id', async () => {
+ const id = '8f5b1d9e-0c4a-4e21-9d6b-2a7c3f0e1b44';
+ await seedSession(id);
+ const dump = await build().exportData();
+ const session = dump.tables.sessions[0];
+
+ const res = await build().importData({
+ tables: { ...dump.tables, chatStates: [chatStateRow(session.name, session.updatedAt)] as never },
+ });
+
+ expect(res.imported).toBe(true);
+ expect(await storedChatStates()).toEqual([{ sessionId: id, chatId: '[email protected]' }]);
+ });
+
+ it('leaves a chat state row already keyed by a session id alone, even when another session is named that id', async () => {
+ // Session 'a' is named 'session-a', which is also the id of the second session. The row belongs
+ // to the second session and must not be moved onto 'a'.
+ await seedSession('a');
+ await seedSession('session-a');
+ const dump = await build().exportData();
+ const updatedAt = dump.tables.sessions[0].updatedAt;
+
+ const res = await build().importData({
+ tables: { ...dump.tables, chatStates: [chatStateRow('session-a', updatedAt)] as never },
+ });
+
+ expect(res.imported).toBe(true);
+ expect(await storedChatStates()).toEqual([{ sessionId: 'session-a', chatId: '[email protected]' }]);
+ });
+
it('exports and restores automation_rules, which the session wipe would otherwise cascade away', async () => {
await seedSession('s1');
const ruleRepo = ds.getRepository(AutomationRule);
diff --git a/src/modules/infra/infra-data.service.ts b/src/modules/infra/infra-data.service.ts
index 46389be25..f6ef393b9 100644
--- a/src/modules/infra/infra-data.service.ts
+++ b/src/modules/infra/infra-data.service.ts
@@ -12,6 +12,7 @@ import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.
import { ChatStateStoreService } from '../../engine/adapters/baileys-chat-state-store.service';
import { SessionOwnershipService } from '../session/session-ownership.service';
import { ScopeBindingService } from '../integration/scope-binding.service';
+import { ReKeyChatStatesBySessionId1786500000000 } from '../../database/migrations/1786500000000-ReKeyChatStatesBySessionId';
import { Session as SessionEntity, SessionStatus } from '../session/entities/session.entity';
import { In } from 'typeorm';
import { DateUtils } from 'typeorm/util/DateUtils';
@@ -754,6 +755,23 @@ export class InfraDataService {
}
}
+ // An archive taken before 0.23.5 keys chat_states by session NAME. The migration that re-keys
+ // them to the session id has already run on this database, so a restored name-keyed row would
+ // never be read again and its mute, archive and pin state would be silently lost. Run the same
+ // re-key here, inside the transaction. A failure takes the rollback below, like the ownership
+ // restore, because on PostgreSQL it has already aborted the transaction.
+ if (warnings.length === 0) {
+ try {
+ if (await queryRunner.hasTable('chat_states')) {
+ await queryRunner.query(
+ ReKeyChatStatesBySessionId1786500000000.rekey('name', 'id', { skipAlreadyKeyed: true }),
+ );
+ }
+ } catch (error) {
+ warnings.push(`Failed to re-key chat states: ${error instanceof Error ? error.message : String(error)}`);
+ }
+ }
+
// "Replace all data" must be all-or-nothing: the import already DELETEd every row, so if any
// INSERT failed we must roll back (restoring the pre-import data) rather than commit a
// half-wiped DB and report success. A partial restore reported as imported:true was how