diff --git a/src/main/wcdb4-client.ts b/src/main/wcdb4-client.ts index c1ed2c0..2d65ebd 100644 --- a/src/main/wcdb4-client.ts +++ b/src/main/wcdb4-client.ts @@ -569,9 +569,6 @@ export class Wcdb4Client { private wcdbMsgInsertGetSwitches: | ((handle: number, dbPath: string, outJson: WcdbVoidOut) => number) | null = null - private wcdbMsgInsertListShardCatalog: - | ((handle: number, outJson: WcdbVoidOut) => number) - | null = null private wcdbGetGroupNicknames: | ((handle: number, chatroomId: string, outJson: WcdbVoidOut) => number) | null = null @@ -1938,7 +1935,7 @@ export class Wcdb4Client { /** * 读取「微信消息插入规则」的分片目录(只读)。 * - * 每个分片只跑两条查询(表清单 + 规则清单),拿回来之后调用方可以在本地用 + * 每个分片只跑一条 sqlite_master 查询,拿回来之后调用方可以在本地用 * md5(roomId) 匹配出「每个会话落在哪些分片、规则齐不齐」。这样即使会话很多, * 判断全部会话的状态也只是一次目录读取,不需要按会话逐个查库。 */ @@ -1950,29 +1947,40 @@ export class Wcdb4Client { shard: string dbPath: string configTable: boolean - storeTables: { capture: boolean; names: boolean; queue: boolean } tables: string[] rules: Array<{ name: string; table: string }> }> } error?: string } { - if (!this.wcdbMsgInsertListShardCatalog) { + if (!this.wcdbExecQuery) { return { success: false, error: '当前 WCDB 服务不支持消息插入规则目录' } } try { - const catalog = this.callJson<{ - shardCount: number - shards: Array<{ - shard: string - dbPath: string - configTable: boolean - storeTables: { capture: boolean; names: boolean; queue: boolean } - tables: string[] - rules: Array<{ name: string; table: string }> - }> - }>((handle, outJson) => this.wcdbMsgInsertListShardCatalog!(handle, outJson)) - return { success: true, catalog } + // 专用 native 目录接口在部分 Windows 数据库上会终止进程,改走已有的只读 SQL 通道。 + const shards = this.listMessageShardPaths().map((dbPath) => { + const rows = this.callJson<{ name: string; type: string; tbl_name: string }[]>( + (handle, outJson) => + this.wcdbExecQuery!( + handle, + 'message', + dbPath, + "SELECT name, type, tbl_name FROM sqlite_master WHERE type IN ('table', 'trigger')", + outJson + ) + ) + const tables = rows.filter((row) => row.type === 'table').map((row) => row.name) + return { + shard: path.basename(dbPath), + dbPath, + configTable: tables.includes('_tm_config'), + tables, + rules: rows + .filter((row) => row.type === 'trigger') + .map((row) => ({ name: row.name, table: row.tbl_name })) + } + }) + return { success: true, catalog: { shardCount: shards.length, shards } } } catch (error) { return { success: false, error: error instanceof Error ? error.message : String(error) } } @@ -3340,14 +3348,6 @@ export class Wcdb4Client { this.wcdbMsgInsertGetSwitches = null } - try { - this.wcdbMsgInsertListShardCatalog = lib.func( - 'int32 wcdb_msg_insert_list_shard_catalog(int64 handle, _Out_ void** outJson)' - ) as (handle: number, outJson: WcdbVoidOut) => number - } catch { - this.wcdbMsgInsertListShardCatalog = null - } - try { this.wcdbGetGroupNicknames = lib.func( 'int32 wcdb_get_group_nicknames(int64 handle, const char* chatroomId, _Out_ void** outJson)' diff --git a/tests/unit/wcdb-msg-insert-catalog.test.ts b/tests/unit/wcdb-msg-insert-catalog.test.ts new file mode 100644 index 0000000..9eb7074 --- /dev/null +++ b/tests/unit/wcdb-msg-insert-catalog.test.ts @@ -0,0 +1,142 @@ +import { createHash } from 'crypto' +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs' +import { tmpdir } from 'os' +import { basename, join } from 'path' +import { DatabaseSync } from 'node:sqlite' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { Wcdb4Client } from '../../src/main/wcdb4-client' +import { readMsgInsertSwitches } from '../../src/main/services/msg-insert-switch-service' + +vi.mock('../../src/main/resource-paths', () => ({ + getResourceRoots: () => [], + findResource: () => null +})) + +describe('message insert shard catalog', () => { + const roots: string[] = [] + const room = 'fixture-group@chatroom' + const hash = createHash('md5').update(room).digest('hex') + const table = `Msg_${hash}` + const capture = `_tm_msg_insert_capture_${hash}` + + afterEach(() => { + roots.splice(0).forEach((root) => rmSync(root, { recursive: true, force: true })) + }) + + function fixture() { + const root = mkdtempSync(join(tmpdir(), 'wcdb-insert-catalog-')) + roots.push(root) + const messageRoot = join(root, 'message') + mkdirSync(messageRoot) + for (const name of ['message_0.db', 'message_1.db']) { + const db = new DatabaseSync(join(messageRoot, name)) + try { + db.exec(`CREATE TABLE ${table}(content TEXT);`) + if (name === 'message_0.db') { + db.exec(` + CREATE TABLE _tm_config(key TEXT PRIMARY KEY, value INTEGER); + CREATE TRIGGER ${capture} AFTER INSERT ON ${table} BEGIN SELECT 1; END; + `) + } + } finally { + db.close() + } + } + for (const name of ['media_0.db', 'message_0 (SFConflict).db', 'message_0.db-wal']) { + writeFileSync(join(messageRoot, name), '') + } + const nativeCatalog = vi.fn(() => { + throw new Error('unsafe native catalog called') + }) + const query = vi.fn((_handle, kind, dbPath: string, sql: string, out: unknown[]) => { + expect(kind).toBe('message') + const db = new DatabaseSync(dbPath, { readOnly: true }) + try { + out[0] = db.prepare(sql).all() + } finally { + db.close() + } + return 0 + }) + const client = Object.assign(Object.create(Wcdb4Client.prototype), { + dbStoragePath: root, + wcdbMsgInsertListShardCatalog: nativeCatalog, + wcdbExecQuery: query, + callJson: (call: (handle: number, out: unknown[]) => number) => { + const out: unknown[] = [null] + call(1, out) + return out[0] + }, + getSessions: () => [{ username: room }], + getMsgInsertSwitches: () => ({ success: true, switches: { recall_notice: true } }) + }) as Wcdb4Client + return { client, nativeCatalog, query, messageRoot } + } + + it('reads tables and trigger attachments through read-only SQL without the crashing native API', () => { + const { client, nativeCatalog, query, messageRoot } = fixture() + + expect(client.listMsgInsertShardCatalog()).toEqual({ + success: true, + catalog: { + shardCount: 2, + shards: [ + { + shard: 'message_0.db', + dbPath: join(messageRoot, 'message_0.db'), + configTable: true, + tables: [table, '_tm_config'], + rules: [{ name: capture, table }] + }, + { + shard: 'message_1.db', + dbPath: join(messageRoot, 'message_1.db'), + configTable: false, + tables: [table], + rules: [] + } + ] + } + }) + expect(nativeCatalog).not.toHaveBeenCalled() + expect(query.mock.calls.map((call) => basename(call[2]))).toEqual([ + 'message_0.db', + 'message_1.db' + ]) + }) + + it('preserves the rule coverage calculation across shards', () => { + const { client } = fixture() + + const snapshot = readMsgInsertSwitches({ client, monitoredRoomIds: [] }) + expect(snapshot.success).toBe(true) + expect(snapshot.switches.recall_notice).toMatchObject({ + desiredEnabled: true, + effectiveEnabled: false, + totalShards: 2, + totalInstallableRooms: 1, + readyInstallableRooms: 0, + notReadyRooms: [{ roomId: room, notReadyShards: ['message_1.db'] }] + }) + }) + + it('reports a query failure instead of returning a partial catalog', () => { + const { client, query } = fixture() + query.mockImplementationOnce(() => { + throw new Error('fixture shard unavailable') + }) + + expect(client.listMsgInsertShardCatalog()).toEqual({ + success: false, + error: 'fixture shard unavailable' + }) + }) + + it('reports an unsupported SQL channel without calling the unsafe native API', () => { + const { client, nativeCatalog } = fixture() + Reflect.set(client, 'wcdbExecQuery', null) + + expect(client.listMsgInsertShardCatalog()).toMatchObject({ success: false }) + expect(nativeCatalog).not.toHaveBeenCalled() + }) +})