@mebular/mcp 0.1.1 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/mebular.mjs +504 -3
- package/package.json +8 -3
- package/scripts/publish-manifest.mjs +7 -6
- package/src/admin.mjs +26 -4
- package/src/client.mjs +3 -1
- package/src/cloud-switch.mjs +21 -2
- package/src/runtime-current.mjs +240 -0
- package/src/runtime-installer.mjs +1040 -0
- package/src/runtime-layout.mjs +44 -0
- package/src/runtime-providers.mjs +378 -0
- package/src/runtime-service.mjs +812 -0
- package/src/runtime-supervisor.mjs +1673 -0
- package/src/runtime-update.mjs +1074 -0
- package/src/runtime-upgrade.mjs +887 -0
- package/src/serve.mjs +61 -10
- package/src/server.mjs +2 -1
- package/src/service-control.mjs +21 -3
- package/src/service-loader.mjs +84 -0
- package/src/version.mjs +8 -0
|
@@ -0,0 +1,1040 @@
|
|
|
1
|
+
// 共享 Runtime 安装器(Phase 4a/5a):把固定版本的 `@mebular/core` 安装到
|
|
2
|
+
// `<cloudRoot>/runtime/<version>/`,注册 `kind:shared` provider,并写 current 指针。
|
|
3
|
+
//
|
|
4
|
+
// 边界(本阶段):
|
|
5
|
+
// - 只安装文件 + provider + current;不停止/重启正在运行的 daemon/service;
|
|
6
|
+
// - service 生命周期在 runtime-service.mjs,受控升级在 runtime-upgrade.mjs;
|
|
7
|
+
// - 来源固定 npm registry 的 `@mebular/core@<version>`,不接受 URL/tarball;
|
|
8
|
+
// - 全流程离线可测:npm spawn / 时钟 / PID 存活 / provider 注册均可注入。
|
|
9
|
+
//
|
|
10
|
+
// 失败映射(稳定 reason):offline / registry_unreachable / http_error /
|
|
11
|
+
// integrity_mismatch / disk_full / permission_denied / npm_missing /
|
|
12
|
+
// unsupported_version / cancelled;另有 install_locked、provider_registration_failed
|
|
13
|
+
// 与兜底 install_failed。日志/错误只返回脱敏后的片段,不含 token。
|
|
14
|
+
|
|
15
|
+
import { randomBytes } from 'node:crypto';
|
|
16
|
+
import { spawn } from 'node:child_process';
|
|
17
|
+
import { existsSync, readFileSync, rmSync } from 'node:fs';
|
|
18
|
+
import { mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';
|
|
19
|
+
import { homedir } from 'node:os';
|
|
20
|
+
import { basename, join, resolve } from 'node:path';
|
|
21
|
+
import { APP_VERSION } from './version.mjs';
|
|
22
|
+
import { cloudError, pidAlive, resolveCloudRoot } from './profiles.mjs';
|
|
23
|
+
import { registerExclusiveRuntimeProvider } from './runtime-providers.mjs';
|
|
24
|
+
import {
|
|
25
|
+
RUNTIME_CLI_RELATIVE,
|
|
26
|
+
RUNTIME_PACKAGE_NAME,
|
|
27
|
+
RUNTIME_PACKAGE_RELATIVE,
|
|
28
|
+
assertRuntimeVersion,
|
|
29
|
+
manualRuntimeInstallCommand,
|
|
30
|
+
runtimeRootPath,
|
|
31
|
+
runtimeVersionPath,
|
|
32
|
+
sharedRuntimeCliPath,
|
|
33
|
+
} from './runtime-layout.mjs';
|
|
34
|
+
import { readRuntimeCurrent, writeRuntimeCurrent } from './runtime-current.mjs';
|
|
35
|
+
|
|
36
|
+
export {
|
|
37
|
+
RUNTIME_CLI_RELATIVE,
|
|
38
|
+
RUNTIME_DIR,
|
|
39
|
+
RUNTIME_PACKAGE_NAME,
|
|
40
|
+
RUNTIME_PACKAGE_RELATIVE,
|
|
41
|
+
assertRuntimeVersion,
|
|
42
|
+
manualRuntimeInstallCommand,
|
|
43
|
+
runtimeRootPath,
|
|
44
|
+
runtimeVersionPath,
|
|
45
|
+
sharedRuntimeCliPath,
|
|
46
|
+
} from './runtime-layout.mjs';
|
|
47
|
+
|
|
48
|
+
export const RUNTIME_INSTALL_LOCK_FILE = 'install.lock';
|
|
49
|
+
export const RUNTIME_INSTALL_TIMEOUT_MS = 10 * 60_000;
|
|
50
|
+
export const RUNTIME_KILL_GRACE_MS = 500;
|
|
51
|
+
export const RUNTIME_SHARED_CAPABILITIES = Object.freeze(['serve']);
|
|
52
|
+
export const RUNTIME_STAGING_PREFIX = '.tmp-install-';
|
|
53
|
+
export const RUNTIME_BACKUP_PREFIX = '.backup-';
|
|
54
|
+
|
|
55
|
+
export const RUNTIME_INSTALL_REASONS = Object.freeze([
|
|
56
|
+
'offline',
|
|
57
|
+
'registry_unreachable',
|
|
58
|
+
'http_error',
|
|
59
|
+
'integrity_mismatch',
|
|
60
|
+
'disk_full',
|
|
61
|
+
'permission_denied',
|
|
62
|
+
'npm_missing',
|
|
63
|
+
'unsupported_version',
|
|
64
|
+
'cancelled',
|
|
65
|
+
]);
|
|
66
|
+
|
|
67
|
+
const INSTALL_REASON_SET = new Set(RUNTIME_INSTALL_REASONS);
|
|
68
|
+
const MAX_VERSION_LENGTH = 128;
|
|
69
|
+
const MAX_LOG_BYTES = 64 * 1024;
|
|
70
|
+
|
|
71
|
+
export function runtimeInstallLockPath(root) {
|
|
72
|
+
return join(runtimeRootPath(root), RUNTIME_INSTALL_LOCK_FILE);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function safeRequestedVersion(value) {
|
|
76
|
+
if (typeof value !== 'string') return value === undefined || value === null ? null : String(value).slice(0, MAX_VERSION_LENGTH);
|
|
77
|
+
return value.trim().slice(0, MAX_VERSION_LENGTH);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function timestampId(now) {
|
|
81
|
+
const raw = typeof now === 'string' ? now : new Date().toISOString();
|
|
82
|
+
return raw.replace(/[^0-9A-Za-z_-]/g, '-');
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function randomSuffix() {
|
|
86
|
+
return randomBytes(6).toString('hex');
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* 固定 npm 安装命令:`npm install --prefix <temp> --ignore-scripts --no-audit --no-fund
|
|
91
|
+
* @mebular/core@<version>`。只有 Windows 的 npm.cmd 允许 shell;参数全部由本模块构造。
|
|
92
|
+
*/
|
|
93
|
+
export function buildNpmInstallCommand({
|
|
94
|
+
version,
|
|
95
|
+
prefix,
|
|
96
|
+
platform = process.platform,
|
|
97
|
+
npmPath = null,
|
|
98
|
+
} = {}) {
|
|
99
|
+
const safeVersion = assertRuntimeVersion(version);
|
|
100
|
+
if (typeof prefix !== 'string' || prefix.length === 0) {
|
|
101
|
+
throw cloudError('install_failed', '缺少 npm 安装 prefix');
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
let command;
|
|
105
|
+
let leading = [];
|
|
106
|
+
let shell = false;
|
|
107
|
+
const rawPath = typeof npmPath === 'string' && npmPath.trim().length > 0 ? npmPath.trim() : null;
|
|
108
|
+
|
|
109
|
+
if (rawPath !== null) {
|
|
110
|
+
const name = platform === 'win32'
|
|
111
|
+
? (rawPath.split(/[\\/]/).pop() ?? rawPath)
|
|
112
|
+
: basename(rawPath);
|
|
113
|
+
if (/\.(mjs|cjs|js)$/i.test(name)) {
|
|
114
|
+
command = process.execPath;
|
|
115
|
+
leading = [rawPath];
|
|
116
|
+
} else if (platform === 'win32' && (/\.(cmd|bat)$/i.test(name) || name === 'npm')) {
|
|
117
|
+
command = /\.(cmd|bat)$/i.test(name) ? rawPath : `${rawPath}.cmd`;
|
|
118
|
+
shell = true;
|
|
119
|
+
} else {
|
|
120
|
+
command = rawPath;
|
|
121
|
+
}
|
|
122
|
+
} else if (platform === 'win32') {
|
|
123
|
+
// Windows 固定走 npm.cmd + shell;不依赖 npm_execpath(可能是 .js,也可能来自其他包管理器)。
|
|
124
|
+
command = 'npm.cmd';
|
|
125
|
+
shell = true;
|
|
126
|
+
} else {
|
|
127
|
+
command = 'npm';
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const args = [
|
|
131
|
+
...leading,
|
|
132
|
+
'install',
|
|
133
|
+
'--prefix',
|
|
134
|
+
prefix,
|
|
135
|
+
'--ignore-scripts',
|
|
136
|
+
'--no-audit',
|
|
137
|
+
'--no-fund',
|
|
138
|
+
`${RUNTIME_PACKAGE_NAME}@${safeVersion}`,
|
|
139
|
+
];
|
|
140
|
+
|
|
141
|
+
// shell=true(仅 Windows npm.cmd)时 Node 只做空格拼接:含空格的 path/参数必须自行加引号。
|
|
142
|
+
const cmdQuote = (value) => (/[\s&|<>^]/.test(value) ? `"${value.replace(/"/g, '""')}"` : value);
|
|
143
|
+
const spawnArgs = shell ? args.map((entry) => cmdQuote(String(entry))) : args;
|
|
144
|
+
const spawnCommand = shell && /\s/.test(command) ? `"${command}"` : command;
|
|
145
|
+
|
|
146
|
+
return {
|
|
147
|
+
command: spawnCommand,
|
|
148
|
+
args: spawnArgs,
|
|
149
|
+
shell,
|
|
150
|
+
version: safeVersion,
|
|
151
|
+
display: `npm install --prefix ${prefix} --ignore-scripts --no-audit --no-fund ${RUNTIME_PACKAGE_NAME}@${safeVersion}`,
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** 脱敏 npm 输出:去掉 registry 凭据、token/password/auth 赋值与 URL userinfo。 */
|
|
156
|
+
export function sanitizeRuntimeInstallLog(value) {
|
|
157
|
+
return String(value ?? '')
|
|
158
|
+
.replace(/(_authToken|_auth|password|passwd|secret|authorization|bearer|token)\s*[=:]\s*[^\s,;]+/gi, '$1=[redacted]')
|
|
159
|
+
.replace(/(https?:\/\/)[^/\s@]+@/gi, '$1[redacted]@')
|
|
160
|
+
.replace(/(^|\s)\/\/[^:\s/]+:[^@\s]+@/g, '$1//[redacted]@');
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function firstUsefulLine(text) {
|
|
164
|
+
const line = String(text ?? '')
|
|
165
|
+
.split(/\r?\n/)
|
|
166
|
+
.map((entry) => entry.trim())
|
|
167
|
+
.find((entry) => entry.length > 0);
|
|
168
|
+
return line === undefined ? null : sanitizeRuntimeInstallLog(line).slice(0, 300);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function statusFromText(text) {
|
|
172
|
+
const explicit = /\b(?:E|HTTP\s*)([45]\d{2})\b/i.exec(text);
|
|
173
|
+
if (explicit) return Number(explicit[1]);
|
|
174
|
+
const plain = /(?:^|\s)([45]\d{2})(?:\s|$)/m.exec(text);
|
|
175
|
+
return plain ? Number(plain[1]) : null;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* 从 spawn 错误 / 退出码 / npm stderr 稳定分类。
|
|
180
|
+
* 返回 `{ reason, status?, detail? }`;detail 已脱敏。
|
|
181
|
+
*/
|
|
182
|
+
export function classifyNpmInstallFailure({ spawnError = null, exitCode = null, stdout = '', stderr = '' } = {}) {
|
|
183
|
+
const text = `${stderr}\n${stdout}`;
|
|
184
|
+
const lower = text.toLowerCase();
|
|
185
|
+
const spawnCode = typeof spawnError?.code === 'string' ? spawnError.code.toUpperCase() : '';
|
|
186
|
+
|
|
187
|
+
const result = (reason, extra = {}) => ({
|
|
188
|
+
reason,
|
|
189
|
+
detail: firstUsefulLine(text) ?? (spawnError?.message ? sanitizeRuntimeInstallLog(spawnError.message).slice(0, 300) : null),
|
|
190
|
+
...extra,
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
if (spawnError) {
|
|
194
|
+
if (spawnCode === 'ENOENT') return result('npm_missing');
|
|
195
|
+
if (spawnCode === 'EACCES' || spawnCode === 'EPERM') return result('permission_denied');
|
|
196
|
+
if (spawnCode === 'ENOSPC') return result('disk_full');
|
|
197
|
+
if (spawnCode === 'ETIMEDOUT') return result('registry_unreachable');
|
|
198
|
+
if (spawnCode === 'ECONNREFUSED' || spawnCode === 'ECONNRESET') {
|
|
199
|
+
return result('registry_unreachable');
|
|
200
|
+
}
|
|
201
|
+
if (spawnCode === 'ENOTFOUND' || spawnCode === 'EAI_AGAIN'
|
|
202
|
+
|| spawnCode === 'ENETUNREACH' || spawnCode === 'EHOSTUNREACH') {
|
|
203
|
+
return result('offline');
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
if (/eintegrity|integrity checksum|integrity.*(?:fail|mismatch)|shasum|checksum.*(?:fail|mismatch)/i.test(text)) {
|
|
208
|
+
return result('integrity_mismatch');
|
|
209
|
+
}
|
|
210
|
+
if (/enospc|no space left on device|disk (?:is )?full|not enough space/i.test(text)) {
|
|
211
|
+
return result('disk_full');
|
|
212
|
+
}
|
|
213
|
+
if (/eacces|eperm|permission denied|operation not permitted|access is denied/i.test(text)) {
|
|
214
|
+
return result('permission_denied');
|
|
215
|
+
}
|
|
216
|
+
if (exitCode === 127 || /npm: command not found|npm: not found|'npm' is not recognized|not recognized as an internal/i.test(text)) {
|
|
217
|
+
return result('npm_missing');
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const status = statusFromText(text);
|
|
221
|
+
if (/etarget|no matching version|version not found/i.test(text)) {
|
|
222
|
+
return result('unsupported_version', { status: 404 });
|
|
223
|
+
}
|
|
224
|
+
if (/e404|404 not found|not in this registry/i.test(text)) {
|
|
225
|
+
return result('http_error', { status: 404 });
|
|
226
|
+
}
|
|
227
|
+
if (/e401|401 unauthorized|e403|403 forbidden|unauthorized|forbidden/i.test(text)) {
|
|
228
|
+
return result('http_error', { status: status ?? (/401/.test(text) ? 401 : 403) });
|
|
229
|
+
}
|
|
230
|
+
if (status !== null || /http error|response code|bad gateway|service unavailable|internal server error/i.test(text)) {
|
|
231
|
+
return result('http_error', { status });
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
if (/enotfound|eai_again|eai_fail|getaddrinfo|enotreach|network is unreachable|offline|dns lookup/i.test(lower)) {
|
|
235
|
+
return result('offline');
|
|
236
|
+
}
|
|
237
|
+
if (/econnrefused|econnreset|etimedout|esockettimedout|socket hang up|network request.*failed|request to .* failed|registry.*unreachable/i.test(lower)) {
|
|
238
|
+
return result('registry_unreachable');
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// npm 非零退出但无法进一步分类:归入 registry/http 失败,仍给出稳定 reason。
|
|
242
|
+
return result(exitCode === 0 ? 'install_failed' : 'http_error', { status });
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function classifyFsError(error) {
|
|
246
|
+
const code = typeof error?.code === 'string' ? error.code.toUpperCase() : '';
|
|
247
|
+
if (code === 'ENOSPC') return 'disk_full';
|
|
248
|
+
if (code === 'EACCES' || code === 'EPERM' || code === 'EROFS') return 'permission_denied';
|
|
249
|
+
return 'install_failed';
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function failureError(reason, message, extra = {}) {
|
|
253
|
+
return cloudError(INSTALL_REASON_SET.has(reason) || reason === 'install_locked' || reason === 'install_failed'
|
|
254
|
+
? reason
|
|
255
|
+
: 'install_failed', message, extra);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
async function readJsonFile(path) {
|
|
259
|
+
try {
|
|
260
|
+
return JSON.parse(await readFile(path, 'utf-8'));
|
|
261
|
+
} catch {
|
|
262
|
+
return null;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function readJsonFileSync(path) {
|
|
267
|
+
try {
|
|
268
|
+
return JSON.parse(readFileSync(path, 'utf-8'));
|
|
269
|
+
} catch {
|
|
270
|
+
return null;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** 检查一个 npm prefix 是否就是目标共享 runtime(版本 + CLI 路径存在)。 */
|
|
275
|
+
export async function inspectInstalledRuntime(directory, version) {
|
|
276
|
+
const packagePath = join(directory, RUNTIME_PACKAGE_RELATIVE);
|
|
277
|
+
const cliPath = join(directory, RUNTIME_CLI_RELATIVE);
|
|
278
|
+
let raw;
|
|
279
|
+
try {
|
|
280
|
+
raw = await readFile(packagePath, 'utf-8');
|
|
281
|
+
} catch (error) {
|
|
282
|
+
if (error?.code === 'ENOENT') {
|
|
283
|
+
return { ok: false, reason: 'missing', detail: 'package_json_missing', runtimePath: directory, cliPath };
|
|
284
|
+
}
|
|
285
|
+
return {
|
|
286
|
+
ok: false,
|
|
287
|
+
reason: classifyFsError(error),
|
|
288
|
+
detail: `package_json_unreadable:${error?.code ?? 'error'}`,
|
|
289
|
+
runtimePath: directory,
|
|
290
|
+
cliPath,
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
let manifest;
|
|
295
|
+
try {
|
|
296
|
+
manifest = JSON.parse(raw);
|
|
297
|
+
} catch {
|
|
298
|
+
return { ok: false, reason: 'integrity_mismatch', detail: 'package_json_invalid', runtimePath: directory, cliPath };
|
|
299
|
+
}
|
|
300
|
+
if (manifest?.name !== undefined && manifest.name !== RUNTIME_PACKAGE_NAME) {
|
|
301
|
+
return {
|
|
302
|
+
ok: false,
|
|
303
|
+
reason: 'integrity_mismatch',
|
|
304
|
+
detail: 'package_name_mismatch',
|
|
305
|
+
installedName: typeof manifest.name === 'string' ? manifest.name.slice(0, 80) : null,
|
|
306
|
+
runtimePath: directory,
|
|
307
|
+
cliPath,
|
|
308
|
+
};
|
|
309
|
+
}
|
|
310
|
+
if (manifest?.version !== version) {
|
|
311
|
+
return {
|
|
312
|
+
ok: false,
|
|
313
|
+
reason: 'integrity_mismatch',
|
|
314
|
+
detail: 'version_mismatch',
|
|
315
|
+
installedVersion: typeof manifest.version === 'string' ? manifest.version.slice(0, MAX_VERSION_LENGTH) : null,
|
|
316
|
+
runtimePath: directory,
|
|
317
|
+
cliPath,
|
|
318
|
+
};
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
try {
|
|
322
|
+
const info = await stat(cliPath);
|
|
323
|
+
if (!info.isFile()) {
|
|
324
|
+
return { ok: false, reason: 'integrity_mismatch', detail: 'cli_not_file', runtimePath: directory, cliPath };
|
|
325
|
+
}
|
|
326
|
+
} catch (error) {
|
|
327
|
+
if (error?.code === 'ENOENT') {
|
|
328
|
+
return { ok: false, reason: 'integrity_mismatch', detail: 'cli_missing', runtimePath: directory, cliPath };
|
|
329
|
+
}
|
|
330
|
+
return {
|
|
331
|
+
ok: false,
|
|
332
|
+
reason: classifyFsError(error),
|
|
333
|
+
detail: `cli_unreadable:${error?.code ?? 'error'}`,
|
|
334
|
+
runtimePath: directory,
|
|
335
|
+
cliPath,
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
return { ok: true, packageVersion: manifest.version, runtimePath: directory, cliPath };
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
async function acquireInstallLock({ root, version, reinstall, now, pidAliveFn }) {
|
|
343
|
+
const runtimeDir = runtimeRootPath(root);
|
|
344
|
+
await mkdir(runtimeDir, { recursive: true });
|
|
345
|
+
const path = runtimeInstallLockPath(root);
|
|
346
|
+
const startedAt = now();
|
|
347
|
+
const payload = JSON.stringify({
|
|
348
|
+
pid: process.pid,
|
|
349
|
+
startedAt,
|
|
350
|
+
version,
|
|
351
|
+
mode: reinstall ? 'reinstall' : 'install',
|
|
352
|
+
});
|
|
353
|
+
const acquire = () => writeFile(path, payload, { mode: 0o600, flag: 'wx' });
|
|
354
|
+
|
|
355
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
356
|
+
try {
|
|
357
|
+
await acquire();
|
|
358
|
+
return {
|
|
359
|
+
path,
|
|
360
|
+
startedAt,
|
|
361
|
+
async release() {
|
|
362
|
+
try {
|
|
363
|
+
const held = await readJsonFile(path);
|
|
364
|
+
if (held?.pid === process.pid && held?.startedAt === startedAt) {
|
|
365
|
+
await rm(path, { force: true });
|
|
366
|
+
}
|
|
367
|
+
} catch {
|
|
368
|
+
// 已释放/被回收
|
|
369
|
+
}
|
|
370
|
+
},
|
|
371
|
+
};
|
|
372
|
+
} catch (error) {
|
|
373
|
+
if (error?.code !== 'EEXIST') throw error;
|
|
374
|
+
const held = await readJsonFile(path);
|
|
375
|
+
const holderPid = Number(held?.pid);
|
|
376
|
+
if (Number.isInteger(holderPid) && holderPid > 0 && pidAliveFn(holderPid)) {
|
|
377
|
+
throw failureError('install_locked', `另一个进程正在安装 runtime(pid ${holderPid});请稍后重试`, {
|
|
378
|
+
holderPid,
|
|
379
|
+
lockPath: path,
|
|
380
|
+
});
|
|
381
|
+
}
|
|
382
|
+
await rm(path, { force: true }).catch(() => undefined);
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
throw failureError('install_locked', 'runtime 安装锁被占用;请稍后重试', { lockPath: path });
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
async function removeStaleStaging(runtimeDir) {
|
|
389
|
+
let entries;
|
|
390
|
+
try {
|
|
391
|
+
entries = await readdir(runtimeDir, { withFileTypes: true });
|
|
392
|
+
} catch {
|
|
393
|
+
return;
|
|
394
|
+
}
|
|
395
|
+
await Promise.all(entries
|
|
396
|
+
.filter((entry) => entry.name.startsWith(RUNTIME_STAGING_PREFIX))
|
|
397
|
+
.map((entry) => rm(join(runtimeDir, entry.name), { recursive: true, force: true }).catch(() => undefined)));
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
function installExitCleanup(state) {
|
|
401
|
+
const onExit = () => {
|
|
402
|
+
if (state.tempPath) {
|
|
403
|
+
try { rmSync(state.tempPath, { recursive: true, force: true }); } catch { /* 进程退出清理尽力而为 */ }
|
|
404
|
+
}
|
|
405
|
+
const lockPath = state.lockPath ?? (state.root ? runtimeInstallLockPath(state.root) : null);
|
|
406
|
+
if (lockPath) {
|
|
407
|
+
try {
|
|
408
|
+
const held = readJsonFileSync(lockPath);
|
|
409
|
+
// 本进程是唯一可能持有该 PID 的安装者;进程退出时直接回收自己的锁。
|
|
410
|
+
if (Number(held?.pid) === process.pid) rmSync(lockPath, { force: true });
|
|
411
|
+
} catch {
|
|
412
|
+
// 已释放/被回收
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
};
|
|
416
|
+
process.once('exit', onExit);
|
|
417
|
+
return () => process.removeListener('exit', onExit);
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
function runNpmInstall({
|
|
421
|
+
command,
|
|
422
|
+
args,
|
|
423
|
+
shell,
|
|
424
|
+
cwd,
|
|
425
|
+
env,
|
|
426
|
+
timeoutMs,
|
|
427
|
+
killGraceMs,
|
|
428
|
+
signal,
|
|
429
|
+
spawnFn,
|
|
430
|
+
}) {
|
|
431
|
+
return new Promise((resolvePromise) => {
|
|
432
|
+
let child = null;
|
|
433
|
+
let settled = false;
|
|
434
|
+
let stdout = '';
|
|
435
|
+
let stderr = '';
|
|
436
|
+
let timer = null;
|
|
437
|
+
let killTimer = null;
|
|
438
|
+
let forceTimer = null;
|
|
439
|
+
let exitTimer = null;
|
|
440
|
+
let aborted = false;
|
|
441
|
+
let timedOut = false;
|
|
442
|
+
let killSignals = [];
|
|
443
|
+
|
|
444
|
+
const append = (current, chunk) => (current + String(chunk)).slice(-MAX_LOG_BYTES);
|
|
445
|
+
const cleanup = () => {
|
|
446
|
+
if (timer !== null) clearTimeout(timer);
|
|
447
|
+
if (killTimer !== null) clearTimeout(killTimer);
|
|
448
|
+
if (forceTimer !== null) clearTimeout(forceTimer);
|
|
449
|
+
if (exitTimer !== null) clearTimeout(exitTimer);
|
|
450
|
+
if (signal && typeof signal.removeEventListener === 'function') signal.removeEventListener('abort', onAbort);
|
|
451
|
+
};
|
|
452
|
+
const finish = (result) => {
|
|
453
|
+
if (settled) return;
|
|
454
|
+
settled = true;
|
|
455
|
+
cleanup();
|
|
456
|
+
resolvePromise({ stdout, stderr, aborted, timedOut, killSignals, ...result });
|
|
457
|
+
};
|
|
458
|
+
const killChild = (name) => {
|
|
459
|
+
if (!child || typeof child.kill !== 'function') return;
|
|
460
|
+
killSignals = [...killSignals, name];
|
|
461
|
+
try { child.kill(name); } catch { /* 已退出 */ }
|
|
462
|
+
};
|
|
463
|
+
const terminate = () => {
|
|
464
|
+
killChild('SIGTERM');
|
|
465
|
+
if (killTimer === null) {
|
|
466
|
+
killTimer = setTimeout(() => killChild('SIGKILL'), Math.max(0, killGraceMs));
|
|
467
|
+
}
|
|
468
|
+
if (forceTimer === null) {
|
|
469
|
+
forceTimer = setTimeout(() => finish({ exitCode: null, signal: null, forced: true }), Math.max(0, killGraceMs) + 500);
|
|
470
|
+
}
|
|
471
|
+
};
|
|
472
|
+
const onAbort = () => {
|
|
473
|
+
if (settled) return;
|
|
474
|
+
aborted = true;
|
|
475
|
+
terminate();
|
|
476
|
+
};
|
|
477
|
+
|
|
478
|
+
if (signal?.aborted) {
|
|
479
|
+
aborted = true;
|
|
480
|
+
finish({ exitCode: null, signal: null });
|
|
481
|
+
return;
|
|
482
|
+
}
|
|
483
|
+
if (signal && typeof signal.addEventListener === 'function') {
|
|
484
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
try {
|
|
488
|
+
child = spawnFn(command, args, {
|
|
489
|
+
cwd,
|
|
490
|
+
env,
|
|
491
|
+
shell: shell === true,
|
|
492
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
493
|
+
windowsHide: true,
|
|
494
|
+
});
|
|
495
|
+
} catch (error) {
|
|
496
|
+
finish({ spawnError: error, exitCode: null, signal: null });
|
|
497
|
+
return;
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
const listen = (emitter, event, handler) => {
|
|
501
|
+
if (typeof emitter?.once === 'function') emitter.once(event, handler);
|
|
502
|
+
else if (typeof emitter?.on === 'function') emitter.on(event, handler);
|
|
503
|
+
};
|
|
504
|
+
child.stdout?.on?.('data', (chunk) => { stdout = append(stdout, chunk); });
|
|
505
|
+
child.stderr?.on?.('data', (chunk) => { stderr = append(stderr, chunk); });
|
|
506
|
+
listen(child, 'error', (error) => finish({ spawnError: error, exitCode: null, signal: null }));
|
|
507
|
+
listen(child, 'close', (code, name) => finish({ exitCode: code, signal: name }));
|
|
508
|
+
listen(child, 'exit', (code, name) => {
|
|
509
|
+
if (!child.stdout && !child.stderr) {
|
|
510
|
+
finish({ exitCode: code, signal: name });
|
|
511
|
+
return;
|
|
512
|
+
}
|
|
513
|
+
// 真实 child 随后会发 close;假 child/异常平台只发 exit 时也给一个短暂兜底。
|
|
514
|
+
if (exitTimer === null) {
|
|
515
|
+
exitTimer = setTimeout(() => finish({ exitCode: code, signal: name }), 100);
|
|
516
|
+
}
|
|
517
|
+
});
|
|
518
|
+
|
|
519
|
+
if (Number.isFinite(timeoutMs) && timeoutMs > 0) {
|
|
520
|
+
timer = setTimeout(() => {
|
|
521
|
+
timedOut = true;
|
|
522
|
+
terminate();
|
|
523
|
+
}, timeoutMs);
|
|
524
|
+
}
|
|
525
|
+
});
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
async function detectRunning({ root, home, pidAliveFn }) {
|
|
529
|
+
const active = readJsonFileSync(join(root, 'active.lock'));
|
|
530
|
+
const activePid = Number(active?.pid);
|
|
531
|
+
const activeAlive = Number.isInteger(activePid) && activePid > 0 && pidAliveFn(activePid);
|
|
532
|
+
const homeLock = readJsonFileSync(join(home, 'lock'));
|
|
533
|
+
const homePid = Number(homeLock?.pid);
|
|
534
|
+
const homeAlive = Number.isInteger(homePid) && homePid > 0 && pidAliveFn(homePid);
|
|
535
|
+
const runtime = readJsonFileSync(join(home, 'runtime.json'));
|
|
536
|
+
const runtimePid = Number(runtime?.pid);
|
|
537
|
+
const runtimeAlive = Number.isInteger(runtimePid) && runtimePid > 0 && pidAliveFn(runtimePid);
|
|
538
|
+
return {
|
|
539
|
+
daemonRunning: activeAlive || homeAlive || runtimeAlive,
|
|
540
|
+
serviceRunning: null,
|
|
541
|
+
runningDetected: activeAlive || homeAlive || runtimeAlive,
|
|
542
|
+
pid: runtimeAlive ? runtimePid : (homeAlive ? homePid : (activeAlive ? activePid : null)),
|
|
543
|
+
version: typeof runtime?.version === 'string' ? runtime.version : null,
|
|
544
|
+
};
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
function publicProvider(provider, meta = {}) {
|
|
548
|
+
if (!provider) return null;
|
|
549
|
+
return {
|
|
550
|
+
id: provider.id ?? null,
|
|
551
|
+
kind: provider.kind,
|
|
552
|
+
path: provider.path,
|
|
553
|
+
version: provider.version ?? null,
|
|
554
|
+
capabilities: Array.isArray(provider.capabilities) ? [...provider.capabilities] : [],
|
|
555
|
+
...meta,
|
|
556
|
+
};
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
function successResult(context, fields = {}) {
|
|
560
|
+
return {
|
|
561
|
+
ok: true,
|
|
562
|
+
code: null,
|
|
563
|
+
reason: null,
|
|
564
|
+
message: null,
|
|
565
|
+
command: context.command,
|
|
566
|
+
root: context.root,
|
|
567
|
+
cloudRoot: context.root,
|
|
568
|
+
runtimeRoot: context.runtimeRoot,
|
|
569
|
+
version: context.version,
|
|
570
|
+
runtimePath: context.runtimePath,
|
|
571
|
+
cliPath: context.cliPath,
|
|
572
|
+
manualCommand: context.manualCommand,
|
|
573
|
+
reinstall: context.reinstall,
|
|
574
|
+
reused: false,
|
|
575
|
+
changed: true,
|
|
576
|
+
previous: null,
|
|
577
|
+
backupPath: null,
|
|
578
|
+
runtimeInstalled: true,
|
|
579
|
+
providerRegistered: false,
|
|
580
|
+
provider: null,
|
|
581
|
+
current: null,
|
|
582
|
+
restartRequired: false,
|
|
583
|
+
running: null,
|
|
584
|
+
note: null,
|
|
585
|
+
warnings: [],
|
|
586
|
+
checkedAt: context.checkedAt,
|
|
587
|
+
...fields,
|
|
588
|
+
};
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
function failureResult(context, error, fields = {}) {
|
|
592
|
+
const code = typeof error?.code === 'string' && error.code.length > 0 ? error.code : 'install_failed';
|
|
593
|
+
return {
|
|
594
|
+
ok: false,
|
|
595
|
+
code,
|
|
596
|
+
reason: code,
|
|
597
|
+
message: sanitizeRuntimeInstallLog(fields.message ?? error?.message ?? String(error)).slice(0, 600),
|
|
598
|
+
command: context.command,
|
|
599
|
+
root: context.root,
|
|
600
|
+
cloudRoot: context.root,
|
|
601
|
+
runtimeRoot: context.runtimeRoot,
|
|
602
|
+
version: context.version,
|
|
603
|
+
requestedVersion: context.requestedVersion,
|
|
604
|
+
runtimePath: context.runtimePath,
|
|
605
|
+
cliPath: context.cliPath,
|
|
606
|
+
manualCommand: context.manualCommand,
|
|
607
|
+
reinstall: context.reinstall,
|
|
608
|
+
reused: false,
|
|
609
|
+
changed: false,
|
|
610
|
+
previous: fields.previous ?? null,
|
|
611
|
+
backupPath: fields.backupPath ?? null,
|
|
612
|
+
runtimeInstalled: fields.runtimeInstalled === true,
|
|
613
|
+
providerRegistered: fields.providerRegistered === true,
|
|
614
|
+
provider: fields.provider ?? null,
|
|
615
|
+
current: fields.current ?? null,
|
|
616
|
+
targetPreserved: fields.targetPreserved === true,
|
|
617
|
+
restartRequired: false,
|
|
618
|
+
running: fields.running ?? null,
|
|
619
|
+
detail: fields.detail ?? error?.detail ?? null,
|
|
620
|
+
status: fields.status ?? error?.status ?? null,
|
|
621
|
+
installedVersion: fields.installedVersion ?? error?.installedVersion ?? null,
|
|
622
|
+
logTail: fields.logTail ?? error?.logTail ?? null,
|
|
623
|
+
timedOut: fields.timedOut === true,
|
|
624
|
+
providerErrorCode: fields.providerErrorCode ?? null,
|
|
625
|
+
currentWriteFailed: fields.currentWriteFailed === true,
|
|
626
|
+
holderPid: fields.holderPid ?? error?.holderPid ?? null,
|
|
627
|
+
previousPreserved: fields.previousPreserved ?? error?.previousPreserved ?? null,
|
|
628
|
+
warnings: fields.warnings ?? [],
|
|
629
|
+
checkedAt: context.checkedAt,
|
|
630
|
+
};
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
/**
|
|
634
|
+
* 安装/重装共享 runtime。
|
|
635
|
+
*
|
|
636
|
+
* `reinstall: true` 时即使目标版本已存在也会重新下载/校验/原子替换,并把旧目录
|
|
637
|
+
* rename 为 backup 保留;失败时旧目录/旧 provider 保持不变。
|
|
638
|
+
*/
|
|
639
|
+
export async function installRuntime(options = {}) {
|
|
640
|
+
const {
|
|
641
|
+
version: requestedVersion = APP_VERSION,
|
|
642
|
+
reinstall = false,
|
|
643
|
+
root: explicitRoot,
|
|
644
|
+
home: explicitHome,
|
|
645
|
+
env = process.env,
|
|
646
|
+
userHome = homedir(),
|
|
647
|
+
platform = process.platform,
|
|
648
|
+
npmPath = null,
|
|
649
|
+
spawnFn = spawn,
|
|
650
|
+
timeoutMs = RUNTIME_INSTALL_TIMEOUT_MS,
|
|
651
|
+
killGraceMs = RUNTIME_KILL_GRACE_MS,
|
|
652
|
+
signal = null,
|
|
653
|
+
pidAliveFn = pidAlive,
|
|
654
|
+
registerProviderFn = registerExclusiveRuntimeProvider,
|
|
655
|
+
detectRunningFn = null,
|
|
656
|
+
now = () => new Date().toISOString(),
|
|
657
|
+
} = options;
|
|
658
|
+
|
|
659
|
+
const command = reinstall ? 'reinstall' : 'install';
|
|
660
|
+
const checkedAt = now();
|
|
661
|
+
const context = {
|
|
662
|
+
command,
|
|
663
|
+
root: null,
|
|
664
|
+
runtimeRoot: null,
|
|
665
|
+
version: null,
|
|
666
|
+
requestedVersion: safeRequestedVersion(requestedVersion),
|
|
667
|
+
runtimePath: null,
|
|
668
|
+
cliPath: null,
|
|
669
|
+
manualCommand: null,
|
|
670
|
+
reinstall: reinstall === true,
|
|
671
|
+
checkedAt,
|
|
672
|
+
};
|
|
673
|
+
|
|
674
|
+
try {
|
|
675
|
+
context.version = assertRuntimeVersion(requestedVersion);
|
|
676
|
+
context.manualCommand = manualRuntimeInstallCommand(context.version);
|
|
677
|
+
} catch (error) {
|
|
678
|
+
context.version = context.requestedVersion;
|
|
679
|
+
return failureResult(context, error, { targetPreserved: false });
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
let cloud;
|
|
683
|
+
try {
|
|
684
|
+
if (typeof explicitRoot === 'string' && explicitRoot.trim().length > 0) {
|
|
685
|
+
cloud = { available: true, root: resolve(explicitRoot.trim()) };
|
|
686
|
+
} else {
|
|
687
|
+
cloud = resolveCloudRoot({ env, userHome });
|
|
688
|
+
}
|
|
689
|
+
if (!cloud.available) {
|
|
690
|
+
throw failureError('install_failed', `runtime 上下文不可用(${cloud.reason ?? 'cloud_unavailable'})`);
|
|
691
|
+
}
|
|
692
|
+
} catch (error) {
|
|
693
|
+
return failureResult(context, error, { targetPreserved: false });
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
const root = cloud.root;
|
|
697
|
+
const home = typeof explicitHome === 'string' && explicitHome.trim().length > 0 ? resolve(explicitHome) : root;
|
|
698
|
+
const runtimeDir = runtimeRootPath(root);
|
|
699
|
+
const targetPath = runtimeVersionPath(root, context.version);
|
|
700
|
+
const cliPath = sharedRuntimeCliPath(root, context.version);
|
|
701
|
+
context.root = root;
|
|
702
|
+
context.runtimeRoot = runtimeDir;
|
|
703
|
+
context.runtimePath = targetPath;
|
|
704
|
+
context.cliPath = cliPath;
|
|
705
|
+
|
|
706
|
+
const state = { root, tempPath: null, lockPath: null, startedAt: null };
|
|
707
|
+
let lock = null;
|
|
708
|
+
let removeExitCleanup = null;
|
|
709
|
+
let backupPath = null;
|
|
710
|
+
let previous = null;
|
|
711
|
+
let runtimeInstalled = false;
|
|
712
|
+
|
|
713
|
+
const detect = async () => {
|
|
714
|
+
if (typeof detectRunningFn === 'function') return detectRunningFn({ root, home, pidAliveFn });
|
|
715
|
+
return detectRunning({ root, home, pidAliveFn });
|
|
716
|
+
};
|
|
717
|
+
const detectSafe = async () => {
|
|
718
|
+
try {
|
|
719
|
+
return await detect();
|
|
720
|
+
} catch (error) {
|
|
721
|
+
return {
|
|
722
|
+
daemonRunning: null,
|
|
723
|
+
serviceRunning: null,
|
|
724
|
+
runningDetected: false,
|
|
725
|
+
error: sanitizeRuntimeInstallLog(error?.message ?? error).slice(0, 300),
|
|
726
|
+
};
|
|
727
|
+
}
|
|
728
|
+
};
|
|
729
|
+
|
|
730
|
+
const registerProvider = async () => {
|
|
731
|
+
try {
|
|
732
|
+
const registration = await registerProviderFn(root, {
|
|
733
|
+
kind: 'shared',
|
|
734
|
+
path: cliPath,
|
|
735
|
+
version: context.version,
|
|
736
|
+
capabilities: RUNTIME_SHARED_CAPABILITIES,
|
|
737
|
+
}, { now: now() });
|
|
738
|
+
return {
|
|
739
|
+
ok: true,
|
|
740
|
+
registration,
|
|
741
|
+
provider: publicProvider(registration?.provider, {
|
|
742
|
+
created: registration?.created === true,
|
|
743
|
+
unchanged: registration?.unchanged === true,
|
|
744
|
+
replaced: Array.isArray(registration?.replaced)
|
|
745
|
+
? registration.replaced.map((entry) => ({ kind: entry.kind, path: entry.path, version: entry.version ?? null }))
|
|
746
|
+
: [],
|
|
747
|
+
}),
|
|
748
|
+
};
|
|
749
|
+
} catch (error) {
|
|
750
|
+
return { ok: false, error };
|
|
751
|
+
}
|
|
752
|
+
};
|
|
753
|
+
|
|
754
|
+
// 4a/4b 共用语义:安装成功后写 current。已存在的同路径/同版本 current 保留 installedAt,
|
|
755
|
+
// 避免幂等 install 每次刷新“安装时间”;新安装使用本次 checkedAt。
|
|
756
|
+
const persistCurrent = async () => {
|
|
757
|
+
try {
|
|
758
|
+
const previous = await readRuntimeCurrent(root);
|
|
759
|
+
const installedAt = previous.usable
|
|
760
|
+
&& previous.current?.runtimePath === targetPath
|
|
761
|
+
&& previous.current?.version === context.version
|
|
762
|
+
? previous.current.installedAt
|
|
763
|
+
: checkedAt;
|
|
764
|
+
const current = await writeRuntimeCurrent(root, {
|
|
765
|
+
version: context.version,
|
|
766
|
+
runtimePath: targetPath,
|
|
767
|
+
cliPath,
|
|
768
|
+
provider: 'shared',
|
|
769
|
+
owner: 'shared',
|
|
770
|
+
installedAt,
|
|
771
|
+
}, { now: checkedAt });
|
|
772
|
+
return { ok: true, current };
|
|
773
|
+
} catch (error) {
|
|
774
|
+
return { ok: false, error };
|
|
775
|
+
}
|
|
776
|
+
};
|
|
777
|
+
|
|
778
|
+
try {
|
|
779
|
+
removeExitCleanup = installExitCleanup(state);
|
|
780
|
+
lock = await acquireInstallLock({
|
|
781
|
+
root,
|
|
782
|
+
version: context.version,
|
|
783
|
+
reinstall: reinstall === true,
|
|
784
|
+
now,
|
|
785
|
+
pidAliveFn,
|
|
786
|
+
});
|
|
787
|
+
state.lockPath = lock.path;
|
|
788
|
+
state.startedAt = lock.startedAt;
|
|
789
|
+
|
|
790
|
+
await removeStaleStaging(runtimeDir);
|
|
791
|
+
|
|
792
|
+
const targetExistsBeforeInstall = existsSync(targetPath);
|
|
793
|
+
const existing = await inspectInstalledRuntime(targetPath, context.version);
|
|
794
|
+
if (existing.ok) {
|
|
795
|
+
previous = { version: existing.packageVersion, runtimePath: targetPath, valid: true };
|
|
796
|
+
} else if (targetExistsBeforeInstall) {
|
|
797
|
+
previous = { version: null, runtimePath: targetPath, valid: false };
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
// install 对已存在且完整的同版本是幂等的;reinstall 明确覆盖。
|
|
801
|
+
if (!reinstall && existing.ok) {
|
|
802
|
+
const registration = await registerProvider();
|
|
803
|
+
if (!registration.ok) {
|
|
804
|
+
const error = cloudError(
|
|
805
|
+
'provider_registration_failed',
|
|
806
|
+
'runtime 已存在且可用,但 provider 注册失败;请修复 runtime-providers.json 后重试',
|
|
807
|
+
{ detail: sanitizeRuntimeInstallLog(registration.error?.message ?? registration.error).slice(0, 300) },
|
|
808
|
+
);
|
|
809
|
+
return failureResult(context, error, {
|
|
810
|
+
runtimeInstalled: true,
|
|
811
|
+
providerRegistered: false,
|
|
812
|
+
targetPreserved: true,
|
|
813
|
+
previous: null,
|
|
814
|
+
backupPath: null,
|
|
815
|
+
providerErrorCode: registration.error?.code ?? null,
|
|
816
|
+
});
|
|
817
|
+
}
|
|
818
|
+
const running = await detectSafe();
|
|
819
|
+
const current = await persistCurrent();
|
|
820
|
+
if (!current.ok) {
|
|
821
|
+
return failureResult(context, cloudError(
|
|
822
|
+
'install_failed',
|
|
823
|
+
'共享 runtime 已存在,但 current 指针写入失败;现有 runtime/provider 未被删除',
|
|
824
|
+
{ detail: sanitizeRuntimeInstallLog(current.error?.message ?? current.error).slice(0, 300), currentWriteFailed: true },
|
|
825
|
+
), {
|
|
826
|
+
runtimeInstalled: true,
|
|
827
|
+
providerRegistered: true,
|
|
828
|
+
targetPreserved: true,
|
|
829
|
+
previous: null,
|
|
830
|
+
backupPath: null,
|
|
831
|
+
});
|
|
832
|
+
}
|
|
833
|
+
return successResult(context, {
|
|
834
|
+
reused: true,
|
|
835
|
+
changed: false,
|
|
836
|
+
previous: null,
|
|
837
|
+
backupPath: null,
|
|
838
|
+
providerRegistered: true,
|
|
839
|
+
provider: registration.provider,
|
|
840
|
+
current: current.current,
|
|
841
|
+
restartRequired: running.runningDetected === true,
|
|
842
|
+
running,
|
|
843
|
+
note: running.runningDetected
|
|
844
|
+
? '共享 runtime 已存在;正在运行的 daemon/service 未停止,重启后使用该版本'
|
|
845
|
+
: '共享 runtime 已存在;可使用 mebular runtime ensure 启动',
|
|
846
|
+
});
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
const tempPath = join(runtimeDir, `${RUNTIME_STAGING_PREFIX}${context.version}-${process.pid}-${randomSuffix()}`);
|
|
850
|
+
state.tempPath = tempPath;
|
|
851
|
+
await mkdir(tempPath, { recursive: true });
|
|
852
|
+
|
|
853
|
+
const invocation = buildNpmInstallCommand({
|
|
854
|
+
version: context.version,
|
|
855
|
+
prefix: tempPath,
|
|
856
|
+
platform,
|
|
857
|
+
npmPath,
|
|
858
|
+
});
|
|
859
|
+
const childEnv = { ...env };
|
|
860
|
+
delete childEnv.npm_config_global;
|
|
861
|
+
delete childEnv.npm_config_argv;
|
|
862
|
+
delete childEnv.npm_config_prefix;
|
|
863
|
+
|
|
864
|
+
const run = await runNpmInstall({
|
|
865
|
+
command: invocation.command,
|
|
866
|
+
args: invocation.args,
|
|
867
|
+
shell: invocation.shell,
|
|
868
|
+
cwd: tempPath,
|
|
869
|
+
env: childEnv,
|
|
870
|
+
timeoutMs,
|
|
871
|
+
killGraceMs,
|
|
872
|
+
signal,
|
|
873
|
+
spawnFn,
|
|
874
|
+
});
|
|
875
|
+
|
|
876
|
+
if (run.aborted) {
|
|
877
|
+
throw failureError('cancelled', 'runtime 安装已取消', { detail: 'aborted' });
|
|
878
|
+
}
|
|
879
|
+
if (run.timedOut) {
|
|
880
|
+
throw failureError('cancelled', `runtime 安装超时(${timeoutMs}ms)`, { detail: 'timeout', timedOut: true });
|
|
881
|
+
}
|
|
882
|
+
if (run.spawnError || run.exitCode !== 0) {
|
|
883
|
+
const classified = classifyNpmInstallFailure({
|
|
884
|
+
spawnError: run.spawnError,
|
|
885
|
+
exitCode: run.exitCode,
|
|
886
|
+
stdout: run.stdout,
|
|
887
|
+
stderr: run.stderr,
|
|
888
|
+
});
|
|
889
|
+
throw failureError(classified.reason, `runtime 安装失败(${classified.reason})`, {
|
|
890
|
+
detail: classified.detail,
|
|
891
|
+
status: classified.status,
|
|
892
|
+
logTail: sanitizeRuntimeInstallLog(`${run.stderr}\n${run.stdout}`).slice(-4000) || null,
|
|
893
|
+
});
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
const installed = await inspectInstalledRuntime(tempPath, context.version);
|
|
897
|
+
if (!installed.ok) {
|
|
898
|
+
const reason = installed.reason === 'missing' ? 'integrity_mismatch' : installed.reason;
|
|
899
|
+
throw failureError(reason, 'runtime 安装校验失败(包版本或 CLI 路径不匹配)', {
|
|
900
|
+
detail: installed.detail ?? installed.reason,
|
|
901
|
+
installedVersion: installed.installedVersion ?? null,
|
|
902
|
+
logTail: null,
|
|
903
|
+
});
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
// 先备份旧目录,再原子换入新目录;任何一步失败都恢复旧目录。
|
|
907
|
+
if (existsSync(targetPath)) {
|
|
908
|
+
backupPath = join(runtimeDir, `${RUNTIME_BACKUP_PREFIX}${context.version}-${timestampId(now())}-${randomSuffix()}`);
|
|
909
|
+
await rename(targetPath, backupPath);
|
|
910
|
+
}
|
|
911
|
+
try {
|
|
912
|
+
await rename(tempPath, targetPath);
|
|
913
|
+
state.tempPath = null;
|
|
914
|
+
} catch (error) {
|
|
915
|
+
if (backupPath !== null) {
|
|
916
|
+
try {
|
|
917
|
+
await rename(backupPath, targetPath);
|
|
918
|
+
backupPath = null;
|
|
919
|
+
} catch (restoreError) {
|
|
920
|
+
throw failureError('permission_denied', `换入新 runtime 失败且无法恢复旧目录:${restoreError?.message ?? restoreError}`, {
|
|
921
|
+
detail: 'swap_restore_failed',
|
|
922
|
+
backupPath,
|
|
923
|
+
});
|
|
924
|
+
}
|
|
925
|
+
}
|
|
926
|
+
throw failureError(classifyFsError(error), `换入 runtime 目录失败(${error?.code ?? 'error'})`, {
|
|
927
|
+
detail: 'swap_failed',
|
|
928
|
+
backupPath,
|
|
929
|
+
});
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
const finalCheck = await inspectInstalledRuntime(targetPath, context.version);
|
|
933
|
+
if (!finalCheck.ok) {
|
|
934
|
+
const failedPath = join(runtimeDir, `${RUNTIME_STAGING_PREFIX}failed-${context.version}-${randomSuffix()}`);
|
|
935
|
+
await rename(targetPath, failedPath).catch(() => undefined);
|
|
936
|
+
await rm(failedPath, { recursive: true, force: true }).catch(() => undefined);
|
|
937
|
+
let restored = false;
|
|
938
|
+
if (backupPath !== null) {
|
|
939
|
+
try {
|
|
940
|
+
await rename(backupPath, targetPath);
|
|
941
|
+
backupPath = null;
|
|
942
|
+
restored = true;
|
|
943
|
+
} catch {
|
|
944
|
+
restored = false;
|
|
945
|
+
}
|
|
946
|
+
}
|
|
947
|
+
throw failureError('integrity_mismatch', 'runtime 原子换入后校验失败', {
|
|
948
|
+
detail: finalCheck.detail ?? 'final_validation_failed',
|
|
949
|
+
previousPreserved: restored,
|
|
950
|
+
});
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
runtimeInstalled = true;
|
|
954
|
+
|
|
955
|
+
const registration = await registerProvider();
|
|
956
|
+
if (!registration.ok) {
|
|
957
|
+
const error = cloudError(
|
|
958
|
+
'provider_registration_failed',
|
|
959
|
+
'runtime 已安装,但 provider 注册失败;新 runtime 保留,现有 provider 未被覆盖',
|
|
960
|
+
{ detail: sanitizeRuntimeInstallLog(registration.error?.message ?? registration.error).slice(0, 300) },
|
|
961
|
+
);
|
|
962
|
+
return failureResult(context, error, {
|
|
963
|
+
runtimeInstalled: true,
|
|
964
|
+
providerRegistered: false,
|
|
965
|
+
targetPreserved: true,
|
|
966
|
+
previous,
|
|
967
|
+
backupPath,
|
|
968
|
+
providerErrorCode: registration.error?.code ?? null,
|
|
969
|
+
});
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
const running = await detectSafe();
|
|
973
|
+
const current = await persistCurrent();
|
|
974
|
+
if (!current.ok) {
|
|
975
|
+
return failureResult(context, cloudError(
|
|
976
|
+
'install_failed',
|
|
977
|
+
'runtime 已安装,但 current 指针写入失败;现有 runtime/provider 未被删除',
|
|
978
|
+
{ detail: sanitizeRuntimeInstallLog(current.error?.message ?? current.error).slice(0, 300), currentWriteFailed: true },
|
|
979
|
+
), {
|
|
980
|
+
runtimeInstalled: true,
|
|
981
|
+
providerRegistered: true,
|
|
982
|
+
targetPreserved: true,
|
|
983
|
+
previous,
|
|
984
|
+
backupPath,
|
|
985
|
+
provider: registration.provider,
|
|
986
|
+
});
|
|
987
|
+
}
|
|
988
|
+
return successResult(context, {
|
|
989
|
+
reused: false,
|
|
990
|
+
changed: true,
|
|
991
|
+
previous,
|
|
992
|
+
backupPath,
|
|
993
|
+
providerRegistered: true,
|
|
994
|
+
provider: registration.provider,
|
|
995
|
+
current: current.current,
|
|
996
|
+
restartRequired: running.runningDetected === true,
|
|
997
|
+
running,
|
|
998
|
+
note: running.runningDetected
|
|
999
|
+
? '共享 runtime 已安装;正在运行的 daemon/service 未停止,重启后使用新版本(Phase 5)'
|
|
1000
|
+
: '共享 runtime 已安装;可使用 mebular runtime ensure 启动',
|
|
1001
|
+
});
|
|
1002
|
+
} catch (error) {
|
|
1003
|
+
const fsReason = classifyFsError(error);
|
|
1004
|
+
const domainCode = typeof error?.code === 'string'
|
|
1005
|
+
&& (INSTALL_REASON_SET.has(error.code) || error.code === 'install_locked' || error.code === 'install_failed');
|
|
1006
|
+
const normalized = fsReason !== 'install_failed'
|
|
1007
|
+
? failureError(fsReason, `runtime 安装失败(${fsReason})`, {
|
|
1008
|
+
detail: `fs:${error?.code ?? 'error'}`,
|
|
1009
|
+
logTail: null,
|
|
1010
|
+
})
|
|
1011
|
+
: (domainCode
|
|
1012
|
+
? error
|
|
1013
|
+
: failureError('install_failed', error?.message ?? String(error), {
|
|
1014
|
+
detail: `fs:${error?.code ?? 'error'}`,
|
|
1015
|
+
logTail: null,
|
|
1016
|
+
}));
|
|
1017
|
+
return failureResult(context, normalized, {
|
|
1018
|
+
runtimeInstalled,
|
|
1019
|
+
providerRegistered: false,
|
|
1020
|
+
targetPreserved: existsSync(targetPath),
|
|
1021
|
+
previous,
|
|
1022
|
+
backupPath,
|
|
1023
|
+
detail: normalized?.detail ?? error?.detail ?? null,
|
|
1024
|
+
logTail: normalized?.logTail ?? error?.logTail ?? null,
|
|
1025
|
+
timedOut: normalized?.timedOut === true,
|
|
1026
|
+
holderPid: normalized?.holderPid ?? error?.holderPid ?? null,
|
|
1027
|
+
});
|
|
1028
|
+
} finally {
|
|
1029
|
+
if (state.tempPath) {
|
|
1030
|
+
await rm(state.tempPath, { recursive: true, force: true }).catch(() => undefined);
|
|
1031
|
+
}
|
|
1032
|
+
removeExitCleanup?.();
|
|
1033
|
+
await lock?.release?.();
|
|
1034
|
+
}
|
|
1035
|
+
}
|
|
1036
|
+
|
|
1037
|
+
/** 语义包装:明确覆盖/保留旧版本。 */
|
|
1038
|
+
export async function reinstallRuntime(options = {}) {
|
|
1039
|
+
return installRuntime({ ...options, reinstall: true });
|
|
1040
|
+
}
|