dsh-folia 4.20.1 → 4.21.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.
@@ -100,6 +100,11 @@ export function createDownloadQueue(opts = {}) {
100
100
  const job = jobs.get(id);
101
101
  // 已完成但文件被删 ⇒ 重新排队
102
102
  if (job.status === 'done' && !existsSync(job.dest)) { job.status = 'queued'; job.received = 0; }
103
+ // ⚠️ **必须再 pump 一次**:老实现"存在就直接返回",于是一个已经 queued 的 job
104
+ // 如果当时没有在跑的 pump(例如上一条刚结束、或快照被重置成 queued),
105
+ // 就永远没人来启动它 ⇒ 调用方(皮肤安装)会一直等到超时。实测就是这样卡了 5 分钟。
106
+ persist();
107
+ pump();
103
108
  return { job: snapshot().find((x) => x.id === id), existed: true };
104
109
  }
105
110
  jobs.set(id, {
@@ -283,6 +288,15 @@ export function createDownloadQueue(opts = {}) {
283
288
  load();
284
289
  pump();
285
290
 
291
+ /** 按 dest 反查 job(含 dest/状态/总大小)——代理复用同一条下载用。 */
292
+ function jobFor(dest) {
293
+ for (const j of jobs.values()) {
294
+ if (j.dest !== dest) continue;
295
+ return { id: j.id, dest: j.dest, status: j.status, total: j.total, received: j.received };
296
+ }
297
+ return null;
298
+ }
299
+
286
300
  /** 已落地文件的绝对路径(未完成 / 不存在 ⇒ null)。/folia/local-media/<id> 用它。 */
287
301
  function pathFor(id) {
288
302
  const job = jobs.get(id);
@@ -290,5 +304,5 @@ export function createDownloadQueue(opts = {}) {
290
304
  try { return existsSync(job.dest) ? job.dest : null; } catch { return null; }
291
305
  }
292
306
 
293
- return { add, cancel, snapshot, pump, statePath, pathFor };
307
+ return { add, cancel, snapshot, pump, statePath, pathFor, jobFor };
294
308
  }
@@ -44,15 +44,25 @@ function libraryDest(kind, slug, ext) {
44
44
  * 未命中 ⇒ 返回 null,调用方保持原来的远端/代理地址(用户点了会先入队下载)。
45
45
  */
46
46
  export function localCopyFor(url, kind = 'wallpaper') {
47
+ try {
48
+ const job = queueJobFor(url, kind);
49
+ if (!job || job.status !== 'done') return null;
50
+ return { id: job.id, url: `/folia/local-media/${job.id}`, bytes: job.total };
51
+ } catch { return null; }
52
+ }
53
+
54
+ /**
55
+ * 这条 URL 在下载队列里的**原始 job**(含 dest 绝对路径与状态),供 site-media 代理复用:
56
+ * 代理拿着 dest 就能"渐进读正在增长的文件",而不是再开一条上游连接。
57
+ * 返回 null = 队列里没有这条(代理照旧走远端流式)。
58
+ */
59
+ export function queueJobFor(url, kind = 'wallpaper') {
47
60
  try {
48
61
  const u = new URL(String(url));
49
62
  const ext = (u.pathname.match(/\.([a-z0-9]{2,5})$/i) || [])[1] || 'bin';
50
63
  const slug = u.pathname.split('/').filter(Boolean).pop() || 'item';
51
64
  const dest = libraryDest(kind, slug, ext);
52
- const q = getDownloadQueue();
53
- const job = q.snapshot().find((j) => j.dest === dest);
54
- if (!job || job.status !== 'done') return null;
55
- return { id: job.id, url: `/folia/local-media/${job.id}`, bytes: job.total };
65
+ return getDownloadQueue().jobFor(dest);
56
66
  } catch { return null; }
57
67
  }
58
68
 
@@ -26,7 +26,9 @@
26
26
  *
27
27
  * 注入契约(ADR-0013 D12):`DEPS` 逐键由 `lib/index.js` 给到。
28
28
  */
29
- import { createHash } from 'node:crypto';
29
+ import { createHash } from 'node:crypto';
30
+ import { openSync, readSync, closeSync } from 'node:fs';
31
+ import { queueJobFor } from './downloads.js';
30
32
  import { Readable } from 'node:stream';
31
33
  import { createWriteStream, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, utimesSync, writeFileSync } from 'node:fs';
32
34
  import { join, extname } from 'node:path';
@@ -76,6 +78,69 @@ function keyFor(u) {
76
78
  return h + (EXT_OK.has(ext) ? ext : '.bin');
77
79
  }
78
80
 
81
+ /**
82
+ * 从"正在增长的文件"里按偏移读给客户端(**渐进读**)。
83
+ *
84
+ * 场景:下载队列正在把这条壁纸拉到本地(`<dest>.part`),播放器同时要播。
85
+ * 与其再开一条上游连接(会抢带宽、还会被播放器背压拖成 0.6 MB/s),
86
+ * 不如直接读这份正在长大的文件:队列按线路速度推进,读端有多少字节喂多少。
87
+ *
88
+ * 终止条件:读到 job 状态变成 done 且读到 total;或 job 失败/取消;或客户端断开。
89
+ * 任何异常都只是提前结束响应,不抛出(不能让一次播放把进程搞崩)。
90
+ */
91
+ async function serveGrowingFile(filePath, job, res, headOnly) {
92
+ const openAt = () => { try { return openSync(filePath, 'r'); } catch { return -1; } };
93
+ let fd = openAt();
94
+ let offset = 0;
95
+ let stalled = 0;
96
+ const sleep = (ms) => new Promise((r) => { setTimeout(r, ms); });
97
+ try {
98
+ res.statusCode = 200;
99
+ res.setHeader('content-type', 'application/octet-stream');
100
+ res.setHeader('accept-ranges', 'none');
101
+ res.setHeader('cache-control', 'no-store');
102
+ res.setHeader('x-folia-source', 'library');
103
+ if (headOnly) { res.end(); return true; }
104
+ const BUF = Buffer.alloc(256 * 1024);
105
+ for (;;) {
106
+ if (res.writableEnded) break;
107
+ if (fd < 0) fd = openAt();
108
+ let n = 0;
109
+ if (fd >= 0) {
110
+ try { n = readSync(fd, BUF, 0, BUF.length, offset); } catch { n = 0; }
111
+ }
112
+ if (n > 0) {
113
+ offset += n;
114
+ stalled = 0;
115
+ const ok = res.write(BUF.subarray(0, n));
116
+ if (!ok) await new Promise((r) => { res.once('drain', r); });
117
+ continue;
118
+ }
119
+ // 暂时没有新字节:看队列是否还在推进
120
+ const cur = typeof job.refresh === 'function' ? job.refresh() : job;
121
+ if (cur && cur.status === 'done') {
122
+ // 完成的瞬间 .part 会被 rename 掉;重新打开最终文件继续读完
123
+ try { if (fd >= 0) closeSync(fd); } catch { /* ignore */ }
124
+ fd = -1;
125
+ if (offset >= (cur.total || 0)) break;
126
+ filePath = cur.dest || filePath;
127
+ continue;
128
+ }
129
+ if (cur && (cur.status === 'failed' || cur.status === 'cancelled')) break;
130
+ stalled += 1;
131
+ if (stalled > 600) break; // ≈ 30 秒没有新字节就收尾(不无限挂着)
132
+ await sleep(50);
133
+ }
134
+ res.end();
135
+ return true;
136
+ } catch {
137
+ try { res.end(); } catch { /* ignore */ }
138
+ return false;
139
+ } finally {
140
+ try { if (fd >= 0) closeSync(fd); } catch { /* ignore */ }
141
+ }
142
+ }
143
+
79
144
  /** 目录总量与最旧条目(LRU 用;只看本目录的常规文件,跳过分片)。 */
80
145
  function scanCache(dir) {
81
146
  let total = 0;
@@ -341,6 +406,22 @@ export function registerSiteMediaRoutes(webServer, c) {
341
406
  const key = keyFor(u);
342
407
  const abs = join(dir, key);
343
408
 
409
+ // **单源复用**:如果下载队列已经在为这条 URL 拉文件(用户点它时入队的),
410
+ // 就直接读那个**正在增长的本地文件**,不再开第二条上游连接。
411
+ // 为什么重要:实测同一份字节被拉两遍(代理 0.6 MB/s + 队列 3.2 MB/s),
412
+ // 互相抢带宽,缓存补全速度还不如只跑一条。复用后带宽只花一份,速度=线路速度。
413
+ try {
414
+ const job = queueJobFor(u.toString(), 'wallpaper');
415
+ if (job && (job.status === 'done' || job.status === 'running')) {
416
+ const partPath = job.status === 'done' ? job.dest : job.dest + '.part';
417
+ if (existsSync(partPath)) {
418
+ if (job.status === 'done') { try { res.setHeader('x-folia-cache', 'hit'); } catch { /* ignore */ } }
419
+ await serveGrowingFile(partPath, job, res, headOnly);
420
+ return;
421
+ }
422
+ }
423
+ } catch { /* 复用失败就照旧走远端流式 */ }
424
+
344
425
  if (ensureCache(dir) && existsSync(abs)) {
345
426
  stats.hits += 1;
346
427
  touch(abs);
@@ -614,7 +614,9 @@ export function registerSkinsRoutes(webServer, c) {
614
614
  const q = getDownloadQueue();
615
615
  const added = q.add({ url: url.toString(), dest: zipDest, kind: 'skin' });
616
616
  const jobId = added && added.job ? added.job.id : null;
617
- const deadline = Date.now() + 10 * 60 * 1000;
617
+ // 上限 120 秒:宁可给用户一个明确的"超时/失败"答复,也不要让他对着界面等 10 分钟
618
+ // (实测过"点了没反应":就是因为这里给了 10 分钟,而队列里的 job 没被 pump 起来)。
619
+ const deadline = Date.now() + 120 * 1000;
618
620
  let state = added && added.job ? added.job : null;
619
621
  while (Date.now() < deadline) {
620
622
  state = q.snapshot().find((j) => j.id === jobId) || state;
@@ -627,6 +629,11 @@ export function registerSkinsRoutes(webServer, c) {
627
629
  }
628
630
  const total = Number(state && state.total) || 0;
629
631
  if (total && total > MAX_ZIP_BYTES) { sendJson(res, 413, { ok: false, error: 'too-large' }); return; }
632
+ // 超时/状态不对:**明确失败**,别让调用方以为"装好了"
633
+ if (!state || state.status !== 'done' || !existsSync(zipDest)) {
634
+ sendJson(res, 504, { ok: false, error: 'download-timeout', detail: (state && state.status) || 'unknown' });
635
+ return;
636
+ }
630
637
  buf = readFileSync(zipDest);
631
638
  if (buf.length > MAX_ZIP_BYTES) { sendJson(res, 413, { ok: false, error: 'too-large' }); return; }
632
639
  } catch (e) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-folia",
3
- "version": "4.20.1",
3
+ "version": "4.21.0",
4
4
  "description": "Folia 壁纸引擎:把本机 Wallpaper Engine 壁纸搬进 DSH 界面(场景实时渲染 / 视频 / 网页),内置液态玻璃与 Folia 吉祥物,并可从自建站点拉取壁纸。单包形态(组件已合并)。",
5
5
  "type": "module",
6
6
  "engines": {