Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions changelog.d/sentry-deploy-20260908.fix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
project: update
修复源码更新中途被打断会留下残缺文件、启动报错的问题
154 changes: 154 additions & 0 deletions frontend/electron/services/repositoryService.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
import * as fs from 'fs'
import * as os from 'os'
import * as path from 'path'

import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'

import { RepositoryService } from './repositoryService'

vi.mock('electron', () => ({ app: { getVersion: () => '5.5.0-beta.3' } }))
vi.mock('./logger', () => ({
getLogger: () => ({
error: vi.fn(),
warn: vi.fn(),
info: vi.fn(),
verbose: vi.fn(),
debug: vi.fn(),
silly: vi.fn(),
}),
}))

/**
* ESM 下 vi.spyOn 改不了模块导出,这里把 fs 整体包一层,
* 用 hooks 在单条用例里注入失败或记录调用顺序。
*/
const hooks: {
copyFileSync?: (src: string, dst: string) => void
mkdirSync?: (target: string) => void
} = {}

vi.mock('fs', async importOriginal => {
const actual = await importOriginal<typeof import('fs')>()
const wrapped = {
...actual,
copyFileSync: (src: fs.PathLike, dst: fs.PathLike, mode?: number) => {
hooks.copyFileSync?.(String(src), String(dst))
return actual.copyFileSync(src, dst, mode)
},
mkdirSync: (target: fs.PathLike, opts?: fs.MakeDirectoryOptions & { recursive: true }) => {
hooks.mkdirSync?.(String(target))
return actual.mkdirSync(target, opts)
},
}
return { ...wrapped, default: wrapped }
})

/**
* copyToRoot 是私有方法,这里直接取出来调用:它是源码部署的唯一落盘出口,
* 中断后留下残缺 app/ 正是 #544 的根因,值得单独立测。
*/
type CopyToRoot = () => Promise<void>

let appRoot = ''

const makeCopyToRoot = (): CopyToRoot => {
const svc = new RepositoryService(appRoot, {} as never, 'dev')
return (svc as unknown as { copyToRoot: CopyToRoot }).copyToRoot.bind(svc)
}

/** 在 repo/ 下造一份可部署的源码 */
const writeRepo = (appContent: string) => {
const repo = path.join(appRoot, 'repo')
fs.mkdirSync(path.join(repo, 'app', 'core'), { recursive: true })
fs.mkdirSync(path.join(repo, 'res'), { recursive: true })
fs.mkdirSync(path.join(repo, '.git'), { recursive: true })
fs.writeFileSync(path.join(repo, 'app', 'core', 'timer.py'), appContent)
fs.writeFileSync(path.join(repo, 'app', '__init__.py'), appContent)
fs.writeFileSync(path.join(repo, 'res', 'version.json'), '{}')
fs.writeFileSync(path.join(repo, '.git', 'HEAD'), 'ref: refs/heads/dev')
fs.writeFileSync(path.join(repo, 'main.py'), appContent)
}

/** 在 appRoot 下造一份「上一版」已部署的源码 */
const writeExistingDeploy = () => {
fs.mkdirSync(path.join(appRoot, 'app', 'core'), { recursive: true })
fs.writeFileSync(path.join(appRoot, 'app', 'core', 'timer.py'), 'old')
fs.writeFileSync(path.join(appRoot, 'app', '__init__.py'), 'old')
fs.writeFileSync(path.join(appRoot, 'app', 'legacy.py'), 'old-only')
}

beforeEach(() => {
appRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'mas-repo-'))
})

afterEach(() => {
delete hooks.copyFileSync
delete hooks.mkdirSync
fs.rmSync(appRoot, { recursive: true, force: true })
})

describe('copyToRoot', () => {
it('正常部署:内容换新,上一版残留被清掉,不留 .new / .old', async () => {
writeRepo('new')
writeExistingDeploy()

await makeCopyToRoot()()

expect(fs.readFileSync(path.join(appRoot, 'app', 'core', 'timer.py'), 'utf-8')).toBe('new')
expect(fs.existsSync(path.join(appRoot, 'app', 'legacy.py'))).toBe(false)
expect(fs.readFileSync(path.join(appRoot, '.git', 'HEAD'), 'utf-8')).toBe('ref: refs/heads/dev')
expect(fs.existsSync(path.join(appRoot, 'app.new'))).toBe(false)
expect(fs.existsSync(path.join(appRoot, 'app.old'))).toBe(false)
})

it('复制中途失败:原有 app/ 完整回滚,不会留下残缺目录', async () => {
writeRepo('new')
writeExistingDeploy()

// 复制 app/ 的第二个文件时抛错,模拟杀软/占用导致的 EPERM
let calls = 0
hooks.copyFileSync = () => {
calls += 1
if (calls === 2) {
throw Object.assign(new Error('EPERM: operation not permitted'), {
code: 'EPERM',
})
}
}

await expect(makeCopyToRoot()()).rejects.toThrow('EPERM')

// 关键断言:旧版本原封不动,而不是被删掉一半
expect(fs.readFileSync(path.join(appRoot, 'app', 'core', 'timer.py'), 'utf-8')).toBe('old')
expect(fs.readFileSync(path.join(appRoot, 'app', '__init__.py'), 'utf-8')).toBe('old')
expect(fs.readFileSync(path.join(appRoot, 'app', 'legacy.py'), 'utf-8')).toBe('old-only')
expect(fs.existsSync(path.join(appRoot, 'app.new'))).toBe(false)
expect(fs.existsSync(path.join(appRoot, 'app.old'))).toBe(false)
})

it('.git 排在 app / res 之后,避免「版本已最新但源码残缺」', async () => {
writeRepo('new')

const order: string[] = []
hooks.mkdirSync = target => {
const name = path.basename(target)
if (name === 'app.new' || name === 'res.new' || name === '.git.new') {
order.push(name)
}
}

await makeCopyToRoot()()

expect(order).toEqual(['app.new', 'res.new', '.git.new'])
})

it('目标此前不存在时也能部署,且不留 .old', async () => {
writeRepo('new')

await makeCopyToRoot()()

expect(fs.readFileSync(path.join(appRoot, 'main.py'), 'utf-8')).toBe('new')
expect(fs.existsSync(path.join(appRoot, 'main.py.old'))).toBe(false)
expect(fs.existsSync(path.join(appRoot, 'main.py.new'))).toBe(false)
})
})
65 changes: 52 additions & 13 deletions frontend/electron/services/repositoryService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -645,14 +645,17 @@ export class RepositoryService {
* 复制文件到根目录
*/
private async copyToRoot(): Promise<void> {
// .git 放在最后: 中途失败时不要让「版本已最新」的假象盖住残缺的源码。
// 否则后端 get_git_version() 会认为 HEAD 已是最新,标题栏不再提示
// 「后端有更新」,用户失去重新拉取的入口。
const itemsToCopy = [
'.git',
'app',
'res',
'main.py',
'requirements.txt',
'LICENSE',
'README.md',
'.git',
]

for (const item of itemsToCopy) {
Expand All @@ -664,32 +667,68 @@ export class RepositoryService {
continue
}

try {
// 删除目标文件/目录
if (fs.existsSync(dstPath)) {
if (fs.statSync(dstPath).isDirectory()) {
fs.rmSync(dstPath, { recursive: true, force: true })
} else {
fs.unlinkSync(dstPath)
}
}
const stagePath = `${dstPath}.new`
const backupPath = `${dstPath}.old`
let backedUp = false

// 复制文件/目录
try {
// 1. 先把新内容整个落到 <item>.new。这一步耗时最长、也最容易被
// 杀软/占用/进程被杀打断,但失败时 <item> 还原封不动。
this.removePath(stagePath)
this.removePath(backupPath)
if (fs.statSync(srcPath).isDirectory()) {
this.copyDirectory(srcPath, dstPath)
this.copyDirectory(srcPath, stagePath)
} else {
fs.copyFileSync(srcPath, dstPath)
fs.copyFileSync(srcPath, stagePath)
}

// 2. 换上。rename 是元数据操作,暴露的空窗远小于逐文件复制的耗时。
if (fs.existsSync(dstPath)) {
fs.renameSync(dstPath, backupPath)
backedUp = true
}
fs.renameSync(stagePath, dstPath)

// 3. 换成功了才删旧的
this.removePath(backupPath)
backedUp = false

logger.info(`复制完成: ${item}`)
} catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error)
logger.error(`复制失败: ${item}, 错误信息: ${errorMsg}`)
try {
// 回滚: 把原内容换回去,不要留下一个残缺的 app/
if (backedUp) {
this.removePath(dstPath)
fs.renameSync(backupPath, dstPath)
logger.warn(`已回滚到原内容: ${item}`)
}
this.removePath(stagePath)
} catch (rollbackError) {
const rollbackMsg =
rollbackError instanceof Error ? rollbackError.message : String(rollbackError)
logger.error(`回滚失败: ${item}, 错误信息: ${rollbackMsg},原内容保留在: ${backupPath}`)
}
throw error
}
}
}

/**
* 删除文件或目录, 不存在时静默返回
*/
private removePath(target: string): void {
if (!fs.existsSync(target)) {
return
}
if (fs.statSync(target).isDirectory()) {
fs.rmSync(target, { recursive: true, force: true })
} else {
fs.unlinkSync(target)
}
}

/**
* 递归复制目录
*/
Expand Down
3 changes: 2 additions & 1 deletion res/version.json
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,8 @@
"MFW专项 准备运行环境确实找不到 uv 时改为给出可照做的中文提示,写明 uv.exe 该放的完整路径,以及本机已有完整 Python 3.12 时可改设环境变量跳过下载 by [@qiyinxi](https://github.com/qiyinxi)",
"MFW专项 修复脚本侧强制停止任务(如 MaaEnd 分辨率不达标时的强停)被记成「任务完成」的问题:现在被强停的任务按失败记录,本轮剩余任务不再投递,不会再出现整轮一件事没做却报成全部成功 by [@qiyinxi](https://github.com/qiyinxi)",
"MAA专项 修复 MAA 卡死后不会被判定为超时、任务一直挂着的问题:MAA 每隔一段时间输出的日志停滞提示被当成任务仍在推进,把超时计时反复重置,剿灭等超时阈值长于提示间隔的模式永远等不到超时;现已识别新旧两版 MAA 的该提示,MAA 的五种界面语言均生效 by [@qiyinxi](https://github.com/qiyinxi)",
"MAA专项 修复关闭理智作战后活动关优先任务一并从任务队列中消失的问题 by [@1w1w11w1](https://github.com/1w1w11w1)"
"MAA专项 修复关闭理智作战后活动关优先任务一并从任务队列中消失的问题 by [@1w1w11w1](https://github.com/1w1w11w1)",
"更新流程 修复源码部署中途被打断会留下残缺源码、下次启动报「找不到模块」甚至后端起不来的问题:原来是先删掉整个 app 目录再逐文件复制,删完之后、复制完成之前任何中断都会留下缺文件的目录;现在改为先把新版本整个放到一旁、再整体换上,失败自动换回原来的版本"
]
},
"v5.5.0-beta.2": {
Expand Down