feat: 微信内退群监控以及撤回

This commit is contained in:
Wxw-Gu committed 2026-10-12 15:48:14 +08:00
1 parent e5f0aa59f4
commit 632ec9ee13
15 files changed
+1944 -12

No files matched your search

+225
View File
@@ -1,3 +1,4 @@
import path from 'node:path'
import {
isLegacyMigrationHelper,
isUserDataIsolated,
@@ -124,7 +125,110 @@ import { MessageListenerService } from './services/message-listener-service'
import { automationRuleStore } from './services/automation-rule-store'
import { automationExecutionLogService } from './services/automation-execution-log-service'
import { initAutomationService, getAutomationService } from './services/automation-service'
import {
applyMsgInsertSwitch,
emptyMsgInsertStatus,
eventModeStatus,
readMsgInsertSwitches,
reconcileMsgInsertRules,
resolveHelperPath,
type MsgInsertScopeInput,
type MsgInsertSwitchName
} from './services/msg-insert-switch-service'
import { GroupStatsService } from './services/group-stats-service'
import {
configureWechatLocalExitNotice,
wechatLocalExitNoticeService
} from './services/wechat-local-exit-notice-service'
/**
* 微信消息插入开关的作用面输入。
*
* 目标群列表**复用退群监控的配置**,不在这里另维护一份。
* 数据库没连上时返回 null,调用方据此禁用写入而不是假装能改。
*/
function monitoredRoomCount(): number {
return (groupExitMonitorService.getState().monitoredRoomIds || []).length
}
function resolveMsgInsertScopeInput(): MsgInsertScopeInput | null {
const client = chat.getChatDb()?.getWcdb4Client()
if (!client) return null
return {
client,
monitoredRoomIds: groupExitMonitorService.getState().monitoredRoomIds || []
}
}
/**
* 轻量 reconciliation —— 把退群监控选中的群缺失的规则补齐,不动开关值。
*
* 触发点:连库完成后 / 退群监控群列表变化后 / 用户打开开关时(那条在 service 里)。
* 不轮询。微信新建 message_4.db 并把目标群的新表放进去时,下一次触发就会补上。
*/
let lastMsgInsertReconciledShards = ''
/**
* 启动时补齐 —— 防撤回 reconciliation 的入口之一。
*
* 只在**持久化的开关已经是开**的时候跑(说明用户上次明确打开过)。开关是关的
* 就什么都不做,避免每次启动都扫一遍目标会话。
*
* 顺带覆盖「已启用时检测到新 shard / 新表」:分片清单变了就重新补齐,并把新的
* 清单记下来。渲染层读状态**不会**走到这里 —— GET 必须是纯读。
*/
async function reconcileMsgInsertRulesOnStart(): Promise<void> {
const scope = resolveMsgInsertScopeInput()
const client = chat.getChatDb()?.getWcdb4Client()
if (!scope || !client) return
let enabled = false
try {
const shards = client.listMessageShardPaths()
const shardSignature = shards.map((item) => path.basename(item)).join(',')
if (lastMsgInsertReconciledShards && lastMsgInsertReconciledShards !== shardSignature) {
/* 微信新建了 message_N.db(或清理了旧的)—— 分片集合变了就重新补齐。 */
console.log('[MsgInsert] 检测到消息分片变化,重新补齐规则')
}
lastMsgInsertReconciledShards = shardSignature
for (const shardPath of shards) {
const read = client.getMsgInsertSwitches(shardPath)
if (read.success && read.switches?.recall_notice) {
enabled = true
break
}
}
} catch (error) {
console.warn('[MsgInsert] 启动检查失败:', error)
return
}
if (!enabled) return
await reconcileMsgInsertRulesNow()
}
async function reconcileMsgInsertRulesNow(): Promise<boolean> {
const scope = resolveMsgInsertScopeInput()
const client = chat.getChatDb()?.getWcdb4Client()
if (!scope || !client) return false
try {
const result = await reconcileMsgInsertRules({
...scope,
myWxid: String(chat.getSelfAccountInfo()?.wxid || ''),
databaseKey: client.getKey()
})
if (result.rooms === 0) {
// 群列表还没就绪(或用户本来就没选群)—— 不算跑过,让下一次触发重试。
return false
}
if (!result.done) {
console.warn(`[MsgInsert] reconcile 未完成 errorCode=${result.errorCode || 'UNKNOWN'}`)
}
return true
} catch (error) {
console.warn('[MsgInsert] reconcile 失败:', error)
return true
}
}
import { wechatActionLogService } from './services/wechat-action-log-service'
import { toPersonalWechatSendResult, wechatActionGateway } from './services/wechat-action-gateway'
import { personalWechatSendService } from './services/personal-wechat-send-service'
@@ -1087,7 +1191,32 @@ app.whenReady().then(async () => {
* `handleGroupExit` 自己吞掉异常,这里再兜一层 `.catch` 是防御性的 ——
* 未捕获的 rejection 会污染监控循环,而退群事实早就已经记录成功了。
*/
/* 退群本地提示的运行时依赖:密钥 / wxid / 账号目录都由主进程提供,
* 服务自己不依赖 chat-service 的具体形态。 */
configureWechatLocalExitNotice({
resolveDatabaseKey: () => chat.getChatDb()?.getWcdb4Client()?.getKey() || '',
resolveMyWxid: () => String(chat.getSelfAccountInfo()?.wxid || ''),
resolveAccountRoot: () => {
const shards = chat.getChatDb()?.getWcdb4Client()?.listMessageShardPaths() || []
if (shards.length > 0) return path.dirname(path.dirname(path.dirname(shards[0])))
return String(chat.getCurrentAccountRoot() || '')
}
})
/*
* 防撤回 reconciliation 的启动入口:只有当持久化的开关已经是「开」时才会跑。
* 渲染层读状态、群列表变化都不会触发 DDL。
*/
void reconcileMsgInsertRulesOnStart()
groupExitMonitorService.setGroupExitHandler((event) => {
/*
* 微信内退群监控消息:一次性往群里插一条本地提示。
*
* 与下面的自动化通知**完全独立**:自己不抛异常(handleExitEvent 内部兜底)、
* 不 await、失败只记日志 —— 插入失败绝不能影响退群监控循环或自动化通知。
*/
void wechatLocalExitNoticeService.handleExitEvent(event)
try {
return getAutomationService()
.handleGroupExit(event)
@@ -1693,6 +1822,8 @@ app.whenReady().then(async () => {
* 只有一个参数:旧版第二个参数(通知群聊)已经迁到「自动化 → 退群通知」,
* 退群监控不再持有任何通知配置。
*/
/* 监控范围变化不再触发任何规则补齐:防撤回的目标是「全部有消息表的会话」,
* 与退群监控选中的群无关;退群提示也已经改成事件驱动、不依赖 per-room 规则。 */
ipcMain.handle('group-exit-monitor:setGroups', (_, roomIds: string[]) =>
groupExitMonitorService.setMonitoredRoomIds(Array.isArray(roomIds) ? roomIds : [])
)
@@ -1757,6 +1888,100 @@ app.whenReady().then(async () => {
})
ipcMain.handle('automation:clearExecutions', () => automationExecutionLogService.clear())
ipcMain.handle('automation:listGroups', () => tryAutomationService()?.listGroups() ?? [])
/**
* 微信消息插入开关 —— 读取。
*
* 只走本进程只读路径(分片目录 + 开关值),不持有任何写权限。
* 状态里同时给出 desiredEnabled / effectiveEnabled:开关值写成功不等于功能
* 真的生效(规则可能没装齐),渲染层不能只看前者。
*/
ipcMain.handle('automation:getMsgInsertSwitches', () => {
/* 🔴 纯读:任何 get/status 都不允许写微信库、不允许触发 DDL。
* 规则补齐只发生在「用户打开开关」(helper 的 apply 内部先 ensure)与
* 「应用启动且持久化开关为开」这两个时机。 */
const scope = resolveMsgInsertScopeInput()
if (scope) {
const snapshot = readMsgInsertSwitches(scope)
/* 退群提示的开关状态来自本地设置(事件驱动,不装规则),
* 不是微信库里的 _tm_config。 */
snapshot.switches.group_exit_notice = eventModeStatus(
'group_exit_notice',
wechatLocalExitNoticeService.isEnabled(),
monitoredRoomCount()
)
return snapshot
}
return {
success: false,
switches: {
recall_notice: emptyMsgInsertStatus('recall_notice'),
group_exit_notice: eventModeStatus(
'group_exit_notice',
wechatLocalExitNoticeService.isEnabled()
)
},
helperAvailable: resolveHelperPath() !== null,
detail: '微信数据库尚未连接'
}
})
/**
* 微信消息插入开关 —— 写入。
*
* 绝不使用本进程的 WCDB 句柄写(只读池会把它钉死)。这里 spawn 一次性 helper:
* 先补齐目标会话的规则 → 再写开关值 → 读回校验 → 本进程只读复核。
* 失败不伪装成功:partial 会带 failedShards / notReadyRooms 回渲染层。
*/
ipcMain.handle('automation:setMsgInsertSwitch', async (_, input: unknown) => {
const payload = (input || {}) as { name?: unknown; enabled?: unknown }
const name = String(payload.name || '') as MsgInsertSwitchName
if (name !== 'recall_notice' && name !== 'group_exit_notice') {
return {
success: false,
status: emptyMsgInsertStatus('recall_notice'),
errorCode: 'UNSUPPORTED_SWITCH',
message: '未知的开关'
}
}
/*
* 退群提示是**事件驱动**的(GroupExitMonitorService 发事件 → 一次性插一条),
* 不装任何 per-room 规则。所以它的开关只是本地设置:
* 既不 spawn helper,也不碰微信库。
*/
if (name === 'group_exit_notice') {
const toggled = wechatLocalExitNoticeService.setEnabled(payload.enabled === true)
if (toggled.error) {
return {
success: false,
status: eventModeStatus(name, toggled.enabled, monitoredRoomCount()),
errorCode: 'UNKNOWN',
message: '保存开关状态失败'
}
}
return {
success: true,
status: eventModeStatus(name, toggled.enabled, monitoredRoomCount())
}
}
const scope = resolveMsgInsertScopeInput()
const client = chat.getChatDb()?.getWcdb4Client()
if (!scope || !client) {
return {
success: false,
status: emptyMsgInsertStatus(name),
errorCode: 'DATABASE_UNAVAILABLE',
message: '微信数据库尚未连接'
}
}
return applyMsgInsertSwitch({
...scope,
name,
enabled: payload.enabled === true,
myWxid: String(chat.getSelfAccountInfo()?.wxid || ''),
/* 密钥只在这里读一次,随后直接进 helper 的 stdin,绝不落盘 / 进 argv */
databaseKey: client.getKey()
})
})
/**
* 保存「退群通知」规则(singleton upsert)。
*
@@ -0,0 +1,729 @@
/**
* 微信消息插入开关 —— 主进程侧封装。
*
* 为什么写操作不能在本进程做
* --------------------------
* WCDB 的 CommonCore 按**路径**池化底层库对象(CoreBridge.cpp:
* `getOrCreateDatabase` + 只在 readOnly 时 `setReadOnly()`),而只读标志一旦
* 设上去就没有逆操作。TraceMemo 启动后会用只读方式打开 message 分片,于是同一
* 进程里任何「可写打开」拿到的都是那个只读对象 —— 写入必然得到
* `-3004 attempt to write a readonly database`。
*
* 所以:
* **读** → 本进程只读路径(分片目录 + 开关值),零写权限
* **写** → spawn 一次性子进程 `tm-wcdb-config-helper`,池随进程销毁
*
* 子进程的密钥只从 stdin 进,绝不进 argv / env(否则会出现在 `ps` 与进程环境里)。
*
* 状态语义(不要退回「开关值写成功 = 功能已生效」)
* ------------------------------------------------
* 真正干活的是挂在 `Msg_<md5(roomId)>` 表上的规则。一个分片完全可能
* 「有 _tm_config 却没规则」,此时开关写成 1 也毫无效果。而且一个会话可能同时
* 存在于 2~4 个分片,必须**所有命中分片都 ready** 才算这个会话 ready。
*
* 判断「是否生效」始终按目标会话算,不按分片算。
*/
import { spawn } from 'node:child_process'
import { createHash } from 'node:crypto'
import path from 'node:path'
import { findResource } from '../resource-paths'
import type { Wcdb4Client } from '../wcdb4-client'
import {
MSG_INSERT_SWITCHES,
type MsgInsertApplyResult,
type MsgInsertErrorCode,
type MsgInsertScope,
type MsgInsertSwitchName,
type MsgInsertSwitchStatus,
type MsgInsertSwitchesSnapshot
} from '../../shared/msg-insert-switch'
export {
MSG_INSERT_SWITCHES,
type MsgInsertSwitchName,
type MsgInsertSwitchStatus,
type MsgInsertSwitchesSnapshot
}
/* --------------------------------------------------------------- 常量 */
const HELPER_NAME = 'tm-wcdb-config-helper'
const HELPER_TIMEOUT_MS = 60_000
/** 分片里规则的名字(与 native 侧一致) */
const RULE_CAPTURE = '_tm_msg_insert_capture'
/* notice 规则只装在 winner 分片、且不参与就绪判据,读路径不需要它的名字。
* 退群已改事件驱动,不再有 queue 规则(常量已退役)。 */
/**
* 规则名在 native 侧按会话加了后缀。
*
* SQLite 的 trigger 名是**库级唯一**的:如果所有会话都用固定名字,给第二个会话装规则
* 会直接覆盖第一个。所以真实名字形如 `_tm_msg_insert_capture_<md5(roomId)>`。
*
* ⚠️ 读路径必须用带后缀的名字去查目录,否则会得出「库里明明有规则、界面却显示 0」这种
* 自相矛盾的结论。
*/
function ruleName(base: string, roomId: string): string {
return `${base}_${md5Hex(roomId)}`
}
const SWITCH_SCOPE: Record<MsgInsertSwitchName, MsgInsertScope> = {
// 防撤回:群聊和私聊都要覆盖,所以目标是「全部可定位会话」
recall_notice: 'all_sessions',
// 退群监控:只作用于退群监控当前选中的群
group_exit_notice: 'monitored_rooms'
}
interface HelperRunResult {
ok: boolean
exitCode: number | null
json?: Record<string, unknown>
errorCode?: MsgInsertErrorCode
message?: string
detail?: string
}
function md5Hex(value: string): string {
return createHash('md5').update(value).digest('hex')
}
function messageTableFor(roomId: string): string {
return `Msg_${md5Hex(roomId)}`
}
export const SWITCH_MODE: Record<MsgInsertSwitchName, 'rules' | 'event'> = {
// 防撤回靠装规则
recall_notice: 'rules',
// 退群提示靠事件驱动的一次性插入,不装规则
group_exit_notice: 'event'
}
/**
* 事件驱动型开关的状态。
*
* 它没有 room / shard 维度(不装规则),所以 room 计数一律为 0 —— UI 据此不显示
* 「N / M 已启用」。desired 与 effective 同值:这条路径没有「值写了对但规则没装」
* 的中间态,插入失败会记在 service 的 recent 里,不影响开关本身。
*/
export function eventModeStatus(
name: MsgInsertSwitchName,
enabled: boolean,
monitoredRoomCount = 0
): MsgInsertSwitchStatus {
const status = emptyMsgInsertStatus(name)
status.mode = 'event'
status.desiredEnabled = enabled
status.effectiveEnabled = enabled
status.operationOk = true
/* 事件驱动型没有「预装规则覆盖率」。这里给的只是**监控范围**,
* 用来告诉用户「开了之后哪些群的退群会被插提示」,不是覆盖率。 */
status.monitoredRoomCount = monitoredRoomCount
return status
}
export function emptyMsgInsertStatus(
name: MsgInsertSwitchName,
errorCode?: MsgInsertErrorCode,
message?: string
): MsgInsertSwitchStatus {
return {
switch: name,
scope: SWITCH_SCOPE[name],
mode: SWITCH_MODE[name],
desiredEnabled: false,
effectiveEnabled: false,
operationOk: false,
totalInstallableRooms: 0,
readyInstallableRooms: 0,
roomsWithoutTable: 0,
totalShards: 0,
targetShards: 0,
configuredShards: 0,
readyShards: 0,
notReadyShards: 0,
failedShards: 0,
errorCode,
message
}
}
/* ------------------------------------------------------- helper 定位与调用 */
/**
* helper 与 libwcdb_api.dylib 同目录部署(依赖 @loader_path 解析 dylib)。
* 开发态与打包态都靠 findResource 解析,不依赖当前工作目录。
*/
export function resolveHelperPath(): string | null {
/*
* 平台/架构都要分。Windows 交付在 `resources/wcdb/win32/x64/`(注意是 win32 不是 windows),
* 文件名带 `.exe`。以前这里三个候选全写死 macos —— Windows 上会恒返回 null,
* 表现为「缺少写入组件」+ 开关永久置灰。
*
* 同目录还有 wcdb_api.dll / WCDB.dll / SDL2.dll,MSVC 运行库在 resources/runtime/win32/,
* 两者都由 preload-env.ts 加进 DLL 搜索路径,所以 helper.exe 能直接加载。
*/
const archDir = process.arch === 'x64' ? 'x64' : 'arm64'
const otherArchDir = archDir === 'arm64' ? 'x64' : 'arm64'
const platformDir = process.platform === 'win32' ? 'win32' : 'macos'
const suffix = process.platform === 'win32' ? '.exe' : ''
const candidates = [
`wcdb/${platformDir}/${archDir}/${HELPER_NAME}${suffix}`,
`wcdb/${platformDir}/${otherArchDir}/${HELPER_NAME}${suffix}`,
`wcdb/${platformDir}/${HELPER_NAME}${suffix}`
]
for (const candidate of candidates) {
const resolved = findResource(candidate)
if (resolved) return resolved
}
return null
}
/** 从分片路径反推账号根目录(helper 需要它来枚举分片) */
function accountRootFromShard(shardPath: string): string {
// <root>/db_storage/message/message_N.db
return path.dirname(path.dirname(path.dirname(shardPath)))
}
/**
* 跑一次 helper。**密钥只走 stdin**。
*
* 请求体是一行 JSON:{"key":"<hex>","rooms":[...],"myWxid":"..."}
* 用 JSON 而不是 argv,是因为目标会话可能有上千个,argv 会被撑爆;
* 顺带保证密钥永远不进进程参数表。
*/
function runHelper(
helperPath: string,
args: string[],
request: { key: string; rooms: string[]; myWxid: string },
timeoutMs = HELPER_TIMEOUT_MS
): Promise<HelperRunResult> {
return new Promise((resolve) => {
let child: ReturnType<typeof spawn>
try {
child = spawn(helperPath, args, { stdio: ['pipe', 'pipe', 'pipe'] })
} catch (error) {
resolve({
ok: false,
exitCode: null,
errorCode: 'HELPER_START_FAILED',
message: 'helper 启动失败',
detail: error instanceof Error ? error.message : String(error)
})
return
}
let stdout = ''
let stderr = ''
let settled = false
const finish = (result: HelperRunResult): void => {
if (settled) return
settled = true
clearTimeout(timer)
resolve(result)
}
const timer = setTimeout(() => {
try {
child.kill('SIGKILL')
} catch {
/* 已经退出了 */
}
finish({
ok: false,
exitCode: null,
errorCode: 'HELPER_TIMEOUT',
message: '写入超时,已中止',
detail: `timeout=${timeoutMs}ms stderr=${stderr.slice(-400)}`
})
}, timeoutMs)
child.stdout?.on('data', (chunk: Buffer) => {
stdout += chunk.toString()
})
child.stderr?.on('data', (chunk: Buffer) => {
stderr = `${stderr}${chunk.toString()}`.slice(-4000)
})
child.on('error', (error) => {
finish({
ok: false,
exitCode: null,
errorCode: 'HELPER_START_FAILED',
message: 'helper 启动失败',
detail: error.message
})
})
child.on('close', (code) => {
const lines = stdout.trim().split('\n').filter(Boolean)
let json: Record<string, unknown> | undefined
try {
json = JSON.parse(lines[lines.length - 1] || '') as Record<string, unknown>
} catch {
finish({
ok: false,
exitCode: code,
errorCode: 'HELPER_BAD_OUTPUT',
message: 'helper 返回了无法解析的结果',
detail: `exit=${code} stdout=${stdout.slice(-400)} stderr=${stderr.slice(-400)}`
})
return
}
const success = json.success === true
finish({
ok: code === 0 || (code === 1 && json.success === false),
exitCode: code,
json,
errorCode: success ? undefined : inferErrorCode(json),
message: success ? undefined : describeFailure(json),
detail: `exit=${code} ${stderr.slice(-400)}`.trim()
})
})
/* 密钥与请求一起写进 stdin,然后立刻关闭 —— 不进 argv、不进 env、不落盘。 */
try {
child.stdin?.write(`${JSON.stringify(request)}\n`)
child.stdin?.end()
} catch (error) {
finish({
ok: false,
exitCode: null,
errorCode: 'HELPER_START_FAILED',
message: '无法把密钥交给 helper',
detail: error instanceof Error ? error.message : String(error)
})
}
})
}
function inferErrorCode(json: Record<string, unknown>): MsgInsertErrorCode {
const code = String(json.code || '')
if (code === 'HELPER_BAD_ARGS') return 'HELPER_BAD_OUTPUT'
if (code === 'UNSUPPORTED_SWITCH') return 'UNSUPPORTED_SWITCH'
if (code === 'HELPER_NO_SHARDS') return 'DATABASE_UNAVAILABLE'
if (code === 'RULE_MISSING') return 'RULE_MISSING'
const failed = Number(json.failedShards || 0)
if (failed > 0) return 'SHARD_WRITE_FAILED'
/* roomsWithoutTable 是中性 pending,不是失败 —— 只有当**一个可安装会话都没有**
* 的时候才算没有目标。 */
if (
Number(json.totalTargetRooms || 0) > 0 &&
Number(json.totalTargetRooms || 0) === Number(json.roomsWithoutTable || 0)
) {
return 'NO_TARGET_ROOMS'
}
return 'UNKNOWN'
}
function describeFailure(json: Record<string, unknown>): string {
const failed = Number(json.failedShards || 0)
if (failed > 0) return `${failed} 个消息库写入失败`
const without = Number(json.roomsWithoutTable || 0)
if (Number(json.totalTargetRooms || 0) > 0 && Number(json.totalTargetRooms) === without) {
return `${without} 个目标会话在微信库里都还没有消息表`
}
const code = String(json.code || '')
const detail = String(json.error || '')
return code ? `${code}${detail ? `:${detail}` : ''}` : '操作未完成'
}
/* ----------------------------------------------------------- 目标会话解析 */
export interface MsgInsertScopeInput {
client: Wcdb4Client
/** 退群监控当前选中的群(来自 group-exit-monitor 服务,不在这里另维护一份) */
monitoredRoomIds: string[]
}
/**
* 解析某个开关的目标会话集合。
*
* - group_exit_notice → 退群监控选中的群(复用现有配置,不重新维护第二份群列表)
* - recall_notice → 全部可定位会话(群聊 + 私聊)
*/
export function resolveTargetRooms(
input: MsgInsertScopeInput,
name: MsgInsertSwitchName
): { scope: MsgInsertScope; rooms: string[]; error?: string } {
const scope = SWITCH_SCOPE[name]
if (scope === 'monitored_rooms') {
const rooms = Array.from(new Set(input.monitoredRoomIds.filter(Boolean)))
return { scope, rooms }
}
try {
const rooms = Array.from(
new Set(
input.client
.getSessions()
.map((session) => String(session.username || '').trim())
.filter(Boolean)
)
)
return { scope, rooms }
} catch (error) {
return {
scope,
rooms: [],
error: error instanceof Error ? error.message : String(error)
}
}
}
/* --------------------------------------------------------------- 只读状态 */
interface CatalogShard {
shard: string
dbPath: string
configTable: boolean
tables: Set<string>
ruleTables: Map<string, string>
}
function readCatalog(client: Wcdb4Client): {
shards: CatalogShard[]
rawCount: number
error?: string
} {
const result = client.listMsgInsertShardCatalog()
if (!result.success || !result.catalog) {
return { shards: [], rawCount: 0, error: result.error || '分片目录读取失败' }
}
const shards = result.catalog.shards.map<CatalogShard>((entry) => ({
shard: entry.shard,
dbPath: entry.dbPath,
configTable: entry.configTable,
tables: new Set(entry.tables || []),
ruleTables: new Map((entry.rules || []).map((rule) => [rule.name, rule.table]))
}))
return { shards, rawCount: shards.length }
}
function roomReadiness(
shards: CatalogShard[],
roomId: string,
name: MsgInsertSwitchName
): { matched: string[]; ready: boolean; notReady: string[] } {
const table = messageTableFor(roomId)
const matched: string[] = []
const notReady: string[] = []
const captureName = ruleName(RULE_CAPTURE, roomId)
/* notice 规则只装在 winner 分片,就绪判据不看它(见下),所以这里不需要它的名字。 */
for (const shard of shards) {
if (!shard.tables.has(table)) continue
matched.push(shard.shard)
/* 同时接受历史遗留的无后缀规则(只要它挂在同一张表上)—— 与 native 侧判据一致,
* 否则用旧脚本装过的那一个会话会被误判成未就绪。 */
const attachedTo = (...names: string[]): boolean =>
names.some((candidate) => shard.ruleTables.get(candidate) === table)
const capture = attachedTo(captureName, RULE_CAPTURE)
/*
* ⚠️ 只要求 capture。
*
* notice 规则**只装在 winner 分片**上(分片之间是独立数据库文件、没有共享状态,
* 每个分片各生成一条会重复插提示)。所以这里不能再要求每个分片都有 notice ——
* 否则所有跨分片会话都会显示成「未就绪」。
* 这条必须与 native 侧 `msgInsertEvaluateRoomShard` 的 `recallReady = capture` 一致。
*/
const ready = name === 'recall_notice' ? capture : true
if (!ready) notReady.push(shard.shard)
}
return { matched, ready: matched.length > 0 && notReady.length === 0, notReady }
}
/**
* 本进程只读地聚合两个开关的状态。
*
* 只用「分片目录 + 开关值」:目录一次拿全,之后在本地用 md5(roomId) 匹配,
* 所以哪怕目标会话很多也不会有额外的查库开销。
*/
export function readMsgInsertSwitches(input: MsgInsertScopeInput): MsgInsertSwitchesSnapshot {
const catalog = readCatalog(input.client)
const shardCount = catalog.rawCount
const switches = {} as Record<MsgInsertSwitchName, MsgInsertSwitchStatus>
if (catalog.error || shardCount === 0) {
for (const name of MSG_INSERT_SWITCHES) {
switches[name] = emptyMsgInsertStatus(
name,
'DATABASE_UNAVAILABLE',
catalog.error || '找不到消息分片(数据库可能尚未连接)'
)
}
return { success: false, switches, helperAvailable: resolveHelperPath() !== null }
}
/* 每个分片读一次开关值,后面既用来算 desired,也用来算分片级 ready */
const valuesByShard = new Map<string, Record<string, boolean>>()
for (const shard of catalog.shards) {
const read = input.client.getMsgInsertSwitches(shard.dbPath)
valuesByShard.set(
shard.shard,
read.success && read.switches
? read.switches
: { recall_notice: false, group_exit_notice: false }
)
}
for (const name of MSG_INSERT_SWITCHES) {
const resolved = resolveTargetRooms(input, name)
const status = emptyMsgInsertStatus(
name,
resolved.error ? 'DATABASE_UNAVAILABLE' : undefined,
resolved.error
)
status.scope = resolved.scope
status.totalShards = shardCount
const targetShardNames = new Set<string>()
const notReadyRooms: MsgInsertSwitchStatus['notReadyRooms'] = []
let readyRooms = 0
let roomsWithoutTable = 0
for (const room of resolved.rooms) {
const readiness = roomReadiness(catalog.shards, room, name)
if (readiness.matched.length === 0) {
/* 公众号 / 服务号 / 系统会话没有 Msg_ 表,装不了规则 —— **中性 pending**,
* 既不算失败,也不进 notReadyRooms,更不能拖累 effectiveEnabled。 */
roomsWithoutTable += 1
continue
}
for (const shard of readiness.matched) targetShardNames.add(shard)
if (readiness.ready) {
readyRooms += 1
} else {
notReadyRooms.push({
roomId: room,
reason: 'rules-missing',
matchedShards: readiness.matched,
notReadyShards: readiness.notReady
})
}
}
status.targetShards = targetShardNames.size
/* 分母是「有消息表、可安装」的会话数,不是全部会话数。
* 否则总会有一部分会话装不了规则,界面会一直显示「部分成功」。 */
status.totalInstallableRooms = readyRooms + notReadyRooms.length
status.readyInstallableRooms = readyRooms
status.roomsWithoutTable = roomsWithoutTable
let configured = 0
let readyShards = 0
let notReadyShards = 0
for (const shard of catalog.shards) {
const values = valuesByShard.get(shard.shard)
const on = Boolean(values?.[name])
if (on) configured += 1
if (!targetShardNames.has(shard.shard)) continue
const recallOk = roomShardsReady(catalog.shards, shard.shard, resolved.rooms, name)
if (on && recallOk) readyShards += 1
else if (on) notReadyShards += 1
}
status.configuredShards = configured
status.readyShards = readyShards
status.notReadyShards = notReadyShards
status.failedShards = 0
status.desiredEnabled = configured > 0
status.operationOk = true
/* 生效判定只看可安装会话:roomsWithoutTable 不能阻止 effectiveEnabled。 */
status.effectiveEnabled =
status.desiredEnabled &&
status.totalInstallableRooms > 0 &&
readyRooms === status.totalInstallableRooms
status.notReadyRooms = notReadyRooms.slice(0, 20)
if (resolved.rooms.length === 0) {
status.message = '没有可作用的目标会话'
}
switches[name] = status
}
return { success: true, switches, helperAvailable: resolveHelperPath() !== null }
}
/** 某分片上「所有目标会话」的规则是否都齐 */
function roomShardsReady(
shards: CatalogShard[],
shardName: string,
rooms: string[],
name: MsgInsertSwitchName
): boolean {
const shard = shards.find((entry) => entry.shard === shardName)
if (!shard) return false
let any = false
for (const room of rooms) {
const table = messageTableFor(room)
if (!shard.tables.has(table)) continue
any = true
const attachedTo = (...names: string[]): boolean =>
names.some((candidate) => shard.ruleTables.get(candidate) === table)
const capture = attachedTo(ruleName(RULE_CAPTURE, room), RULE_CAPTURE)
/* 与 roomReadiness、以及 native 侧 `msgInsertEvaluateRoomShard` 用同一判据:
* notice 只装在 winner 分片,就绪只看 capture。 */
const ready = name === 'recall_notice' ? capture : true
if (!ready) return false
}
return any
}
/* --------------------------------------------------------------- 写入动作 */
export interface MsgInsertApplyInput extends MsgInsertScopeInput {
name: MsgInsertSwitchName
enabled: boolean
myWxid: string
databaseKey: string
}
/**
* 打开 / 关闭一个开关。
*
* 顺序是**先规则、后开关**:开的时候必须先把目标会话的规则补齐并确认 ready,
* 才写开关值;关的时候只写值(规则体自己读 _tm_config,值为 0 时一行都不执行,
* 所以关闭不需要昂贵 DDL,下次打开直接恢复)。
*/
export async function applyMsgInsertSwitch(
input: MsgInsertApplyInput
): Promise<MsgInsertApplyResult> {
/*
* 防御:事件驱动型开关(退群提示)**不允许**走规则路径。
*
* 它没有 per-room 规则,走 apply 只会把 `_tm_config.group_exit_notice` 写成 1 ——
* 一个写了也没人读的脏值,界面还会显示成关闭。
*/
if (SWITCH_MODE[input.name] !== 'rules') {
return {
success: false,
status: eventModeStatus(input.name, false),
errorCode: 'UNSUPPORTED_SWITCH',
message: '这个开关不走规则路径'
}
}
const resolved = resolveTargetRooms(input, input.name)
if (resolved.rooms.length === 0) {
return {
success: false,
status: emptyMsgInsertStatus(input.name, 'NO_TARGET_ROOMS', '没有可作用的目标会话'),
errorCode: 'NO_TARGET_ROOMS',
message: '没有可作用的目标会话'
}
}
if (!input.databaseKey) {
return {
success: false,
status: emptyMsgInsertStatus(input.name, 'DATABASE_UNAVAILABLE', '数据库密钥不可用'),
errorCode: 'DATABASE_UNAVAILABLE',
message: '数据库密钥不可用,请先连接微信数据库'
}
}
const helperPath = resolveHelperPath()
if (!helperPath) {
return {
success: false,
status: emptyMsgInsertStatus(input.name, 'HELPER_NOT_FOUND', '暂无法使用'),
errorCode: 'HELPER_NOT_FOUND',
/* 面向用户是能力语义;errorCode 仍是 HELPER_NOT_FOUND,门禁/授权层照旧能判。 */
message: '暂无法使用:当前安装不包含微信内消息写入组件'
}
}
const shards = input.client.listMessageShardPaths()
const accountRoot = shards.length > 0 ? accountRootFromShard(shards[0]) : ''
if (!accountRoot) {
return {
success: false,
status: emptyMsgInsertStatus(input.name, 'DATABASE_UNAVAILABLE', '找不到账号目录'),
errorCode: 'DATABASE_UNAVAILABLE',
message: '找不到微信账号目录'
}
}
const run = await runHelper(
helperPath,
[
'--account-root',
accountRoot,
'--action',
'apply',
'--switch',
input.name === 'recall_notice' ? 'recall' : 'group_exit',
'--value',
input.enabled ? '1' : '0'
],
{ key: input.databaseKey, rooms: resolved.rooms, myWxid: input.myWxid }
)
/* 无论 helper 成功与否,都用本进程只读路径复核一遍,不拿 helper 的自述当结论 */
const snapshot = readMsgInsertSwitches(input)
const status = snapshot.switches[input.name]
if (!run.json) {
return {
success: false,
status,
errorCode: run.errorCode || 'UNKNOWN',
message: run.message || '操作失败',
detail: run.detail
}
}
const success = run.json.success === true
/* 用 helper 的权威计数覆盖本地只读快照里的 room 分母,避免两边口径漂移。 */
status.totalInstallableRooms = Number(
run.json.installableTargetRooms ?? status.totalInstallableRooms
)
status.readyInstallableRooms = Number(run.json.readyTargetRooms ?? status.readyInstallableRooms)
status.roomsWithoutTable = Number(run.json.roomsWithoutTable ?? status.roomsWithoutTable)
return {
success,
status,
errorCode: success ? undefined : run.errorCode || 'PARTIAL_SUCCESS',
message: success ? undefined : run.message,
detail: run.detail
}
}
/**
* 轻量 reconciliation:把目标会话缺失的规则补齐,**不动开关值**。
*
* 触发时机:启动连库后 / 退群监控群列表变化后 / 用户打开开关时。
* 微信新建 message_4.db 并把某个目标群的新表放进去时,下一次触发就会自动补上。
*/
export async function reconcileMsgInsertRules(
input: MsgInsertScopeInput & { myWxid: string; databaseKey: string }
): Promise<{ done: boolean; rooms: number; written: number; errorCode?: MsgInsertErrorCode }> {
const helperPath = resolveHelperPath()
if (!helperPath || !input.databaseKey) {
return {
done: false,
rooms: 0,
written: 0,
errorCode: helperPath ? 'DATABASE_UNAVAILABLE' : 'HELPER_NOT_FOUND'
}
}
const shards = input.client.listMessageShardPaths()
if (shards.length === 0) {
return { done: false, rooms: 0, written: 0, errorCode: 'DATABASE_UNAVAILABLE' }
}
/* 只补退群监控选中的群 —— 防撤回的作用面由「打开开关」那一刻决定,
* 启动时不做全量扫描,避免每次启动都摸一遍全部会话。 */
const rooms = Array.from(new Set(input.monitoredRoomIds.filter(Boolean)))
if (rooms.length === 0) return { done: true, rooms: 0, written: 0 }
const run = await runHelper(
helperPath,
['--account-root', accountRootFromShard(shards[0]), '--action', 'ensure-rules'],
{ key: input.databaseKey, rooms, myWxid: input.myWxid }
)
if (!run.json) {
return { done: false, rooms: rooms.length, written: 0, errorCode: run.errorCode || 'UNKNOWN' }
}
return {
done: run.json.success === true,
rooms: rooms.length,
written: Number(run.json.rulesWritten || 0),
errorCode: run.json.success === true ? undefined : 'RULE_MISSING'
}
}
@@ -0,0 +1,322 @@
/**
* 微信内退群监控消息 —— 事件驱动的一次性插入。
*
* 为什么不再用 persistent trigger
* ------------------------------
* 退群提示以前是给每个监控群装一条 `_tm_msg_insert_queue` 规则,靠微信自己插消息时
* 触发。问题:粒度是「群 × 分片」,监控群一多就要铺成百上千条规则;而退群这个事实
* TraceMemo 本来就已经知道了(GroupExitMonitorService 是**唯一**退群事实源)。
* 让数据库再算一遍,等于维护两套退群判断,迟早不一致。
*
* 现在改成:
* GroupExitMonitorService → GroupMemberExitedEvent → 本服务 → one-shot helper 插一条
*
* 三条硬约束(都不能违反)
* ------------------------
* 1. **不产生第二套退群事实**:本服务只消费事件、只插消息,从不自己判断谁退群。
* 2. **失败不回滚、不阻塞**:插入失败绝不能让退群事件回滚、不能影响监控循环、
* 不能影响自动化通知。所以 handleExitEvent **永不抛异常**,调用方也不必 await。
* 3. **幂等**:以 eventId 为幂等键,同一事件最多插一次。幂等日志写在微信库里
* (不是内存),所以跨进程、跨重启都有效。
*
* 只插一个目标消息存储:写入分片由 native 侧按 MAX(sort_seq) 选出,不在历史分片
* 重复插入。没有可插入的消息表时返回 NO_MESSAGE_STORE,TraceMemo 内部的退群记录
* 照常保留。
*/
import { spawn } from 'node:child_process'
import fs from 'node:fs'
import path from 'node:path'
import { app } from 'electron'
import type { GroupMemberExitedEvent } from '../../shared/group-exit-event'
import { renderLeaveNotificationText } from '../../shared/group-exit-event'
import { GROUP_EXIT_NOTIFICATION_TEMPLATE } from '../../shared/group-exit-monitor'
import { findResource } from '../resource-paths'
export type LocalExitNoticeOutcome =
| 'inserted'
| 'duplicate'
| 'disabled'
| 'no_message_store'
| 'failed'
| 'helper_unavailable'
export interface LocalExitNoticeResult {
outcome: LocalExitNoticeOutcome
eventId: string
conversationId: string
shard?: string
localId?: number
/** 机器可读的原因,只进日志 */
code?: string
}
interface StoredState {
enabled?: boolean
}
const HELPER_NAME = 'tm-wcdb-config-helper'
const HELPER_TIMEOUT_MS = 20_000
/** 最近若干次插入结果,只用于诊断展示,不参与判定 */
const RECENT_LIMIT = 50
function helperPath(): string | null {
/* 与 msg-insert-switch-service 的 resolveHelperPath 保持一致:
* Windows 走 wcdb/win32/<arch>/ 且文件名带 .exe。 */
const arch = process.arch === 'x64' ? 'x64' : 'arm64'
const other = arch === 'arm64' ? 'x64' : 'arm64'
const platformDir = process.platform === 'win32' ? 'win32' : 'macos'
const suffix = process.platform === 'win32' ? '.exe' : ''
for (const candidate of [
`wcdb/${platformDir}/${arch}/${HELPER_NAME}${suffix}`,
`wcdb/${platformDir}/${other}/${HELPER_NAME}${suffix}`,
`wcdb/${platformDir}/${HELPER_NAME}${suffix}`
]) {
const resolved = findResource(candidate)
if (resolved) return resolved
}
return null
}
/**
* 退群本地提示服务。
*
* 与 GroupExitMonitorService 是**消费**关系:它发事件,这里负责往微信里插一条。
* 这里不持有任何群列表,也不判断退群 —— 避免第二套事实源。
*/
export class WechatLocalExitNoticeService {
private enabled = false
private loaded = false
private recent: LocalExitNoticeResult[] = []
private statePath(): string {
return path.join(app.getPath('userData'), 'wechat-local-exit-notice.json')
}
private ensureLoaded(): void {
if (this.loaded) return
this.loaded = true
try {
const raw = fs.readFileSync(this.statePath(), 'utf8')
const stored = JSON.parse(raw) as StoredState
this.enabled = stored.enabled === true
} catch {
this.enabled = false
}
}
isEnabled(): boolean {
this.ensureLoaded()
return this.enabled
}
setEnabled(enabled: boolean): { enabled: boolean; error?: string } {
this.ensureLoaded()
this.enabled = enabled === true
try {
fs.mkdirSync(path.dirname(this.statePath()), { recursive: true })
fs.writeFileSync(this.statePath(), JSON.stringify({ enabled: this.enabled }, null, 2), 'utf8')
return { enabled: this.enabled }
} catch (error) {
return {
enabled: this.enabled,
error: error instanceof Error ? error.message : String(error)
}
}
}
getRecent(): LocalExitNoticeResult[] {
return [...this.recent]
}
private remember(result: LocalExitNoticeResult): void {
this.recent = [result, ...this.recent].slice(0, RECENT_LIMIT)
}
/**
* 处理一次退群事件。
*
* ⚠️ 本方法**永不抛异常**:它挂在退群监控的事件回调上,抛出去会污染监控循环。
* 返回值只用于日志与诊断,调用方不需要(也不应该)等它。
*/
async handleExitEvent(event: GroupMemberExitedEvent): Promise<LocalExitNoticeResult> {
const base: LocalExitNoticeResult = {
outcome: 'failed',
eventId: event.eventId,
conversationId: event.conversationId
}
try {
this.ensureLoaded()
if (!this.enabled) return this.finish({ ...base, outcome: 'disabled', code: 'DISABLED' })
if (!event.eventId || !event.conversationId) {
return this.finish({ ...base, outcome: 'failed', code: 'EVENT_INCOMPLETE' })
}
const resolved = helperPath()
if (!resolved) {
return this.finish({ ...base, outcome: 'helper_unavailable', code: 'HELPER_NOT_FOUND' })
}
const key = resolveDatabaseKey()
const myWxid = resolveMyWxid()
if (!key || !myWxid) {
return this.finish({ ...base, outcome: 'failed', code: 'DATABASE_UNAVAILABLE' })
}
const accountRoot = resolveAccountRoot()
if (!accountRoot) {
return this.finish({ ...base, outcome: 'failed', code: 'ACCOUNT_ROOT_UNRESOLVED' })
}
const text = renderLeaveNotificationText(event, GROUP_EXIT_NOTIFICATION_TEMPLATE)
const payload = JSON.stringify({
key,
myWxid,
roomId: event.conversationId,
text,
dedupeKey: event.eventId
})
const parsed = await runInsertHelper(resolved, accountRoot, payload)
if (!parsed) {
return this.finish({ ...base, outcome: 'failed', code: 'HELPER_BAD_OUTPUT' })
}
const code = String(parsed.code || '')
const shard = typeof parsed.shard === 'string' && parsed.shard ? parsed.shard : undefined
const localId = Number(parsed.localId) || undefined
if (parsed.ok === true) {
return this.finish({
...base,
outcome: code === 'ALREADY_INSERTED' ? 'duplicate' : 'inserted',
shard,
localId,
code
})
}
if (code === 'NO_MESSAGE_STORE') {
return this.finish({ ...base, outcome: 'no_message_store', code })
}
return this.finish({ ...base, outcome: 'failed', shard, localId, code })
} catch (error) {
/* 兜底:任何意外都不许冒到监控循环里去。 */
return this.finish({
...base,
outcome: 'failed',
code: error instanceof Error ? error.message : String(error)
})
}
}
private finish(result: LocalExitNoticeResult): LocalExitNoticeResult {
this.remember(result)
if (result.outcome === 'failed' || result.outcome === 'helper_unavailable') {
console.warn(
`[LocalExitNotice] 插入未成功 outcome=${result.outcome} code=${result.code || 'UNKNOWN'}`
)
}
return result
}
}
export const wechatLocalExitNoticeService = new WechatLocalExitNoticeService()
/* --------------------------------------------------------------- 依赖注入 */
interface LocalExitRuntime {
resolveDatabaseKey: () => string
resolveMyWxid: () => string
resolveAccountRoot: () => string
}
let runtime: LocalExitRuntime | null = null
/** 由主进程在启动时注入;这样服务本身不依赖 chat-service 的具体形态。 */
export function configureWechatLocalExitNotice(next: LocalExitRuntime): void {
runtime = next
}
function resolveDatabaseKey(): string {
try {
return runtime?.resolveDatabaseKey() || ''
} catch {
return ''
}
}
function resolveMyWxid(): string {
try {
return runtime?.resolveMyWxid() || ''
} catch {
return ''
}
}
function resolveAccountRoot(): string {
try {
return runtime?.resolveAccountRoot() || ''
} catch {
return ''
}
}
/* ------------------------------------------------------------------ 执行 */
function runInsertHelper(
executable: string,
accountRoot: string,
payload: string
): Promise<Record<string, unknown> | null> {
return new Promise((resolve) => {
let child: ReturnType<typeof spawn>
try {
child = spawn(executable, ['--account-root', accountRoot, '--action', 'insert-notice'], {
stdio: ['pipe', 'pipe', 'pipe']
})
} catch {
resolve(null)
return
}
let stdout = ''
let settled = false
const finish = (value: Record<string, unknown> | null): void => {
if (settled) return
settled = true
clearTimeout(timer)
resolve(value)
}
const timer = setTimeout(() => {
try {
child.kill('SIGKILL')
} catch {
/* 已退出 */
}
finish(null)
}, HELPER_TIMEOUT_MS)
child.stdout?.on('data', (chunk: Buffer) => {
stdout += chunk.toString()
})
child.stderr?.on('data', () => {
/* 人类日志直接丢弃:里面不该有密钥,也没必要留 */
})
child.on('error', () => finish(null))
child.on('close', () => {
try {
const lines = stdout.trim().split('\n').filter(Boolean)
finish(JSON.parse(lines[lines.length - 1] || '') as Record<string, unknown>)
} catch {
finish(null)
}
})
try {
child.stdin?.write(`${payload}\n`)
child.stdin?.end()
} catch {
finish(null)
}
})
}
+141
View File
@@ -526,6 +526,16 @@ export class Wcdb4Client {
private wcdbGetGroupMembersBatch:
| ((handle: number, chatroomIdsJson: string, outJson: WcdbVoidOut) => number)
| null = null
// 微信消息插入开关(native extension,不属于最初 27 个绑定)
private wcdbMsgInsertSetSwitch:
| ((handle: number, dbPath: string, name: string, enabled: number) => number)
| null = null
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
@@ -1804,6 +1814,113 @@ export class Wcdb4Client {
return result
}
/**
* 列出账号目录下所有消息分片路径(message_<n>.db)。
*
* 供「微信消息插入开关」这类**按分片存放**的状态遍历使用。
* 只认 message_<数字>.db,不包含 biz_message_* / media_*。
*/
listMessageShardPaths(): string[] {
const messageRoot = path.join(this.dbStoragePath, 'message')
if (!fs.existsSync(messageRoot)) return []
return fs
.readdirSync(messageRoot)
.filter((name) => /^message_\d+\.db$/.test(name))
.sort()
.map((name) => path.join(messageRoot, name))
}
/**
* 读取某个消息分片上的「微信消息插入开关」。
*
* 开关按消息分片存放(native 侧的 _tm_config 表),所以调用方要先把分片路径定下来。
* 返回形如 { recall_notice: boolean, group_exit_notice: boolean }。
*/
getMsgInsertSwitches(dbPath: string): {
success: boolean
switches?: Record<string, boolean>
error?: string
} {
if (!this.wcdbMsgInsertGetSwitches) {
return { success: false, error: '当前 WCDB 服务不支持微信消息插入开关' }
}
try {
const switches = this.callJson<Record<string, boolean>>((handle, outJson) =>
this.wcdbMsgInsertGetSwitches!(handle, dbPath, outJson)
)
return { success: true, switches }
} catch (error) {
return { success: false, error: error instanceof Error ? error.message : String(error) }
}
}
/**
* 设置某个消息分片上的「微信消息插入开关」。
*
* name 只接受 recall_notice / group_exit_notice(native 侧白名单)。
* 写入走 native 单独维护的可写连接,只读查询链路不受影响。
*/
setMsgInsertSwitch(
dbPath: string,
name: string,
enabled: boolean
): { success: boolean; error?: string } {
if (!this.wcdbMsgInsertSetSwitch) {
return { success: false, error: '当前 WCDB 服务不支持微信消息插入开关' }
}
try {
const handle = this.ensureHandle()
const rc = this.wcdbMsgInsertSetSwitch(handle, dbPath, name, enabled ? 1 : 0)
if (rc !== 0) return { success: false, error: `返回码 ${rc}` }
return { success: true }
} catch (error) {
return { success: false, error: error instanceof Error ? error.message : String(error) }
}
}
/**
* 读取「微信消息插入规则」的分片目录(只读)。
*
* 每个分片只跑两条查询(表清单 + 规则清单),拿回来之后调用方可以在本地用
* md5(roomId) 匹配出「每个会话落在哪些分片、规则齐不齐」。这样即使会话很多,
* 判断全部会话的状态也只是一次目录读取,不需要按会话逐个查库。
*/
listMsgInsertShardCatalog(): {
success: boolean
catalog?: {
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 }>
}>
}
error?: string
} {
if (!this.wcdbMsgInsertListShardCatalog) {
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 }
} catch (error) {
return { success: false, error: error instanceof Error ? error.message : String(error) }
}
}
installRecallJournal(usernames: string[]): { installed: number; failed: number } {
const stores = new Map<string, Wcdb4MessageStore>()
for (const username of this.uniq(usernames)) {
@@ -3011,6 +3128,30 @@ export class Wcdb4Client {
this.wcdbGetGroupMembersBatch = null
}
try {
this.wcdbMsgInsertSetSwitch = lib.func(
'int32 wcdb_msg_insert_set_switch(int64 handle, const char* dbPath, const char* name, int32 enabled)'
) as (handle: number, dbPath: string, name: string, enabled: number) => number
} catch {
this.wcdbMsgInsertSetSwitch = null
}
try {
this.wcdbMsgInsertGetSwitches = lib.func(
'int32 wcdb_msg_insert_get_switches(int64 handle, const char* dbPath, _Out_ void** outJson)'
) as (handle: number, dbPath: string, outJson: WcdbVoidOut) => number
} catch {
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)'