Files
37duAutomation/desktop/electron-shell/electron/env-sync.js
T

278 lines
9.0 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 环境包同步(python-env):检查中心机 /api/file-sources/python-env → 下载 → sha256 →
// 解压到 python-env/<version>/ → 更新 current.json → 清理(保留上一版供回滚)。
// 与插件/壳子更新同一套"版本单点 + 校验 + 原子切换"模式;中心机无需改接口(category 为
// 任意字符串,`agent_cli file push --category python-env` 即可发布)。
"use strict";
const fs = require("fs");
const path = require("path");
const crypto = require("crypto");
const AdmZip = require("adm-zip");
const cp = require("./cpclient");
const config = require("./config");
const { versionLt } = require("./crypto");
const { makeLogger } = require("./logger");
const logger = makeLogger("env-sync");
const _STATE = {
installed: false,
version: "",
dir: "",
cloud_available: false,
cloud_version: "",
dl_status: "idle", // idle | downloading | downloaded | failed
dl_received: 0,
dl_total: 0,
dl_pct: 0,
dl_error: "",
checking: false,
};
function envDir() {
return config.envRootDir();
}
// 当前环境包版本(读 current.json;兼容 UTF-8 BOM)
function readCurrent() {
try {
const raw = fs.readFileSync(path.join(envDir(), "current.json"), "utf-8").replace(/^\uFEFF/, "");
const cur = JSON.parse(raw);
return String((cur || {}).version || "").trim();
} catch (e) {
return "";
}
}
// 中心机登记的云端环境包信息
async function cloudInfo() {
if (!config.CONTROLPLANE_URL) return null;
try {
const r = await cp.request("GET", "/api/file-sources/python-env", {
headers: cp.machineHeaders(),
timeout: 8,
});
_STATE.cloud_available = !!(r && r.available);
_STATE.cloud_version = r && r.available ? String(r.version || "") : "";
return r && r.available ? r : null;
} catch (e) {
logger.warning(`获取环境包云端信息失败(离线跳过):${e.message}`);
_STATE.cloud_available = false;
_STATE.cloud_version = "";
return null;
}
}
// 状态(每次从磁盘实时计算安装态;云端信息来自最近一次 cloudInfo)
function status() {
const ver = readCurrent();
const dir = ver ? path.join(envDir(), ver) : "";
const installed = !!dir && fs.existsSync(path.join(dir, "python.exe"));
return {
installed,
version: installed ? ver : "",
dir: installed ? dir : "",
cloud_available: !!_STATE.cloud_available,
cloud_version: _STATE.cloud_version || "",
checking: !!_STATE.checking,
dl: {
status: _STATE.dl_status || "idle",
received: _STATE.dl_received || 0,
total: _STATE.dl_total || 0,
pct: _STATE.dl_pct || 0,
error: _STATE.dl_error || "",
},
};
}
// 刷新状态(供启动后/同步后调用,等价于 status())
function refreshStatus() {
return status();
}
function resetDl() {
_STATE.dl_status = "idle";
_STATE.dl_received = 0;
_STATE.dl_total = 0;
_STATE.dl_pct = 0;
_STATE.dl_error = "";
}
// 下载 zip 到缓存目录(.part → sha256 → rename),返回落盘路径
async function downloadZip(info) {
const url = String(info.url || "").trim();
if (!url) throw new Error("环境包下载地址为空");
const expect = String(info.sha256 || "").toLowerCase();
const filename = String(info.filename || `python-env-${info.version}.zip`).trim();
const cache = path.join(envDir(), "_cache");
fs.mkdirSync(cache, { recursive: true });
const part = path.join(cache, `${filename}.part`);
const zip = path.join(cache, filename);
const sha = crypto.createHash("sha256");
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), 900 * 1000); // 大包 15 分钟上限
const res = await fetch(url, { signal: ctrl.signal, redirect: "follow" });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const total = parseInt(res.headers.get("content-length") || "0", 10);
const out = fs.createWriteStream(part);
let received = 0;
try {
const reader = res.body.getReader();
for (;;) {
const { done, value } = await reader.read();
if (done) break;
out.write(value);
sha.update(value);
received += value.length;
_STATE.dl_received = received;
_STATE.dl_total = total;
_STATE.dl_pct = total ? Math.floor((received * 100) / total) : 0;
}
await new Promise((resolve, reject) => out.end((e) => (e ? reject(e) : resolve())));
} finally {
clearTimeout(timer);
}
const digest = sha.digest("hex");
if (expect && digest !== expect) {
try { fs.unlinkSync(part); } catch (e) { /* 忽略 */ }
throw new Error("环境包 sha256 校验失败");
}
try {
fs.renameSync(part, zip);
} catch (e) {
try { fs.unlinkSync(part); } catch (e2) { /* 忽略 */ }
throw new Error("环境包保存失败");
}
return zip;
}
// 解压 zip → python-env/<version>/,防路径穿越;返回版本目录
async function extractZip(zip, version) {
const target = path.join(envDir(), version);
const tmp = path.join(envDir(), `.${version}.tmp`);
const rm = (p) => {
try { fs.rmSync(p, { recursive: true, force: true }); } catch (e) { /* 忽略 */ }
};
// 清理可能的残留临时目录
rm(tmp);
rm(target);
fs.mkdirSync(tmp, { recursive: true });
const az = new AdmZip(zip);
const entries = az.getEntries();
for (const en of entries) {
const name = en.entryName.replace(/\\/g, "/");
if (name.startsWith("/") || name.split("/").includes("..")) {
throw new Error(`环境包含非法路径: ${name}`);
}
}
az.extractAllTo(tmp, true);
// 冒烟校验:必须含 python.exe + webhost/backend/core/plugin_runner.py
if (!fs.existsSync(path.join(tmp, "python.exe"))) throw new Error("环境包缺少 python.exe");
if (!fs.existsSync(path.join(tmp, "webhost", "backend", "core", "plugin_runner.py"))) {
throw new Error("环境包缺少 plugin_runner.py");
}
// 原子切换(带重试:杀软可能短暂占用新解压文件导致 rename EPERM)
let lastErr = null;
for (let i = 0; i < 3; i++) {
try {
fs.renameSync(tmp, target);
return target;
} catch (e) {
lastErr = e;
await new Promise((r) => setTimeout(r, 500 * (i + 1)));
}
}
throw lastErr || new Error("环境包切换失败");
}
// 切换当前版本 + 清理旧版本(保留上一版供回滚)
function switchCurrent(version) {
const cur = readCurrent();
fs.mkdirSync(envDir(), { recursive: true });
fs.writeFileSync(
path.join(envDir(), "current.json"),
JSON.stringify({ version, updated_at: new Date().toISOString() }, null, 2),
"utf-8"
);
// 清理:保留当前 + 上一版;其余删除(异常残留目录也清)
const keep = new Set([version, cur].filter(Boolean));
try {
for (const name of fs.readdirSync(envDir())) {
if (name === "current.json" || name === "_cache") continue;
if (keep.has(name)) continue;
const p = path.join(envDir(), name);
try { fs.rmSync(p, { recursive: true, force: true }); } catch (e) { /* 忽略 */ }
}
} catch (e) { /* 忽略 */ }
}
let _syncing = false;
// 手动/启动同步:有更新的环境包则下载并切换;无则保持现状
async function checkAndSync(force = false) {
if (_syncing) return { ok: false, reason: "busy" };
_syncing = true;
_STATE.checking = true;
resetDl();
try {
const info = await cloudInfo();
if (!info) return { ok: false, reason: "no-cloud" };
const cur = readCurrent();
if (!force && cur && !versionLt(cur, info.version) && fs.existsSync(path.join(envDir(), cur, "python.exe"))) {
refreshStatus();
return { ok: true, current: true, version: cur };
}
_STATE.dl_status = "downloading";
logger.info(`开始下载环境包 ${info.version}:${info.url}`);
const zip = await downloadZip(info);
_STATE.dl_status = "downloaded";
_STATE.dl_pct = 100;
const dir = await extractZip(zip, info.version);
switchCurrent(info.version);
_STATE.dl_status = "idle";
logger.info(`环境包 ${info.version} 安装完成:${dir}`);
refreshStatus();
return { ok: true, current: false, version: info.version };
} catch (e) {
logger.warning(`环境包同步失败:${e.message}`);
_STATE.dl_status = "failed";
_STATE.dl_error = e.message;
return { ok: false, reason: "error", error: e.message };
} finally {
_syncing = false;
_STATE.checking = false;
}
}
// 回滚到上一版(current.json 前一个版本目录;无则报错)
function rollback() {
const cur = readCurrent();
const versions = [];
try {
for (const name of fs.readdirSync(envDir())) {
if (name === "current.json" || name === "_cache") continue;
if (fs.existsSync(path.join(envDir(), name, "python.exe"))) versions.push(name);
}
} catch (e) { /* 忽略 */ }
const target = versions
.filter((v) => v !== cur)
.sort((a, b) => (versionLt(a, b) ? 1 : -1))[0];
if (!target) return { ok: false, error: "无可回滚版本" };
switchCurrent(target);
refreshStatus();
return { ok: true, version: target };
}
module.exports = {
status,
refreshStatus,
checkAndSync,
rollback,
readCurrent,
envDir,
extractZip,
switchCurrent,
};