mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-12-01 01:05:30 +08:00
feat: 只读验收模式、文件发送类型与消息定位补全
- 只读验收:TRACEMEMO_READ_ONLY=1 时跳过消息写入、自动发送与退群提示 - 微信发送新增 file 类型,文档、能力探测与 Reader Skill 同步 - 消息前后窗口按分片定位,补齐 wcdb4 定位与分片测试
This commit is contained in:
1 parent
0edbf60b2e
commit
518a9662a7
25 files changed
+1278
-154
No files matched your search
@@ -16,6 +16,7 @@ import { buildEventId } from '../extensions/extension-event-bus'
|
||||
import type { PersonalWechatSendCapability } from '../../shared/personal-wechat'
|
||||
import type { Wcdb4Client } from '../wcdb4-client'
|
||||
import type { NormalizedIncomingMessage } from './message-listener-service'
|
||||
import { isReadOnlyMode, logReadOnlySkip } from './read-only-mode'
|
||||
import { getSelfAccountInfo, listContacts } from './chat-service'
|
||||
import { getPersonalWechatSendCapability } from './personal-wechat-capability-service'
|
||||
import {
|
||||
@@ -213,6 +214,10 @@ export class AutomationService {
|
||||
* 抛出去会影响后续监听者。
|
||||
*/
|
||||
async handleMessage(message: NormalizedIncomingMessage): Promise<void> {
|
||||
if (isReadOnlyMode()) {
|
||||
logReadOnlySkip('自动化消息处理')
|
||||
return
|
||||
}
|
||||
let rules: AutomationRule[]
|
||||
try {
|
||||
rules = this.ruleStore.listRules()
|
||||
@@ -340,6 +345,10 @@ export class AutomationService {
|
||||
* 该事件的幂等位(用户随后真的补勾了那个群,反而发不出去)。
|
||||
*/
|
||||
async handleGroupExit(event: GroupMemberExitedEvent): Promise<void> {
|
||||
if (isReadOnlyMode()) {
|
||||
logReadOnlySkip('退群自动化通知')
|
||||
return
|
||||
}
|
||||
const eventId = String(event?.eventId || '').trim()
|
||||
let rule: AutomationRule | undefined
|
||||
try {
|
||||
@@ -474,6 +483,10 @@ export class AutomationService {
|
||||
ruleId: string,
|
||||
options: { trigger: 'schedule' | 'manual'; scheduledSlot?: string }
|
||||
): Promise<ScheduledRuleRunOutcome> {
|
||||
if (isReadOnlyMode()) {
|
||||
logReadOnlySkip('定时日报执行')
|
||||
return { executed: false, reason: 'read_only' }
|
||||
}
|
||||
const key = String(ruleId || '').trim()
|
||||
if (!key) return { executed: false, reason: 'missing_rule' }
|
||||
|
||||
|
||||
@@ -73,14 +73,43 @@ export interface MessageEventRecord {
|
||||
mentionTargets: string[]
|
||||
}
|
||||
|
||||
export type MessageRuntimeState = 'running' | 'stopped' | 'unknown'
|
||||
|
||||
export interface MessageBrokerStatus {
|
||||
/** TraceMemo 自己的数据库句柄是否可用;**不等于**微信进程在运行。 */
|
||||
database: 'ready' | 'unavailable'
|
||||
/** Native Monitor 是否已成功挂上。 */
|
||||
monitor: MessageRuntimeState
|
||||
/** 微信进程状态(缓存采样,非实时探针)。 */
|
||||
wechat: MessageRuntimeState
|
||||
subscribers: number
|
||||
buffered: number
|
||||
oldestSeq: number | null
|
||||
newestSeq: number | null
|
||||
}
|
||||
|
||||
/**
|
||||
* 一次数据库回补的结果。
|
||||
*
|
||||
* `truncated=true` 表示**至少有一个上限命中**,客户端必须知道这段空档没有补全:
|
||||
* - `messageTruncated`:某会话返回行数达到 `perConversationLimit`;
|
||||
* - `conversationTruncated`:订阅的会话数超过 `maxConversations`,后面的被跳过。
|
||||
*/
|
||||
export interface MessageBackfillReport {
|
||||
requestedConversations: number
|
||||
processedConversations: number
|
||||
delivered: number
|
||||
failedConversations: number
|
||||
conversationTruncated: boolean
|
||||
messageTruncated: boolean
|
||||
truncated: boolean
|
||||
/** 是否完整:没有截断、没有会话读取失败。客户端应优先看这个字段。 */
|
||||
complete: boolean
|
||||
perConversationLimit: number
|
||||
maxConversations: number
|
||||
windowSec: number
|
||||
}
|
||||
|
||||
export interface MessageGap {
|
||||
reason: 'buffer_overflow' | 'invalid_cursor' | 'cursor_from_previous_process'
|
||||
requestedLastEventId: string
|
||||
@@ -99,6 +128,8 @@ export interface MessageEventSink {
|
||||
onStatus(status: MessageBrokerStatus & { subscriptionId: string }): void
|
||||
onEvent(event: MessageEventRecord, origin: MessageEventOrigin): void
|
||||
onGap(gap: MessageGap): void
|
||||
/** 回补结束后的完整性报告;旧适配器可以不实现。 */
|
||||
onBackfill?(report: MessageBackfillReport): void
|
||||
}
|
||||
|
||||
export interface MessageSubscribeOptions {
|
||||
@@ -128,6 +159,10 @@ export interface MessageEventBrokerOptions {
|
||||
resolveConversationId: (sessionId: string) => string | undefined
|
||||
/** 数据库当前是否可用。用于 status 事件,不做连接管理。 */
|
||||
isDatabaseReady?: () => boolean
|
||||
/** Native Monitor 当前状态。未注入时 status 报 `unknown`。 */
|
||||
getMonitorState?: () => MessageRuntimeState
|
||||
/** 微信进程状态(调用方应缓存,避免 status 每次都 spawn 探针)。 */
|
||||
getWechatProcessState?: () => MessageRuntimeState
|
||||
/** 回补读取器。参数与 `getMessagesAsync(usernameOrMd5, startSec, endSec, {limit})` 一致。 */
|
||||
readMessages?: (
|
||||
sessionIdOrMd5: string,
|
||||
@@ -283,6 +318,8 @@ export class MessageEventBroker {
|
||||
status(): MessageBrokerStatus {
|
||||
return {
|
||||
database: this.options.isDatabaseReady?.() === false ? 'unavailable' : 'ready',
|
||||
monitor: this.options.getMonitorState?.() ?? 'unknown',
|
||||
wechat: this.options.getWechatProcessState?.() ?? 'unknown',
|
||||
subscribers: this.subscribers.size,
|
||||
buffered: this.buffer.length,
|
||||
oldestSeq: this.buffer[0]?.seq ?? null,
|
||||
@@ -290,6 +327,18 @@ export class MessageEventBroker {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空缓冲与去重表,但**保留订阅者与序号**。
|
||||
*
|
||||
* 用于数据库重开 / 切账号:旧事件不能再被重放,客户端的旧游标会自然落到
|
||||
* `oldestSeq` 之前,从而收到 gap;而已经连着的订阅者不需要断开重连。
|
||||
*/
|
||||
resetBuffer(): void {
|
||||
this.buffer = []
|
||||
this.index.clear()
|
||||
this.seen.clear()
|
||||
}
|
||||
|
||||
stats(): typeof this.counters & MessageBrokerStatus {
|
||||
return { ...this.counters, ...this.status() }
|
||||
}
|
||||
@@ -399,14 +448,20 @@ export class MessageEventBroker {
|
||||
return 'scheduled'
|
||||
}
|
||||
|
||||
/** 执行已经通过 `backfillPlan` 判定的回补。 */
|
||||
/** 执行已经通过 `backfillPlan` 判定的回补,并报告是否被上限截断。 */
|
||||
private async runBackfill(state: SubscriberState): Promise<void> {
|
||||
if (!state.conversationIds || !this.options.readMessages) return
|
||||
|
||||
const nowMs = this.now()
|
||||
const endSec = Math.floor(nowMs / 1000)
|
||||
const startSec = endSec - this.backfillLookbackSec
|
||||
const requestedConversations = state.conversationIds.size
|
||||
const conversations = Array.from(state.conversationIds).slice(0, this.backfillMaxConversations)
|
||||
const conversationTruncated = requestedConversations > conversations.length
|
||||
|
||||
let delivered = 0
|
||||
let failedConversations = 0
|
||||
let messageTruncated = false
|
||||
|
||||
for (const conversationId of conversations) {
|
||||
if (state.closed) return
|
||||
@@ -415,6 +470,7 @@ export class MessageEventBroker {
|
||||
try {
|
||||
rows = await this.options.readMessages(sessionId, startSec, endSec, this.backfillLimit)
|
||||
} catch (error) {
|
||||
failedConversations += 1
|
||||
console.warn(
|
||||
`[MessageEventBroker] backfill read failed: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
@@ -422,6 +478,11 @@ export class MessageEventBroker {
|
||||
)
|
||||
continue
|
||||
}
|
||||
/*
|
||||
* 返回行数达到 limit 就按「可能被截断」上报:多读一条的代价没有必要,
|
||||
* 但把「正好读满」当成完整回补,会让客户端误以为没有漏消息。
|
||||
*/
|
||||
if (rows.length >= this.backfillLimit) messageTruncated = true
|
||||
for (const row of rows) {
|
||||
if (state.closed) return
|
||||
const normalized = normalizeIncomingMessage(sessionId, row)
|
||||
@@ -432,9 +493,34 @@ export class MessageEventBroker {
|
||||
record.seq = this.nextSeq
|
||||
this.nextSeq += 1
|
||||
this.counters.backfilled += 1
|
||||
delivered += 1
|
||||
this.deliver(state, record, 'db_backfill')
|
||||
}
|
||||
}
|
||||
|
||||
if (state.closed) return
|
||||
const report: MessageBackfillReport = {
|
||||
requestedConversations,
|
||||
processedConversations: conversations.length,
|
||||
delivered,
|
||||
failedConversations,
|
||||
conversationTruncated,
|
||||
messageTruncated,
|
||||
truncated: conversationTruncated || messageTruncated,
|
||||
complete: !conversationTruncated && !messageTruncated && failedConversations === 0,
|
||||
perConversationLimit: this.backfillLimit,
|
||||
maxConversations: this.backfillMaxConversations,
|
||||
windowSec: this.backfillLookbackSec
|
||||
}
|
||||
try {
|
||||
state.sink.onBackfill?.(report)
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
`[MessageEventBroker] backfill report sink threw: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private deliverLive(record: MessageEventRecord): void {
|
||||
@@ -475,9 +561,16 @@ export class MessageEventBroker {
|
||||
this.counters.unmapped += 1
|
||||
return null
|
||||
}
|
||||
/*
|
||||
* 消息身份必须是 `create_time:local_id`:
|
||||
* `local_id` 只在单库/单分片内唯一,跨分片会重复;只带 localId 的 ref
|
||||
* 会让 `/query/message-context` 判 `ambiguous_message`。
|
||||
* `locateMessageAsync` 已经支持复合身份,这里与 Knowledge 的 `local:${time}:${id}` 同口径。
|
||||
*/
|
||||
const identity = `${message.createTime}:${message.localId}`
|
||||
let messageRef: string
|
||||
try {
|
||||
messageRef = encodeMessageRef(conversationId, message.localId)
|
||||
messageRef = encodeMessageRef(conversationId, identity)
|
||||
} catch (error) {
|
||||
this.counters.rejected += 1
|
||||
console.warn(
|
||||
@@ -491,7 +584,7 @@ export class MessageEventBroker {
|
||||
const rawText = message.content ?? ''
|
||||
const truncated = rawText.length > this.maxTextChars
|
||||
return {
|
||||
id: eventIdFor(conversationId, message.localId),
|
||||
id: eventIdFor(conversationId, identity),
|
||||
seq: 0,
|
||||
conversationId,
|
||||
messageRef,
|
||||
@@ -548,10 +641,10 @@ export class MessageEventBroker {
|
||||
}
|
||||
}
|
||||
|
||||
/** 同一会话 + 同一条消息的确定性事件 ID。 */
|
||||
export function eventIdFor(conversationId: string, localId: string): string {
|
||||
/** 同一会话 + 同一条消息的确定性事件 ID。`messageIdentity` 为 `createTime:localId`。 */
|
||||
export function eventIdFor(conversationId: string, messageIdentity: string): string {
|
||||
return `evt_${createHash('sha256')
|
||||
.update(`${conversationId}\u0000${localId}`, 'utf8')
|
||||
.update(`${conversationId}\u0000${messageIdentity}`, 'utf8')
|
||||
.digest('hex')
|
||||
.slice(0, 24)}`
|
||||
}
|
||||
|
||||
@@ -50,6 +50,10 @@ const DEFAULT_READ_LIMIT = 50
|
||||
const DEFAULT_DEDUP_TTL_MS = 5 * 60 * 1000
|
||||
/** dedup 容量上限,防止长时间运行后无限增长。 */
|
||||
const DEFAULT_DEDUP_MAX_ENTRIES = 5_000
|
||||
/** 未稳定发送行的重试间隔与最大等待时间,避免把写库中间态误判为对方来信。 */
|
||||
const DEFAULT_SETTLE_RETRY_MS = 400
|
||||
const DEFAULT_MAX_SETTLE_WAIT_MS = 2_000
|
||||
const SYSTEM_MESSAGE_TYPES = new Set([10000, 10002])
|
||||
|
||||
/**
|
||||
* 规范化后的入站消息。
|
||||
@@ -112,6 +116,8 @@ export interface MessageListenerOptions {
|
||||
readLimit?: number
|
||||
dedupTtlMs?: number
|
||||
dedupMaxEntries?: number
|
||||
settleRetryMs?: number
|
||||
maxSettleWaitMs?: number
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -225,6 +231,28 @@ export function normalizeIncomingMessage(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断消息是否处于微信两阶段写库的中间态(发送中或尚未回填发送者与 server_id)。
|
||||
* 提前投递会把未稳定的本人发出行误判为 isSelf=false 并锁死去重键。
|
||||
*/
|
||||
export function isMessageIdentityUnsettled(
|
||||
message: Wcdb4Message,
|
||||
normalized: NormalizedIncomingMessage
|
||||
): boolean {
|
||||
if (normalized.isSelf) return false
|
||||
if (SYSTEM_MESSAGE_TYPES.has(normalized.messageType)) return false
|
||||
|
||||
const raw = (message.raw ?? {}) as Record<string, unknown>
|
||||
const status = raw.status !== undefined && raw.status !== null ? Number(raw.status) : NaN
|
||||
if (status === 1) return true
|
||||
|
||||
const serverId = String(normalized.serverId ?? '').trim()
|
||||
if (!serverId || serverId === '0') return true
|
||||
|
||||
if (!normalized.senderId) return true
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* 实时消息监听。
|
||||
*
|
||||
@@ -255,7 +283,10 @@ export class MessageListenerService {
|
||||
* 120ms 内收到 `A B A C B` 必须回读 A/B/C 三个,绝不能「最后一个 wins」。
|
||||
*/
|
||||
private readonly pendingSessions = new Set<string>()
|
||||
private readonly pendingUnsettled = new Map<string, number>()
|
||||
private readonly settleSessions = new Set<string>()
|
||||
private coalesceTimer: ReturnType<typeof setTimeout> | null = null
|
||||
private settleTimer: ReturnType<typeof setTimeout> | null = null
|
||||
private readbackInFlight = false
|
||||
private pendingReadback = false
|
||||
private disposed = false
|
||||
@@ -266,6 +297,8 @@ export class MessageListenerService {
|
||||
private readonly readLimit: number
|
||||
private readonly dedupTtlMs: number
|
||||
private readonly dedupMaxEntries: number
|
||||
private readonly settleRetryMs: number
|
||||
private readonly maxSettleWaitMs: number
|
||||
|
||||
private counters: MessageListenerStats = {
|
||||
nativeEvents: 0,
|
||||
@@ -286,6 +319,8 @@ export class MessageListenerService {
|
||||
this.readLimit = options.readLimit ?? DEFAULT_READ_LIMIT
|
||||
this.dedupTtlMs = options.dedupTtlMs ?? DEFAULT_DEDUP_TTL_MS
|
||||
this.dedupMaxEntries = options.dedupMaxEntries ?? DEFAULT_DEDUP_MAX_ENTRIES
|
||||
this.settleRetryMs = options.settleRetryMs ?? DEFAULT_SETTLE_RETRY_MS
|
||||
this.maxSettleWaitMs = options.maxSettleWaitMs ?? DEFAULT_MAX_SETTLE_WAIT_MS
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -308,8 +343,14 @@ export class MessageListenerService {
|
||||
clearTimeout(this.coalesceTimer)
|
||||
this.coalesceTimer = null
|
||||
}
|
||||
if (this.settleTimer) {
|
||||
clearTimeout(this.settleTimer)
|
||||
this.settleTimer = null
|
||||
}
|
||||
this.listeners.clear()
|
||||
this.seen.clear()
|
||||
this.pendingUnsettled.clear()
|
||||
this.settleSessions.clear()
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -433,9 +474,21 @@ export class MessageListenerService {
|
||||
if (this.disposed) return 0
|
||||
|
||||
let delivered = 0
|
||||
let needsSettleRetry = false
|
||||
const now = Date.now()
|
||||
for (const message of messages) {
|
||||
const normalized = this.normalize(sessionId, message)
|
||||
if (!normalized) continue
|
||||
const key = `${normalized.sessionId}:${normalized.localId}`
|
||||
if (this.seen.has(key)) {
|
||||
this.counters.deduped += 1
|
||||
continue
|
||||
}
|
||||
if (this.shouldDeferUnsettled(key, message, normalized, now)) {
|
||||
needsSettleRetry = true
|
||||
continue
|
||||
}
|
||||
this.pendingUnsettled.delete(key)
|
||||
// dedup:同一条消息可能在多个读回窗口中反复出现(native 事件本身也可能重复)。
|
||||
if (!this.markSeen(normalized)) {
|
||||
this.counters.deduped += 1
|
||||
@@ -445,9 +498,55 @@ export class MessageListenerService {
|
||||
delivered += 1
|
||||
this.deliver(normalized)
|
||||
}
|
||||
if (needsSettleRetry) {
|
||||
this.scheduleSettleRetry(sessionId)
|
||||
}
|
||||
return delivered
|
||||
}
|
||||
|
||||
private shouldDeferUnsettled(
|
||||
key: string,
|
||||
message: Wcdb4Message,
|
||||
normalized: NormalizedIncomingMessage,
|
||||
now: number
|
||||
): boolean {
|
||||
if (this.maxSettleWaitMs <= 0 || !isMessageIdentityUnsettled(message, normalized)) {
|
||||
return false
|
||||
}
|
||||
const firstSeenAt = this.pendingUnsettled.get(key)
|
||||
if (firstSeenAt === undefined) {
|
||||
this.pendingUnsettled.set(key, now)
|
||||
if (this.pendingUnsettled.size > this.dedupMaxEntries) {
|
||||
this.evictUnsettled(now)
|
||||
}
|
||||
return true
|
||||
}
|
||||
return now - firstSeenAt < this.maxSettleWaitMs
|
||||
}
|
||||
|
||||
private scheduleSettleRetry(sessionId: string): void {
|
||||
if (this.disposed) return
|
||||
this.settleSessions.add(sessionId)
|
||||
if (this.settleTimer) return
|
||||
this.settleTimer = setTimeout(() => {
|
||||
this.settleTimer = null
|
||||
if (this.disposed) return
|
||||
for (const id of this.settleSessions) {
|
||||
this.pendingSessions.add(id)
|
||||
}
|
||||
this.settleSessions.clear()
|
||||
void this.readback()
|
||||
}, this.settleRetryMs)
|
||||
}
|
||||
|
||||
private evictUnsettled(now: number): void {
|
||||
for (const [key, firstSeenAt] of this.pendingUnsettled) {
|
||||
if (now - firstSeenAt >= this.maxSettleWaitMs) {
|
||||
this.pendingUnsettled.delete(key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private deliver(message: NormalizedIncomingMessage): void {
|
||||
for (const listener of this.listeners) {
|
||||
try {
|
||||
|
||||
@@ -38,7 +38,7 @@ export const messagesAroundRadii = (
|
||||
): number[] => (anchorSeconds && anchorSeconds > 0 ? [baseRadius, widenRadius] : [])
|
||||
|
||||
/** 有界窗口 + 精确身份定位。窗口按上限截断,绝不返回整段历史。 */
|
||||
export const sliceMessagesAroundWindow = <T extends { id?: unknown }>(
|
||||
export const sliceMessagesAroundWindow = <T extends { id?: unknown; createTime?: number }>(
|
||||
messages: T[],
|
||||
conversationId: string,
|
||||
targetMessageId: string,
|
||||
@@ -46,9 +46,21 @@ export const sliceMessagesAroundWindow = <T extends { id?: unknown }>(
|
||||
): { window: T[]; index: number; truncated: boolean } => {
|
||||
const truncated = messages.length > maxWindowMessages
|
||||
const window = truncated ? messages.slice(0, maxWindowMessages) : messages
|
||||
const index = window.findIndex(
|
||||
(message) =>
|
||||
normalizeMessageIdentity(conversationId, String(message.id ?? ''))?.messageId === targetMessageId
|
||||
)
|
||||
const separator = targetMessageId.lastIndexOf(':')
|
||||
const wantedTime = separator > 0 ? targetMessageId.slice(0, separator) : ''
|
||||
const wantedLocalId = separator > 0 ? targetMessageId.slice(separator + 1) : ''
|
||||
const matchesTarget = (message: T): boolean => {
|
||||
const identity = normalizeMessageIdentity(conversationId, String(message.id ?? ''))
|
||||
if (!identity) return false
|
||||
// 裸 localId:旧调用方与 query API 的 `message.id` 都走这条。
|
||||
if (identity.messageId === targetMessageId) return true
|
||||
// 复合身份:SSE 的 messageRef 为 `createTime:localId`,必须同时比对时间。
|
||||
return (
|
||||
separator > 0 &&
|
||||
identity.messageId === wantedLocalId &&
|
||||
String(message.createTime ?? '') === wantedTime
|
||||
)
|
||||
}
|
||||
const index = window.findIndex(matchesTarget)
|
||||
return { window, index, truncated }
|
||||
}
|
||||
@@ -31,6 +31,7 @@ import path from 'node:path'
|
||||
import { findResource } from '../resource-paths'
|
||||
import { isMacNativeRuntimeUnavailable, resolveWcdbConfigHelper } from '../native-runtime-paths'
|
||||
import { resolveExternalComponent } from './external-component-locator'
|
||||
import { isReadOnlyMode, logReadOnlySkip } from './read-only-mode'
|
||||
import type { Wcdb4Client } from '../wcdb4-client'
|
||||
import {
|
||||
MSG_INSERT_SWITCHES,
|
||||
@@ -205,6 +206,16 @@ function runHelper(
|
||||
request: { key: string; rooms: string[]; myWxid: string },
|
||||
timeoutMs = HELPER_TIMEOUT_MS
|
||||
): Promise<HelperRunResult> {
|
||||
// 只读测试模式:任何 helper 写入(开关 / ensure-rules)都不允许发生。
|
||||
if (isReadOnlyMode()) {
|
||||
logReadOnlySkip('MsgInsert helper 写入')
|
||||
return Promise.resolve({
|
||||
ok: false,
|
||||
exitCode: null,
|
||||
errorCode: 'READ_ONLY_MODE',
|
||||
message: '只读测试模式:禁止写入微信数据库'
|
||||
})
|
||||
}
|
||||
return new Promise((resolve) => {
|
||||
let child: ReturnType<typeof spawn>
|
||||
try {
|
||||
@@ -730,6 +741,10 @@ export async function applyMsgInsertSwitch(
|
||||
export async function reconcileMsgInsertRules(
|
||||
input: MsgInsertScopeInput & { myWxid: string; databaseKey: string; extraRooms?: string[] }
|
||||
): Promise<{ done: boolean; rooms: number; written: number; errorCode?: MsgInsertErrorCode }> {
|
||||
if (isReadOnlyMode()) {
|
||||
logReadOnlySkip('MsgInsert reconciliation')
|
||||
return { done: false, rooms: 0, written: 0, errorCode: 'READ_ONLY_MODE' }
|
||||
}
|
||||
if (isMacNativeRuntimeUnavailable()) {
|
||||
return { done: false, rooms: 0, written: 0, errorCode: 'HELPER_NOT_FOUND' }
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
import { homedir, tmpdir } from 'os'
|
||||
import { delimiter, dirname, extname, join, sep, basename } from 'path'
|
||||
import { resolveBundledFfmpegPath } from '../ffmpeg-path'
|
||||
import { isReadOnlyMode, logReadOnlySkip } from './read-only-mode'
|
||||
import { promisify } from 'util'
|
||||
import type {
|
||||
PersonalWechatSendRequest,
|
||||
@@ -809,6 +810,14 @@ export class PersonalWechatSendService {
|
||||
}
|
||||
|
||||
async send(request: PersonalWechatSendRequest): Promise<PersonalWechatSendResult> {
|
||||
if (isReadOnlyMode()) {
|
||||
logReadOnlySkip('个人微信发送')
|
||||
return {
|
||||
success: false,
|
||||
status: await this.getStatus(),
|
||||
error: '只读测试模式:不发送任何微信消息'
|
||||
}
|
||||
}
|
||||
if (process.platform === 'win32') return this.sendWindows(request)
|
||||
if (process.platform === 'darwin') {
|
||||
if (request.type === 'text') return this.sendMacText(request)
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* 只读验收模式。
|
||||
*
|
||||
* 用于「接真实微信库、但不允许任何写副作用」的验收场景。启用后:
|
||||
* - 不执行 MsgInsert reconciliation / 规则写入;
|
||||
* - 不发送任何微信消息(网关直接 blocked);
|
||||
* - 不执行自动化与定时日报的发送步骤;
|
||||
* - 不写退群本地提示。
|
||||
*
|
||||
* 读取、SSE 订阅、数据库回补不受影响。
|
||||
*
|
||||
* 生产模式默认关闭:只有显式设置 `TRACEMEMO_READ_ONLY=1` 才生效。
|
||||
*/
|
||||
export const READ_ONLY_ENV = 'TRACEMEMO_READ_ONLY'
|
||||
|
||||
const TRUE_VALUES = new Set(['1', 'true', 'yes', 'on'])
|
||||
|
||||
export function isReadOnlyMode(): boolean {
|
||||
const value = process.env[READ_ONLY_ENV]
|
||||
return typeof value === 'string' && TRUE_VALUES.has(value.trim().toLowerCase())
|
||||
}
|
||||
|
||||
/** 统一日志:只记录被跳过的操作名,不记录会话 / 消息内容。 */
|
||||
export function logReadOnlySkip(operation: string): void {
|
||||
console.log(`[ReadOnly] 已跳过 ${operation}`)
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import { app } from 'electron'
|
||||
import { createHash, randomUUID } from 'crypto'
|
||||
import fs from 'fs-extra'
|
||||
import path from 'path'
|
||||
import { isReadOnlyMode } from './read-only-mode'
|
||||
import type {
|
||||
PersonalWechatSendCapability,
|
||||
PersonalWechatSendRequest,
|
||||
@@ -186,6 +187,22 @@ export class WechatActionGateway {
|
||||
}
|
||||
|
||||
async execute(request: WechatActionRequest): Promise<WechatActionResult> {
|
||||
/*
|
||||
* 只读闸门必须在幂等查表**之前**:否则同一个 idempotencyKey 命中历史
|
||||
* 已发送记录时,会直接返回旧的 sent 结果,看似没发、实际绕过了闸门。
|
||||
*/
|
||||
if (isReadOnlyMode()) {
|
||||
const startedAt = this.deps.now().toISOString()
|
||||
return {
|
||||
actionId: String(request?.id || '').trim() || randomUUID(),
|
||||
status: 'blocked',
|
||||
decision: 'block',
|
||||
errorCode: 'READ_ONLY_MODE',
|
||||
reason: '只读测试模式:不发送任何微信消息',
|
||||
startedAt,
|
||||
finishedAt: startedAt
|
||||
}
|
||||
}
|
||||
const normalized = normalizeActionRequest(request)
|
||||
const idempotencyKey = normalized ? this.idempotencyKey(normalized) : undefined
|
||||
if (idempotencyKey) {
|
||||
|
||||
@@ -35,6 +35,7 @@ import { renderLeaveNotificationText } from '../../shared/group-exit-event'
|
||||
import { GROUP_EXIT_NOTIFICATION_TEMPLATE } from '../../shared/group-exit-monitor'
|
||||
import { resolveWcdbConfigHelper } from '../native-runtime-paths'
|
||||
import { msgInsertCapabilityService } from './msg-insert-capability-service'
|
||||
import { isReadOnlyMode, logReadOnlySkip } from './read-only-mode'
|
||||
import { resolveHelperPath } from './msg-insert-switch-service'
|
||||
|
||||
export type LocalExitNoticeOutcome =
|
||||
@@ -140,6 +141,10 @@ export class WechatLocalExitNoticeService {
|
||||
eventId: event.eventId,
|
||||
conversationId: event.conversationId
|
||||
}
|
||||
if (isReadOnlyMode()) {
|
||||
logReadOnlySkip('退群本地提示写入')
|
||||
return { ...base, outcome: 'disabled', code: 'READ_ONLY_MODE' }
|
||||
}
|
||||
try {
|
||||
this.ensureLoaded()
|
||||
if (!this.enabled) return this.finish({ ...base, outcome: 'disabled', code: 'DISABLED' })
|
||||
|
||||
Reference in new issue
Block a user