From b171818df500265b87df3f2619184f8b6475e600 Mon Sep 17 00:00:00 2001 From: Wxw-Gu <84499436+Wxw-Gu@users.noreply.github.com> Date: Mon, 16 Nov 2026 10:02:20 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20Windows=E5=A2=9E=E5=8A=A0=E5=8F=91?= =?UTF-8?q?=E9=80=81=E8=A7=86=E9=A2=91=20dy=E4=B8=8B=E8=BD=BD=E8=84=9A?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../douyin-sender/background/index.js | 61 +- .../extensions/douyin-sender/lib/douyin.js | 22 +- .../douyin-sender/scripts/fetch_wheels.py | 130 ++++ .../douyin-sender/tests/douyin.test.mjs | 29 +- src/main/services/bootstrap-cache.ts | 426 +++++++++++-- .../services/personal-wechat-send-service.ts | 56 +- .../chat/PersonalWechatWindowsSendDialog.tsx | 1 + tests/unit/bootstrap-cache.test.ts | 601 +++++++++++++++++- 8 files changed, 1262 insertions(+), 64 deletions(-) create mode 100644 examples/extensions/douyin-sender/scripts/fetch_wheels.py diff --git a/examples/extensions/douyin-sender/background/index.js b/examples/extensions/douyin-sender/background/index.js index 08ff07c..9562120 100644 --- a/examples/extensions/douyin-sender/background/index.js +++ b/examples/extensions/douyin-sender/background/index.js @@ -260,12 +260,55 @@ function sleep(milliseconds) { return new Promise((resolve) => setTimeout(resolve, milliseconds)) } -/** - * 在 Apple Silicon macOS 上,若宿主的默认 python3 是 x86_64(Rosetta 2), - * 直接启动会把 P_TRANSLATED 标志遗传给子进程 Google Chrome,导致抖音页面卡在加载中。 - * 这里优先选用缓存 venv 的原生 Python,并通过 /usr/bin/arch -arm64 强制切换为原生 arm64。 - */ +/** WindowsApps 下的是 Microsoft Store 别名,执行不成脚本,探测时要跳过。 */ +function isStoreAliasPath(value) { + return /[\\/]WindowsApps[\\/]/i.test(String(value || '')) +} + +/** 在 PATH 中按顺序找第一个真实存在的可执行文件。 */ +function findOnPath(names) { + const dirs = String(process.env.PATH || '') + .split(path.delimiter) + .filter((dir) => dir && !isStoreAliasPath(dir)) + for (const name of names) { + for (const dir of dirs) { + for (const ext of ['.exe', '.EXE', '']) { + const candidate = path.join(dir, name + ext) + try { + if (fsSync.existsSync(candidate) && fsSync.statSync(candidate).isFile()) return candidate + } catch { + // 目录不可读就跳过,继续下一个候选。 + } + } + } + } + return '' +} + +/** 配置为空或是默认名时,按 py -3 → python 的顺序探测。 */ +function resolveWindowsPython(pythonPath) { + const configured = expandHome(pythonPath) + const looksDefault = !configured || configured === 'python' || configured === 'python3' + if (!looksDefault && !isStoreAliasPath(configured)) { + return { file: configured, prefixArgs: [] } + } + const py = findOnPath(['py']) + if (py) return { file: py, prefixArgs: ['-3'] } + const python = findOnPath(['python']) + if (python) return { file: python, prefixArgs: [] } + return { file: 'python', prefixArgs: [] } +} + +// Apple Silicon 上 x86_64 的 python3 会把 P_TRANSLATED 传给 Chrome,页面卡加载; +// 优先用 venv 原生解释器并经 /usr/bin/arch -arm64 强制原生运行。 function resolvePythonInvocation(pythonPath, scriptPath, args) { + if (process.platform === 'win32') { + const resolved = resolveWindowsPython(pythonPath) + return { + file: resolved.file, + args: [...resolved.prefixArgs, scriptPath, ...args] + } + } if (process.platform !== 'darwin') { return { file: pythonPath, args: [scriptPath, ...args] } } @@ -414,10 +457,10 @@ async function resolveAndDownloadVideo(url, config, options = {}) { } catch (error) { stdout = String((error && error.stdout) || '') if (!stdout.trim()) { - return parseFailure( - temporaryCookieFile ? 'Cookie 文件不可用或解析超时' : describeExecError(error), - temporaryCookieFile ? 'COOKIE_OR_TIMEOUT' : errorType(error) - ) + // 别把失败统一报成「Cookie 不可用」,否则 ENOENT 和脚本退出码都被盖掉。 + const reason = describeExecError(error) + const withMode = temporaryCookieFile ? `${reason}(Cookie 模式)` : reason + return parseFailure(withMode, temporaryCookieFile ? 'COOKIE_OR_TIMEOUT' : errorType(error)) } } finally { if (temporaryCookieFile) { diff --git a/examples/extensions/douyin-sender/lib/douyin.js b/examples/extensions/douyin-sender/lib/douyin.js index 2b85be8..ee74c58 100644 --- a/examples/extensions/douyin-sender/lib/douyin.js +++ b/examples/extensions/douyin-sender/lib/douyin.js @@ -20,10 +20,14 @@ const DEFAULT_SCRIPT_PATH = 'scripts/douyin.py' /** 画质白名单;空串表示「最高」,不传 `-q` 给脚本。 */ const QUALITY_VALUES = ['', '1080', '720', '540'] +// Windows 的 python3.exe 通常是 Microsoft Store 别名,执行不成脚本。 +const DEFAULT_PYTHON_PATH = + typeof process !== 'undefined' && process.platform === 'win32' ? 'python' : 'python3' + const DEFAULT_CONFIG = { configVersion: 1, enabled: false, - pythonPath: 'python3', + pythonPath: DEFAULT_PYTHON_PATH, scriptPath: DEFAULT_SCRIPT_PATH, quality: '720', /** 排障开关:显示浏览器窗口以观察实际页面状态。 */ @@ -214,18 +218,29 @@ function parseSavedPath(stdout) { // 去掉尾部的「(N 个文件)」之类附注,它不属于路径。 rest = rest.replace(/\s*[((][^(())]*[))]\s*$/, '').trim() if (!rest) continue - if (rest[0] !== '/') continue + if (!isAbsoluteMediaPath(rest)) continue return rest } return null } +// 绝对路径判定:POSIX `/x`、Windows `C:\x` / `C:/x`、UNC `\\server\share`。 +function isAbsoluteMediaPath(value) { + if (typeof value !== 'string') return false + const text = value.trim() + if (!text) return false + if (text.startsWith('/')) return true // POSIX + if (/^[A-Za-z]:[\\/]/.test(text)) return true // C:\ 或 C:/ + if (text.startsWith('\\\\')) return true // UNC \\server\share + return false +} + function parseDownloadedResult(stdout) { const results = parseResolveJson(stdout) const video = pickVideoResult(results) if (video) { const saved = Array.isArray(video.saved) - ? video.saved.find((value) => typeof value === 'string' && value.startsWith('/')) + ? video.saved.find((value) => isAbsoluteMediaPath(value)) : null if (saved) return { ok: true, meta: video, path: saved } if (video.error) return { ok: false, message: video.error, errorType: 'DOWNLOAD_FAILED' } @@ -346,6 +361,7 @@ module.exports = { extractDouyinUrl, parseResolveJson, parseSavedPath, + isAbsoluteMediaPath, parseDownloadedResult, renderCaption, shouldHandle, diff --git a/examples/extensions/douyin-sender/scripts/fetch_wheels.py b/examples/extensions/douyin-sender/scripts/fetch_wheels.py new file mode 100644 index 0000000..9c41a4c --- /dev/null +++ b/examples/extensions/douyin-sender/scripts/fetch_wheels.py @@ -0,0 +1,130 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +用 urllib 从镜像拉 wheel,再交给 pip 本地安装 —— 绕开 pip 自己那层网络栈。 + + python fetch_wheels.py <目标目录> [包名 ...] +""" + +import os +import re +import ssl +import sys +import urllib.parse +import urllib.request +from pathlib import Path + +MIRRORS = [ + "https://pypi.tuna.tsinghua.edu.cn/simple", + "https://mirrors.aliyun.com/pypi/simple", +] + +DEFAULT_PACKAGES = ["requests", "playwright"] + +WHEEL_RE = re.compile(r'href="([^"#]+\.whl)[^"]*"') +VER_RE = re.compile(r'-(\d+(?:\.\d+)*)') + +# 部分镜像对浏览器 UA 返回 403,用 pip 自己的才放行。 +USER_AGENT = "pip/26.1.2" + + +def page_links(mirror: str, package: str) -> list[str]: + """索引页 href 是相对路径,用 urljoin 归一。""" + url = f"{mirror}/{package}/" + ctx = ssl.create_default_context() + req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT}) + with urllib.request.urlopen(req, timeout=30, context=ctx) as resp: + html = resp.read().decode("utf-8", "replace") + return [urllib.parse.urljoin(url, href) for href in WHEEL_RE.findall(html)] + + +def wheel_key(name: str) -> tuple: + """排序键:越靠后越优先。""" + base = name.rsplit("/", 1)[-1].lower() + pure = 1 if ("none-any" in base) else 0 + win_amd64 = 1 if "win_amd64" in base else 0 + cp313 = 1 if "cp313" in base else 0 + abi3 = 1 if "abi3" in base else 0 + return (pure, win_amd64, abi3, cp313) + + +def version_key(url: str) -> tuple: + """从文件名取版本号数字段。""" + m = VER_RE.search(url.rsplit("/", 1)[-1]) + if not m: + return () + return tuple(int(part) for part in m.group(1).split(".")) + + +def pick(links: list[str]) -> str | None: + """挑一个 Windows x64 / cp313 可用的 wheel。""" + candidates = [] + for link in links: + low = link.lower() + if "macosx" in low or "manylinux" in low or "musllinux" in low: + continue + if "win32" in low or "win_arm64" in low: + continue + if "none-any.whl" in low or "win_amd64.whl" in low: + candidates.append(link) + if not candidates: + return None + candidates.sort(key=lambda url: (wheel_key(url), version_key(url))) + return candidates[-1] + + +def download(url: str, dest_dir: Path) -> Path: + name = url.rsplit("/", 1)[-1].split("#")[0] + target = dest_dir / name + if target.exists() and target.stat().st_size > 0: + print(f" cached {name}") + return target + req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT}) + with urllib.request.urlopen(req, timeout=60) as resp: + data = resp.read() + target.write_bytes(data) + print(f" saved {name} ({len(data)//1024} KB)") + return target + + +def main() -> int: + if len(sys.argv) < 2: + print(__doc__) + return 2 + dest = Path(sys.argv[1]).expanduser() + packages = sys.argv[2:] or DEFAULT_PACKAGES + dest.mkdir(parents=True, exist_ok=True) + + failed = [] + for package in packages: + print(f"[{package}]") + chosen = None + for mirror in MIRRORS: + try: + links = page_links(mirror, package) + except Exception as exc: + print(f" mirror {mirror} failed: {type(exc).__name__}") + continue + chosen = pick(links) + if chosen: + print(f" mirror {mirror}") + break + if not chosen: + print(" no compatible wheel found") + failed.append(package) + continue + try: + download(chosen, dest) + except Exception as exc: + print(f" download failed: {type(exc).__name__} {exc}") + failed.append(package) + + if failed: + print("FAILED: " + ", ".join(failed)) + return 1 + print(f"OK -> {dest}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/examples/extensions/douyin-sender/tests/douyin.test.mjs b/examples/extensions/douyin-sender/tests/douyin.test.mjs index 733dcf1..df3ef96 100644 --- a/examples/extensions/douyin-sender/tests/douyin.test.mjs +++ b/examples/extensions/douyin-sender/tests/douyin.test.mjs @@ -16,6 +16,7 @@ const { extractDouyinUrl, parseResolveJson, parseSavedPath, + isAbsoluteMediaPath, parseDownloadedResult, renderCaption, shouldHandle, @@ -190,6 +191,31 @@ test('从 JSON 下载结果同时提取作品元数据和保存路径', () => { ) }) +test('Windows 盘符路径同样算绝对路径', () => { + const winPath = 'C:\\fixture\\Downloads\\张三 - 标题 - 730.mp4' + assert.equal(isAbsoluteMediaPath(winPath), true) + assert.equal(isAbsoluteMediaPath('C:/fixture/a.mp4'), true) + assert.equal(isAbsoluteMediaPath('\\\\server\\share\\a.mp4'), true) + assert.equal(isAbsoluteMediaPath('Downloads/a.mp4'), false) + assert.equal(isAbsoluteMediaPath(''), false) + assert.equal(isAbsoluteMediaPath(null), false) + + // 只认 '/' 开头会把 Windows 的 ✅ 行整条丢掉 + const stdout = [ + ' ✓ 解析成功:video | 张三 | 标题', + ' ✅ ' + winPath, + ' 5.2MB | MP4' + ].join('\n') + assert.equal(parseSavedPath(stdout), winPath) + + const json = JSON.stringify([ + { url: 'https://v.douyin.com/fixture123', ok: true, type: 'video', saved: [winPath] } + ]) + const parsed = parseDownloadedResult(json) + assert.equal(parsed.ok, true) + assert.equal(parsed.path, winPath) +}) + test('JSON 下载失败保留脚本错误,图集保持不支持状态', () => { assert.deepEqual( parseDownloadedResult( @@ -247,7 +273,8 @@ test('默认配置符合约定', () => { const config = normalizeConfig(undefined) assert.equal(config.configVersion, 1) assert.equal(config.enabled, false) - assert.equal(config.pythonPath, 'python3') + // Windows 的 python3.exe 通常是 Microsoft Store 的应用执行别名,默认改用 python。 + assert.equal(config.pythonPath, process.platform === 'win32' ? 'python' : 'python3') assert.equal(config.scriptPath, 'scripts/douyin.py') assert.equal(config.quality, '720') assert.equal(config.showUi, false) diff --git a/src/main/services/bootstrap-cache.ts b/src/main/services/bootstrap-cache.ts index 6038242..e413fd0 100644 --- a/src/main/services/bootstrap-cache.ts +++ b/src/main/services/bootstrap-cache.ts @@ -55,6 +55,8 @@ interface CachedGroupSnapshotFile { interface ScheduledWrite { value: unknown + /** 内容指纹,与 value 一一对应;用于判断"磁盘上是否已经是这份内容" */ + signature: string revision: number generation: number cleanupFile?: string @@ -78,6 +80,27 @@ const MAX_MEMORY_GROUP_SNAPSHOTS = 32 const WRITE_DEBOUNCE_MS = 300 const PRUNE_INTERVAL_MS = 30_000 +/** + * 替换目标文件时的重试节奏(毫秒)。 + * + * 覆盖写走 `rename`(Windows 上是 MoveFileEx+REPLACE_EXISTING),杀软扫描、索引器 + * 短暂持有句柄都会让它抛 EPERM/EBUSY/EACCES —— 这类占用是瞬时的,重试即可。 + * 4 次总计约 0.5s,超过这个量级说明是真的写不进去,应该保留旧缓存而不是继续磨。 + */ +const REPLACE_RETRY_DELAYS_MS = [40, 120, 300] as const +/** 可重试的瞬时错误码。除此以外的错误重试也不会好。 */ +const REPLACE_RETRYABLE_CODES = new Set(['EPERM', 'EACCES', 'EBUSY', 'ENOTEMPTY', 'EAGAIN']) +/** + * 退出刷盘的重试总预算(毫秒)。 + * + * 单文件最坏重试等待 40+120+300=460ms;待写文件一多,累加起来就是肉眼可见的 + * 退出卡顿。这里给整批一个固定预算,预算耗尽后不再等待重试,剩余文件各试一次。 + * 首次尝试(真正的 writeFileSync + renameSync)不受预算限制 —— 那是必须做的写。 + */ +const FLUSH_RETRY_BUDGET_MS = 120 +/** 恢复写入用临时文件名的偏移量,避免与普通 revision 撞名。 */ +const RESTORE_REVISION_OFFSET = 1_000_000 + const startupMemory = new Map() const messageMemory = new Map() const groupMemory = new Map() @@ -86,6 +109,32 @@ const writeQueues = new Map>() const scheduledWrites = new Map() const writeRevisions = new Map() const lastPrunedAt = new Map() +/** + * 磁盘上**已经确认写入成功**的内容指纹。 + * + * 与 `startupMemory` / `scheduledWrites` 是三份独立状态: + * - startupMemory = 最新内存状态(可能是还没落盘的) + * - scheduledWrites = 待写入队列(可能被后来的调用顶掉) + * - persistedSignatures = 上一次真正 rename 成功的内容 + * 只有 rename 成功才更新它;失败的写入绝不能把内存态标记成"已持久化", + * 否则后续相同内容的保存会被指纹闸门静默丢掉,缓存永远追不上内存。 + */ +const persistedSignatures = new Map() +/** + * 最近一次成功落盘的内容(只记启动缓存这类带指纹的文件)。 + * + * 存在的唯一理由:rename 是"检查-执行"两段,检查通过之后到 rename 真正生效之间, + * 退出刷盘或清缓存仍可能插进来。事后靠这份日志判断"我这一笔是不是把更新的内容踩了", + * 是就把它恢复回来。只留一条/文件,内存占用与一个 startup.json 同级。 + */ +const lastCommits = new Map() +/** + * 退出刷盘纪元。 + * + * `flushBootstrapCacheWritesSync()` 自增它,让已经越过检查点、正在飞行的异步写入 + * 在最后一步放弃 —— 退出时同步写的内容不应该被一个更早发起的异步写覆盖回去。 + */ +let flushEpoch = 0 let cacheGeneration = 0 function normalizeRoot(accountRoot?: string): string { @@ -96,6 +145,151 @@ function digest(value: string): string { return crypto.createHash('sha1').update(value).digest('hex').slice(0, 24) } +/** + * 按 JSON 语义递归规范化:对象键排序、跳过值为 `undefined` 的属性。 + * + * 与 `JSON.stringify` 的行为保持一致(后者同样丢弃 undefined 属性、保留 null), + * 这样"指纹看到的"和"写进磁盘的"是同一份内容。 + */ +function sortForStable(value: unknown): unknown { + if (Array.isArray(value)) return value.map((item) => sortForStable(item)) + if (value === null || typeof value !== 'object') return value + const source = value as Record + const sorted: Record = {} + for (const key of Object.keys(source).sort()) { + const item = source[key] + if (item === undefined) continue + sorted[key] = sortForStable(item) + } + return sorted +} + +/** 稳定序列化:同一份数据不论键序如何,结果一致。 */ +function stableStringify(value: unknown): string { + return JSON.stringify(sortForStable(value)) +} + +/** + * 启动缓存内容指纹。 + * + * 覆盖**实际会被持久化的全部内容**:直接对 `self` 和每个 `contact` 做稳定序列化, + * 不维护字段白名单 —— 白名单漏一个字段就会出现"字段变了却不写盘"的静默失效, + * 这比多写一次严重得多。`updatedAt` / `version` / `platform` 因为不属于 self 或 + * 任一 contact,天然不参与计算。 + * + * 联系人顺序不参与语义:先压成规范串再对**字符串数组**排序; + * 排序的是派生副本,传入数组本身不会被原地修改。 + * + * 复杂度 O(n·k log k),n = 联系人数、k = 单条字段数;相比写 2MB 磁盘可忽略。 + */ +function startupSignature(cache: StartupCacheFile): string { + const contacts = Array.isArray(cache.contacts) ? cache.contacts : [] + const contactKeys = contacts.map((contact) => stableStringify(contact)) + contactKeys.sort() + const selfKey = cache.self ? stableStringify(cache.self) : 'none' + return crypto + .createHash('sha1') + .update(`v${CACHE_VERSION}|${cache.platform}|${normalizeRoot(cache.accountRoot)}`) + .update('|self|') + .update(selfKey) + .update('|contacts|') + .update(contactKeys.join('\n')) + .digest('hex') +} + +function delay(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)) +} + +/** 同步 sleep:退出路径不能用 setTimeout,用 Atomics.wait 才不会空转烧 CPU。 */ +function delaySync(ms: number): void { + if (ms <= 0) return + try { + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms) + } catch { + const until = Date.now() + ms + while (Date.now() < until) { + /* 极端环境下退化:没有 SharedArrayBuffer 时只能忙等 */ + } + } +} + +/** + * 原子替换:临时文件 → 目标文件,全程不删除目标。 + * + * `fs.rename` 在 Windows 上走 MoveFileExW(MOVEFILE_REPLACE_EXISTING),在 POSIX 上是 + * rename(2):两者都是"用新名字替换旧名字",旧文件内容由文件系统在提交点丢弃, + * 不存在"先删掉目标再尝试改名"的空窗期。 + * + * EXDEV(跨卷)在这里是**不可恢复**的:临时文件天生建在目标同目录,正常永远跨不了卷。 + * 真出现 EXDEV 说明路径本身出了问题,此时唯一安全的动作是放弃本次写入 —— + * `copyFile` 覆盖没有原子性,写到一半断电/磁盘满会把旧缓存截成半截 JSON, + * 比"这次没更新"严重得多。所以这里直接抛出,旧文件原样保留。 + */ +async function replaceFileAtomic(tempFile: string, file: string): Promise { + let lastError: unknown = null + for (let attempt = 0; attempt <= REPLACE_RETRY_DELAYS_MS.length; attempt += 1) { + try { + await fs.rename(tempFile, file) + return + } catch (error) { + const code = (error as NodeJS.ErrnoException)?.code || '' + if (code === 'EXDEV') throw error + if (!REPLACE_RETRYABLE_CODES.has(code)) throw error + lastError = error + if (attempt < REPLACE_RETRY_DELAYS_MS.length) { + await delay(REPLACE_RETRY_DELAYS_MS[attempt]) + } + } + } + throw lastError instanceof Error ? lastError : new Error('replace failed') +} + +/** + * `replaceFileAtomic` 的同步版本,供退出时的 `flushBootstrapCacheWritesSync` 使用。 + * + * `deadline` 是整批刷盘的重试预算:超过它就不再等待重试,直接把这个文件的失败 + * 算掉(旧缓存保留)。不设预算的话,N 个待写文件 × 460ms 能把退出拖成分钟级。 + */ +function replaceFileAtomicSync( + tempFile: string, + file: string, + deadline = Number.POSITIVE_INFINITY +): void { + let lastError: unknown = null + for (let attempt = 0; attempt <= REPLACE_RETRY_DELAYS_MS.length; attempt += 1) { + try { + fs.renameSync(tempFile, file) + return + } catch (error) { + const code = (error as NodeJS.ErrnoException)?.code || '' + // 与异步路径同样的判断:跨卷不做覆盖复制,直接失败、旧文件保留。 + if (code === 'EXDEV') throw error + if (!REPLACE_RETRYABLE_CODES.has(code)) throw error + lastError = error + if (attempt < REPLACE_RETRY_DELAYS_MS.length) { + const wait = REPLACE_RETRY_DELAYS_MS[attempt] + if (Date.now() + wait > deadline) break + delaySync(wait) + } + } + } + throw lastError instanceof Error ? lastError : new Error('replace failed') +} + +function makeTempFile(file: string, revision: number): string { + // 临时文件必须与目标同目录:跨卷 rename 会退化成 EXDEV。 + return `${file}.${process.pid}.${revision}.tmp` +} + +function removeTempFileSync(tempFile: string): void { + try { + if (fs.existsSync(tempFile)) fs.removeSync(tempFile) + } catch { + // 清理失败不改变本次写入的结论,只是留下一个 .tmp + } +} + function getAccountCachePaths(accountRoot: string): AccountCachePaths { const normalizedRoot = normalizeRoot(accountRoot) const accountKey = digest(`${process.platform}:${normalizedRoot}`) @@ -192,7 +386,7 @@ function readStartupCacheFile(accountRoot: string): StartupCacheFile | null { contacts: Array.isArray(legacy.contacts) ? legacy.contacts : [] } startupMemory.set(file, migrated) - scheduleWrite(file, migrated, { cleanupFile: paths.legacy }) + scheduleWrite(file, migrated, startupSignature(migrated), { cleanupFile: paths.legacy }) return migrated } const raw = fs.readJsonSync(file) as Partial @@ -206,6 +400,9 @@ function readStartupCacheFile(accountRoot: string): StartupCacheFile | null { contacts: Array.isArray(raw.contacts) ? raw.contacts : [] } startupMemory.set(file, result) + // 刚从磁盘读出来的内容就等于磁盘内容,直接登记为"已持久化"。 + // 不登记的话,每次启动后的第一次保存都会无条件重写一遍 —— 正是要消掉的放大。 + if (!persistedSignatures.has(file)) persistedSignatures.set(file, startupSignature(result)) return result } catch (error) { console.warn('[BootstrapCache] startup read failed:', error) @@ -322,6 +519,7 @@ async function pruneCacheDirectory(directory: string, maxFiles: number): Promise function queueWrite(file: string): void { const scheduled = scheduledWrites.get(file) if (!scheduled) return + const epochAtSchedule = flushEpoch const previous = writeQueues.get(file) || Promise.resolve() const next = previous .catch(() => undefined) @@ -335,19 +533,91 @@ function queueWrite(file: string): void { return } - const tempFile = `${file}.${process.pid}.${scheduled.revision}.tmp` + const tempFile = makeTempFile(file, scheduled.revision) await fs.ensureDir(path.dirname(file)) + // 先把完整内容写进临时文件:目标文件在整个过程中始终是上一份完整数据。 await fs.writeFile(tempFile, JSON.stringify(current.value), 'utf8') + const latest = scheduledWrites.get(file) if ( !latest || latest.revision !== scheduled.revision || - latest.generation !== cacheGeneration + latest.generation !== cacheGeneration || + flushEpoch !== epochAtSchedule ) { - await fs.remove(tempFile) + await fs.remove(tempFile).catch(() => undefined) return } - await fs.move(tempFile, file, { overwrite: true }) + + // 替换前的最后一道闸:被 clear 掉(generation 变)或退出刷盘(epoch 变)就不提交。 + if (flushEpoch !== epochAtSchedule || scheduled.generation !== cacheGeneration) { + await fs.remove(tempFile).catch(() => undefined) + return + } + + try { + await replaceFileAtomic(tempFile, file) + } catch (error) { + // 失败:目标文件仍是旧内容(rename 是原子替换,没有"先删后改"的中间态), + // 本次临时文件必须清掉,否则反复失败会堆 .tmp。 + await fs.remove(tempFile).catch(() => undefined) + // 同时撤掉这条待写入记录:留着它会让下一次 commitStartupCache 误以为 + // "队列里还有一份不同内容",白写一次。 + const failed = scheduledWrites.get(file) + if (failed?.revision === scheduled.revision) scheduledWrites.delete(file) + throw error + } + + // 落盘之后核一次账:rename 是原子的,但"检查 epoch/generation"和"rename 生效" + // 之间仍有窗口 —— 退出刷盘或清缓存可能正好插在中间。 + // 这时我们刚写下去的可能是旧内容,必须按日志把更新的那份放回去。 + const clobberedByFlush = flushEpoch !== epochAtSchedule + const clobberedByClear = scheduled.generation !== cacheGeneration + let committedSignature = scheduled.signature + let committedValue: unknown = scheduled.value + + if (scheduled.signature && (clobberedByFlush || clobberedByClear)) { + const newer = lastCommits.get(file) + if (newer && newer.signature !== scheduled.signature) { + // 有比我们更新的一份已经落过盘:恢复它。 + const restoreTemp = makeTempFile(file, scheduled.revision + RESTORE_REVISION_OFFSET) + try { + fs.writeFileSync(restoreTemp, JSON.stringify(newer.value), 'utf8') + replaceFileAtomicSync(restoreTemp, file) + committedSignature = newer.signature + committedValue = newer.value + } catch (error) { + removeTempFileSync(restoreTemp) + console.warn('[BootstrapCache] restore after race failed:', error) + } + } else if (clobberedByClear) { + // 清缓存之后才落地的旧数据:不该留在磁盘上(否则等于缓存复活)。 + try { + fs.removeSync(file) + } catch { + // 删不掉也不阻塞后续流程,下一次保存会覆盖它 + } + committedSignature = '' + committedValue = undefined + } + } + + // 只有 rename 成功才承认"磁盘上是这份内容"。superseded 的情况下也照记: + // persistedSignatures 描述的是磁盘现状,不是"最新意图"。 + if (scheduled.signature) { + if (committedSignature) { + persistedSignatures.set(file, committedSignature) + lastCommits.set(file, { + value: committedValue, + signature: committedSignature, + generation: scheduled.generation + }) + } else { + persistedSignatures.delete(file) + lastCommits.delete(file) + } + } + const completed = scheduledWrites.get(file) if ( completed?.revision === scheduled.revision && @@ -372,6 +642,7 @@ function queueWrite(file: string): void { function scheduleWrite( file: string, value: unknown, + signature: string, options?: { cleanupFile?: string; prune?: { directory: string; maxFiles: number } } ): void { const existingTimer = writeTimers.get(file) @@ -380,6 +651,7 @@ function scheduleWrite( writeRevisions.set(file, revision) scheduledWrites.set(file, { value, + signature, revision, generation: cacheGeneration, cleanupFile: options?.cleanupFile, @@ -394,6 +666,17 @@ function scheduleWrite( ) } +/** 取消待写入任务(不动磁盘、不动内存态)。revision 递增让在途写入失效。 */ +function cancelScheduledWrite(file: string): void { + const timer = writeTimers.get(file) + if (timer) { + clearTimeout(timer) + writeTimers.delete(file) + } + writeRevisions.set(file, (writeRevisions.get(file) || 0) + 1) + scheduledWrites.delete(file) +} + function loadOrCreateStartupCache(accountRoot: string): StartupCacheFile | null { const normalizedRoot = normalizeRoot(accountRoot) if (!normalizedRoot) return null @@ -410,10 +693,39 @@ function loadOrCreateStartupCache(accountRoot: string): StartupCacheFile | null return created } -function writeStartupCache(cache: StartupCacheFile): void { - const paths = getAccountCachePaths(cache.accountRoot) - startupMemory.set(paths.startup, cache) - scheduleWrite(paths.startup, cache, { cleanupFile: paths.legacy }) +/** + * 提交一份新的启动缓存状态。 + * + * 调用方必须传**新建的对象**(copy-on-write),不能传 `loadOrCreateStartupCache()` + * 返回的那个内存对象本身 —— 否则"旧状态"和"新状态"是同一个引用, + * 指纹永远相等,缓存就再也写不下去了。 + */ +function commitStartupCache(next: StartupCacheFile): void { + const paths = getAccountCachePaths(next.accountRoot) + const file = paths.startup + const signature = startupSignature(next) + const persisted = persistedSignatures.get(file) + const pending = scheduledWrites.get(file) + + startupMemory.set(file, next) + + if (persisted === signature) { + // 磁盘上已经是这份内容。 + if (!pending) return + if (pending.signature === signature) { + // 队列里排着的就是要写的同一份内容:撤掉它,别做无意义的一次替换。 + cancelScheduledWrite(file) + return + } + // 队列里排着一份**不同**的内容(A→B→A 的收尾):必须再写一次, + // 否则 B 落盘后内存里的 A 就永远丢了。 + } + + // 只有真正要写盘时才推进 updatedAt:内容没变却刷新时间戳, + // 会让上层"上次更新时间"变成噪音。 + const value: StartupCacheFile = { ...next, updatedAt: Date.now() } + startupMemory.set(file, value) + scheduleWrite(file, value, signature, { cleanupFile: paths.legacy }) } function containsLegacyMisparsedAppMessage(items: Message[]): boolean { @@ -523,9 +835,8 @@ export function mergeCachedContactAvatars(accountRoot: string, contacts: Contact export function saveBootstrapSelf(accountRoot: string, self: CachedSelfInfo): void { const cache = loadOrCreateStartupCache(accountRoot) if (!cache) return - cache.self = self - cache.updatedAt = Date.now() - writeStartupCache(cache) + // copy-on-write:不原地改内存对象,指纹才可能是"这次的新内容"。 + commitStartupCache({ ...cache, self }) } export function saveBootstrapContacts(accountRoot: string, contacts: Contact[]): void { @@ -543,7 +854,8 @@ export function saveBootstrapContacts(accountRoot: string, contacts: Contact[]): ) .map((contact) => [contact.m_nsUsrName, contact.m_nsNickName]) ) - cache.contacts = contacts.map((contact) => ({ + // 注意:`contacts.map` 产出新数组,传入的数组本身不会被排序或改写。 + const merged = contacts.map((contact) => ({ ...contact, avatar: contact.avatar || !avatarByUsername.has(contact.m_nsUsrName) @@ -554,23 +866,21 @@ export function saveBootstrapContacts(accountRoot: string, contacts: Contact[]): ? contact.m_nsNickName : nameByUsername.get(contact.m_nsUsrName) || contact.m_nsNickName })) - cache.updatedAt = Date.now() - writeStartupCache(cache) + commitStartupCache({ ...cache, contacts: merged }) } export function mergeBootstrapAvatars(accountRoot: string, avatars: Record): void { const cache = loadOrCreateStartupCache(accountRoot) if (!cache?.contacts.length) return let changed = false - cache.contacts = cache.contacts.map((contact) => { + const merged = cache.contacts.map((contact) => { const avatar = avatars[contact.m_nsUsrName] if (!avatar || contact.avatar === avatar) return contact changed = true return { ...contact, avatar } }) if (!changed) return - cache.updatedAt = Date.now() - writeStartupCache(cache) + commitStartupCache({ ...cache, contacts: merged }) } export function getCachedMessages( @@ -610,29 +920,29 @@ export function saveCachedGroupSnapshot( const file = getGroupCacheFile(normalizedRoot, userMd5) const previous = readGroupSnapshotFile(normalizedRoot, userMd5)?.snapshot const previousByWxid = new Map((previous?.members || []).map((member) => [member.wxid, member])) - const mergedSnapshot: CachedGroupSnapshot = previous && previous.roomId === snapshot.roomId - ? { - ...snapshot, - members: snapshot.members.map((member) => { - const oldMember = previousByWxid.get(member.wxid) - const freshGroupNickname = String(member.groupNickname || '').trim() - const freshWechatNickname = String(member.wechatNickname || '').trim() - const oldGroupNickname = String(oldMember?.groupNickname || '').trim() - const freshLooksLikeContactFallback = - !freshGroupNickname || - freshGroupNickname === freshWechatNickname - const groupNickname = - freshLooksLikeContactFallback && oldGroupNickname - ? oldGroupNickname - : freshGroupNickname - return { - ...member, - groupNickname, - nickname: groupNickname || member.nickname - } - }) - } - : snapshot + const mergedSnapshot: CachedGroupSnapshot = + previous && previous.roomId === snapshot.roomId + ? { + ...snapshot, + members: snapshot.members.map((member) => { + const oldMember = previousByWxid.get(member.wxid) + const freshGroupNickname = String(member.groupNickname || '').trim() + const freshWechatNickname = String(member.wechatNickname || '').trim() + const oldGroupNickname = String(oldMember?.groupNickname || '').trim() + const freshLooksLikeContactFallback = + !freshGroupNickname || freshGroupNickname === freshWechatNickname + const groupNickname = + freshLooksLikeContactFallback && oldGroupNickname + ? oldGroupNickname + : freshGroupNickname + return { + ...member, + groupNickname, + nickname: groupNickname || member.nickname + } + }) + } + : snapshot const value: CachedGroupSnapshotFile = { version: CACHE_VERSION, platform: process.platform, @@ -642,7 +952,9 @@ export function saveCachedGroupSnapshot( snapshot: mergedSnapshot } touchMemory(groupMemory, file, value, MAX_MEMORY_GROUP_SNAPSHOTS) - scheduleWrite(file, value, { + // 消息桶/群快照不做内容指纹(每次读都是一份新数据),signature 传空串, + // queueWrite 会跳过 persistedSignatures 登记。 + scheduleWrite(file, value, '', { prune: { directory: paths.groups, maxFiles: MAX_GROUP_SNAPSHOTS } }) return mergedSnapshot @@ -671,22 +983,43 @@ export function saveCachedMessages( items: messages.slice(-MAX_MESSAGES_PER_BUCKET) } touchMemory(messageMemory, file, value, MAX_MEMORY_MESSAGE_BUCKETS) - scheduleWrite(file, value, { + scheduleWrite(file, value, '', { prune: { directory: paths.messages, maxFiles: MAX_MESSAGE_BUCKETS } }) } export function flushBootstrapCacheWritesSync(): void { + // 自增纪元:已经越过检查点、正在飞行的异步写会在 rename 前发现自己过期并放弃, + // 避免退出时的同步内容被一个更早发起的异步写覆盖回去。 + flushEpoch += 1 for (const timer of writeTimers.values()) clearTimeout(timer) writeTimers.clear() const writes = Array.from(scheduledWrites.entries()) scheduledWrites.clear() + // 整批共享一份重试预算,避免 N 个文件各自重试把退出拖成分钟级。 + const deadline = Date.now() + FLUSH_RETRY_BUDGET_MS for (const [file, scheduled] of writes) { + // 退出时同步写也算一次 revision 变更,让队列里同一文件的任务作废。 + writeRevisions.set(file, (writeRevisions.get(file) || 0) + 1) + const tempFile = makeTempFile(file, scheduled.revision) try { fs.ensureDirSync(path.dirname(file)) - fs.writeFileSync(file, JSON.stringify(scheduled.value), 'utf8') + // 与异步路径保持同一套语义:先写完整临时文件,再原子换名,绝不先删目标。 + fs.writeFileSync(tempFile, JSON.stringify(scheduled.value), 'utf8') + replaceFileAtomicSync(tempFile, file, deadline) + if (scheduled.signature) { + persistedSignatures.set(file, scheduled.signature) + // 记进提交日志:若此时还有一笔在途异步写正好落在我们之后, + // 它会在核账时发现自己踩了更新的内容,并按这条日志恢复。 + lastCommits.set(file, { + value: scheduled.value, + signature: scheduled.signature, + generation: scheduled.generation + }) + } if (scheduled.cleanupFile) fs.removeSync(scheduled.cleanupFile) } catch (error) { + removeTempFileSync(tempFile) console.warn('[BootstrapCache] flush failed:', error) } } @@ -694,12 +1027,17 @@ export function flushBootstrapCacheWritesSync(): void { export function clearBootstrapCache(): void { cacheGeneration += 1 + // 清缓存同样让在途写入作废,并且丢掉"已持久化"记录 —— 磁盘上的文件可能马上被删, + // 留着旧指纹会让下一次保存误以为"磁盘上已经有了"而不写。 + flushEpoch += 1 for (const timer of writeTimers.values()) clearTimeout(timer) writeTimers.clear() scheduledWrites.clear() writeQueues.clear() writeRevisions.clear() lastPrunedAt.clear() + persistedSignatures.clear() + lastCommits.clear() startupMemory.clear() messageMemory.clear() groupMemory.clear() diff --git a/src/main/services/personal-wechat-send-service.ts b/src/main/services/personal-wechat-send-service.ts index c6fa91a..67b6451 100644 --- a/src/main/services/personal-wechat-send-service.ts +++ b/src/main/services/personal-wechat-send-service.ts @@ -254,7 +254,11 @@ function windowsImageTempRoot(): string { throw new Error('无法创建 Windows 图片临时目录') } -export function prepareWindowsImageFile(filePath: string): { +/** hook 侧用 ANSI API 判文件存在,非 ASCII 路径一律判成不存在,先拷一份 ASCII 副本。 */ +export function prepareWindowsMediaFile( + filePath: string, + options: { prefix: string; fallbackExtension: string } +): { filePath: string temporary: boolean } { @@ -262,12 +266,12 @@ export function prepareWindowsImageFile(filePath: string): { if (isAsciiPath(normalized)) return { filePath: normalized, temporary: false } const extension = extname(normalized).toLowerCase() - const safeExtension = /^\.[a-z0-9]{1,8}$/.test(extension) ? extension : '.png' + const safeExtension = /^\.[a-z0-9]{1,8}$/.test(extension) ? extension : options.fallbackExtension const temporaryPath = join( windowsImageTempRoot(), - `tm-img-${randomBytes(8).toString('hex')}${safeExtension}` + `${options.prefix}${randomBytes(8).toString('hex')}${safeExtension}` ) - if (!isAsciiPath(temporaryPath)) throw new Error('Windows 图片临时路径必须只包含 ASCII 字符') + if (!isAsciiPath(temporaryPath)) throw new Error('Windows 媒体临时路径必须只包含 ASCII 字符') try { copyFileSync(normalized, temporaryPath) } catch (error) { @@ -281,6 +285,13 @@ export function prepareWindowsImageFile(filePath: string): { return { filePath: temporaryPath, temporary: true } } +export function prepareWindowsImageFile(filePath: string): { + filePath: string + temporary: boolean +} { + return prepareWindowsMediaFile(filePath, { prefix: 'tm-img-', fallbackExtension: '.png' }) +} + function prepareMacWechatImageFile( filePath: string, senderWxid: string, @@ -558,6 +569,7 @@ function windowsStatusBase(host = windowsHookHost() || ''): PersonalWechatSender canSendText: false, canSendImage: false, canSendVoice: false, + canSendVideo: false, message: '正在检查 Windows 微信消息接口' } } @@ -607,6 +619,21 @@ function logSendDiagnostic( */ const WINDOWS_TEMP_IMAGE_GRACE_MS = 0 +/** 视频上传在 send_message 返回后才开始,删早了接收端只能拿到空文件。 */ +const WINDOWS_TEMP_VIDEO_GRACE_MS = 10 * 60 * 1000 + +// unref: 不让清理定时器拖住进程退出 +function scheduleTempFileCleanup(target: string, delayMs: number): void { + const timer = setTimeout(() => { + try { + unlinkSync(target) + } catch { + // best effort + } + }, delayMs) + timer.unref?.() +} + async function requestWindowsHook( endpoint: string, body: Record, @@ -744,6 +771,7 @@ export class PersonalWechatSendService { canSendText: true, canSendImage: true, canSendVoice: true, + canSendVideo: true, message: 'Windows 微信发送能力已连接,可以发送消息' } } catch (error) { @@ -1147,6 +1175,7 @@ export class PersonalWechatSendService { if (!status.canSend) return { success: false, status, error: status.error || status.message } let temporaryImagePath: string | undefined + let temporaryVideoPath: string | undefined let temporaryVoicePath: string | undefined try { if (request.type === 'text') { @@ -1169,8 +1198,20 @@ export class PersonalWechatSendService { }) await requestWindowsHook(windowsRequest.endpoint, windowsRequest.body, 60_000) } else if (request.type === 'video') { - // 视频不复制到临时目录:原生 Host 直接按绝对路径读取。 - const windowsRequest = buildWindowsWechatRequest(request) + const preparedVideo = prepareWindowsMediaFile(request.filePath, { + prefix: 'tm-video-', + fallbackExtension: '.mp4' + }) + temporaryVideoPath = preparedVideo.temporary ? preparedVideo.filePath : undefined + logSendDiagnostic('video-prepared', { + sourceBytes: safeFileSize(request.filePath), + usedTempCopy: preparedVideo.temporary, + copiedBytes: safeFileSize(preparedVideo.filePath) + }) + const windowsRequest = buildWindowsWechatRequest({ + ...request, + filePath: preparedVideo.filePath + }) await requestWindowsHook(windowsRequest.endpoint, windowsRequest.body, 180_000) } else if (request.type === 'voice') { const fromId = String(request.fromId || '').trim() @@ -1223,6 +1264,9 @@ export class PersonalWechatSendService { } } } + if (temporaryVideoPath) { + scheduleTempFileCleanup(temporaryVideoPath, WINDOWS_TEMP_VIDEO_GRACE_MS) + } if (temporaryVoicePath) { try { unlinkSync(temporaryVoicePath) diff --git a/src/renderer/src/components/chat/PersonalWechatWindowsSendDialog.tsx b/src/renderer/src/components/chat/PersonalWechatWindowsSendDialog.tsx index a9b3fe7..da093ce 100644 --- a/src/renderer/src/components/chat/PersonalWechatWindowsSendDialog.tsx +++ b/src/renderer/src/components/chat/PersonalWechatWindowsSendDialog.tsx @@ -30,6 +30,7 @@ function fallbackStatus(error: unknown): PersonalWechatSenderStatus { canSendText: false, canSendImage: false, canSendVoice: false, + canSendVideo: false, message: '无法检测 Windows 微信发送能力', error: error instanceof Error ? error.message : String(error) } diff --git a/tests/unit/bootstrap-cache.test.ts b/tests/unit/bootstrap-cache.test.ts index 4913a8e..7ba699c 100644 --- a/tests/unit/bootstrap-cache.test.ts +++ b/tests/unit/bootstrap-cache.test.ts @@ -1,7 +1,18 @@ -import { mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync, mkdirSync } from 'fs' +import { + mkdtempSync, + readFileSync, + readdirSync, + rmSync, + writeFileSync, + mkdirSync, + statSync, + chmodSync, + existsSync +} from 'fs' import { createHash } from 'crypto' import { tmpdir } from 'os' import { join } from 'path' +import fsExtra from 'fs-extra' import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' import type { Contact, Message } from '../../src/shared/types' @@ -16,6 +27,7 @@ import { flushBootstrapCacheWritesSync, getBootstrapCache, getCachedMessages, + mergeBootstrapAvatars, mergeCachedSelfInfo, saveBootstrapContacts, saveBootstrapSelf, @@ -209,3 +221,590 @@ describe('bootstrap cache', () => { }) }) }) + +// --------------------------------------------------------------------------- +// 写入闸门 / 原子替换回归 +// +// 这一组断言的是**真实文件系统**的结果(inode、mtime、内容哈希、残留 .tmp), +// 不是函数调用次数 —— 换实现时计数会骗人,inode 不会。 +// --------------------------------------------------------------------------- + +const BIG_AVATAR = `data:image/jpeg;base64,${Buffer.alloc(2800, 0x41).toString('base64')}` + +function cacheFileFor(root: string): string { + const accountKey = createHash('sha1') + .update(`${process.platform}:${root}`) + .digest('hex') + .slice(0, 24) + return join(userData, 'cache', 'bootstrap', `${process.platform}-${accountKey}`, 'startup.json') +} + +interface FileSnapshot { + exists: boolean + ino: number + mtimeMs: number + size: number + sha: string +} + +function snapshotFile(file: string): FileSnapshot { + if (!existsSync(file)) return { exists: false, ino: 0, mtimeMs: 0, size: 0, sha: '' } + const stat = statSync(file) + const content = readFileSync(file) + return { + exists: true, + ino: stat.ino, + mtimeMs: stat.mtimeMs, + size: stat.size, + sha: createHash('sha256').update(content).digest('hex') + } +} + +function tempFilesIn(directory: string): string[] { + if (!existsSync(directory)) return [] + return readdirSync(directory).filter((name) => name.endsWith('.tmp')) +} + +/** 防抖 300ms + 写盘;失败路径还要多等 4 次重试(约 0.5s)。 */ +const settle = (ms = 800): Promise => new Promise((resolve) => setTimeout(resolve, ms)) + +function makeContacts( + count: number, + mutate?: (contact: Contact, index: number) => Contact +): Contact[] { + return Array.from({ length: count }, (_, index) => { + const contact: Contact = { + m_nsUsrName: `wxid_fixture_${index}`, + m_nsNickName: `脱敏联系人${index}`, + md5: createHash('md5').update(String(index)).digest('hex'), + type: 'user', + avatar: BIG_AVATAR, + wechatNickname: `脱敏联系人${index}`, + remark: '' + } + return mutate ? mutate(contact, index) : contact + }) +} + +describe('bootstrap cache write gating', () => { + beforeEach(() => clearBootstrapCache()) + + it('writes the first save and then stops writing identical content', async () => { + const root = '/fixture/gate-identical' + const file = cacheFileFor(root) + + saveBootstrapContacts(root, makeContacts(3)) + await settle() + const first = snapshotFile(file) + expect(first.exists).toBe(true) + + for (let index = 0; index < 100; index += 1) { + saveBootstrapContacts(root, makeContacts(3)) + } + await settle() + + const second = snapshotFile(file) + expect(second.ino).toBe(first.ino) + expect(second.mtimeMs).toBe(first.mtimeMs) + expect(second.sha).toBe(first.sha) + }) + + it('treats a reordered contact list as unchanged and never mutates the input array', async () => { + const root = '/fixture/gate-reorder' + const file = cacheFileFor(root) + const original = makeContacts(4) + + saveBootstrapContacts(root, original) + await settle() + const first = snapshotFile(file) + + const reordered = [original[2], original[0], original[3], original[1]] + const inputSnapshot = reordered.map((contact) => contact.m_nsUsrName) + saveBootstrapContacts(root, reordered) + await settle() + + const second = snapshotFile(file) + expect(second.ino).toBe(first.ino) + expect(second.sha).toBe(first.sha) + // 指纹排序的是派生副本,调用方数组顺序必须原样保留 + expect(reordered.map((contact) => contact.m_nsUsrName)).toEqual(inputSnapshot) + }) + + it('persists every kind of real content change', async () => { + const root = '/fixture/gate-changes' + const file = cacheFileFor(root) + + saveBootstrapContacts(root, makeContacts(4)) + await settle() + let previous = snapshotFile(file) + + const cases: { name: string; contacts: Contact[] }[] = [ + { + name: 'remark', + contacts: makeContacts(4, (contact, index) => + index === 1 ? { ...contact, remark: '新备注' } : contact + ) + }, + { + name: 'avatar', + contacts: makeContacts(4, (contact, index) => + index === 2 + ? { + ...contact, + avatar: `data:image/png;base64,${Buffer.alloc(1200, 0x42).toString('base64')}` + } + : contact + ) + }, + { name: 'added', contacts: makeContacts(5) }, + { name: 'removed', contacts: makeContacts(3) } + ] + + for (const testCase of cases) { + saveBootstrapContacts(root, testCase.contacts) + await settle() + const current = snapshotFile(file) + expect(current.ino, `${testCase.name} 应该触发一次真实替换`).not.toBe(previous.ino) + expect(JSON.parse(readFileSync(file, 'utf8')).contacts).toHaveLength(testCase.contacts.length) + previous = current + } + }) + + it('gates self info and avatar merges the same way', async () => { + const root = '/fixture/gate-self' + const file = cacheFileFor(root) + const contacts = makeContacts(2) + + saveBootstrapContacts(root, contacts) + await settle() + saveBootstrapSelf(root, { + wxid: 'wxid_self', + nickname: '自己的昵称', + accountRoot: root + }) + await settle() + const afterSelf = snapshotFile(file) + expect(afterSelf.exists).toBe(true) + + // 相同的 self → 不再写 + saveBootstrapSelf(root, { + wxid: 'wxid_self', + nickname: '自己的昵称', + accountRoot: root + }) + await settle() + const afterSameSelf = snapshotFile(file) + expect(afterSameSelf.ino).toBe(afterSelf.ino) + expect(afterSameSelf.mtimeMs).toBe(afterSelf.mtimeMs) + + // 改昵称 → 必须写 + saveBootstrapSelf(root, { + wxid: 'wxid_self', + nickname: '改过的昵称', + accountRoot: root + }) + await settle() + expect(snapshotFile(file).ino).not.toBe(afterSelf.ino) + + // 头像合并:值相同不写,值不同写 + const beforeMerge = snapshotFile(file) + mergeBootstrapAvatars(root, { [`wxid_fixture_0`]: BIG_AVATAR }) + await settle() + expect(snapshotFile(file).ino).toBe(beforeMerge.ino) + + mergeBootstrapAvatars(root, { + [`wxid_fixture_0`]: `data:image/png;base64,${Buffer.alloc(900, 0x43).toString('base64')}` + }) + await settle() + expect(snapshotFile(file).ino).not.toBe(beforeMerge.ino) + }) + + it('keeps the previous cache when replacement fails, then recovers', async () => { + const root = '/fixture/gate-rename-failure' + const file = cacheFileFor(root) + const directory = join(cacheFileFor(root), '..') + + saveBootstrapContacts(root, makeContacts(2)) + await settle() + const good = snapshotFile(file) + const goodContent = readFileSync(file, 'utf8') + expect(good.exists).toBe(true) + + // 只读目标在 Windows 上让 MoveFileEx/REPLACE_EXISTING 抛 EPERM; + // 这不是 mock,是真实的文件系统行为。 + chmodSync(file, 0o444) + try { + saveBootstrapContacts( + root, + makeContacts(3, (contact) => ({ ...contact, remark: '失败尝试' })) + ) + await settle(1500) + + const failed = snapshotFile(file) + expect(failed.ino, '替换失败时目标文件必须原样保留').toBe(good.ino) + expect(readFileSync(file, 'utf8')).toBe(goodContent) + expect(tempFilesIn(directory), '失败后不能残留 .tmp').toHaveLength(0) + } finally { + chmodSync(file, 0o666) + } + + // 失败过的内容再存一次必须能真正落盘,不能被指纹闸门吞掉 + const target = makeContacts(3, (contact) => ({ ...contact, remark: '失败尝试' })) + saveBootstrapContacts(root, target) + await settle() + const recovered = snapshotFile(file) + expect(recovered.ino).not.toBe(good.ino) + expect(JSON.parse(readFileSync(file, 'utf8')).contacts).toHaveLength(3) + expect(tempFilesIn(directory)).toHaveLength(0) + }) + + it('lands the newest revision under rapid changes', async () => { + const root = '/fixture/gate-rapid' + const file = cacheFileFor(root) + + for (let index = 0; index < 40; index += 1) { + saveBootstrapContacts( + root, + makeContacts(2, (contact, contactIndex) => + contactIndex === 0 ? { ...contact, remark: `rev-${index}` } : contact + ) + ) + } + await settle() + + const contacts = JSON.parse(readFileSync(file, 'utf8')).contacts as Contact[] + expect(contacts[0].remark).toBe('rev-39') + }) + + it('does not lose the final state on an A → B → A sequence', async () => { + const root = '/fixture/gate-aba' + const file = cacheFileFor(root) + const stateA = makeContacts(2, (contact) => ({ ...contact, remark: 'A' })) + const stateB = makeContacts(2, (contact) => ({ ...contact, remark: 'B' })) + + saveBootstrapContacts(root, stateA) + await settle() + // 同一防抖窗口内 B 紧接着 A:队列里排着 B,最终内存态又是 A + saveBootstrapContacts(root, stateB) + saveBootstrapContacts(root, stateA) + await settle() + + const contacts = JSON.parse(readFileSync(file, 'utf8')).contacts as Contact[] + expect(contacts.every((contact) => contact.remark === 'A')).toBe(true) + }) + + it('never resurrects writes that were pending when the cache was cleared', async () => { + const root = '/fixture/gate-clear' + const file = cacheFileFor(root) + + saveBootstrapContacts(root, makeContacts(2)) + await settle() + const persisted = snapshotFile(file) + + // 待写入任务还在防抖窗口里就清缓存:不应有任何旧内容被写回 + saveBootstrapContacts( + root, + makeContacts(3, (contact) => ({ ...contact, remark: 'pending' })) + ) + clearBootstrapCache() + await settle() + + const afterClear = snapshotFile(file) + expect(afterClear.ino).toBe(persisted.ino) + expect(afterClear.sha).toBe(persisted.sha) + }) + + it('flushes the newest pending state on quit without being overwritten later', async () => { + const root = '/fixture/gate-flush' + const file = cacheFileFor(root) + + saveBootstrapContacts( + root, + makeContacts(2, (contact) => ({ ...contact, remark: 'old' })) + ) + // 不等待防抖,直接换成新内容再同步刷盘 + saveBootstrapContacts( + root, + makeContacts(2, (contact) => ({ ...contact, remark: 'new' })) + ) + flushBootstrapCacheWritesSync() + + const flushed = JSON.parse(readFileSync(file, 'utf8')).contacts as Contact[] + expect(flushed.every((contact) => contact.remark === 'new')).toBe(true) + expect(tempFilesIn(join(file, '..'))).toHaveLength(0) + + // 已经飞起来的异步写不能把同步刷盘的内容覆盖回去 + await settle() + const afterSettle = JSON.parse(readFileSync(file, 'utf8')).contacts as Contact[] + expect(afterSettle.every((contact) => contact.remark === 'new')).toBe(true) + }) + + it('recovers from a corrupted startup.json and writes again', async () => { + const root = '/fixture/gate-corrupted' + const file = cacheFileFor(root) + + saveBootstrapContacts(root, makeContacts(2)) + await settle() + writeFileSync(file, '{broken', 'utf8') + clearBootstrapCache() + expect(getBootstrapCache(root)).toBeNull() + + saveBootstrapContacts( + root, + makeContacts(2, (contact) => ({ ...contact, remark: 'recovered' })) + ) + await settle() + + const contacts = JSON.parse(readFileSync(file, 'utf8')).contacts as Contact[] + expect(contacts).toHaveLength(2) + expect(contacts[0].remark).toBe('recovered') + }) +}) + +/** + * 可控屏障:让测试精确控制"异步写入已经到达 rename、但还没执行"这个时刻, + * 而不是靠 sleep 或随机并发去碰运气。 + */ +function createDeferred(): { promise: Promise; resolve: () => void } { + let resolve!: () => void + const promise = new Promise((r) => { + resolve = r + }) + return { promise, resolve } +} + +describe('bootstrap cache replace hardening', () => { + beforeEach(() => { + clearBootstrapCache() + vi.restoreAllMocks() + }) + + it('fails the write instead of copy-overwriting on EXDEV, keeping the old cache', async () => { + const root = '/fixture/hard-exdev' + const file = cacheFileFor(root) + const directory = join(file, '..') + + saveBootstrapContacts( + root, + makeContacts(2, (contact) => ({ ...contact, remark: 'OLD' })) + ) + await settle() + const good = snapshotFile(file) + const goodContent = readFileSync(file, 'utf8') + + const renameSpy = vi + .spyOn(fsExtra, 'rename') + .mockRejectedValueOnce( + Object.assign(new Error('EXDEV: cross-device link'), { code: 'EXDEV' }) + ) + const copySpy = vi.spyOn(fsExtra, 'copyFile') + + saveBootstrapContacts( + root, + makeContacts(2, (contact) => ({ ...contact, remark: 'NEW' })) + ) + await settle(1200) + + expect(renameSpy).toHaveBeenCalledTimes(1) + // 关键:跨卷时绝不允许退化成"覆盖复制",那会把旧缓存截断 + expect(copySpy).not.toHaveBeenCalled() + expect(snapshotFile(file).ino).toBe(good.ino) + expect(readFileSync(file, 'utf8')).toBe(goodContent) + expect(tempFilesIn(directory)).toHaveLength(0) + + vi.restoreAllMocks() + // 路径恢复正常后,同一份内容必须能落盘 + saveBootstrapContacts( + root, + makeContacts(2, (contact) => ({ ...contact, remark: 'NEW' })) + ) + await settle() + expect(snapshotFile(file).ino).not.toBe(good.ino) + expect((JSON.parse(readFileSync(file, 'utf8')).contacts as Contact[])[0].remark).toBe('NEW') + }) + + it('fingerprints every persisted field, including unknown ones, but ignores key order', async () => { + const root = '/fixture/hard-fingerprint' + const file = cacheFileFor(root) + + const base = makeContacts(3) + saveBootstrapContacts(root, base) + await settle() + const first = snapshotFile(file) + + // 1) 没在白名单里的新字段:必须触发写盘 + const withExtraField = base.map((contact, index) => + index === 0 ? ({ ...contact, brandNewField: 'first' } as Contact) : contact + ) + saveBootstrapContacts(root, withExtraField) + await settle() + const afterExtra = snapshotFile(file) + expect(afterExtra.ino).not.toBe(first.ino) + expect(readFileSync(file, 'utf8')).toContain('brandNewField') + + // 2) 同字段同值再来一次:不写 + saveBootstrapContacts( + root, + base.map((contact, index) => + index === 0 ? ({ ...contact, brandNewField: 'first' } as Contact) : contact + ) + ) + await settle() + expect(snapshotFile(file).ino).toBe(afterExtra.ino) + + // 3) 字段插入顺序变化、undefined 字段增删:内容等价 → 不写 + const reorderedKeys = base.map((contact, index) => { + if (index !== 0) return { ...contact } + return { + brandNewField: 'first', + m_nsUsrName: contact.m_nsUsrName, + m_nsNickName: contact.m_nsNickName, + md5: contact.md5, + type: contact.type, + avatar: contact.avatar, + wechatNickname: contact.wechatNickname, + remark: contact.remark, + optionalField: undefined + } as Contact + }) + saveBootstrapContacts(root, reorderedKeys) + await settle() + expect(snapshotFile(file).ino).toBe(afterExtra.ino) + + // 4) 可选字段从无到有(真实内容变化):必须写 + saveBootstrapContacts( + root, + reorderedKeys.map((contact, index) => + index === 0 ? ({ ...contact, optionalField: 'now-set' } as Contact) : contact + ) + ) + await settle() + expect(snapshotFile(file).ino).not.toBe(afterExtra.ino) + expect(readFileSync(file, 'utf8')).toContain('now-set') + }) + + it('keeps the newest content when flush happens mid-flight, before rename', async () => { + const root = '/fixture/hard-flush-race' + const file = cacheFileFor(root) + + saveBootstrapContacts( + root, + makeContacts(2, (contact) => ({ ...contact, remark: 'A' })) + ) + await settle() + + const gate = createDeferred() + const entered = createDeferred() + const originalRename = fsExtra.rename as unknown as ( + src: string, + dest: string, + cb: (error: NodeJS.ErrnoException | null) => void + ) => void + const passThrough = (src: string, dest: string): Promise => + new Promise((resolve, reject) => { + originalRename(src, dest, (error) => (error ? reject(error) : resolve())) + }) + + let gated = true + vi.spyOn(fsExtra, 'rename').mockImplementation(((src: string, dest: string) => { + if (!gated) return passThrough(src, dest) + entered.resolve() + return gate.promise.then(() => passThrough(src, dest)) + }) as never) + + // B 进入异步写入:临时文件已写好,卡在 rename 之前 + saveBootstrapContacts( + root, + makeContacts(2, (contact) => ({ ...contact, remark: 'B' })) + ) + await Promise.race([entered.promise, settle(3000)]) + // 此刻再来一份更新的内容,然后模拟退出刷盘 + saveBootstrapContacts( + root, + makeContacts(2, (contact) => ({ ...contact, remark: 'C' })) + ) + flushBootstrapCacheWritesSync() + expect((JSON.parse(readFileSync(file, 'utf8')).contacts as Contact[])[0].remark).toBe('C') + + // 放开屏障:那笔已经飞起来的旧写入绝不能把 C 踩掉 + gated = false + gate.resolve() + await settle(1200) + + const final = JSON.parse(readFileSync(file, 'utf8')).contacts as Contact[] + expect(final.every((contact) => contact.remark === 'C')).toBe(true) + vi.restoreAllMocks() + }) + + it('does not resurrect the cache when it is cleared while a write is mid-flight', async () => { + const root = '/fixture/hard-clear-race' + const file = cacheFileFor(root) + + saveBootstrapContacts( + root, + makeContacts(2, (contact) => ({ ...contact, remark: 'A' })) + ) + await settle() + + const gate = createDeferred() + const entered = createDeferred() + const originalRename = fsExtra.rename as unknown as ( + src: string, + dest: string, + cb: (error: NodeJS.ErrnoException | null) => void + ) => void + + vi.spyOn(fsExtra, 'rename').mockImplementation(((src: string, dest: string) => { + entered.resolve() + return gate.promise.then( + () => + new Promise((resolve, reject) => { + originalRename(src, dest, (error) => (error ? reject(error) : resolve())) + }) as never + ) + }) as never) + + saveBootstrapContacts( + root, + makeContacts(2, (contact) => ({ ...contact, remark: 'B' })) + ) + await Promise.race([entered.promise, settle(3000)]) + + clearBootstrapCache() + gate.resolve() + await settle(1200) + + expect(existsSync(file), '清缓存后落地的旧写入不能把文件复活').toBe(false) + vi.restoreAllMocks() + }) + + it('bounds the retry wait of a whole flush batch', async () => { + const root = '/fixture/hard-flush-budget' + // 造 12 个待写文件:一个启动缓存 + 11 个消息桶 + saveBootstrapContacts(root, makeContacts(2)) + for (let index = 0; index < 11; index += 1) { + saveCachedMessages(root, `md5_${index}`, undefined, undefined, [ + { + id: String(index), + from: 'fixture', + type: '文本', + datetime: '2026-01-01 00:00:00', + content: `fixture-${index}`, + isSender: false + } + ]) + } + + vi.spyOn(fsExtra, 'renameSync').mockImplementation(() => { + throw Object.assign(new Error('EBUSY: locked'), { code: 'EBUSY' }) + }) + + const startedAt = Date.now() + flushBootstrapCacheWritesSync() + const elapsed = Date.now() - startedAt + + // 无预算时 12 个文件 × 460ms ≈ 5.5s;预算 120ms + 12 次首试 + expect(elapsed).toBeLessThan(1200) + vi.restoreAllMocks() + }) +})