Repository navigation
Expand file tree
/
Copy pathpython-runtime.cjs
More file actions
287 lines (266 loc) · 14.9 KB
/
Copy pathpython-runtime.cjs
File metadata and controls
287 lines (266 loc) · 14.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
"use strict";
/* python-runtime.cjs —— 统一 Python 运行时解析与健康探测(主进程热模块 v1)。
*
* 背景:config.json 的 python_path 是安装期写下的绝对路径;托管资源升级/清理(versions/<id> 被退役)
* 后它变成死路径,旧实现只读这一个值,主桥/更新器 spawn ENOENT 永久卡死、SessionStart 无修复路径
* (复现 evidence/WP01/repro-stale-path.py;WP02 已让 SessionStart 按 python_path_source 自愈到稳定入口)。
* 本模块把「从哪里找 Python、哪个能用」收进一个有界、单飞、带缓存与冷却的解析器:
*
* 候选序:config python_path(custom/unknown 一律先试,仅该路径)→ 宿主托管稳定入口
* (<runtimeDir>/../preinstalled-tools/<release>/bin/zcode-python,bin 由宿主维护、跨资源版本存活,
* HOST-CONTRACT HC1/HC2)→ 平台默认名(win: python→python3→py -3;其它: python3→python→py -3)。
*
* 契约(WP03 gate):
* - 一切执行走候选本体;托管入口存在性再以同目录 .shim 描述文件的 target 校验(只校验存在性,
* 不解析执行 target——绕过 shim 会丢 PYTHONNOUSERSITE/PIP_CONSTRAINT/PYTHONHOME 合同,HC4)。
* - 探针 spawn `<candidate> -B -X utf8 -c <固定代码>`:版本 >=3.8、sqlite3 内存查询、UTF-8 回包;
* stdout 上限/总超时/并发单飞;错误分类成稳定错误码(PYTHON_NOT_FOUND / PYTHON_SPAWN_FAILED /
* PYTHON_VERSION_LOW / SQLITE_UNAVAILABLE / PYTHON_STATE_UNKNOWN)。
* - 成功短 TTL、失败冷却;config.json 与入口文件身份变化即失效;绝不因为缓存把失败永久化,
* 也不在稳态每帧 spawn 探针。
* - 解析失败返回 { executable: null, error },调用方按各自既有 stats_error/fail-open 契约呈现,
* 本模块不写 config、不重试业务请求、不杀任何进程。
*
* 热换:无顶层副作用,inject-main 经 createPythonRuntime() 装配,hotReloadMainModules 同拍重建。
*/
const fs = require("fs");
const path = require("path");
const { spawn } = require("child_process");
const PROBE_TIMEOUT_MS = 8000;
const PROBE_MAX_BUFFER = 64 * 1024;
const OK_TTL_MS = 30 * 60 * 1000; // 成功缓存:稳态不反复探针
const FAIL_COOLDOWN_MS = 60 * 1000; // 失败冷却:冷却后允许重探(入口恢复可自愈)
const MANAGED_RELEASES = ("production preview").split(" ");
const MIN_VERSION = [3, 8, 0];
// 探针代码:3.8 可解析;不触碰真实数据库、不联网、不导入重库。严格读「最后一行 JSON」。
const PROBE_CODE = "import json,sqlite3,sys\n"
+ "ok=True\n"
+ "try:\n"
+ " con=sqlite3.connect(':memory:')\n"
+ " ok=bool(con.execute('select 1+1').fetchone()[0]==2)\n"
+ " con.close()\n"
+ "except Exception:\n"
+ " ok=False\n"
+ "print(json.dumps({'v':list(sys.version_info[:3]),'sq':ok,'u8':'\\u6d4b'.encode('utf-8').decode('utf-8')=='\\u6d4b'}))";
function versionAtLeast(actual, min) {
for (let i = 0; i < 3; i++) {
const a = actual[i] || 0, b = min[i] || 0;
if (a !== b) return a > b;
}
return true;
}
function classifySpawnError(err) {
const code = err && (err.code || err.errno);
if (code === "ENOENT" || code === "ENOTDIR" || code === -4058) return { code: "PYTHON_NOT_FOUND", detail: String(code) };
if (code === "EACCES" || code === "EINVAL" || code === "EISDIR" || code === "EMFILE") return { code: "PYTHON_SPAWN_FAILED", detail: String(code) };
return { code: "PYTHON_SPAWN_FAILED", detail: String(code || (err && err.message) || "unknown") };
}
/* 托管入口候选:从运行目录锚点派生(<runtimeDir>/../preinstalled-tools/<release>/bin/zcode-python)。
* 运行目录恒在 <home>/.zcode 下(install/overlay_install 两链一致),--dev 指到仓库时父目录里
* 没有 preinstalled-tools,候选自然为空——不硬编码 HOME、不猜版本目录、不遍历磁盘(HC1/HC2)。 */
function managedEntryCandidates(runtimeDir, platform) {
const out = [];
if (!runtimeDir) return out;
const exeName = platform === "win32" ? "zcode-python.exe" : "zcode-python";
for (const release of MANAGED_RELEASES) {
const entry = path.join(path.dirname(path.resolve(runtimeDir)), "preinstalled-tools", release, "bin", exeName);
// shim 描述文件与 exe 同名去后缀:bin 里是 zcode-python.exe + zcode-python.shim(不能拼成 .exe.shim)
const shim = path.join(path.dirname(entry), exeName.replace(/\.exe$/, "") + ".shim");
let ok = false;
try {
if (fs.statSync(entry).isFile()) {
// .shim 的 target 只做存在性校验:bin 条目与资源本体的一致性证据,不执行其内容(HC4)
try {
const desc = JSON.parse(fs.readFileSync(shim, "utf8"));
ok = !!(desc && typeof desc.target === "string" && desc.target && fs.statSync(desc.target).isFile());
} catch (e) { ok = false; }
}
} catch (e) { ok = false; }
if (ok) out.push({ executable: entry, prefixArgs: [], source: "managed", identity: "managed:" + release });
}
return out;
}
function configCandidates(configPath) {
const out = [];
if (configPath) {
try {
const cfg = JSON.parse(fs.readFileSync(configPath, "utf8"));
const p = cfg && typeof cfg.python_path === "string" ? cfg.python_path.trim() : "";
if (p) {
const stale = !fs.existsSync(p);
out.push({ executable: p, prefixArgs: [], source: "config", identity: "config:" + p,
stale, reason: stale ? "PYTHON_PATH_STALE" : undefined });
}
out.configSource = cfg && cfg.python_path_source === "auto" ? "auto" : (cfg.python_path_source === "manual" ? "manual" : undefined);
} catch (e) { /* 损坏/缺失配置:按无 config 候选继续(不重建,不写回) */ }
}
return out;
}
function defaultCandidates(platform) {
const names = platform === "win32"
? [["python"], ["python3"], ["py", "-3"]]
: [["python3"], ["python"]];
return names.map((parts) => ({
executable: parts[0], prefixArgs: parts.slice(1), source: "default",
identity: "default:" + parts.join(" "),
}));
}
function buildCandidates(runtimeDir, configPath, platform) {
return [].concat(configCandidates(configPath), managedEntryCandidates(runtimeDir, platform), defaultCandidates(platform));
}
function createPythonRuntime(options) {
const o = options || {};
const runtimeDir = o.runtimeDir || null;
const configPath = o.configPath || null;
const platform = o.platform || process.platform;
const spawnFn = o.spawn || spawn;
const log = typeof o.log === "function" ? o.log : function () {};
const okTtlMs = o.okTtlMs || OK_TTL_MS;
const failCooldownMs = o.failCooldownMs || FAIL_COOLDOWN_MS;
const probeTimeoutMs = o.probeTimeoutMs || PROBE_TIMEOUT_MS;
const cache = new Map(); // identity -> {state:"ok"|"fail", at, probe}
const inflight = new Map(); // identity -> Promise(单飞)
let resolved = null; // 最近一次成功解析(含 epoch)
let epoch = 0;
let disposed = false;
function spawnProbe(candidate) {
return new Promise((resolve) => {
let child;
const timer = setTimeout(() => {
try { if (child) child.kill(); } catch (e) { }
resolve({ ok: false, error: { code: "PYTHON_STATE_UNKNOWN", detail: "probe-timeout" } });
}, probeTimeoutMs);
if (typeof timer.unref === "function") timer.unref();
try {
child = spawnFn(candidate.executable, [].concat(candidate.prefixArgs, ["-B", "-X", "utf8", "-c", PROBE_CODE]),
{ windowsHide: true, shell: false });
} catch (err) {
clearTimeout(timer);
resolve({ ok: false, error: classifySpawnError(err) });
return;
}
let out = "", errText = "", settled = false, killedByLimit = false;
child.stdout.on("data", (d) => {
out += d;
if (out.length > PROBE_MAX_BUFFER) { killedByLimit = true; try { child.kill(); } catch (e) { } }
});
child.stderr.on("data", (d) => {
errText += d;
if (errText.length > PROBE_MAX_BUFFER) { killedByLimit = true; try { child.kill(); } catch (e) { } }
});
child.on("error", (err) => {
if (settled) return; settled = true; clearTimeout(timer);
resolve({ ok: false, error: classifySpawnError(err) });
});
child.on("close", (code) => {
if (settled) return; settled = true; clearTimeout(timer);
if (killedByLimit) { resolve({ ok: false, error: { code: "PYTHON_STATE_UNKNOWN", detail: "probe-output-limit" } }); return; }
// Windows 商店存根:进程成功退出码 9009、零输出——按 SPAWN_FAILED 分类,不当成探针失败重试无限循环
if (code === 9009) { resolve({ ok: false, error: { code: "PYTHON_SPAWN_FAILED", detail: "exit-9009" } }); return; }
if (code !== 0) { resolve({ ok: false, error: { code: "PYTHON_STATE_UNKNOWN", detail: "exit-" + code } }); return; }
const lines = String(out).trim().split(/\r?\n/);
const last = lines.length ? lines[lines.length - 1] : "";
let parsed;
try { parsed = JSON.parse(last); } catch (e) { parsed = null; }
if (!parsed || !Array.isArray(parsed.v)) { resolve({ ok: false, error: { code: "PYTHON_STATE_UNKNOWN", detail: "bad-probe-json" } }); return; }
if (!versionAtLeast(parsed.v, MIN_VERSION)) { resolve({ ok: false, error: { code: "PYTHON_VERSION_LOW", detail: parsed.v.join(".") } }); return; }
if (!parsed.sq) { resolve({ ok: false, error: { code: "SQLITE_UNAVAILABLE", detail: "sqlite3" } }); return; }
if (!parsed.u8) { resolve({ ok: false, error: { code: "PYTHON_STATE_UNKNOWN", detail: "utf8" } }); return; }
resolve({ ok: true, probe: { version: parsed.v, sqlite: true, utf8: true } });
});
});
}
function cachedOk(candidate, now) {
const hit = cache.get(candidate.identity);
return !!(hit && hit.state === "ok" && now - hit.at < okTtlMs) ? hit : null;
}
function inCooldown(candidate, now) {
const hit = cache.get(candidate.identity);
return !!(hit && hit.state === "fail" && now - hit.at < failCooldownMs);
}
async function probeCandidate(candidate, now) {
const hit = cachedOk(candidate, now);
if (hit) return { ok: true, probe: hit.probe, cached: true };
let pending = inflight.get(candidate.identity);
if (pending) return pending;
pending = spawnProbe(candidate).then((result) => {
inflight.delete(candidate.identity);
if (result.ok) cache.set(candidate.identity, { state: "ok", at: Date.now(), probe: result.probe });
else cache.set(candidate.identity, { state: "fail", at: Date.now(), error: result.error });
return result;
}, (err) => {
inflight.delete(candidate.identity);
return { ok: false, error: classifySpawnError(err) };
});
inflight.set(candidate.identity, pending);
return pending;
}
async function resolve(reason) {
if (disposed) return { executable: null, prefixArgs: [], source: "none", epoch, error: { code: "PYTHON_STATE_UNKNOWN", detail: "disposed" } };
const now = Date.now();
const candidates = buildCandidates(runtimeDir, configPath, platform);
const tried = [];
let configFailed = false;
for (const candidate of candidates) {
if (candidate.source === "config" && (candidate.stale || inCooldown(candidate, now))) configFailed = true;
if (candidate.stale) { tried.push({ identity: candidate.identity, skipped: candidate.reason }); continue; }
if (inCooldown(candidate, now)) { tried.push({ identity: candidate.identity, skipped: "cooldown" }); continue; }
const result = await probeCandidate(candidate, now);
if (result.ok) {
if (!resolved || resolved.executable !== candidate.executable
|| JSON.stringify(resolved.prefixArgs) !== JSON.stringify(candidate.prefixArgs)) {
epoch += 1;
}
// 规格 §4:config 候选(用户显式值)失败/不可用而由后继候选回退胜出时,结果必须
// 可归因——source 标 "fallback",via 保留真实胜出来源(消费方按需展示)。
const isFallback = configFailed && candidate.source !== "config";
resolved = {
executable: candidate.executable, prefixArgs: candidate.prefixArgs,
source: isFallback ? "fallback" : candidate.source, via: candidate.source,
probe: result.probe, epoch,
reason: reason || candidate.reason || candidate.source, resolvedAt: now, cached: !!result.cached,
};
log("python runtime resolved:", candidate.source, candidate.executable, "epoch", epoch);
return Object.assign({ attempts: tried }, resolved);
}
tried.push({ identity: candidate.identity, error: result.error });
}
// 全部候选失败:有界聚合错误;resolved 保留旧值供调用方参考,但 epoch 不变、不再假装健康
return {
executable: null, prefixArgs: [], source: "none", epoch,
error: { code: "PYTHON_NOT_FOUND", detail: "no-probe-passed" }, attempts: tried,
lastResolved: resolved ? { executable: resolved.executable, source: resolved.source, epoch: resolved.epoch } : null,
};
}
function currentSync() {
// 同步视图:热路径 spawn 用。未解析(冷启动窗)返回 null,调用方回退旧口径
// (config python_path || 平台默认名)——与旧行为一致,不改错不猜。
return resolved ? { executable: resolved.executable, prefixArgs: resolved.prefixArgs, source: resolved.source, epoch: resolved.epoch } : null;
}
function status() {
// 脱敏诊断视图:给 doctor/诊断用。只含来源、错误码与缓存状态,不含 PATH/环境。
const entries = [];
for (const [identity, hit] of cache) {
entries.push({ identity: identity, state: hit.state, ageMs: Date.now() - hit.at, error: hit.error || null });
}
return { resolved: resolved ? { source: resolved.source, epoch: resolved.epoch, version: resolved.probe && resolved.probe.version } : null, probes: entries };
}
function invalidate(reason) {
// 业务 spawn 遇到「解释器未启动」类失败时由调用方触发:清探测缓存并撤销当前决议——
// currentSync 立即回 None,调用方走旧口径(config||平台默认名,旧行为),同时由调用方
// 发起一次异步 resolve 重探(单飞)。否则 resolved 会把启动期决议钉死到重启为止,
// 托管资源会话中轮换 / SessionStart 改写 python_path 都无法会话中期自愈(A8-F1)。
cache.clear();
resolved = null;
log("python runtime cache invalidated:", reason || "manual");
}
function dispose() {
disposed = true;
cache.clear();
inflight.clear();
resolved = null;
}
return { resolve, probe: spawnProbe, currentSync, status, invalidate, dispose,
managedEntryCandidates: () => managedEntryCandidates(runtimeDir, platform) };
}
module.exports = { createPythonRuntime, buildCandidates, managedEntryCandidates, versionAtLeast, classifySpawnError, PROBE_CODE, MIN_VERSION };