@animastor/installer 0.1.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/LICENSE +21 -0
- package/README.md +66 -0
- package/ai/install-manifests/audio/qwen-tts.json +445 -0
- package/ai/install-manifests/image/qwen-image.json +465 -0
- package/ai/install-manifests/video/ltx-2.3.json +892 -0
- package/package.json +42 -0
- package/src/installer/cli.js +1067 -0
- package/src/installer/compatibility-resolver.js +1287 -0
- package/src/installer/download-planner.js +172 -0
- package/src/installer/engine/comfyui.js +508 -0
- package/src/installer/engine/downloader.js +514 -0
- package/src/installer/engine/engine.js +1180 -0
- package/src/installer/engine/io.js +437 -0
- package/src/installer/engine/logger.js +75 -0
- package/src/installer/engine/nodes.js +146 -0
- package/src/installer/engine/prereq.js +399 -0
- package/src/installer/engine/probe.js +349 -0
- package/src/installer/engine/progress.js +350 -0
- package/src/installer/engine/state.js +170 -0
- package/src/installer/engine/term.js +298 -0
- package/src/installer/engine/worker.js +430 -0
- package/src/installer/engine/workflows.js +153 -0
- package/src/installer/index.js +40 -0
- package/src/installer/install-manifest.js +376 -0
- package/src/installer/install-plan.js +741 -0
- package/src/installer/management.js +489 -0
- package/src/installer/platform/deployment/docker.js +78 -0
- package/src/installer/platform/deployment/native.js +36 -0
- package/src/installer/platform/index.js +165 -0
- package/src/installer/platform/linux.js +341 -0
- package/src/installer/platform/windows.js +360 -0
- package/src/installer/safety-rules.js +156 -0
- package/src/installer/setup-contract.js +1401 -0
- package/src/installer/uninstaller.js +572 -0
- package/src/installer/verification-report.js +220 -0
- package/src/installer/worker-bundle-source.js +64 -0
- package/src/installer/workflow-artifacts.js +152 -0
|
@@ -0,0 +1,514 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Downloader — Private Worker Installer Phase 2.
|
|
5
|
+
*
|
|
6
|
+
* Real model/file downloading on top of download-planner specs:
|
|
7
|
+
* - canonical source from the manifest ONLY (URLs are never invented);
|
|
8
|
+
* - idempotent: a verified final file is never re-downloaded;
|
|
9
|
+
* - resumable: .part file + HTTP Range where the source supports it;
|
|
10
|
+
* - a partially downloaded file is NEVER treated as a ready model;
|
|
11
|
+
* - atomic rename .part → final only after full verification;
|
|
12
|
+
* - size check + SHA-256 when the manifest provides them;
|
|
13
|
+
* - retry with backoff on transient failures;
|
|
14
|
+
* - clear errors; BLOCKED when the source is not researched.
|
|
15
|
+
*
|
|
16
|
+
* Platform abstraction: huggingface and modelscope adapters translate a
|
|
17
|
+
* manifest source into a download strategy without tying the engine to one
|
|
18
|
+
* platform. Tokens (HF_TOKEN, MODELSCOPE_API_TOKEN) are read from the
|
|
19
|
+
* environment, passed as headers only, and NEVER logged.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
const SIZE_TOLERANCE = 0.05;
|
|
23
|
+
|
|
24
|
+
function normPath(p) {
|
|
25
|
+
return String(p || '').replace(/\\/g, '/').replace(/^\/+/, '');
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Verify an already-present file against the manifest expectations.
|
|
30
|
+
* @returns {ok: boolean, grade: string, reason?: string}
|
|
31
|
+
*/
|
|
32
|
+
async function verifyFile(io, absPath, { checksum = null, sizeBytesApprox = null }) {
|
|
33
|
+
if (!io.fs.existsSync(absPath)) return { ok: false, grade: 'absent' };
|
|
34
|
+
const st = io.fs.statSync(absPath);
|
|
35
|
+
if (checksum && checksum.value) {
|
|
36
|
+
const actual = await io.hashFile(absPath, checksum.algo || 'sha256');
|
|
37
|
+
if (actual.toLowerCase() === String(checksum.value).toLowerCase()) {
|
|
38
|
+
return { ok: true, grade: 'checksum-verified' };
|
|
39
|
+
}
|
|
40
|
+
return { ok: false, grade: 'corrupt', reason: `sha256 mismatch (got ${actual.slice(0, 12)}…)` };
|
|
41
|
+
}
|
|
42
|
+
if (checksum && checksum.value_prefix) {
|
|
43
|
+
const actual = await io.hashFile(absPath, checksum.algo || 'sha256');
|
|
44
|
+
if (actual.toLowerCase().startsWith(String(checksum.value_prefix).toLowerCase())) {
|
|
45
|
+
return { ok: true, grade: 'checksum-prefix-verified' };
|
|
46
|
+
}
|
|
47
|
+
return { ok: false, grade: 'corrupt', reason: `sha256 prefix mismatch (got ${actual.slice(0, 12)}…)` };
|
|
48
|
+
}
|
|
49
|
+
if (typeof sizeBytesApprox === 'number' && sizeBytesApprox > 0) {
|
|
50
|
+
const rel = Math.abs(st.size - sizeBytesApprox) / sizeBytesApprox;
|
|
51
|
+
if (rel <= SIZE_TOLERANCE) return { ok: true, grade: 'size-verified', size: st.size };
|
|
52
|
+
return { ok: false, grade: 'size-mismatch', reason: `size ${st.size} differs from expected ~${sizeBytesApprox} by ${(rel * 100).toFixed(1)}%` };
|
|
53
|
+
}
|
|
54
|
+
return { ok: true, grade: 'presence' };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Download one file per a download-planner spec.
|
|
59
|
+
*
|
|
60
|
+
* @param {object} io io adapter (http.download, fs, hashFile)
|
|
61
|
+
* @param {object} spec download-planner spec
|
|
62
|
+
* @param {object} opts { root, getHeader, retries, retryDelayMs, onProgress, log }
|
|
63
|
+
* @returns {{ status: 'verified'|'downloaded'|'resumed'|'skipped'|'blocked'|'failed',
|
|
64
|
+
* grade?, reason?, target_path, attempts }}
|
|
65
|
+
*/
|
|
66
|
+
async function downloadArtifact(io, spec, opts = {}) {
|
|
67
|
+
const {
|
|
68
|
+
root = '',
|
|
69
|
+
getHeader = () => ({}),
|
|
70
|
+
retries = 3,
|
|
71
|
+
retryDelayMs = 500,
|
|
72
|
+
onProgress = null,
|
|
73
|
+
log = null,
|
|
74
|
+
} = opts;
|
|
75
|
+
|
|
76
|
+
const targetRel = normPath(spec.target_path);
|
|
77
|
+
const absTarget = root ? `${root}/${targetRel}` : targetRel;
|
|
78
|
+
const absPart = `${absTarget}.part`;
|
|
79
|
+
|
|
80
|
+
if (!spec.ready) {
|
|
81
|
+
return {
|
|
82
|
+
status: 'blocked',
|
|
83
|
+
reason: spec.blockers && spec.blockers.length > 0
|
|
84
|
+
? spec.blockers.join('; ')
|
|
85
|
+
: 'download source is not researched/configured in the manifest — URLs are never invented',
|
|
86
|
+
target_path: targetRel,
|
|
87
|
+
attempts: 0,
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// Idempotency: a verified final file is never re-downloaded.
|
|
92
|
+
const existing = await verifyFile(io, absTarget, { checksum: spec.checksum, sizeBytesApprox: spec.size_bytes_approx });
|
|
93
|
+
if (existing.ok) {
|
|
94
|
+
return { status: 'skipped', grade: existing.grade, target_path: targetRel, attempts: 0 };
|
|
95
|
+
}
|
|
96
|
+
if (existing.grade === 'corrupt' || existing.grade === 'size-mismatch') {
|
|
97
|
+
// never continue with a possibly corrupt model — remove and re-download
|
|
98
|
+
try { io.fs.unlinkSync(absTarget); } catch (_) { /* already gone */ }
|
|
99
|
+
if (log) log.warn(`${spec.id}: existing file failed verification (${existing.reason}) — re-downloading`);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const dir = absTarget.replace(/\/[^/]+$/, '');
|
|
103
|
+
if (dir && !io.fs.existsSync(dir)) io.fs.mkdirSync(dir, { recursive: true });
|
|
104
|
+
|
|
105
|
+
const headers = getHeader(spec);
|
|
106
|
+
let attempt = 0;
|
|
107
|
+
let lastError = null;
|
|
108
|
+
|
|
109
|
+
for (attempt = 1; attempt <= retries; attempt += 1) {
|
|
110
|
+
try {
|
|
111
|
+
let appendFrom = 0;
|
|
112
|
+
if (io.fs.existsSync(absPart)) {
|
|
113
|
+
try { appendFrom = io.fs.statSync(absPart).size; } catch (_) { appendFrom = 0; }
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const res = await io.http.download({
|
|
117
|
+
url: spec.url,
|
|
118
|
+
dest: absPart,
|
|
119
|
+
appendFrom,
|
|
120
|
+
headers,
|
|
121
|
+
onProgress,
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
if (res.status === 416 && appendFrom > 0) {
|
|
125
|
+
// Range not satisfiable — the part may already be complete or
|
|
126
|
+
// the server disagrees; verify below, else restart once.
|
|
127
|
+
} else if (res.status !== 200 && res.status !== 206) {
|
|
128
|
+
const authHint = res.status === 401 || res.status === 403
|
|
129
|
+
? ' — authentication error: check the access token (gated/private model?). The token value is never logged.'
|
|
130
|
+
: '';
|
|
131
|
+
throw new Error(`HTTP ${res.status} from source${authHint}${res.error ? ` (${String(res.error).slice(0, 200)})` : ''}`);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const verification = await verifyFile(io, absPart, { checksum: spec.checksum, sizeBytesApprox: spec.size_bytes_approx });
|
|
135
|
+
if (!verification.ok) {
|
|
136
|
+
try { io.fs.unlinkSync(absPart); } catch (_) { /* ignore */ }
|
|
137
|
+
return {
|
|
138
|
+
status: 'failed',
|
|
139
|
+
grade: verification.grade,
|
|
140
|
+
reason: verification.reason,
|
|
141
|
+
target_path: targetRel,
|
|
142
|
+
attempts: attempt,
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// atomic publish — only a fully verified file becomes the model
|
|
147
|
+
io.fs.renameSync(absPart, absTarget);
|
|
148
|
+
return {
|
|
149
|
+
status: res.resumed ? 'resumed' : 'downloaded',
|
|
150
|
+
grade: verification.grade,
|
|
151
|
+
target_path: targetRel,
|
|
152
|
+
attempts: attempt,
|
|
153
|
+
};
|
|
154
|
+
} catch (err) {
|
|
155
|
+
lastError = err;
|
|
156
|
+
if (log) log.warn(`${spec.id}: download attempt ${attempt}/${retries} failed: ${err.message}`);
|
|
157
|
+
if (attempt < retries && retryDelayMs > 0) {
|
|
158
|
+
await new Promise((r) => setTimeout(r, retryDelayMs * attempt));
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
return {
|
|
164
|
+
status: 'failed',
|
|
165
|
+
reason: lastError ? lastError.message : 'download failed',
|
|
166
|
+
target_path: targetRel,
|
|
167
|
+
attempts: attempt - 1,
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// ---------------------------------------------------------------------------
|
|
172
|
+
// Platform adapters — manifest source → request headers
|
|
173
|
+
// ---------------------------------------------------------------------------
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Build the auth header provider for a spec. Tokens come from environment
|
|
177
|
+
* variables; they are used in request headers ONLY and never logged.
|
|
178
|
+
* @param {object} envVars usually process.env (injectable for tests)
|
|
179
|
+
*/
|
|
180
|
+
function makeHeaderProvider(envVars = {}) {
|
|
181
|
+
return (spec) => {
|
|
182
|
+
const headers = {};
|
|
183
|
+
if (spec.kind === 'huggingface') {
|
|
184
|
+
const token = envVars.HF_TOKEN || envVars.HUGGINGFACE_HUB_TOKEN;
|
|
185
|
+
if (token) headers.Authorization = `Bearer ${token}`;
|
|
186
|
+
}
|
|
187
|
+
if (spec.kind === 'modelscope') {
|
|
188
|
+
const token = envVars.MODELSCOPE_API_TOKEN;
|
|
189
|
+
if (token) headers.Authorization = `Bearer ${token}`;
|
|
190
|
+
}
|
|
191
|
+
return headers;
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* ModelScope strategy: D2 closed — installer pre-downloads ModelScope repos
|
|
197
|
+
* for deterministic/offline operation. The custom node's auto_download is
|
|
198
|
+
* NOT relied upon.
|
|
199
|
+
*/
|
|
200
|
+
function modelscopeStrategy(dep) {
|
|
201
|
+
if (dep.delivery && dep.delivery.mechanism === 'installer_preload') {
|
|
202
|
+
return {
|
|
203
|
+
mechanism: 'installer_preload',
|
|
204
|
+
note: 'installer pre-downloads this ModelScope repo (D2 closed: deterministic/offline)',
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
if (dep.delivery && dep.delivery.mechanism === 'node_auto_download') {
|
|
208
|
+
return {
|
|
209
|
+
mechanism: 'node_auto_download',
|
|
210
|
+
note: 'the custom node downloads this ModelScope repo on first run; the installer verifies presence afterwards',
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
return {
|
|
214
|
+
mechanism: 'blocked',
|
|
215
|
+
note: 'ModelScope snapshot download is not configured for this entry — no URL is invented',
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// ---------------------------------------------------------------------------
|
|
220
|
+
// ModelScope snapshot download (D2 closed: deterministic/offline)
|
|
221
|
+
// ---------------------------------------------------------------------------
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* ModelScope REST API base for file operations.
|
|
225
|
+
* Listing: /api/v1/models/{owner}/{name}/repo/files?Revision={rev}[&Root={dir}]
|
|
226
|
+
* → { Code, Data: { Files: [{ Name, Path, Type: 'tree'|'blob', Size, Sha256 }] } }
|
|
227
|
+
* ('tree' entries are subdirectories — list them via Root=Path)
|
|
228
|
+
* Download: /api/v1/models/{owner}/{name}/repo?Revision={rev}&FilePath={path}
|
|
229
|
+
*/
|
|
230
|
+
const MODELSCOPE_API_BASE = 'https://modelscope.cn/api/v1/models';
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* Build a ModelScope file download URL.
|
|
234
|
+
* @param {string} repository e.g. "Qwen/Qwen3-TTS-12Hz-1.7B-VoiceDesign"
|
|
235
|
+
* @param {string} filePath relative path within the repo
|
|
236
|
+
* @param {string} [revision] git revision (default: master)
|
|
237
|
+
* @returns {string} full download URL
|
|
238
|
+
*/
|
|
239
|
+
function modelscopeFileUrl(repository, filePath, revision = 'master') {
|
|
240
|
+
const encoded = encodeURIComponent(filePath);
|
|
241
|
+
return `${MODELSCOPE_API_BASE}/${repository}/repo?Revision=${encodeURIComponent(revision)}&FilePath=${encoded}`;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* List ALL files in a ModelScope repository via the REST API.
|
|
246
|
+
*
|
|
247
|
+
* The files endpoint lists ONE directory level at a time; subdirectories
|
|
248
|
+
* (Type='tree') are recursed via the Root parameter, so nested files like
|
|
249
|
+
* `speech_tokenizer/model.safetensors` are included with their full path.
|
|
250
|
+
*
|
|
251
|
+
* @param {object} io io adapter (io.http.fetchJson)
|
|
252
|
+
* @param {string} repository e.g. "Qwen/Qwen3-TTS-12Hz-1.7B-VoiceDesign"
|
|
253
|
+
* @param {string} [revision] git revision (default: master)
|
|
254
|
+
* @param {string} [token] MODELSCOPE_API_TOKEN (optional, public repos work without)
|
|
255
|
+
* @returns {{ ok: boolean, files?: Array<{Path, Size, Sha256}>, error?: string }}
|
|
256
|
+
*/
|
|
257
|
+
async function listModelScopeFiles(io, repository, revision = 'master', token = null) {
|
|
258
|
+
const headers = {};
|
|
259
|
+
if (token) headers.Authorization = `Bearer ${token}`;
|
|
260
|
+
|
|
261
|
+
const listDir = async (rootPath) => {
|
|
262
|
+
let url = `${MODELSCOPE_API_BASE}/${repository}/repo/files?Revision=${encodeURIComponent(revision)}`;
|
|
263
|
+
if (rootPath) url += `&Root=${encodeURIComponent(rootPath)}`;
|
|
264
|
+
const { status, json } = await io.http.fetchJson(url, { headers });
|
|
265
|
+
if (status === 401 || status === 403) {
|
|
266
|
+
throw new Error(`HTTP ${status} — authentication required (private/gated ModelScope repo?)`);
|
|
267
|
+
}
|
|
268
|
+
if (status !== 200 || !json) {
|
|
269
|
+
throw new Error(`HTTP ${status} listing ModelScope repo ${repository}${rootPath ? ` (at ${rootPath})` : ''}`);
|
|
270
|
+
}
|
|
271
|
+
// Real API shape: { Data: { Files: [...] } }; keep tolerant fallbacks
|
|
272
|
+
// for legacy/flat shapes.
|
|
273
|
+
if (json.Data && Array.isArray(json.Data.Files)) return json.Data.Files;
|
|
274
|
+
if (json.Data && Array.isArray(json.Data.Items)) return json.Data.Items;
|
|
275
|
+
if (Array.isArray(json)) return json;
|
|
276
|
+
return [];
|
|
277
|
+
};
|
|
278
|
+
|
|
279
|
+
try {
|
|
280
|
+
const files = [];
|
|
281
|
+
const seenFiles = new Set();
|
|
282
|
+
const seenDirs = new Set();
|
|
283
|
+
const queue = [''];
|
|
284
|
+
while (queue.length > 0) {
|
|
285
|
+
const dir = queue.shift();
|
|
286
|
+
if (seenDirs.has(dir)) continue;
|
|
287
|
+
seenDirs.add(dir);
|
|
288
|
+
const items = await listDir(dir);
|
|
289
|
+
for (const item of items) {
|
|
290
|
+
const p = normPath(item.Path || item.path || item.Name || item.name || '');
|
|
291
|
+
if (!p) continue;
|
|
292
|
+
const isDir = item.Type === 'tree' || item.type === 'tree' || item.Mode === '16384' || p.endsWith('/');
|
|
293
|
+
if (isDir) {
|
|
294
|
+
queue.push(p.replace(/\/+$/, ''));
|
|
295
|
+
continue;
|
|
296
|
+
}
|
|
297
|
+
if (seenFiles.has(p)) continue; // never double-list a file
|
|
298
|
+
seenFiles.add(p);
|
|
299
|
+
files.push({
|
|
300
|
+
Path: p,
|
|
301
|
+
Size: typeof item.Size === 'number' ? item.Size : (typeof item.size === 'number' ? item.size : 0),
|
|
302
|
+
Sha256: item.Sha256 || item.sha256 || null,
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
return { ok: true, files };
|
|
307
|
+
} catch (err) {
|
|
308
|
+
return { ok: false, error: err.message.startsWith('HTTP') || err.message.includes('listing ModelScope')
|
|
309
|
+
? err.message
|
|
310
|
+
: `failed to list ModelScope repo ${repository}: ${err.message}` };
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* Download all files from a ModelScope repo into a target directory.
|
|
316
|
+
*
|
|
317
|
+
* This is the `installer_preload` implementation: the engine calls this
|
|
318
|
+
* instead of downloadArtifact when the dependency source kind is modelscope
|
|
319
|
+
* and the delivery mechanism is installer_preload.
|
|
320
|
+
*
|
|
321
|
+
* Behavior:
|
|
322
|
+
* - Lists files via ModelScope REST API
|
|
323
|
+
* - Downloads each file individually with the same retry/resume/verify
|
|
324
|
+
* logic as downloadArtifact
|
|
325
|
+
* - Idempotent: verified files are skipped
|
|
326
|
+
* - Checksum mismatch: file is deleted and re-downloaded
|
|
327
|
+
* - Creates subdirectories as needed (e.g. speech_tokenizer/)
|
|
328
|
+
*
|
|
329
|
+
* @param {object} io io adapter
|
|
330
|
+
* @param {object} spec download-planner spec (from planModelDownload)
|
|
331
|
+
* @param {object} opts { root, getHeader, retries, retryDelayMs, log, expectedFiles, checksums }
|
|
332
|
+
* @returns {{ status, files?, reason?, attempts }}
|
|
333
|
+
*/
|
|
334
|
+
async function downloadModelScopeRepo(io, spec, opts = {}) {
|
|
335
|
+
const {
|
|
336
|
+
root = '',
|
|
337
|
+
getHeader = () => ({}),
|
|
338
|
+
retries = 3,
|
|
339
|
+
retryDelayMs = 500,
|
|
340
|
+
log = null,
|
|
341
|
+
expectedFiles = null,
|
|
342
|
+
checksums = null,
|
|
343
|
+
progress = null,
|
|
344
|
+
} = opts;
|
|
345
|
+
|
|
346
|
+
const repository = spec.repository || (spec.url && spec.url.replace(/.*\/models\//, '').replace(/\/repo.*/, ''));
|
|
347
|
+
const revision = spec.revision || 'master';
|
|
348
|
+
const targetDir = normPath(spec.target_path);
|
|
349
|
+
const absTargetDir = root ? `${root}/${targetDir}` : targetDir;
|
|
350
|
+
|
|
351
|
+
if (!repository) {
|
|
352
|
+
return { status: 'blocked', reason: 'ModelScope repository is not specified in the manifest' };
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
// Step 1: list files
|
|
356
|
+
const token = (typeof process !== 'undefined' && process.env)
|
|
357
|
+
? (process.env.MODELSCOPE_API_TOKEN || null)
|
|
358
|
+
: null;
|
|
359
|
+
const listing = await listModelScopeFiles(io, repository, revision, token);
|
|
360
|
+
if (!listing.ok) {
|
|
361
|
+
return { status: 'failed', reason: `ModelScope file listing failed: ${listing.error}` };
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
if (listing.files.length === 0) {
|
|
365
|
+
return { status: 'failed', reason: `ModelScope repo ${repository} has no downloadable files` };
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
// Step 2: determine which files to download
|
|
369
|
+
// Use expectedFiles from manifest if provided, otherwise download all
|
|
370
|
+
let filesToDownload = listing.files;
|
|
371
|
+
if (expectedFiles && expectedFiles.length > 0) {
|
|
372
|
+
const expectedSet = new Set(expectedFiles.map(normPath));
|
|
373
|
+
filesToDownload = listing.files.filter((f) => expectedSet.has(normPath(f.Path)));
|
|
374
|
+
if (filesToDownload.length === 0) {
|
|
375
|
+
return { status: 'failed', reason: `none of the expected files (${expectedFiles.join(', ')}) were found in ModelScope repo ${repository}` };
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
// Step 3: download each file
|
|
380
|
+
const results = [];
|
|
381
|
+
let totalAttempts = 0;
|
|
382
|
+
let anyFailed = false;
|
|
383
|
+
|
|
384
|
+
// Aggregate progress across the whole repo (bytes + file counters).
|
|
385
|
+
if (progress && progress.beginRepo) {
|
|
386
|
+
const bytesTotal = filesToDownload.reduce((acc, f) => acc + (typeof f.Size === 'number' && f.Size > 0 ? f.Size : 0), 0);
|
|
387
|
+
progress.beginRepo({ repository, filesTotal: filesToDownload.length, bytesTotal: bytesTotal || null });
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
for (const file of filesToDownload) {
|
|
391
|
+
const filePath = normPath(file.Path);
|
|
392
|
+
const absFile = `${absTargetDir}/${filePath}`;
|
|
393
|
+
const absPart = `${absFile}.part`;
|
|
394
|
+
|
|
395
|
+
// Checksum for this specific file: manifest-provided first; otherwise
|
|
396
|
+
// the registry's own sha256 from the listing (real API data, never
|
|
397
|
+
// invented) — empty registry sha256 falls back to size verification.
|
|
398
|
+
const fileChecksum = (checksums && checksums[filePath])
|
|
399
|
+
|| (file.Sha256 ? { algo: 'sha256', value: file.Sha256 } : null);
|
|
400
|
+
|
|
401
|
+
// Idempotency: verify existing file
|
|
402
|
+
const existing = await verifyFile(io, absFile, { checksum: fileChecksum || null, sizeBytesApprox: file.Size || null });
|
|
403
|
+
if (existing.ok) {
|
|
404
|
+
results.push({ path: filePath, status: 'skipped', grade: existing.grade });
|
|
405
|
+
if (progress && progress.fileSkipped) progress.fileSkipped(filePath, file.Size);
|
|
406
|
+
continue;
|
|
407
|
+
}
|
|
408
|
+
if (existing.grade === 'corrupt' || existing.grade === 'size-mismatch') {
|
|
409
|
+
try { io.fs.unlinkSync(absFile); } catch (_) { /* already gone */ }
|
|
410
|
+
if (log) log.warn(`${spec.id}: file ${filePath} failed verification (${existing.reason}) — re-downloading`);
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
// Ensure directory exists
|
|
414
|
+
const dir = absFile.replace(/\/[^/]+$/, '');
|
|
415
|
+
if (dir && !io.fs.existsSync(dir)) io.fs.mkdirSync(dir, { recursive: true });
|
|
416
|
+
|
|
417
|
+
// Download with retry
|
|
418
|
+
const url = modelscopeFileUrl(repository, filePath, revision);
|
|
419
|
+
const headers = getHeader({ kind: 'modelscope' });
|
|
420
|
+
let fileAttempts = 0;
|
|
421
|
+
let lastError = null;
|
|
422
|
+
|
|
423
|
+
if (progress && progress.beginFile) progress.beginFile(`${repository}/${filePath}`, file.Size || null);
|
|
424
|
+
|
|
425
|
+
for (let attempt = 1; attempt <= retries; attempt += 1) {
|
|
426
|
+
fileAttempts = attempt;
|
|
427
|
+
try {
|
|
428
|
+
let appendFrom = 0;
|
|
429
|
+
if (io.fs.existsSync(absPart)) {
|
|
430
|
+
try { appendFrom = io.fs.statSync(absPart).size; } catch (_) { appendFrom = 0; }
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
const res = await io.http.download({
|
|
434
|
+
url,
|
|
435
|
+
dest: absPart,
|
|
436
|
+
appendFrom,
|
|
437
|
+
headers,
|
|
438
|
+
onProgress: progress && progress.onChunk ? (e) => progress.onChunk(e) : undefined,
|
|
439
|
+
});
|
|
440
|
+
|
|
441
|
+
if (res.status === 416 && appendFrom > 0) {
|
|
442
|
+
// Range not satisfiable — verify below
|
|
443
|
+
} else if (res.status !== 200 && res.status !== 206) {
|
|
444
|
+
const authHint = res.status === 401 || res.status === 403
|
|
445
|
+
? ' — authentication error: check the MODELSCOPE_API_TOKEN' : '';
|
|
446
|
+
throw new Error(`HTTP ${res.status} from ModelScope${authHint}`);
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
// Verify downloaded file
|
|
450
|
+
const verification = await verifyFile(io, absPart, {
|
|
451
|
+
checksum: fileChecksum || null,
|
|
452
|
+
sizeBytesApprox: file.Size || null,
|
|
453
|
+
});
|
|
454
|
+
if (!verification.ok) {
|
|
455
|
+
try { io.fs.unlinkSync(absPart); } catch (_) { /* ignore */ }
|
|
456
|
+
results.push({ path: filePath, status: 'failed', grade: verification.grade, reason: verification.reason });
|
|
457
|
+
if (progress && progress.endFile) progress.endFile({ status: 'failed', bytes: appendFrom });
|
|
458
|
+
anyFailed = true;
|
|
459
|
+
break;
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
// Atomic publish
|
|
463
|
+
io.fs.renameSync(absPart, absFile);
|
|
464
|
+
results.push({ path: filePath, status: res.resumed ? 'resumed' : 'downloaded', grade: verification.grade });
|
|
465
|
+
if (progress && progress.endFile) progress.endFile({ status: res.resumed ? 'resumed' : 'downloaded', bytes: file.Size });
|
|
466
|
+
lastError = null;
|
|
467
|
+
break;
|
|
468
|
+
} catch (err) {
|
|
469
|
+
lastError = err;
|
|
470
|
+
if (log) log.warn(`${spec.id}: file ${filePath} attempt ${attempt}/${retries} failed: ${err.message}`);
|
|
471
|
+
if (attempt < retries && retryDelayMs > 0) {
|
|
472
|
+
await new Promise((r) => setTimeout(r, retryDelayMs * attempt));
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
if (lastError) {
|
|
478
|
+
results.push({ path: filePath, status: 'failed', reason: lastError.message });
|
|
479
|
+
if (progress && progress.endFile) progress.endFile({ status: 'failed', bytes: 0 });
|
|
480
|
+
anyFailed = true;
|
|
481
|
+
}
|
|
482
|
+
totalAttempts += fileAttempts;
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
if (progress && progress.endRepo) progress.endRepo({ status: anyFailed ? 'failed' : 'downloaded' });
|
|
486
|
+
|
|
487
|
+
if (anyFailed) {
|
|
488
|
+
const failed = results.filter((r) => r.status === 'failed');
|
|
489
|
+
return {
|
|
490
|
+
status: 'failed',
|
|
491
|
+
reason: `${failed.length} file(s) failed to download from ModelScope repo ${repository}`,
|
|
492
|
+
files: results,
|
|
493
|
+
attempts: totalAttempts,
|
|
494
|
+
};
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
return {
|
|
498
|
+
status: 'downloaded',
|
|
499
|
+
files: results,
|
|
500
|
+
attempts: totalAttempts,
|
|
501
|
+
};
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
module.exports = {
|
|
505
|
+
SIZE_TOLERANCE,
|
|
506
|
+
verifyFile,
|
|
507
|
+
downloadArtifact,
|
|
508
|
+
makeHeaderProvider,
|
|
509
|
+
modelscopeStrategy,
|
|
510
|
+
listModelScopeFiles,
|
|
511
|
+
downloadModelScopeRepo,
|
|
512
|
+
modelscopeFileUrl,
|
|
513
|
+
MODELSCOPE_API_BASE,
|
|
514
|
+
};
|