odant-work 1.0.21 → 1.0.23

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.
@@ -35,6 +35,7 @@ import https from 'node:https';
35
35
  import crypto from 'node:crypto';
36
36
  import { spawn } from 'node:child_process';
37
37
  import { startHuggingFaceDownload, listHuggingFaceDownloads, registerLocalModelNode } from './huggingface.js';
38
+ import { loadTrainerNetworkSettings, createNetworkFetch, downloadFileMultipart } from './downloader.js';
38
39
 
39
40
  export const HALOGEN_DEFAULT_PORT = Number(process.env.HALOGEN_API_PORT) || 8731;
40
41
  export const HALOGEN_DEFAULT_BASE_URL = process.env.HALOGEN_BASE_URL || `http://127.0.0.1:${HALOGEN_DEFAULT_PORT}/v1/chat/completions`;
@@ -852,43 +853,57 @@ export async function prepareWindowsBuboRuntime({
852
853
  // Шаг 1: Если `bubo.exe` ещё не установлен, скачиваем официальный релиз `bubo-v0.1.2-windows-x64-gfx1151.zip`
853
854
  if (!envInfo.buboInstalled || step === 'download-bubo') {
854
855
  const zipPath = path.join(runtimeRoot, BUBO_WINDOWS_RELEASE.zipFileName);
855
- appendLog(`Скачивание ${BUBO_WINDOWS_RELEASE.zipFileName} (${(BUBO_WINDOWS_RELEASE.sizeBytes / (1024 * 1024)).toFixed(1)} МБ)…`);
856
+ const netCfg = loadTrainerNetworkSettings(rootDir);
857
+ const effProxy = fetchImpl === globalThis.fetch ? netCfg.proxyUrl : '';
858
+ const netFetch = createNetworkFetch({ proxyUrl: effProxy, fetchImpl });
859
+
860
+ appendLog(`Скачивание ${BUBO_WINDOWS_RELEASE.zipFileName} (${(BUBO_WINDOWS_RELEASE.sizeBytes / (1024 * 1024)).toFixed(1)} МБ, ${netCfg.threads} потоков)…`);
856
861
  _windowsPrepareState.progress = 15;
857
862
 
858
- const res = await fetchImpl(BUBO_WINDOWS_RELEASE.downloadUrl);
859
- if (!res?.ok)
860
- throw new Error(`Ошибка загрузки Bubo ZIP: HTTP ${res?.status || 'unknown'}`);
863
+ const dlRes = await downloadFileMultipart({
864
+ url: BUBO_WINDOWS_RELEASE.downloadUrl,
865
+ stagedFile: zipPath,
866
+ expectedSize: BUBO_WINDOWS_RELEASE.sizeBytes,
867
+ threads: netCfg.threads,
868
+ fetchImpl: netFetch,
869
+ onProgress: ({ downloadedBytes, totalBytes }) => {
870
+ const denom = totalBytes || BUBO_WINDOWS_RELEASE.sizeBytes;
871
+ if (denom > 0)
872
+ _windowsPrepareState.progress = Math.min(55, 15 + Math.round((downloadedBytes / denom) * 40));
873
+ },
874
+ });
861
875
 
862
- const hash = crypto.createHash('sha256');
863
- const chunks = [];
864
- let received = 0;
865
- if (res.body && typeof res.body[Symbol.asyncIterator] === 'function') {
866
- for await (const chunk of res.body) {
867
- const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
868
- hash.update(buf);
869
- chunks.push(buf);
870
- received += buf.length;
871
- _windowsPrepareState.progress = Math.min(55, 15 + Math.round((received / BUBO_WINDOWS_RELEASE.sizeBytes) * 40));
876
+ const statZip = await fsp.stat(zipPath);
877
+ if (statZip.size === BUBO_WINDOWS_RELEASE.sizeBytes) {
878
+ const hash = crypto.createHash('sha256');
879
+ await new Promise((resolve, reject) => {
880
+ const rs = fs.createReadStream(zipPath);
881
+ rs.on('data', c => hash.update(c));
882
+ rs.once('end', resolve);
883
+ rs.once('error', reject);
884
+ });
885
+ const digest = hash.digest('hex');
886
+ if (digest !== BUBO_WINDOWS_RELEASE.sha256) {
887
+ await fsp.rm(zipPath, { force: true }).catch(() => {});
888
+ throw new Error(`Контрольная сумма SHA-256 архива Bubo не совпала: ожидалась ${BUBO_WINDOWS_RELEASE.sha256}, получена ${digest}`);
872
889
  }
873
890
  }
874
- else if (typeof res.arrayBuffer === 'function') {
875
- const buf = Buffer.from(await res.arrayBuffer());
876
- hash.update(buf);
877
- chunks.push(buf);
878
- }
879
891
 
880
- const fullZip = Buffer.concat(chunks);
881
- const digest = hash.digest('hex');
882
- if (fullZip.length === BUBO_WINDOWS_RELEASE.sizeBytes && digest !== BUBO_WINDOWS_RELEASE.sha256) {
883
- throw new Error(`Контрольная сумма SHA-256 архива Bubo не совпала: ожидалась ${BUBO_WINDOWS_RELEASE.sha256}, получена ${digest}`);
884
- }
885
-
886
- await fsp.writeFile(zipPath, fullZip);
887
892
  await fsp.mkdir(buboDir, { recursive: true });
888
893
  appendLog('Распаковка архива Halowin Bubo…');
889
894
  _windowsPrepareState.progress = 60;
890
895
 
891
- if (os.platform() === 'win32' && fullZip.slice(0, 2).toString('ascii') === 'PK') {
896
+ let isPkZip = false;
897
+ try {
898
+ const fh = await fsp.open(zipPath, 'r');
899
+ const magic = Buffer.alloc(2);
900
+ await fh.read(magic, 0, 2, 0);
901
+ await fh.close();
902
+ isPkZip = magic.toString('ascii') === 'PK';
903
+ }
904
+ catch { /* ignore */ }
905
+
906
+ if (os.platform() === 'win32' && isPkZip) {
892
907
  await new Promise((resolve, reject) => {
893
908
  const ps = spawnImpl('powershell', [
894
909
  '-NoProfile',
@@ -10,8 +10,19 @@ import fs from 'node:fs';
10
10
  import fsp from 'node:fs/promises';
11
11
  import path from 'node:path';
12
12
  import crypto from 'node:crypto';
13
-
14
- const HF_ORIGIN = 'https://huggingface.co';
13
+ import {
14
+ DEFAULT_HF_ORIGIN,
15
+ loadTrainerNetworkSettings,
16
+ normalizeEndpointUrl,
17
+ describeSourceLabel,
18
+ canSendAuthToUrl,
19
+ createNetworkFetch,
20
+ downloadFileMultipart,
21
+ mergeRanges,
22
+ sumRangesBytes,
23
+ } from './downloader.js';
24
+
25
+ const HF_ORIGIN = DEFAULT_HF_ORIGIN;
15
26
  const REPO_ID_RE = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
16
27
 
17
28
  /**
@@ -617,10 +628,10 @@ export function evaluateModelFit(model, usableMemoryGb = 16) {
617
628
  };
618
629
  }
619
630
 
620
- function hfHeaders(token) {
631
+ function hfHeaders(token, targetUrl = '', endpointUrl = HF_ORIGIN) {
621
632
  const h = { 'User-Agent': 'WORK-AI-Trainer/2.0' };
622
633
  const t = String(token || process.env.HF_TOKEN || '').trim();
623
- if (t)
634
+ if (t && (!targetUrl || canSendAuthToUrl(targetUrl, endpointUrl)))
624
635
  h.Authorization = `Bearer ${t}`;
625
636
  return h;
626
637
  }
@@ -686,6 +697,9 @@ export async function searchHuggingFaceModels({
686
697
  limit = 25,
687
698
  token = '',
688
699
  usableMemoryGb = 24,
700
+ rootDir = process.cwd(),
701
+ endpointUrl,
702
+ proxyUrl,
689
703
  fetchImpl = globalThis.fetch,
690
704
  } = {}) {
691
705
  const q = String(query || '').trim();
@@ -724,6 +738,12 @@ export async function searchHuggingFaceModels({
724
738
  }
725
739
 
726
740
  try {
741
+ const netCfg = loadTrainerNetworkSettings(rootDir);
742
+ const effEndpoint = normalizeEndpointUrl(endpointUrl || netCfg.endpointUrl || HF_ORIGIN);
743
+ const effProxy = proxyUrl !== undefined ? proxyUrl : (fetchImpl === globalThis.fetch ? netCfg.proxyUrl : '');
744
+ const effToken = token || netCfg.token || '';
745
+ const netFetch = createNetworkFetch({ proxyUrl: effProxy, fetchImpl });
746
+
727
747
  const params = new URLSearchParams();
728
748
  if (q)
729
749
  params.set('search', q);
@@ -736,9 +756,9 @@ export async function searchHuggingFaceModels({
736
756
  params.set('direction', '-1');
737
757
  params.set('limit', String(Math.min(50, Math.max(5, Number(limit) || 25))));
738
758
 
739
- const url = `${HF_ORIGIN}/api/models?${params.toString()}`;
740
- const res = await fetchImpl(url, {
741
- headers: { Accept: 'application/json', ...hfHeaders(token) },
759
+ const url = `${effEndpoint}/api/models?${params.toString()}`;
760
+ const res = await netFetch(url, {
761
+ headers: { Accept: 'application/json', ...hfHeaders(effToken, url, effEndpoint) },
742
762
  signal: AbortSignal.timeout?.(10000),
743
763
  });
744
764
  if (!res.ok)
@@ -806,6 +826,9 @@ export async function inspectHuggingFaceRepo(repoId, {
806
826
  revision = 'main',
807
827
  token = '',
808
828
  usableMemoryGb = 24,
829
+ rootDir = process.cwd(),
830
+ endpointUrl,
831
+ proxyUrl,
809
832
  fetchImpl = globalThis.fetch,
810
833
  } = {}) {
811
834
  const cleanId = validateRepoId(repoId);
@@ -813,9 +836,15 @@ export async function inspectHuggingFaceRepo(repoId, {
813
836
 
814
837
  if (typeof fetchImpl === 'function') {
815
838
  try {
816
- const url = `${HF_ORIGIN}/api/models/${cleanId}?blobs=true`;
817
- const res = await fetchImpl(url, {
818
- headers: { Accept: 'application/json', ...hfHeaders(token) },
839
+ const netCfg = loadTrainerNetworkSettings(rootDir);
840
+ const effEndpoint = normalizeEndpointUrl(endpointUrl || netCfg.endpointUrl || HF_ORIGIN);
841
+ const effProxy = proxyUrl !== undefined ? proxyUrl : (fetchImpl === globalThis.fetch ? netCfg.proxyUrl : '');
842
+ const effToken = token || netCfg.token || '';
843
+ const netFetch = createNetworkFetch({ proxyUrl: effProxy, fetchImpl });
844
+
845
+ const url = `${effEndpoint}/api/models/${cleanId}?blobs=true`;
846
+ const res = await netFetch(url, {
847
+ headers: { Accept: 'application/json', ...hfHeaders(effToken, url, effEndpoint) },
819
848
  signal: AbortSignal.timeout?.(12000),
820
849
  });
821
850
  if (res.ok) {
@@ -1033,9 +1062,18 @@ async function writeDownloadStateSafe(stagingDir, job, extra = {}) {
1033
1062
  revision: job.revision,
1034
1063
  providerFolder: job.providerFolder,
1035
1064
  folderName: job.folderName,
1065
+ endpointUrl: job.endpointUrl || HF_ORIGIN,
1066
+ sourceLabel: job.sourceLabel || describeSourceLabel(job.endpointUrl || HF_ORIGIN),
1067
+ threads: Number(job.threads) || 1,
1036
1068
  registerInWork: extra.registerInWork !== false,
1037
1069
  nodeMeta: extra.nodeMeta || null,
1038
- files: (job.files || []).map(f => ({ name: f.name, size: Number(f.size) || 0 })),
1070
+ files: (job.files || []).map(f => ({
1071
+ name: f.name,
1072
+ size: Number(f.size) || 0,
1073
+ downloaded: Number(f.downloaded) || 0,
1074
+ done: Boolean(f.done),
1075
+ ranges: Array.isArray(f.ranges) ? f.ranges : [],
1076
+ })),
1039
1077
  totalBytes: Number(job.totalBytes) || 0,
1040
1078
  downloadedBytes: Number(job.downloadedBytes) || 0,
1041
1079
  status: job.status,
@@ -1087,6 +1125,10 @@ export async function startHuggingFaceDownload({
1087
1125
  waitForCompletion = false,
1088
1126
  maxRetries = 20,
1089
1127
  retryBaseDelayMs = 3000,
1128
+ endpointUrl,
1129
+ proxyUrl,
1130
+ threads,
1131
+ parallelFiles,
1090
1132
  fetchImpl = globalThis.fetch,
1091
1133
  } = {}) {
1092
1134
  const cleanId = validateRepoId(repoId);
@@ -1103,7 +1145,22 @@ export async function startHuggingFaceDownload({
1103
1145
  }
1104
1146
  }
1105
1147
 
1106
- const repoMeta = await inspectHuggingFaceRepo(cleanId, { revision, token, fetchImpl });
1148
+ const netCfg = loadTrainerNetworkSettings(rootDir);
1149
+ const effEndpoint = normalizeEndpointUrl(endpointUrl || netCfg.endpointUrl || HF_ORIGIN);
1150
+ const effProxy = proxyUrl !== undefined ? proxyUrl : (fetchImpl === globalThis.fetch ? netCfg.proxyUrl : '');
1151
+ const effThreads = threads !== undefined ? Math.min(16, Math.max(1, Math.round(Number(threads) || 1))) : netCfg.threads;
1152
+ const effParallelFiles = parallelFiles !== undefined ? Math.min(4, Math.max(1, Math.round(Number(parallelFiles) || 1))) : netCfg.parallelFiles;
1153
+ const effToken = token || netCfg.token || '';
1154
+ const netFetch = createNetworkFetch({ proxyUrl: effProxy, fetchImpl });
1155
+
1156
+ const repoMeta = await inspectHuggingFaceRepo(cleanId, {
1157
+ revision,
1158
+ token: effToken,
1159
+ rootDir,
1160
+ endpointUrl: effEndpoint,
1161
+ proxyUrl: effProxy,
1162
+ fetchImpl,
1163
+ });
1107
1164
  const selected = selectFilesToDownload(repoMeta, { files, quant });
1108
1165
  if (!selected.length)
1109
1166
  throw new Error(`В репозитории ${cleanId} не найдено подходящих файлов весов (.gguf / .safetensors)`);
@@ -1123,6 +1180,15 @@ export async function startHuggingFaceDownload({
1123
1180
 
1124
1181
  await fsp.mkdir(stagingDir, { recursive: true });
1125
1182
 
1183
+ // Читаем предыдущий download-state.json (если был), чтобы не потерять карту диапазонов при докачке
1184
+ let prevState = {};
1185
+ const stateFilePath = path.join(stagingDir, DOWNLOAD_STATE_FILE);
1186
+ if (fs.existsSync(stateFilePath)) {
1187
+ try { prevState = JSON.parse(await fsp.readFile(stateFilePath, 'utf-8')) || {}; }
1188
+ catch { /* ignore */ }
1189
+ }
1190
+ const prevFilesMap = new Map((Array.isArray(prevState.files) ? prevState.files : []).map(pf => [pf.name, pf]));
1191
+
1126
1192
  // Убираем старые завершённые/паузовые записи для той же папки из памяти
1127
1193
  for (const [k, entry] of _downloads.entries()) {
1128
1194
  if (entry.job.status !== 'downloading' && entry.job.providerFolder === safeProvider && entry.job.folderName === folderName)
@@ -1136,23 +1202,35 @@ export async function startHuggingFaceDownload({
1136
1202
  const partFile = stagedFile + '.part';
1137
1203
  let downloaded = 0;
1138
1204
  let done = false;
1205
+ let ranges = [];
1139
1206
  try {
1140
1207
  const stDone = await fsp.stat(stagedFile);
1141
1208
  if (stDone.isFile() && stDone.size > 0 && (!size || stDone.size === size)) {
1142
1209
  downloaded = stDone.size;
1143
1210
  done = true;
1211
+ ranges = [[0, downloaded]];
1144
1212
  }
1145
1213
  }
1146
1214
  catch { /* ещё не завершён */ }
1147
1215
  if (!done) {
1148
1216
  try {
1149
1217
  const stPart = await fsp.stat(partFile);
1150
- if (stPart.isFile())
1151
- downloaded = stPart.size;
1218
+ if (stPart.isFile()) {
1219
+ const prevF = prevFilesMap.get(f.name);
1220
+ if (Array.isArray(prevF?.ranges) && prevF.ranges.length) {
1221
+ ranges = mergeRanges(prevF.ranges);
1222
+ downloaded = sumRangesBytes(ranges);
1223
+ }
1224
+ else {
1225
+ // Совместимость со старым однопоточным .part: считаем [0, size) уже готовым!
1226
+ downloaded = stPart.size;
1227
+ ranges = downloaded > 0 ? [[0, downloaded]] : [];
1228
+ }
1229
+ }
1152
1230
  }
1153
1231
  catch { /* .part ещё нет */ }
1154
1232
  }
1155
- jobFiles.push({ name: f.name, size: size || (done ? downloaded : 0), downloaded, done });
1233
+ jobFiles.push({ name: f.name, size: size || (done ? downloaded : 0), downloaded, done, ranges });
1156
1234
  }
1157
1235
 
1158
1236
  const jobId = 'hf_' + crypto.randomUUID().slice(0, 8);
@@ -1174,6 +1252,11 @@ export async function startHuggingFaceDownload({
1174
1252
  rootDir,
1175
1253
  stagingDir,
1176
1254
  weightsDir,
1255
+ endpointUrl: effEndpoint,
1256
+ sourceLabel: describeSourceLabel(effEndpoint),
1257
+ threads: effThreads,
1258
+ usingProxy: Boolean(effProxy),
1259
+ lowSpeedWarning: false,
1177
1260
  status: 'downloading',
1178
1261
  files: jobFiles,
1179
1262
  currentFile: (jobFiles.find(f => !f.done) || jobFiles[0])?.name || '',
@@ -1201,148 +1284,120 @@ export async function startHuggingFaceDownload({
1201
1284
 
1202
1285
  const runPromise = (async () => {
1203
1286
  const t0 = Date.now();
1204
- let sessionDownloadedBytes = 0;
1205
- const updateMetrics = () => {
1287
+ const speedSamples = [];
1288
+ let lastStateSave = 0;
1289
+
1290
+ const updateMetrics = (deltaBytes = 0) => {
1291
+ const now = Date.now();
1292
+ if (deltaBytes > 0)
1293
+ speedSamples.push([now, deltaBytes]);
1294
+ const cutoff = now - 5000;
1295
+ while (speedSamples.length && speedSamples[0][0] < cutoff)
1296
+ speedSamples.shift();
1297
+
1206
1298
  job.downloadedBytes = job.files.reduce((acc, f) => acc + (Number(f.downloaded) || 0), 0);
1299
+ job.totalBytes = job.files.reduce((acc, f) => acc + (Number(f.size) || 0), 0);
1207
1300
  if (job.totalBytes > 0)
1208
1301
  job.progress = Math.min(99, Math.round((job.downloadedBytes / job.totalBytes) * 100));
1209
- const elapsedSec = Math.max(0.2, (Date.now() - t0) / 1000);
1210
- const bytesPerSec = sessionDownloadedBytes / elapsedSec;
1302
+
1303
+ let windowBytes = 0;
1304
+ for (const [, b] of speedSamples)
1305
+ windowBytes += b;
1306
+ const spanSec = speedSamples.length
1307
+ ? Math.max(0.5, (now - Math.min(speedSamples[0][0], now - 500)) / 1000)
1308
+ : Math.max(0.5, (now - t0) / 1000);
1309
+ const bytesPerSec = windowBytes / spanSec;
1211
1310
  job.speedMBs = +(bytesPerSec / (1024 * 1024)).toFixed(2);
1311
+
1212
1312
  if (job.totalBytes > 0 && bytesPerSec > 1024) {
1213
1313
  const remaining = Math.max(0, job.totalBytes - job.downloadedBytes);
1214
1314
  job.etaSeconds = Math.round(remaining / bytesPerSec);
1215
1315
  }
1316
+ const activeSec = (now - t0) / 1000;
1317
+ job.lowSpeedWarning = activeSec >= 15 && job.speedMBs > 0 && job.speedMBs < 2 && !job.retryAttempt;
1318
+
1319
+ if (now - lastStateSave >= 1500) {
1320
+ lastStateSave = now;
1321
+ writeDownloadStateSafe(stagingDir, job, { nodeMeta, registerInWork });
1322
+ }
1216
1323
  };
1217
1324
 
1218
1325
  try {
1219
- for (const fileEntry of job.files) {
1326
+ const pendingQueue = job.files.filter(f => !f.done);
1327
+ const workerCount = Math.min(effParallelFiles, Math.max(1, pendingQueue.length));
1328
+ // Делим потоки между одновременно качаемыми файлами, но минимум 1 поток на файл
1329
+ const perFileThreads = pendingQueue.length > 1 && effParallelFiles > 1
1330
+ ? Math.max(1, Math.min(effThreads, Math.ceil(effThreads / Math.min(2, pendingQueue.length)) + 1))
1331
+ : effThreads;
1332
+ let fileFatalErr = null;
1333
+
1334
+ const processFile = async (fileEntry) => {
1220
1335
  if (controller.signal.aborted)
1221
1336
  throw new Error('Загрузка приостановлена пользователем');
1222
- if (fileEntry.done)
1223
- continue;
1224
-
1225
1337
  job.currentFile = fileEntry.name;
1226
1338
  const stagedFile = path.join(stagingDir, path.basename(fileEntry.name));
1227
1339
  const partFile = stagedFile + '.part';
1228
1340
  const encodedPath = fileEntry.name.split('/').map(encodeURIComponent).join('/');
1229
- const url = `${HF_ORIGIN}/${cleanId}/resolve/${encodeURIComponent(job.revision)}/${encodedPath}`;
1230
-
1231
- let attempt = 0;
1232
- while (true) {
1233
- if (controller.signal.aborted)
1234
- throw new Error('Загрузка приостановлена пользователем');
1235
-
1236
- let existingSize = 0;
1237
- try {
1238
- const st = await fsp.stat(partFile);
1239
- if (st.isFile())
1240
- existingSize = st.size;
1241
- }
1242
- catch { /* файла ещё нет */ }
1243
-
1244
- if (fileEntry.size > 0 && existingSize >= fileEntry.size) {
1245
- await fsp.rename(partFile, stagedFile);
1246
- fileEntry.downloaded = fileEntry.size;
1247
- fileEntry.done = true;
1248
- updateMetrics();
1249
- break;
1250
- }
1251
-
1252
- try {
1253
- const headers = hfHeaders(token);
1254
- if (existingSize > 0)
1255
- headers.Range = `bytes=${existingSize}-`;
1256
-
1257
- const res = await fetchImpl(url, { headers, signal: controller.signal });
1258
- if (res.status === 416) {
1259
- if (existingSize > 0 && (!fileEntry.size || existingSize >= fileEntry.size)) {
1260
- await fsp.rename(partFile, stagedFile);
1261
- fileEntry.size = fileEntry.size || existingSize;
1262
- fileEntry.downloaded = existingSize;
1263
- fileEntry.done = true;
1264
- updateMetrics();
1265
- break;
1266
- }
1267
- await fsp.rm(partFile, { force: true }).catch(() => {});
1268
- existingSize = 0;
1269
- const err416 = new Error(`Сбой Range для ${fileEntry.name}: HTTP 416`);
1270
- err416.retryable = true;
1271
- throw err416;
1272
- }
1273
- if (!res.ok && res.status !== 206) {
1274
- const errHttp = new Error(`Ошибка загрузки ${fileEntry.name}: HTTP ${res.status}`);
1275
- errHttp.httpStatus = res.status;
1276
- throw errHttp;
1277
- }
1278
-
1279
- const isPartial = res.status === 206;
1280
- if (!isPartial)
1281
- existingSize = 0;
1282
-
1283
- const contentLen = Number(res.headers?.get?.('content-length') || 0);
1284
- if (!fileEntry.size && contentLen > 0) {
1285
- fileEntry.size = existingSize + contentLen;
1286
- job.totalBytes = job.files.reduce((acc, f) => acc + (Number(f.size) || 0), 0);
1287
- }
1288
-
1289
- fileEntry.downloaded = existingSize;
1341
+ const url = `${effEndpoint}/${cleanId}/resolve/${encodeURIComponent(job.revision)}/${encodedPath}`;
1342
+ const headers = hfHeaders(effToken, url, effEndpoint);
1343
+
1344
+ const res = await downloadFileMultipart({
1345
+ url,
1346
+ stagedFile,
1347
+ partFile,
1348
+ expectedSize: Number(fileEntry.size) || 0,
1349
+ headers,
1350
+ threads: perFileThreads,
1351
+ initialRanges: fileEntry.ranges,
1352
+ signal: controller.signal,
1353
+ maxRetries,
1354
+ retryBaseDelayMs,
1355
+ fetchImpl: netFetch,
1356
+ onProgress: ({ downloadedBytes, totalBytes: fTotal, deltaBytes, ranges }) => {
1357
+ if (fTotal > 0 && !fileEntry.size)
1358
+ fileEntry.size = fTotal;
1359
+ fileEntry.downloaded = downloadedBytes;
1360
+ fileEntry.ranges = ranges;
1290
1361
  job.retryAttempt = 0;
1291
1362
  job.retryError = '';
1292
- updateMetrics();
1293
-
1294
- if (res.body) {
1295
- const flags = isPartial ? 'a' : 'w';
1296
- const out = fs.createWriteStream(partFile, { flags });
1297
- try {
1298
- for await (const chunk of res.body) {
1299
- if (controller.signal.aborted)
1300
- throw new Error('Загрузка приостановлена пользователем');
1301
- const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
1302
- if (!out.write(buf))
1303
- await new Promise(r => out.once('drain', r));
1304
- fileEntry.downloaded += buf.length;
1305
- sessionDownloadedBytes += buf.length;
1306
- updateMetrics();
1307
- }
1308
- await new Promise((resolve, reject) => {
1309
- out.end();
1310
- out.once('finish', resolve);
1311
- out.once('error', reject);
1312
- });
1313
- }
1314
- catch (streamErr) {
1315
- await new Promise((resolve) => {
1316
- out.once('finish', resolve);
1317
- out.once('error', resolve);
1318
- out.once('close', resolve);
1319
- try { out.end(); } catch { resolve(); }
1320
- });
1321
- if (!controller.signal.aborted && !streamErr.httpStatus)
1322
- streamErr.retryable = true;
1323
- throw streamErr;
1324
- }
1325
- }
1326
-
1327
- await fsp.rename(partFile, stagedFile);
1328
- fileEntry.done = true;
1329
- updateMetrics();
1330
- break;
1331
- }
1332
- catch (err) {
1333
- if (controller.signal.aborted)
1334
- throw err;
1335
- if (!isRetryableDownloadError(err) || attempt >= maxRetries)
1336
- throw err;
1337
- attempt++;
1363
+ updateMetrics(deltaBytes);
1364
+ },
1365
+ onRetry: ({ attempt, error }) => {
1338
1366
  job.retryAttempt = attempt;
1339
- job.retryError = String(err?.message || err);
1340
- await writeDownloadStateSafe(stagingDir, job, { nodeMeta, registerInWork });
1341
- const delay = Math.min(30000, retryBaseDelayMs * attempt);
1342
- await waitAbortable(delay, controller.signal);
1367
+ job.retryError = error;
1368
+ writeDownloadStateSafe(stagingDir, job, { nodeMeta, registerInWork });
1369
+ },
1370
+ });
1371
+
1372
+ fileEntry.size = fileEntry.size || res.size;
1373
+ fileEntry.downloaded = fileEntry.size || res.size;
1374
+ fileEntry.ranges = res.ranges;
1375
+ fileEntry.done = true;
1376
+ updateMetrics(0);
1377
+ };
1378
+
1379
+ const fileWorkers = [];
1380
+ for (let fw = 0; fw < workerCount; fw++) {
1381
+ fileWorkers.push((async () => {
1382
+ while (!fileFatalErr && !controller.signal.aborted) {
1383
+ const nextFile = pendingQueue.shift();
1384
+ if (!nextFile)
1385
+ break;
1386
+ try {
1387
+ await processFile(nextFile);
1388
+ }
1389
+ catch (err) {
1390
+ if (!fileFatalErr)
1391
+ fileFatalErr = err;
1392
+ }
1343
1393
  }
1344
- }
1394
+ })());
1345
1395
  }
1396
+ await Promise.all(fileWorkers);
1397
+ if (fileFatalErr)
1398
+ throw fileFatalErr;
1399
+ if (controller.signal.aborted)
1400
+ throw new Error('Загрузка приостановлена пользователем');
1346
1401
 
1347
1402
  // Переносим готовые файлы из скрытой папки #downloads в целевую папку модели #weights
1348
1403
  await fsp.mkdir(weightsDir, { recursive: true });
@@ -1455,6 +1510,7 @@ export function listHuggingFaceDownloads(rootDir = process.cwd()) {
1455
1510
  catch { /* ignore */ }
1456
1511
  }
1457
1512
  const dirFiles = fs.readdirSync(folderDir, { withFileTypes: true });
1513
+ const stateFilesMap = new Map((Array.isArray(state.files) ? state.files : []).map(sf => [sf.name, sf]));
1458
1514
  let diskBytes = 0;
1459
1515
  const parsedFiles = [];
1460
1516
  for (const f of dirFiles) {
@@ -1462,12 +1518,23 @@ export function listHuggingFaceDownloads(rootDir = process.cwd()) {
1462
1518
  continue;
1463
1519
  try {
1464
1520
  const st = fs.statSync(path.join(folderDir, f.name));
1465
- diskBytes += st.size || 0;
1521
+ const baseName = f.name.replace(/\.part$/, '');
1522
+ const isPart = f.name.endsWith('.part');
1523
+ const sf = stateFilesMap.get(baseName);
1524
+ let downloaded = st.size || 0;
1525
+ if (isPart && sf) {
1526
+ if (Array.isArray(sf.ranges) && sf.ranges.length)
1527
+ downloaded = sumRangesBytes(sf.ranges);
1528
+ else if (Number(sf.downloaded) > 0)
1529
+ downloaded = Math.min(downloaded || Number(sf.downloaded), Number(sf.downloaded));
1530
+ }
1531
+ diskBytes += downloaded;
1466
1532
  parsedFiles.push({
1467
- name: f.name.replace(/\.part$/, ''),
1468
- size: st.size || 0,
1469
- downloaded: st.size || 0,
1470
- done: !f.name.endsWith('.part'),
1533
+ name: baseName,
1534
+ size: Number(sf?.size) || st.size || 0,
1535
+ downloaded,
1536
+ done: !isPart,
1537
+ ranges: sf?.ranges || [],
1471
1538
  });
1472
1539
  }
1473
1540
  catch { /* ignore */ }
@@ -1485,6 +1552,9 @@ export function listHuggingFaceDownloads(rootDir = process.cwd()) {
1485
1552
  revision: state.revision || 'main',
1486
1553
  providerFolder: 'Local',
1487
1554
  folderName: e.name,
1555
+ endpointUrl: state.endpointUrl || HF_ORIGIN,
1556
+ sourceLabel: state.sourceLabel || describeSourceLabel(state.endpointUrl || HF_ORIGIN),
1557
+ threads: Number(state.threads) || 1,
1488
1558
  status: state.status === 'failed' ? 'failed' : 'paused',
1489
1559
  files: Array.isArray(state.files) && state.files.length ? state.files : parsedFiles,
1490
1560
  currentFile: parsedFiles[0]?.name || '',
@@ -1518,6 +1588,7 @@ export function pauseHuggingFaceDownload(jobId) {
1518
1588
  entry.job.status = 'paused';
1519
1589
  entry.job.etaSeconds = null;
1520
1590
  entry.job.finishedAt = Date.now();
1591
+ writeDownloadStateSafe(entry.job.stagingDir, entry.job, { nodeMeta: entry.nodeMeta, registerInWork: entry.registerInWork });
1521
1592
  return { ...entry.job };
1522
1593
  }
1523
1594
 
@@ -1549,6 +1620,10 @@ export async function resumeHuggingFaceDownload({
1549
1620
  token = '',
1550
1621
  nodeMeta = null,
1551
1622
  rootDir = process.cwd(),
1623
+ endpointUrl,
1624
+ proxyUrl,
1625
+ threads,
1626
+ parallelFiles,
1552
1627
  fetchImpl = globalThis.fetch,
1553
1628
  } = {}) {
1554
1629
  const key = String(jobId || '');
@@ -1576,6 +1651,10 @@ export async function resumeHuggingFaceDownload({
1576
1651
  targetNodeName: cleanFolder,
1577
1652
  nodeMeta: nodeMeta || entry?.nodeMeta || state.nodeMeta || null,
1578
1653
  registerInWork: entry?.registerInWork ?? state.registerInWork ?? true,
1654
+ endpointUrl,
1655
+ proxyUrl,
1656
+ threads,
1657
+ parallelFiles,
1579
1658
  fetchImpl,
1580
1659
  });
1581
1660
  }