@v587d/capital-generation 2.23.0 → 2.25.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/CHANGELOG.md +49 -0
- package/README.md +9 -4
- package/THIRD_PARTY_NOTICES.md +20 -0
- package/automation/package.json +1 -1
- package/chart-ui/package.json +1 -1
- package/config/client.js +21 -5
- package/config/client.src.cjs +264 -0
- package/config/package.json +1 -1
- package/cordis.patch.yml +9 -2
- package/lib/agents/role-tool-policy.d.ts +1 -1
- package/lib/agents/root-tool-policy.d.ts +3 -3
- package/lib/agents/root-tool-policy.js +2 -2
- package/lib/data-collector/catalog-taxonomy.d.ts +16 -0
- package/lib/data-collector/catalog-taxonomy.js +179 -0
- package/lib/data-collector/hub.d.ts +16 -3
- package/lib/data-collector/hub.js +40 -6
- package/lib/data-collector/tools.js +46 -8
- package/lib/python-runtime/child-env.d.ts +11 -0
- package/lib/python-runtime/child-env.js +39 -0
- package/lib/python-runtime/errors.d.ts +8 -0
- package/lib/python-runtime/errors.js +34 -0
- package/lib/python-runtime/lock.d.ts +11 -0
- package/lib/python-runtime/lock.js +68 -0
- package/lib/python-runtime/manager.d.ts +61 -0
- package/lib/python-runtime/manager.js +517 -0
- package/lib/python-runtime/manifest.d.ts +5 -0
- package/lib/python-runtime/manifest.js +160 -0
- package/lib/python-runtime/paths.d.ts +20 -0
- package/lib/python-runtime/paths.js +156 -0
- package/lib/python-runtime/platform.d.ts +32 -0
- package/lib/python-runtime/platform.js +145 -0
- package/lib/python-runtime/pnpm.d.ts +24 -0
- package/lib/python-runtime/pnpm.js +115 -0
- package/lib/python-runtime/probe.d.ts +13 -0
- package/lib/python-runtime/probe.js +101 -0
- package/lib/python-runtime/routes.d.ts +6 -0
- package/lib/python-runtime/routes.js +152 -0
- package/lib/python-runtime/types.d.ts +105 -0
- package/lib/python-runtime/types.js +3 -0
- package/lib/python-runtime-entry.d.ts +10 -0
- package/lib/python-runtime-entry.js +60 -0
- package/lib/sources/eastmoney-http.js +346 -1
- package/lib/sources/tencent-http.js +248 -2
- package/lib/sources/tencent-public-core.js +1 -1
- package/lib/sources-entry.d.ts +1 -1
- package/lib/time/tools.js +2 -0
- package/lib/web-retriever/local-fetch.d.ts +1 -1
- package/lib/web-retriever/local-fetch.js +1 -1
- package/lib/web-retriever/sources.d.ts +16 -1
- package/lib/web-retriever/sources.js +133 -1
- package/lib/web-retriever/tools.js +41 -1
- package/lib/web-retriever/wind-client.d.ts +1 -1
- package/lib/web-retriever/wind-client.js +1 -1
- package/package.json +13 -1
- package/plugin-page/README.en.md +1 -7
- package/plugin-page/README.zh.md +1 -8
- package/preset/capital-generation/agent.patch.yml +12 -13
- package/preset/capital-generation/skills/capital-data-protocol/SKILL.md +21 -22
- package/preset/capital-generation/skills/capital-web-protocol/SKILL.md +10 -4
- package/python/worker.py +154 -0
- package/runtime/manifest.json +75 -0
- package/scripts/python-runtime.mjs +139 -0
- package/watchlist/package.json +1 -1
|
@@ -0,0 +1,517 @@
|
|
|
1
|
+
import { chmod, mkdir, rename, rm, stat } from 'node:fs/promises';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import { join, resolve } from 'node:path';
|
|
4
|
+
import { pathToFileURL } from 'node:url';
|
|
5
|
+
import { PythonRuntimeError, isPythonRuntimeError, messageOf } from './errors.js';
|
|
6
|
+
import { withInstallLock } from './lock.js';
|
|
7
|
+
import { normalizePackNames, packTarget } from './manifest.js';
|
|
8
|
+
import { availableBytes, directoryBytes, exists, isInside, lockRoot, packRoot, readJson, readyFileShape, readyPath, removeStaleStaging, resolveDshHome, runtimeRoot, safeRelative, stagingRoot, storeRoot, writeJsonAtomic, } from './paths.js';
|
|
9
|
+
import { findPnpmCli } from './platform.js';
|
|
10
|
+
import { classifyPnpmFailure, installArgs, runPnpm, writeInstallProject } from './pnpm.js';
|
|
11
|
+
import { probePython } from './probe.js';
|
|
12
|
+
const PACK_ORDER = ['base', 'parquet'];
|
|
13
|
+
function nowIso(now) {
|
|
14
|
+
return now().toISOString();
|
|
15
|
+
}
|
|
16
|
+
function copyJob(job) {
|
|
17
|
+
return {
|
|
18
|
+
...job,
|
|
19
|
+
packs: [...job.packs],
|
|
20
|
+
...(job.error === undefined ? {} : { error: { ...job.error } }),
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
function targetParts(target) {
|
|
24
|
+
const index = target.lastIndexOf('-');
|
|
25
|
+
return { platform: target.slice(0, index), arch: target.slice(index + 1) };
|
|
26
|
+
}
|
|
27
|
+
function normalizeMachine(value) {
|
|
28
|
+
const machine = value.toLowerCase();
|
|
29
|
+
if (machine === 'amd64' || machine === 'x86_64' || machine === 'x64')
|
|
30
|
+
return 'x64';
|
|
31
|
+
if (machine === 'aarch64' || machine === 'arm64')
|
|
32
|
+
return 'arm64';
|
|
33
|
+
return machine;
|
|
34
|
+
}
|
|
35
|
+
function packagesMatch(actual, expected) {
|
|
36
|
+
return Object.entries(expected).every(([name, version]) => actual[name] === version);
|
|
37
|
+
}
|
|
38
|
+
export class PythonRuntimeManager {
|
|
39
|
+
manifest;
|
|
40
|
+
dshHome;
|
|
41
|
+
cacheRoot;
|
|
42
|
+
workerPath;
|
|
43
|
+
target;
|
|
44
|
+
profileDir;
|
|
45
|
+
packageManager;
|
|
46
|
+
packSources;
|
|
47
|
+
registry;
|
|
48
|
+
logger;
|
|
49
|
+
now;
|
|
50
|
+
runPnpm;
|
|
51
|
+
probePython;
|
|
52
|
+
jobs = new Map();
|
|
53
|
+
activeJobId;
|
|
54
|
+
pnpmInvocation;
|
|
55
|
+
constructor(options) {
|
|
56
|
+
this.manifest = options.manifest;
|
|
57
|
+
this.dshHome = resolveDshHome(options.dshHome);
|
|
58
|
+
this.cacheRoot = runtimeRoot(this.dshHome, options.manifest.cacheRoot);
|
|
59
|
+
this.workerPath = options.workerPath;
|
|
60
|
+
this.target = options.target;
|
|
61
|
+
this.profileDir = options.profileDir;
|
|
62
|
+
this.packageManager = options.packageManager;
|
|
63
|
+
this.packSources = options.packSources ?? {};
|
|
64
|
+
this.registry = options.registry;
|
|
65
|
+
this.logger = options.logger;
|
|
66
|
+
this.now = options.now ?? (() => new Date());
|
|
67
|
+
this.runPnpm = options.runPnpm ?? runPnpm;
|
|
68
|
+
this.probePython = options.probePython ?? probePython;
|
|
69
|
+
}
|
|
70
|
+
targetId() {
|
|
71
|
+
if (this.target.target === null || !this.target.supported) {
|
|
72
|
+
throw new PythonRuntimeError('unsupported-platform', this.target.reason);
|
|
73
|
+
}
|
|
74
|
+
return this.target.target;
|
|
75
|
+
}
|
|
76
|
+
async readReady(pack, version, target) {
|
|
77
|
+
const root = packRoot(this.cacheRoot, pack, version, target);
|
|
78
|
+
const value = await readJson(readyPath(root));
|
|
79
|
+
return readyFileShape(value) ? value : undefined;
|
|
80
|
+
}
|
|
81
|
+
async packStatus(pack) {
|
|
82
|
+
const target = this.target.target;
|
|
83
|
+
const spec = target === null ? undefined : this.manifest.packs[pack].targets[target];
|
|
84
|
+
const version = spec?.version ?? '';
|
|
85
|
+
const packageName = spec?.package ?? '';
|
|
86
|
+
const base = {
|
|
87
|
+
name: pack,
|
|
88
|
+
state: 'not-installed',
|
|
89
|
+
kind: this.manifest.packs[pack].kind,
|
|
90
|
+
version,
|
|
91
|
+
package: packageName,
|
|
92
|
+
target,
|
|
93
|
+
pythonVersion: this.manifest.python,
|
|
94
|
+
packages: { ...this.manifest.packs[pack].packages },
|
|
95
|
+
bytes: 0,
|
|
96
|
+
path: target === null ? '' : packRoot(this.cacheRoot, pack, version, target),
|
|
97
|
+
};
|
|
98
|
+
if (target === null || spec === undefined)
|
|
99
|
+
return base;
|
|
100
|
+
const root = packRoot(this.cacheRoot, pack, version, target);
|
|
101
|
+
if (!await exists(root))
|
|
102
|
+
return base;
|
|
103
|
+
const ready = await this.readReady(pack, version, target);
|
|
104
|
+
if (ready === undefined) {
|
|
105
|
+
return { ...base, state: 'broken', error: 'ready.json 缺失或不可读。' };
|
|
106
|
+
}
|
|
107
|
+
if (ready.pack !== pack
|
|
108
|
+
|| ready.packVersion !== version
|
|
109
|
+
|| ready.target !== target
|
|
110
|
+
|| ready.package !== packageName
|
|
111
|
+
|| ready.pythonVersion !== this.manifest.python
|
|
112
|
+
|| !packagesMatch(ready.packages, this.manifest.packs[pack].packages)) {
|
|
113
|
+
return { ...base, state: 'broken', error: 'ready.json 与当前 manifest 不一致。' };
|
|
114
|
+
}
|
|
115
|
+
try {
|
|
116
|
+
if (pack === 'base' && ready.python === null) {
|
|
117
|
+
return { ...base, state: 'broken', error: 'base ready.json 缺少 Python 可执行文件。' };
|
|
118
|
+
}
|
|
119
|
+
if (ready.python !== null)
|
|
120
|
+
await stat(safeRelative(root, ready.python));
|
|
121
|
+
for (const item of ready.sitePackages)
|
|
122
|
+
await stat(safeRelative(root, item));
|
|
123
|
+
}
|
|
124
|
+
catch (error) {
|
|
125
|
+
return { ...base, state: 'broken', error: `运行时文件缺失:${messageOf(error)}` };
|
|
126
|
+
}
|
|
127
|
+
return {
|
|
128
|
+
...base,
|
|
129
|
+
state: 'ready',
|
|
130
|
+
installedAt: ready.installedAt,
|
|
131
|
+
bytes: ready.bytes ?? await directoryBytes(root),
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
async status() {
|
|
135
|
+
const base = await this.packStatus('base');
|
|
136
|
+
const parquet = await this.packStatus('parquet');
|
|
137
|
+
const active = this.activeJobId === undefined ? undefined : this.jobs.get(this.activeJobId)?.job;
|
|
138
|
+
return {
|
|
139
|
+
supported: this.target.supported,
|
|
140
|
+
...(this.target.reason === undefined ? {} : { reason: this.target.reason }),
|
|
141
|
+
target: this.target.target,
|
|
142
|
+
platform: this.target.platform,
|
|
143
|
+
arch: this.target.arch,
|
|
144
|
+
python: this.manifest.python,
|
|
145
|
+
cacheRoot: this.cacheRoot,
|
|
146
|
+
base,
|
|
147
|
+
parquet,
|
|
148
|
+
ready: base.state === 'ready',
|
|
149
|
+
...(active === undefined ? {} : { activeJob: copyJob(active) }),
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
prepare(packs = ['base']) {
|
|
153
|
+
const names = normalizePackNames(packs);
|
|
154
|
+
const target = this.targetId();
|
|
155
|
+
for (const name of names)
|
|
156
|
+
packTarget(this.manifest, name, target);
|
|
157
|
+
if (this.activeJobId !== undefined) {
|
|
158
|
+
const active = this.jobs.get(this.activeJobId);
|
|
159
|
+
if (active !== undefined && active.job.state === 'running') {
|
|
160
|
+
if (active.job.packs.length === names.length && active.job.packs.every((name, index) => name === names[index])) {
|
|
161
|
+
return copyJob(active.job);
|
|
162
|
+
}
|
|
163
|
+
throw new PythonRuntimeError('busy', '已有另一个运行时准备任务在进行。');
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
const id = randomUUID();
|
|
167
|
+
const job = {
|
|
168
|
+
id,
|
|
169
|
+
packs: names,
|
|
170
|
+
state: 'running',
|
|
171
|
+
stage: 'checking',
|
|
172
|
+
message: '检查平台与缓存…',
|
|
173
|
+
startedAt: nowIso(this.now),
|
|
174
|
+
};
|
|
175
|
+
const controller = new AbortController();
|
|
176
|
+
const active = { job, controller, promise: Promise.resolve() };
|
|
177
|
+
this.jobs.set(id, active);
|
|
178
|
+
this.activeJobId = id;
|
|
179
|
+
active.promise = this.runJob(active).catch((error) => {
|
|
180
|
+
this.logger?.error?.(`python-runtime prepare failed: ${messageOf(error)}`);
|
|
181
|
+
}).finally(() => {
|
|
182
|
+
if (this.activeJobId === id)
|
|
183
|
+
this.activeJobId = undefined;
|
|
184
|
+
});
|
|
185
|
+
return copyJob(job);
|
|
186
|
+
}
|
|
187
|
+
getJob(id) {
|
|
188
|
+
const active = this.jobs.get(id);
|
|
189
|
+
return active === undefined ? undefined : copyJob(active.job);
|
|
190
|
+
}
|
|
191
|
+
async waitForJob(id) {
|
|
192
|
+
const active = this.jobs.get(id);
|
|
193
|
+
if (active === undefined)
|
|
194
|
+
throw new PythonRuntimeError('invalid-request', `没有这个运行时任务:${id}`);
|
|
195
|
+
await active.promise;
|
|
196
|
+
return copyJob(active.job);
|
|
197
|
+
}
|
|
198
|
+
cancel(id) {
|
|
199
|
+
const active = this.jobs.get(id);
|
|
200
|
+
if (active === undefined || active.job.state !== 'running')
|
|
201
|
+
return false;
|
|
202
|
+
active.controller.abort();
|
|
203
|
+
active.job.message = '正在取消…';
|
|
204
|
+
return true;
|
|
205
|
+
}
|
|
206
|
+
async runJob(active) {
|
|
207
|
+
const { job, controller } = active;
|
|
208
|
+
try {
|
|
209
|
+
await mkdir(this.cacheRoot, { recursive: true, mode: 0o700 });
|
|
210
|
+
await removeStaleStaging(stagingRoot(this.cacheRoot));
|
|
211
|
+
for (const pack of job.packs) {
|
|
212
|
+
if (controller.signal.aborted)
|
|
213
|
+
throw new PythonRuntimeError('cancelled');
|
|
214
|
+
job.current = pack;
|
|
215
|
+
job.stage = 'checking';
|
|
216
|
+
job.message = `检查 ${pack}…`;
|
|
217
|
+
const status = await this.packStatus(pack);
|
|
218
|
+
if (status.state === 'ready')
|
|
219
|
+
continue;
|
|
220
|
+
job.stage = 'installing';
|
|
221
|
+
job.message = `安装 ${pack}…`;
|
|
222
|
+
await this.ensurePack(active, pack);
|
|
223
|
+
}
|
|
224
|
+
job.stage = 'done';
|
|
225
|
+
job.state = 'done';
|
|
226
|
+
job.message = '分析环境已就绪。';
|
|
227
|
+
job.endedAt = nowIso(this.now);
|
|
228
|
+
delete job.current;
|
|
229
|
+
}
|
|
230
|
+
catch (error) {
|
|
231
|
+
const runtimeError = isPythonRuntimeError(error)
|
|
232
|
+
? error
|
|
233
|
+
: new PythonRuntimeError('unknown', messageOf(error));
|
|
234
|
+
job.state = runtimeError.code === 'cancelled' ? 'cancelled' : 'failed';
|
|
235
|
+
job.stage = 'done';
|
|
236
|
+
job.message = runtimeError.message;
|
|
237
|
+
job.error = { code: runtimeError.code, message: runtimeError.message };
|
|
238
|
+
job.endedAt = nowIso(this.now);
|
|
239
|
+
this.logger?.error?.(`python-runtime: ${runtimeError.code}: ${runtimeError.message}`);
|
|
240
|
+
if (runtimeError.diagnostics !== undefined)
|
|
241
|
+
this.logger?.warn?.(runtimeError.diagnostics);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
getPnpm() {
|
|
245
|
+
if (this.pnpmInvocation !== undefined)
|
|
246
|
+
return this.pnpmInvocation;
|
|
247
|
+
this.pnpmInvocation = this.packageManager ?? findPnpmCli();
|
|
248
|
+
return this.pnpmInvocation;
|
|
249
|
+
}
|
|
250
|
+
async ensurePack(active, pack) {
|
|
251
|
+
const target = this.targetId();
|
|
252
|
+
const spec = packTarget(this.manifest, pack, target);
|
|
253
|
+
const root = packRoot(this.cacheRoot, pack, spec.version, target);
|
|
254
|
+
const lock = join(lockRoot(this.cacheRoot), `${pack}-${spec.version}-${target}`);
|
|
255
|
+
const { job, controller } = active;
|
|
256
|
+
await mkdir(lockRoot(this.cacheRoot), { recursive: true, mode: 0o700 });
|
|
257
|
+
await withInstallLock(lock, async () => {
|
|
258
|
+
const current = await this.packStatus(pack);
|
|
259
|
+
if (current.state === 'ready')
|
|
260
|
+
return;
|
|
261
|
+
job.stage = 'checking';
|
|
262
|
+
job.message = `检查磁盘空间…`;
|
|
263
|
+
const free = await availableBytes(this.cacheRoot);
|
|
264
|
+
if (free !== undefined && free < this.manifest.limits.minFreeBytes) {
|
|
265
|
+
throw new PythonRuntimeError('disk-space', `磁盘空间不足:需要约 ${Math.ceil(this.manifest.limits.minFreeBytes / 1048576)} MB,当前约 ${Math.floor(free / 1048576)} MB。`);
|
|
266
|
+
}
|
|
267
|
+
const staging = join(stagingRoot(this.cacheRoot), `${pack}-${spec.version}-${target}-${randomUUID()}`);
|
|
268
|
+
const installDir = join(staging, 'install');
|
|
269
|
+
const payload = join(staging, 'payload');
|
|
270
|
+
const probeHome = join(staging, 'probe-home');
|
|
271
|
+
const probeTemp = join(staging, 'probe-tmp');
|
|
272
|
+
try {
|
|
273
|
+
await mkdir(staging, { recursive: true, mode: 0o700 });
|
|
274
|
+
const source = this.packSources[pack];
|
|
275
|
+
// A package.json dependency value is a range or a file URL, never `name@version`:
|
|
276
|
+
// pnpm treats the latter as a relative directory and installs nothing.
|
|
277
|
+
const dependency = source === undefined ? spec.version : pathToFileURL(resolve(source)).href;
|
|
278
|
+
await writeInstallProject(installDir, spec.package, dependency, this.registry);
|
|
279
|
+
job.stage = 'installing';
|
|
280
|
+
job.message = source === undefined ? `下载并安装 ${pack}(约 ${Math.ceil(spec.bytes / 1048576)} MB)…` : `安装本地 ${pack} 包…`;
|
|
281
|
+
const result = await this.runPnpm(this.getPnpm(), installArgs(installDir, storeRoot(this.cacheRoot), this.registry), {
|
|
282
|
+
cwd: this.profileDir ?? staging,
|
|
283
|
+
timeoutMs: this.manifest.limits.installTimeoutMs,
|
|
284
|
+
signal: controller.signal,
|
|
285
|
+
});
|
|
286
|
+
if (result.code !== 0 || result.timedOut || result.aborted)
|
|
287
|
+
throw classifyPnpmFailure(result);
|
|
288
|
+
const installed = join(installDir, 'node_modules', ...spec.package.split('/'));
|
|
289
|
+
if (!await exists(installed)) {
|
|
290
|
+
throw new PythonRuntimeError('pack-invalid', `pnpm 安装完成但找不到 ${spec.package}。`);
|
|
291
|
+
}
|
|
292
|
+
await rename(installed, payload);
|
|
293
|
+
await rm(installDir, { recursive: true, force: true });
|
|
294
|
+
const metadata = await this.readPackMetadata(payload, pack, target);
|
|
295
|
+
const executable = metadata.executable === null ? undefined : safeRelative(payload, metadata.executable);
|
|
296
|
+
if (metadata.kind === 'base') {
|
|
297
|
+
if (executable === undefined)
|
|
298
|
+
throw new PythonRuntimeError('pack-invalid', 'base pack 缺少 executable。');
|
|
299
|
+
if (this.target.platform !== 'win32')
|
|
300
|
+
await chmod(executable, 0o755);
|
|
301
|
+
}
|
|
302
|
+
const sitePackages = metadata.sitePackages.map((item) => safeRelative(payload, item));
|
|
303
|
+
const baseReady = pack === 'base' ? undefined : await this.readReady('base', this.manifest.packs.base.targets[target]?.version ?? '', target);
|
|
304
|
+
const baseRoot = pack === 'base' ? undefined : packRoot(this.cacheRoot, 'base', this.manifest.packs.base.targets[target]?.version ?? '', target);
|
|
305
|
+
const python = pack === 'base'
|
|
306
|
+
? executable
|
|
307
|
+
: (baseReady?.python === null || baseReady?.python === undefined || baseRoot === undefined ? undefined : safeRelative(baseRoot, baseReady.python));
|
|
308
|
+
if (python === undefined)
|
|
309
|
+
throw new PythonRuntimeError('pack-invalid', `${pack} pack 找不到可用的 Python 解释器;请先安装 base。`);
|
|
310
|
+
const probeSites = pack === 'base'
|
|
311
|
+
? sitePackages
|
|
312
|
+
: [
|
|
313
|
+
...(baseReady?.sitePackages ?? []).map((item) => safeRelative(baseRoot, item)),
|
|
314
|
+
...sitePackages,
|
|
315
|
+
];
|
|
316
|
+
job.stage = 'verifying';
|
|
317
|
+
job.message = `自检 ${pack}…`;
|
|
318
|
+
const report = await this.probePython({
|
|
319
|
+
python,
|
|
320
|
+
workerPath: this.workerPath,
|
|
321
|
+
sitePackages: probeSites,
|
|
322
|
+
homeDir: probeHome,
|
|
323
|
+
tempDir: probeTemp,
|
|
324
|
+
timeoutMs: this.manifest.limits.probeTimeoutMs,
|
|
325
|
+
signal: controller.signal,
|
|
326
|
+
});
|
|
327
|
+
this.validateProbe(report, pack, target, python, probeSites, payload, baseRoot);
|
|
328
|
+
const ready = {
|
|
329
|
+
schemaVersion: 1,
|
|
330
|
+
pack,
|
|
331
|
+
packVersion: spec.version,
|
|
332
|
+
target,
|
|
333
|
+
package: spec.package,
|
|
334
|
+
pythonVersion: this.manifest.python,
|
|
335
|
+
packages: { ...this.manifest.packs[pack].packages },
|
|
336
|
+
python: metadata.executable === null ? null : `payload/${metadata.executable}`,
|
|
337
|
+
sitePackages: metadata.sitePackages.map((item) => `payload/${item}`),
|
|
338
|
+
installedAt: nowIso(this.now),
|
|
339
|
+
probe: { ok: true, at: nowIso(this.now) },
|
|
340
|
+
bytes: await directoryBytes(payload),
|
|
341
|
+
};
|
|
342
|
+
await writeJsonAtomic(readyPath(staging), ready);
|
|
343
|
+
await mkdir(join(root, '..'), { recursive: true });
|
|
344
|
+
if (await exists(root)) {
|
|
345
|
+
const previous = `${root}.broken-${Date.now()}`;
|
|
346
|
+
await rename(root, previous);
|
|
347
|
+
await rm(previous, { recursive: true, force: true }).catch(() => undefined);
|
|
348
|
+
}
|
|
349
|
+
await rename(staging, root);
|
|
350
|
+
}
|
|
351
|
+
finally {
|
|
352
|
+
await rm(staging, { recursive: true, force: true }).catch(() => undefined);
|
|
353
|
+
}
|
|
354
|
+
}, { timeoutMs: 30_000, staleMs: 120_000 });
|
|
355
|
+
}
|
|
356
|
+
async readPackMetadata(payload, pack, target) {
|
|
357
|
+
const value = await readJson(join(payload, 'runtime-pack.json'));
|
|
358
|
+
if (value === undefined)
|
|
359
|
+
throw new PythonRuntimeError('pack-invalid', '运行时包缺少 runtime-pack.json。');
|
|
360
|
+
const parts = targetParts(target);
|
|
361
|
+
const expected = this.manifest.packs[pack];
|
|
362
|
+
if (value.schemaVersion !== 1
|
|
363
|
+
|| value.kind !== expected.kind
|
|
364
|
+
|| value.platform !== parts.platform
|
|
365
|
+
|| value.arch !== parts.arch
|
|
366
|
+
|| value.pythonVersion !== this.manifest.python
|
|
367
|
+
|| value.packages === null
|
|
368
|
+
|| typeof value.packages !== 'object'
|
|
369
|
+
|| Array.isArray(value.packages)) {
|
|
370
|
+
throw new PythonRuntimeError('pack-invalid', 'runtime-pack.json 与 manifest/当前平台不一致。');
|
|
371
|
+
}
|
|
372
|
+
if (!packagesMatch(value.packages, expected.packages)) {
|
|
373
|
+
throw new PythonRuntimeError('pack-invalid', 'runtime-pack.json 的三方库版本与 manifest 不一致。');
|
|
374
|
+
}
|
|
375
|
+
if (value.executable !== null && typeof value.executable !== 'string') {
|
|
376
|
+
throw new PythonRuntimeError('pack-invalid', 'runtime-pack.json.executable 必须是字符串或 null。');
|
|
377
|
+
}
|
|
378
|
+
if (!Array.isArray(value.sitePackages) || value.sitePackages.length === 0 || value.sitePackages.some((item) => typeof item !== 'string')) {
|
|
379
|
+
throw new PythonRuntimeError('pack-invalid', 'runtime-pack.json.sitePackages 必须是非空字符串数组。');
|
|
380
|
+
}
|
|
381
|
+
const metadata = value;
|
|
382
|
+
for (const item of metadata.sitePackages) {
|
|
383
|
+
const path = safeRelative(payload, item);
|
|
384
|
+
if (!await exists(path))
|
|
385
|
+
throw new PythonRuntimeError('pack-invalid', `site-packages 不存在:${item}`);
|
|
386
|
+
}
|
|
387
|
+
if (metadata.executable !== null) {
|
|
388
|
+
const path = safeRelative(payload, metadata.executable);
|
|
389
|
+
if (!await exists(path))
|
|
390
|
+
throw new PythonRuntimeError('pack-invalid', `Python 可执行文件不存在:${metadata.executable}`);
|
|
391
|
+
}
|
|
392
|
+
return metadata;
|
|
393
|
+
}
|
|
394
|
+
validateProbe(report, pack, target, python, sitePackages, payload, baseRoot) {
|
|
395
|
+
const parts = targetParts(target);
|
|
396
|
+
if (report.pythonVersion !== this.manifest.python) {
|
|
397
|
+
throw new PythonRuntimeError('probe-failed', `Python 版本不匹配:期望 ${this.manifest.python},实际 ${report.pythonVersion}。`);
|
|
398
|
+
}
|
|
399
|
+
if (report.platform !== parts.platform) {
|
|
400
|
+
throw new PythonRuntimeError('probe-failed', `Python 平台不匹配:期望 ${parts.platform},实际 ${report.platform}。`);
|
|
401
|
+
}
|
|
402
|
+
if (normalizeMachine(report.arch) !== parts.arch) {
|
|
403
|
+
throw new PythonRuntimeError('probe-failed', `Python 架构不匹配:期望 ${parts.arch},实际 ${report.arch}。`);
|
|
404
|
+
}
|
|
405
|
+
if (!packagesMatch(report.packages, this.manifest.packs[pack].packages)) {
|
|
406
|
+
throw new PythonRuntimeError('probe-failed', `Python 三方库版本不匹配:${JSON.stringify(report.packages)}。`);
|
|
407
|
+
}
|
|
408
|
+
const reportPython = resolve(report.executable);
|
|
409
|
+
const expectedPython = resolve(python);
|
|
410
|
+
const root = pack === 'base' ? payload : baseRoot;
|
|
411
|
+
if (root === undefined || reportPython !== expectedPython || !isInside(root, reportPython)) {
|
|
412
|
+
throw new PythonRuntimeError('probe-failed', 'probe 使用了 payload 之外的解释器。');
|
|
413
|
+
}
|
|
414
|
+
for (const item of report.sitePackages) {
|
|
415
|
+
const allowed = sitePackages.some((candidate) => resolve(candidate) === resolve(item))
|
|
416
|
+
|| (baseRoot !== undefined && isInside(baseRoot, item));
|
|
417
|
+
if (!allowed)
|
|
418
|
+
throw new PythonRuntimeError('probe-failed', `probe 使用了未授权的 site-packages:${item}`);
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
/** Re-run the self-check against the installed packs; `parquet` also verifies pyarrow. */
|
|
422
|
+
async verify(packs = ['base']) {
|
|
423
|
+
const names = normalizePackNames(packs);
|
|
424
|
+
const handle = await this.resolve(names);
|
|
425
|
+
const target = this.targetId();
|
|
426
|
+
const baseSpec = packTarget(this.manifest, 'base', target);
|
|
427
|
+
const baseRoot = packRoot(this.cacheRoot, 'base', baseSpec.version, target);
|
|
428
|
+
const probeHome = join(this.cacheRoot, 'verify-home');
|
|
429
|
+
const probeTemp = join(this.cacheRoot, 'verify-tmp');
|
|
430
|
+
const report = await this.probePython({
|
|
431
|
+
python: handle.python,
|
|
432
|
+
workerPath: this.workerPath,
|
|
433
|
+
sitePackages: handle.sitePackages,
|
|
434
|
+
homeDir: probeHome,
|
|
435
|
+
tempDir: probeTemp,
|
|
436
|
+
timeoutMs: this.manifest.limits.probeTimeoutMs,
|
|
437
|
+
});
|
|
438
|
+
const parts = targetParts(target);
|
|
439
|
+
if (report.pythonVersion !== this.manifest.python
|
|
440
|
+
|| report.platform !== parts.platform
|
|
441
|
+
|| normalizeMachine(report.arch) !== parts.arch) {
|
|
442
|
+
throw new PythonRuntimeError('probe-failed', `Python 运行时与当前平台不一致:${report.pythonVersion}/${report.platform}/${report.arch}。`);
|
|
443
|
+
}
|
|
444
|
+
if (!packagesMatch(report.packages, handle.packages)) {
|
|
445
|
+
throw new PythonRuntimeError('probe-failed', `Python 三方库版本不匹配:${JSON.stringify(report.packages)}。`);
|
|
446
|
+
}
|
|
447
|
+
const reportPython = resolve(report.executable);
|
|
448
|
+
if (reportPython !== resolve(handle.python) || !isInside(baseRoot, reportPython)) {
|
|
449
|
+
throw new PythonRuntimeError('probe-failed', 'probe 使用了 payload 之外的解释器。');
|
|
450
|
+
}
|
|
451
|
+
for (const item of report.sitePackages) {
|
|
452
|
+
const allowed = handle.sitePackages.some((candidate) => resolve(candidate) === resolve(item))
|
|
453
|
+
|| isInside(baseRoot, item);
|
|
454
|
+
if (!allowed)
|
|
455
|
+
throw new PythonRuntimeError('probe-failed', `probe 使用了未授权的 site-packages:${item}`);
|
|
456
|
+
}
|
|
457
|
+
return report;
|
|
458
|
+
}
|
|
459
|
+
async resolve(packs = ['base']) {
|
|
460
|
+
const names = normalizePackNames(packs);
|
|
461
|
+
const target = this.targetId();
|
|
462
|
+
const baseSpec = packTarget(this.manifest, 'base', target);
|
|
463
|
+
const base = await this.packStatus('base');
|
|
464
|
+
if (base.state !== 'ready')
|
|
465
|
+
throw new PythonRuntimeError('runtime-not-ready');
|
|
466
|
+
const baseRoot = packRoot(this.cacheRoot, 'base', baseSpec.version, target);
|
|
467
|
+
const baseReady = await this.readReady('base', baseSpec.version, target);
|
|
468
|
+
if (baseReady === undefined || baseReady.python === null)
|
|
469
|
+
throw new PythonRuntimeError('runtime-not-ready');
|
|
470
|
+
const sitePackages = baseReady.sitePackages.map((item) => safeRelative(baseRoot, item));
|
|
471
|
+
const packages = { ...baseReady.packages };
|
|
472
|
+
const packVersions = { base: baseSpec.version };
|
|
473
|
+
for (const pack of names.filter((name) => name !== 'base')) {
|
|
474
|
+
const spec = packTarget(this.manifest, pack, target);
|
|
475
|
+
const status = await this.packStatus(pack);
|
|
476
|
+
if (status.state !== 'ready')
|
|
477
|
+
throw new PythonRuntimeError('runtime-not-ready', `${pack} 运行时尚未准备。`);
|
|
478
|
+
const requires = this.manifest.packs[pack].requires?.base;
|
|
479
|
+
if (requires !== undefined && requires !== baseReady.packVersion) {
|
|
480
|
+
throw new PythonRuntimeError('pack-invalid', `${pack} 需要 base ${requires},当前是 ${baseReady.packVersion}。`);
|
|
481
|
+
}
|
|
482
|
+
const root = packRoot(this.cacheRoot, pack, spec.version, target);
|
|
483
|
+
const ready = await this.readReady(pack, spec.version, target);
|
|
484
|
+
if (ready === undefined)
|
|
485
|
+
throw new PythonRuntimeError('runtime-not-ready', `${pack} 运行时尚未准备。`);
|
|
486
|
+
sitePackages.push(...ready.sitePackages.map((item) => safeRelative(root, item)));
|
|
487
|
+
Object.assign(packages, ready.packages);
|
|
488
|
+
packVersions[pack] = spec.version;
|
|
489
|
+
}
|
|
490
|
+
return {
|
|
491
|
+
python: safeRelative(baseRoot, baseReady.python),
|
|
492
|
+
pythonVersion: this.manifest.python,
|
|
493
|
+
sitePackages,
|
|
494
|
+
packages,
|
|
495
|
+
packs: packVersions,
|
|
496
|
+
};
|
|
497
|
+
}
|
|
498
|
+
async remove(pack) {
|
|
499
|
+
if (this.activeJobId !== undefined)
|
|
500
|
+
throw new PythonRuntimeError('busy', '运行时任务进行中,不能移除。');
|
|
501
|
+
if (!PACK_ORDER.includes(pack))
|
|
502
|
+
throw new PythonRuntimeError('invalid-request', `未知 pack:${String(pack)}`);
|
|
503
|
+
if (pack === 'base' && (await this.packStatus('parquet')).state === 'ready') {
|
|
504
|
+
throw new PythonRuntimeError('busy', '请先移除 parquet 运行时,再移除 base。');
|
|
505
|
+
}
|
|
506
|
+
await rm(join(this.cacheRoot, pack), { recursive: true, force: true });
|
|
507
|
+
}
|
|
508
|
+
async dispose() {
|
|
509
|
+
for (const active of this.jobs.values()) {
|
|
510
|
+
if (active.job.state === 'running')
|
|
511
|
+
active.controller.abort();
|
|
512
|
+
}
|
|
513
|
+
await Promise.allSettled([...this.jobs.values()].map((active) => active.promise));
|
|
514
|
+
this.jobs.clear();
|
|
515
|
+
this.activeJobId = undefined;
|
|
516
|
+
}
|
|
517
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { type PackName, type PackTarget, type RuntimeManifest, type TargetId } from './types.js';
|
|
2
|
+
export declare function parseManifest(value: unknown): RuntimeManifest;
|
|
3
|
+
export declare function readManifest(path: string): RuntimeManifest;
|
|
4
|
+
export declare function packTarget(manifest: RuntimeManifest, pack: PackName, target: TargetId): PackTarget;
|
|
5
|
+
export declare function normalizePackNames(value: unknown): PackName[];
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { PythonRuntimeError } from './errors.js';
|
|
3
|
+
import { PACK_NAMES, TARGET_IDS } from './types.js';
|
|
4
|
+
const VERSION = /^\d+(?:\.\d+)+(?:[.\-+][A-Za-z0-9._-]+)*$/u;
|
|
5
|
+
const PYTHON_VERSION = /^\d+\.\d+\.\d+(?:[.\-+][A-Za-z0-9._-]+)*$/u;
|
|
6
|
+
const PACKAGE = /^@?[a-z0-9][a-z0-9._-]*(?:\/[a-z0-9][a-z0-9._-]*)?$/u;
|
|
7
|
+
function record(value, label) {
|
|
8
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
|
9
|
+
throw new PythonRuntimeError('manifest-invalid', `${label} 必须是对象。`);
|
|
10
|
+
}
|
|
11
|
+
return value;
|
|
12
|
+
}
|
|
13
|
+
function string(value, label) {
|
|
14
|
+
if (typeof value !== 'string' || value === '') {
|
|
15
|
+
throw new PythonRuntimeError('manifest-invalid', `${label} 必须是非空字符串。`);
|
|
16
|
+
}
|
|
17
|
+
return value;
|
|
18
|
+
}
|
|
19
|
+
function positiveInteger(value, label) {
|
|
20
|
+
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0) {
|
|
21
|
+
throw new PythonRuntimeError('manifest-invalid', `${label} 必须是正整数。`);
|
|
22
|
+
}
|
|
23
|
+
return value;
|
|
24
|
+
}
|
|
25
|
+
function version(value, label) {
|
|
26
|
+
const text = string(value, label);
|
|
27
|
+
if (!VERSION.test(text))
|
|
28
|
+
throw new PythonRuntimeError('manifest-invalid', `${label} 不是合法版本:${text}`);
|
|
29
|
+
return text;
|
|
30
|
+
}
|
|
31
|
+
function packageName(value, label) {
|
|
32
|
+
const text = string(value, label);
|
|
33
|
+
if (!PACKAGE.test(text))
|
|
34
|
+
throw new PythonRuntimeError('manifest-invalid', `${label} 不是合法包名:${text}`);
|
|
35
|
+
return text;
|
|
36
|
+
}
|
|
37
|
+
function targetId(value) {
|
|
38
|
+
if (!TARGET_IDS.includes(value)) {
|
|
39
|
+
throw new PythonRuntimeError('manifest-invalid', `未知 target:${value}`);
|
|
40
|
+
}
|
|
41
|
+
return value;
|
|
42
|
+
}
|
|
43
|
+
function packName(value) {
|
|
44
|
+
if (!PACK_NAMES.includes(value)) {
|
|
45
|
+
throw new PythonRuntimeError('manifest-invalid', `未知 pack:${value}`);
|
|
46
|
+
}
|
|
47
|
+
return value;
|
|
48
|
+
}
|
|
49
|
+
function parsePack(name, value) {
|
|
50
|
+
const raw = record(value, `packs.${name}`);
|
|
51
|
+
const kind = raw.kind;
|
|
52
|
+
if (kind !== 'base' && kind !== 'lib')
|
|
53
|
+
throw new PythonRuntimeError('manifest-invalid', `packs.${name}.kind 必须是 base 或 lib。`);
|
|
54
|
+
if (name === 'base' && kind !== 'base')
|
|
55
|
+
throw new PythonRuntimeError('manifest-invalid', 'base pack 的 kind 必须是 base。');
|
|
56
|
+
if (name !== 'base' && kind !== 'lib')
|
|
57
|
+
throw new PythonRuntimeError('manifest-invalid', `${name} pack 的 kind 必须是 lib。`);
|
|
58
|
+
const packagesRaw = record(raw.packages, `packs.${name}.packages`);
|
|
59
|
+
const packages = {};
|
|
60
|
+
for (const [packageKey, packageVersion] of Object.entries(packagesRaw)) {
|
|
61
|
+
packages[packageKey] = version(packageVersion, `packs.${name}.packages.${packageKey}`);
|
|
62
|
+
}
|
|
63
|
+
if (Object.keys(packages).length === 0)
|
|
64
|
+
throw new PythonRuntimeError('manifest-invalid', `packs.${name}.packages 不能为空。`);
|
|
65
|
+
const targetsRaw = record(raw.targets, `packs.${name}.targets`);
|
|
66
|
+
const targets = {};
|
|
67
|
+
for (const [key, targetValue] of Object.entries(targetsRaw)) {
|
|
68
|
+
const id = targetId(key);
|
|
69
|
+
const target = record(targetValue, `packs.${name}.targets.${key}`);
|
|
70
|
+
targets[id] = {
|
|
71
|
+
package: packageName(target.package, `packs.${name}.targets.${key}.package`),
|
|
72
|
+
version: version(target.version, `packs.${name}.targets.${key}.version`),
|
|
73
|
+
bytes: positiveInteger(target.bytes, `packs.${name}.targets.${key}.bytes`),
|
|
74
|
+
...(target.sha256 === undefined ? {} : { sha256: string(target.sha256, `packs.${name}.targets.${key}.sha256`) }),
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
if (Object.keys(targets).length === 0)
|
|
78
|
+
throw new PythonRuntimeError('manifest-invalid', `packs.${name}.targets 不能为空。`);
|
|
79
|
+
let requires;
|
|
80
|
+
if (raw.requires !== undefined) {
|
|
81
|
+
const required = record(raw.requires, `packs.${name}.requires`);
|
|
82
|
+
requires = {};
|
|
83
|
+
for (const [key, requiredVersion] of Object.entries(required)) {
|
|
84
|
+
requires[packName(key)] = version(requiredVersion, `packs.${name}.requires.${key}`);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return { kind, packages, targets, ...(requires === undefined ? {} : { requires }) };
|
|
88
|
+
}
|
|
89
|
+
export function parseManifest(value) {
|
|
90
|
+
const raw = record(value, 'manifest');
|
|
91
|
+
if (raw.schemaVersion !== 1)
|
|
92
|
+
throw new PythonRuntimeError('manifest-invalid', 'manifest.schemaVersion 必须是 1。');
|
|
93
|
+
const python = version(raw.python, 'python');
|
|
94
|
+
if (!PYTHON_VERSION.test(python))
|
|
95
|
+
throw new PythonRuntimeError('manifest-invalid', `python 必须是三段式版本:${python}`);
|
|
96
|
+
const cacheRoot = string(raw.cacheRoot, 'cacheRoot');
|
|
97
|
+
if (cacheRoot.startsWith('/') || cacheRoot.includes('..') || cacheRoot.includes('\\')) {
|
|
98
|
+
throw new PythonRuntimeError('manifest-invalid', 'cacheRoot 必须是 DSH home 下的相对 POSIX 路径。');
|
|
99
|
+
}
|
|
100
|
+
const packsRaw = record(raw.packs, 'packs');
|
|
101
|
+
const packs = {
|
|
102
|
+
base: parsePack('base', packsRaw.base),
|
|
103
|
+
parquet: parsePack('parquet', packsRaw.parquet),
|
|
104
|
+
};
|
|
105
|
+
const limitsRaw = record(raw.limits, 'limits');
|
|
106
|
+
return {
|
|
107
|
+
schemaVersion: 1,
|
|
108
|
+
python,
|
|
109
|
+
cacheRoot,
|
|
110
|
+
packs,
|
|
111
|
+
limits: {
|
|
112
|
+
minFreeBytes: positiveInteger(limitsRaw.minFreeBytes, 'limits.minFreeBytes'),
|
|
113
|
+
installTimeoutMs: positiveInteger(limitsRaw.installTimeoutMs, 'limits.installTimeoutMs'),
|
|
114
|
+
probeTimeoutMs: positiveInteger(limitsRaw.probeTimeoutMs, 'limits.probeTimeoutMs'),
|
|
115
|
+
},
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
export function readManifest(path) {
|
|
119
|
+
let text;
|
|
120
|
+
try {
|
|
121
|
+
text = readFileSync(path, 'utf8');
|
|
122
|
+
}
|
|
123
|
+
catch (error) {
|
|
124
|
+
throw new PythonRuntimeError('manifest-invalid', `读不到 runtime manifest:${path}`, String(error));
|
|
125
|
+
}
|
|
126
|
+
try {
|
|
127
|
+
return parseManifest(JSON.parse(text));
|
|
128
|
+
}
|
|
129
|
+
catch (error) {
|
|
130
|
+
if (error instanceof PythonRuntimeError)
|
|
131
|
+
throw error;
|
|
132
|
+
throw new PythonRuntimeError('manifest-invalid', `runtime manifest 不是合法 JSON:${path}`, String(error));
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
export function packTarget(manifest, pack, target) {
|
|
136
|
+
const found = manifest.packs[pack].targets[target];
|
|
137
|
+
if (found === undefined) {
|
|
138
|
+
throw new PythonRuntimeError('unsupported-platform', `${pack} 没有 ${target} 的运行时包。`);
|
|
139
|
+
}
|
|
140
|
+
return found;
|
|
141
|
+
}
|
|
142
|
+
export function normalizePackNames(value) {
|
|
143
|
+
if (value === undefined)
|
|
144
|
+
return ['base'];
|
|
145
|
+
if (!Array.isArray(value) || value.length === 0) {
|
|
146
|
+
throw new PythonRuntimeError('invalid-request', 'packs 必须是非空数组。');
|
|
147
|
+
}
|
|
148
|
+
const names = [];
|
|
149
|
+
for (const item of value) {
|
|
150
|
+
if (typeof item !== 'string' || !PACK_NAMES.includes(item)) {
|
|
151
|
+
throw new PythonRuntimeError('invalid-request', `未知 pack:${String(item)}(只能是 ${PACK_NAMES.join(' 或 ')})。`);
|
|
152
|
+
}
|
|
153
|
+
const name = item;
|
|
154
|
+
if (!names.includes(name))
|
|
155
|
+
names.push(name);
|
|
156
|
+
}
|
|
157
|
+
if (names.includes('parquet'))
|
|
158
|
+
return ['base', ...names.filter((name) => name !== 'base')];
|
|
159
|
+
return names;
|
|
160
|
+
}
|