dsh-folia 4.26.0-pre.53 → 4.26.0-pre.55

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.
@@ -19,31 +19,59 @@ import { dirname, join } from 'node:path';
19
19
  import { Readable } from 'node:stream';
20
20
  import { pipeline } from 'node:stream/promises';
21
21
 
22
- const MEDIA_BASE = 'https://folia-5ve.pages.dev/media/';
23
- const DEFAULT_MANIFEST = MEDIA_BASE + 'asr/v1/manifest.json';
22
+ const MEDIA_BASE = String(
23
+ process.env.FOLIA_ASR_BASE
24
+ || process.env.FOLIA_ASR_MEDIA_BASE
25
+ || 'https://folia-5ve.pages.dev/media/',
26
+ ).replace(/\/?$/, '/');
27
+ const DEFAULT_MANIFEST = String(process.env.FOLIA_ASR_MANIFEST || (MEDIA_BASE + 'asr/v1/manifest.json'));
24
28
 
25
- /** 下载一个文件到 dest(先写 .part,校验通过再改名;支持 Range 续传)。 */
26
- async function downloadOne(url, dest, expectedSize, onBytes) {
29
+ /**
30
+ * 下载一个文件到 dest(先写 .part,校验通过再改名;支持 Range 续传)。
31
+ *
32
+ * v0.2:**边下边报**(onBytes 每个 chunk 调一次),单次请求有超时;
33
+ * 超时/断流时保留 .part,下一轮用 Range 从断点续传,不再“卡住十几分钟没进度”。
34
+ */
35
+ async function downloadOne(url, dest, expectedSize, onBytes, options = {}) {
27
36
  const part = dest + '.part';
28
37
  let start = 0;
29
- if (existsSync(part)) start = statSync(part).size;
38
+ try { if (existsSync(part)) start = statSync(part).size; } catch { start = 0; }
39
+ if (expectedSize > 0 && start > expectedSize) {
40
+ try { rmSync(part, { force: true }); } catch { /* ignore */ }
41
+ start = 0;
42
+ }
30
43
  if (existsSync(dest) && expectedSize > 0 && statSync(dest).size === expectedSize) {
31
44
  if (typeof onBytes === 'function') onBytes(expectedSize);
32
45
  return;
33
46
  }
34
47
  const headers = {};
35
48
  if (start > 0) headers.Range = `bytes=${start}-`;
36
- const resp = await fetch(url, { headers });
37
- if (!resp.ok && resp.status !== 206) throw new Error(`下载失败 ${resp.status} ${url}`);
38
- if (resp.status !== 206) start = 0; // 服务器不支持续传 ⇒ 重头写
39
- await pipeline(Readable.fromWeb(resp.body), createWriteStream(part, { flags: start > 0 ? 'a' : 'w' }));
40
- const size = statSync(part).size;
41
- if (expectedSize > 0 && size !== expectedSize) {
42
- throw new Error(`大小不符:${dest} 期望 ${expectedSize} 实际 ${size}`);
49
+ const controller = new AbortController();
50
+ const timeoutMs = Math.max(15000, Number(options.timeoutMs) || 180000);
51
+ const timer = setTimeout(() => controller.abort(new Error('download-timeout')), timeoutMs);
52
+ try {
53
+ const resp = await fetch(url, { headers, signal: controller.signal });
54
+ if (!resp.ok && resp.status !== 206) throw new Error(`下载失败 ${resp.status} ${url}`);
55
+ if (resp.status !== 206) start = 0; // 服务器不支持续传 ⇒ 重头写
56
+ // 续传已有字节也要计入本轮进度(否则 ETA/百分比会从 0 重新跳)。
57
+ if (start > 0 && typeof onBytes === 'function') onBytes(start);
58
+ const body = Readable.fromWeb(resp.body);
59
+ let received = 0;
60
+ body.on('data', (chunk) => {
61
+ received += chunk.length;
62
+ if (typeof onBytes === 'function') onBytes(chunk.length);
63
+ });
64
+ await pipeline(body, createWriteStream(part, { flags: start > 0 ? 'a' : 'w' }), { signal: controller.signal });
65
+ const size = statSync(part).size;
66
+ if (expectedSize > 0 && size !== expectedSize) {
67
+ throw new Error(`大小不符:${dest} 期望 ${expectedSize} 实际 ${size}`);
68
+ }
69
+ if (received === 0 && expectedSize > start) throw new Error('下载流为空');
70
+ rmSync(dest, { force: true });
71
+ renameSync(part, dest);
72
+ } finally {
73
+ clearTimeout(timer);
43
74
  }
44
- rmSync(dest, { force: true });
45
- renameSync(part, dest);
46
- if (typeof onBytes === 'function') onBytes(expectedSize - start);
47
75
  }
48
76
 
49
77
  /** 校验 sha256(不匹配则删掉重来一次)。 */
@@ -64,28 +92,55 @@ async function verifyOrDrop(file, sha256) {
64
92
  */
65
93
  export async function ensureInstalled(root, options = {}) {
66
94
  const onProgress = typeof options.onProgress === 'function' ? options.onProgress : null;
95
+ const onRetry = typeof options.onRetry === 'function' ? options.onRetry : null;
67
96
  const manifestUrl = options.manifestUrl || DEFAULT_MANIFEST;
68
- const resp = await fetch(manifestUrl, { cache: 'no-store' });
97
+ const mediaBase = String(options.mediaBase || MEDIA_BASE).replace(/\/?$/, '/');
98
+ const timeoutMs = Math.max(1000, Number(options.fileTimeoutMs) || 180000);
99
+ const retries = Math.max(1, Number(options.retries) || 3);
100
+ const resp = await fetch(manifestUrl, { cache: 'no-store', signal: AbortSignal.timeout(20000) });
69
101
  if (!resp.ok) throw new Error(`manifest 获取失败 ${resp.status}`);
70
102
  const manifest = await resp.json();
71
103
  const files = Array.isArray(manifest.files) ? manifest.files : [];
72
104
  const total = files.reduce((sum, f) => sum + (Number(f.size) || 0), 0);
73
105
  let done = 0;
74
106
  for (const file of files) {
107
+ const expected = Number(file.size) || 0;
75
108
  const dest = join(root, ...String(file.key).split('/').slice(2)); // 去掉 'asr/v1/'
76
109
  mkdirSync(dirname(dest), { recursive: true });
77
110
  const ok = await verifyOrDrop(dest, file.sha256);
78
- if (!ok) {
79
- await downloadOne(MEDIA_BASE + file.key, dest, Number(file.size) || 0, (n) => {
80
- done += n;
81
- if (onProgress) onProgress({ doneBytes: done, totalBytes: total, file: file.key });
82
- });
83
- const verified = await verifyOrDrop(dest, file.sha256);
84
- if (!verified) throw new Error(`校验失败:${file.key}`);
85
- } else {
86
- done += Number(file.size) || 0;
87
- if (onProgress) onProgress({ doneBytes: done, totalBytes: total, file: file.key });
111
+ if (ok) {
112
+ done += expected;
113
+ if (onProgress) onProgress({ doneBytes: done, totalBytes: total, file: file.key, phase: 'verify' });
114
+ continue;
115
+ }
116
+ const base = done;
117
+ let lastError = null;
118
+ for (let attempt = 1; attempt <= retries; attempt += 1) {
119
+ try {
120
+ await downloadOne(mediaBase + file.key, dest, expected, (n) => {
121
+ done = Math.min(total, base + n);
122
+ if (onProgress) onProgress({ doneBytes: done, totalBytes: total, file: file.key, phase: 'download' });
123
+ }, { timeoutMs });
124
+ const verified = await verifyOrDrop(dest, file.sha256);
125
+ if (!verified) throw new Error(`校验失败:${file.key}`);
126
+ done = base + expected;
127
+ if (onProgress) onProgress({ doneBytes: done, totalBytes: total, file: file.key, phase: 'verify' });
128
+ lastError = null;
129
+ break;
130
+ } catch (error) {
131
+ lastError = error;
132
+ if (onRetry) {
133
+ onRetry({
134
+ file: file.key, attempt, retries,
135
+ error: String((error && error.message) || error),
136
+ doneBytes: done, totalBytes: total,
137
+ });
138
+ }
139
+ if (attempt >= retries) break;
140
+ await new Promise((resolve) => { setTimeout(resolve, 800 * attempt); });
141
+ }
88
142
  }
143
+ if (lastError) throw lastError;
89
144
  }
90
145
  return { root, manifest };
91
146
  }
@@ -133,7 +188,7 @@ export function startWorker(root) {
133
188
  }
134
189
  }
135
190
  });
136
- child.on('error', (error) => { lastError = String((error && error.message) || error); });
191
+ child.on('error', (error) => { lastError = String((error && error.message) || error); });
137
192
  child.stderr.setEncoding('utf8');
138
193
  let lastError = '';
139
194
  child.stderr.on('data', (chunk) => { lastError = (lastError + chunk).slice(-2000); });