lumigather 1.0.2 → 1.0.4

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.
@@ -15,6 +15,90 @@
15
15
 
16
16
  const fs = require("fs");
17
17
  const path = require("path");
18
+ const { readDimensions, readDimensionsAsync } = require("./image-dimensions");
19
+ const { acquireScanSlot, releaseScanSlot } = require("./scan-queue");
20
+ const { startScan, queuedScan, bumpScan, endScan } = require("./scan-progress");
21
+
22
+ // 索引版本。改动条目结构(增删字段)时必须 +1:
23
+ // 老索引里没有新字段,版本不变的话客户端会一直拿到"没有那个字段"的旧数据。
24
+ // 抽成常量是为了避免下次又在四处 `version: 1` 里漏改一处。
25
+ const INDEX_VERSION = 2;
26
+
27
+ // 压缩判据:JSONL 行数超过"唯一目录数 × 该倍数"才重写一次。
28
+ // 追加会产生同一目录的多行(每次 mtime 变就多一行),这个倍数控制允许的冗余。
29
+ const COMPACT_LINE_RATIO = 2;
30
+
31
+ // 追加写的攒批大小:每 N 个目录 flush 一次(见 walkWithIndex 里的取舍说明)
32
+ const FLUSH_EVERY = 24;
33
+
34
+ // 各 JSONL 的**行数**缓存:只在流式载入时顺带统计(那次本来就要逐行读),
35
+ // 供"文件膨胀到唯一目录数的 2 倍才压缩"的判据使用 —— 不为了数行再读一遍大文件。
36
+ // 任何写操作(追加/重写/单条更新)之后都要让它失效,否则判据会基于过期数字。
37
+ const LINE_COUNTS = new Map();
38
+
39
+ // 追加写之前确保文件有 header 行。**已有内容时绝不覆盖**:
40
+ // 追加只发生在文件末尾,header 永远是第一行;只有文件不存在/为空时才补写。
41
+ function ensureJsonlHeader(file, category) {
42
+ fs.mkdirSync(path.dirname(file), { recursive: true });
43
+ let size = 0;
44
+ try { size = fs.statSync(file).size; } catch (_) { size = 0; }
45
+ if (size > 0) {
46
+ // 已有内容:必须核对 header 版本。
47
+ //
48
+ // 读侧(loadAllJsonl / readDirEntryJsonlFromDisk)遇到不支持的 header 版本会**整份丢弃**。
49
+ // 而追加只往文件末尾写 —— 若保留旧的 version:1 header,新追加的 version:2 行会永远读不到,
50
+ // 表现为「扫描在写、接口返回空」,比不写更糟(白耗 IO 还看不出问题)。
51
+ // 所以旧版本文件在这里直接删掉重建,而不是追加到它后面。
52
+ const existingVersion = readFirstLineVersion(file);
53
+ if (isSupportedVersion(existingVersion)) return false; // 同版本:正常追加
54
+ try {
55
+ fs.unlinkSync(file); // 旧版本/坏 header:整份作废
56
+ size = 0;
57
+ } catch (_) {
58
+ return false; // 删不掉就退回「只改内存」,不冒险往坏文件里追加
59
+ }
60
+ }
61
+ const header = JSON.stringify({
62
+ version: INDEX_VERSION,
63
+ category: category || "uncategorized",
64
+ updatedAt: new Date().toISOString(),
65
+ });
66
+ fs.writeFileSync(file, header + "\n");
67
+ return true;
68
+ }
69
+
70
+ /** 只读文件第一行并解析出版本号;读不到/坏行返回 null */
71
+ function readFirstLineVersion(file) {
72
+ let fd;
73
+ try { fd = fs.openSync(file, "r"); } catch (_) { return null; }
74
+ try {
75
+ const buf = Buffer.alloc(4096); // header 行远小于 4KB
76
+ const n = fs.readSync(fd, buf, 0, buf.length, 0);
77
+ if (n <= 0) return null;
78
+ const line = buf.subarray(0, n).toString("utf8").split("\n")[0];
79
+ return readHeaderVersion(line);
80
+ } catch (_) {
81
+ return null;
82
+ } finally {
83
+ try { fs.closeSync(fd); } catch (_) {}
84
+ }
85
+ }
86
+
87
+ // header 行(JSONL 第一行)里的版本号;坏 header 返回 null(视为不可用)
88
+ function readHeaderVersion(line) {
89
+ try {
90
+ const header = JSON.parse(line);
91
+ const version = header && header.version;
92
+ return typeof version === "number" ? version : null;
93
+ } catch (_) {
94
+ return null;
95
+ }
96
+ }
97
+
98
+ // 老版本索引一律作废(重建时自然会带上新字段)
99
+ function isSupportedVersion(version) {
100
+ return typeof version === "number" && version >= INDEX_VERSION;
101
+ }
18
102
  // StringDecoder:**必须**用它做流式解码,不能用 buf.toString("utf8", 0, n)。
19
103
  // 原因(实测过的线上 bug):1MB 缓冲边界若正好切在一个多字节 UTF-8 字符(例如「洛」= e6b49b 3 字节)中间,
20
104
  // buf.toString 会把两半分别解码 ⇒ 各得到一个替换字符 U+FFFD ⇒ 索引里的路径变成「[库\ufffd\ufffd]」,
@@ -124,6 +208,8 @@ function readDirEntryJsonlFromDisk(category, key) {
124
208
  const dec = new StringDecoder("utf8"); // 跨块多字节字符安全解码(原因见文件头注释)
125
209
  let rest = "";
126
210
  let lineNo = 0;
211
+ let headerVersion = null;
212
+ let found = null; // 最后一条匹配胜出:流式追加会让同一目录出现多行
127
213
  while (true) {
128
214
  const n = fs.readSync(fd, buf, 0, bufSize, null);
129
215
  if (n <= 0) break;
@@ -133,11 +219,16 @@ function readDirEntryJsonlFromDisk(category, key) {
133
219
  const line = rest.slice(0, idx);
134
220
  rest = rest.slice(idx + 1);
135
221
  lineNo++;
136
- if (lineNo === 1 || !line) continue; // header / 空行
222
+ if (lineNo === 1) { // header:先看版本
223
+ headerVersion = readHeaderVersion(line);
224
+ continue;
225
+ }
226
+ if (!line) continue; // 空行
227
+ if (!isSupportedVersion(headerVersion)) return null; // 老/坏索引:当作没有条目,让上层重建
137
228
  if (line.indexOf('"' + key + '"') < 0) continue; // 便宜的预筛,避免对每行 JSON.parse
138
229
  try {
139
230
  const obj = JSON.parse(line);
140
- if (obj && obj.k === key) return obj;
231
+ if (obj && obj.k === key) found = obj;
141
232
  } catch (_) {
142
233
  /* 坏行跳过:单行损坏不应影响其它条目 */
143
234
  }
@@ -146,10 +237,10 @@ function readDirEntryJsonlFromDisk(category, key) {
146
237
  if (rest.trim()) {
147
238
  try {
148
239
  const obj = JSON.parse(rest);
149
- if (obj && obj.k === key) return obj;
240
+ if (obj && obj.k === key) found = obj;
150
241
  } catch (_) { /* 同上 */ }
151
242
  }
152
- return null;
243
+ return found;
153
244
  } finally {
154
245
  try { fs.closeSync(fd); } catch (_) { /* ignore */ }
155
246
  }
@@ -172,7 +263,7 @@ function upsertDirEntryJsonl(category, key, entry) {
172
263
  const dir = path.dirname(file);
173
264
  fs.mkdirSync(dir, { recursive: true });
174
265
  const tmp = path.join(dir, "." + path.basename(file) + "." + process.pid + ".tmp");
175
- const header = JSON.stringify({ version: 1, category: category || "uncategorized", updatedAt: new Date().toISOString() });
266
+ const header = JSON.stringify({ version: INDEX_VERSION, category: category || "uncategorized", updatedAt: new Date().toISOString() });
176
267
  const line = JSON.stringify(Object.assign({ k: key }, entry));
177
268
  const out = fs.openSync(tmp, "w");
178
269
  let replaced = false;
@@ -190,7 +281,7 @@ function upsertDirEntryJsonl(category, key, entry) {
190
281
  if (inFd !== null) {
191
282
  const bufSize = 1 << 20;
192
283
  const buf = Buffer.alloc(bufSize);
193
- const dec = new StringDecoder("utf8"); // 跨块多字节字符安全解码(原因见文件头注释)
284
+ const dec = new StringDecoder("utf8"); // 跨块多字节字符安全解码(原因见文件头注释)
194
285
  let rest = "";
195
286
  let lineNo = 0;
196
287
  while (true) {
@@ -241,6 +332,8 @@ function loadAllJsonl(category) {
241
332
  function loadAllJsonlFromDisk(category) {
242
333
  const file = jsonlPathFor(category);
243
334
  const map = new Map();
335
+ // 行数在 finally 里要记账,所以必须声明在 try 之外(放进去会 ReferenceError)
336
+ let lineNo = 0;
244
337
  let fd;
245
338
  try { fd = fs.openSync(file, "r"); } catch (_) { return map; }
246
339
  try {
@@ -248,10 +341,16 @@ function loadAllJsonlFromDisk(category) {
248
341
  const buf = Buffer.alloc(bufSize);
249
342
  const dec = new StringDecoder("utf8"); // 跨块多字节字符安全解码(原因见文件头注释)
250
343
  let rest = "";
251
- let lineNo = 0;
344
+ let headerVersion = null;
252
345
  const take = (line) => {
253
346
  lineNo++;
254
- if (lineNo === 1 || !line) return;
347
+ if (lineNo === 1) {
348
+ headerVersion = readHeaderVersion(line);
349
+ return;
350
+ }
351
+ if (!line) return;
352
+ // 老/坏索引整份丢弃:里面没有 width/height,留着会让上层一直读到无尺寸的旧条目
353
+ if (!isSupportedVersion(headerVersion)) return;
255
354
  try {
256
355
  const obj = JSON.parse(line);
257
356
  if (obj && obj.k) map.set(obj.k, obj);
@@ -270,6 +369,8 @@ function loadAllJsonlFromDisk(category) {
270
369
  if (rest.trim()) take(rest);
271
370
  } finally {
272
371
  try { fs.closeSync(fd); } catch (_) { /* ignore */ }
372
+ // 顺带记下行数(含 header):压缩判据要用,但不值得为它再读一遍文件
373
+ LINE_COUNTS.set(file, lineNo);
273
374
  }
274
375
  return map;
275
376
  }
@@ -285,7 +386,7 @@ function writeAllJsonl(category, map) {
285
386
  const dir = path.dirname(file);
286
387
  fs.mkdirSync(dir, { recursive: true });
287
388
  const tmp = path.join(dir, "." + path.basename(file) + "." + process.pid + ".tmp");
288
- const header = JSON.stringify({ version: 1, category: category || "uncategorized", updatedAt: new Date().toISOString() });
389
+ const header = JSON.stringify({ version: INDEX_VERSION, category: category || "uncategorized", updatedAt: new Date().toISOString() });
289
390
  const out = fs.openSync(tmp, "w");
290
391
  try {
291
392
  fs.writeSync(out, header + "\n");
@@ -298,6 +399,7 @@ function writeAllJsonl(category, map) {
298
399
  fs.renameSync(tmp, file);
299
400
  // 落盘后立刻失效缓存(理由同 upsertDirEntryJsonl:指纹在极端情况下可能不变)
300
401
  indexCache.invalidate(file);
402
+ LINE_COUNTS.set(file, map.size + 1); // 重写后一定不膨胀:条目数 + header
301
403
  return map.size;
302
404
  }
303
405
 
@@ -309,7 +411,10 @@ function writeAllJsonl(category, map) {
309
411
  function readShard(category, root, dir) {
310
412
  const shard = shardPathFor(category, root, dir);
311
413
  let store = readJsonSafe(shard, null);
312
- if (store && store.dirs) return { store, file: shard, legacy: false };
414
+ // 版本不够的分片直接当不存在:老分片里的条目没有 width/height
415
+ if (store && store.dirs && isSupportedVersion(store.version)) {
416
+ return { store, file: shard, legacy: false };
417
+ }
313
418
 
314
419
  const legacyFile = indexPathOf(category);
315
420
  const legacy = readJsonSafe(legacyFile, null);
@@ -321,7 +426,7 @@ function readShard(category, root, dir) {
321
426
  const p = v && v.dir ? path.resolve(v.dir) : "";
322
427
  if (p && (p === r || p.startsWith(prefix))) dirs[k] = v;
323
428
  }
324
- store = { version: 1, category: category || "uncategorized", dirs, migratedFrom: "index.json" };
429
+ store = { version: INDEX_VERSION, category: category || "uncategorized", dirs, migratedFrom: "index.json" };
325
430
  try {
326
431
  writeJsonAtomic(shard, store);
327
432
  fs.rmSync(legacyFile, { force: true }); // 迁移后删旧大文件(释放数百 MB)
@@ -331,7 +436,7 @@ function readShard(category, root, dir) {
331
436
  return { store, file: shard, legacy: true };
332
437
  }
333
438
 
334
- return { store: { version: 1, category: category || "uncategorized", dirs: {} }, file: shard, legacy: false };
439
+ return { store: { version: INDEX_VERSION, category: category || "uncategorized", dirs: {} }, file: shard, legacy: false };
335
440
  }
336
441
 
337
442
  /** 目录在索引里的键:用目录相对项目根的路径做可读化编码 */
@@ -376,6 +481,69 @@ function dirMtimeMs(dir) {
376
481
  * 子目录里的图会插在该目录后续文件之前;要保证前端显示零变化,必须能原样重放这个顺序。
377
482
  * items: [{ t:'f', img:{name,path,url,size,modified} } | { t:'d', name }]
378
483
  */
484
+ /**
485
+ * 图片条目的字段构建(同步/异步两条扫描路径共用)。
486
+ *
487
+ * 抽出来是为了防漂移:字段一旦在某条路径上多/少一个,客户端会看到"有些图有尺寸有些不有",
488
+ * 而这种差异很难在日志里看出来。
489
+ */
490
+ function buildImageItem(name, full, sizeBytes, mtime, dimensions) {
491
+ return {
492
+ name,
493
+ path: full,
494
+ url: `/api/media?file=${encodeURIComponent(full)}`,
495
+ size: formatSize(sizeBytes),
496
+ modified: mtime.toISOString(),
497
+ width: dimensions ? dimensions.width : null,
498
+ height: dimensions ? dimensions.height : null,
499
+ };
500
+ }
501
+
502
+ /** dirMtimeMs 的异步版:扫描路径专用(同步版留给 getDirEntry 这类单目录读取)。 */
503
+ async function dirMtimeMsAsync(dir) {
504
+ try {
505
+ return (await fs.promises.stat(dir)).mtimeMs;
506
+ } catch (_) {
507
+ return 0;
508
+ }
509
+ }
510
+
511
+ /**
512
+ * scanDirShallow 的异步版:只把 IO 换成 fs.promises,**遍历顺序与产出顺序与同步版逐项一致**。
513
+ *
514
+ * 关键约束:条目循环是**串行 await**,不用 Promise.all —— 并发读目录会让
515
+ * readdir 顺序与完成顺序错开,产出的图片顺序就变了(前端分组/卡片顺序属显示变化,不能动)。
516
+ */
517
+ async function scanDirShallowAsync(dir) {
518
+ const d = path.resolve(String(dir));
519
+ const items = [];
520
+ const images = [];
521
+ let entries = [];
522
+ try {
523
+ entries = await fs.promises.readdir(d, { withFileTypes: true });
524
+ } catch (_) {
525
+ return { items, images, dirMtime: 0 };
526
+ }
527
+ for (const entry of entries) {
528
+ if (entry.isDirectory()) {
529
+ items.push({ t: "d", name: entry.name });
530
+ continue;
531
+ }
532
+ if (!entry.isFile() || !IMG_EXT_RE.test(entry.name)) continue;
533
+ const full = path.join(d, entry.name);
534
+ try {
535
+ const st = await fs.promises.stat(full);
536
+ const dimensions = await readDimensionsAsync(full);
537
+ const img = buildImageItem(entry.name, full, st.size, st.mtime, dimensions);
538
+ items.push({ t: "f", img });
539
+ images.push(img);
540
+ } catch (_) {
541
+ /* 扫描期文件被删/无权限:跳过该文件 */
542
+ }
543
+ }
544
+ return { items, images, dirMtime: await dirMtimeMsAsync(d) };
545
+ }
546
+
379
547
  function scanDirShallow(dir) {
380
548
  const d = path.resolve(String(dir));
381
549
  const items = [];
@@ -395,13 +563,10 @@ function scanDirShallow(dir) {
395
563
  const full = path.join(d, entry.name);
396
564
  try {
397
565
  const st = fs.statSync(full);
398
- const img = {
399
- name: entry.name,
400
- path: full,
401
- url: `/api/media?file=${encodeURIComponent(full)}`,
402
- size: formatSize(st.size),
403
- modified: st.mtime.toISOString(),
404
- };
566
+ // 多读一次文件头拿像素尺寸(几十 KB 的 read,不整文件读)。
567
+ // 读不出来就是 null —— 一张坏图不能让整层扫描失败。
568
+ const dimensions = readDimensions(full);
569
+ const img = buildImageItem(entry.name, full, st.size, st.mtime, dimensions);
405
570
  items.push({ t: "f", img });
406
571
  images.push(img);
407
572
  } catch (_) {
@@ -452,8 +617,33 @@ function getDirEntry(category, dir, opts) {
452
617
  */
453
618
  async function walkWithIndex(category, root, opts) {
454
619
  const options = opts || {};
620
+ // 并发闸门:全局同时只允许 1 个扫描,其余 FIFO 排队。
621
+ // 放在函数最外层(比流式追加那层 try/finally 更外),保证"排队期间什么都没干"。
622
+ const scanSlotKey = `idx:${category}:${path.resolve(String(root))}`;
623
+ await acquireScanSlot(scanSlotKey, (position) => queuedScan(scanSlotKey, position));
624
+ startScan(scanSlotKey);
625
+ try {
455
626
  // 流式载入本分类条目(内存只保留条目本身);不再整份解析 + 整份重写单文件
456
627
  const entries = options.persist === false ? new Map() : loadAllJsonl(category);
628
+ // 流式追加:遍历一开始就以 append 模式打开一次,之后每扫完一个目录立刻写一行。
629
+ // 这样"扫到一半被杀"时已扫的目录仍在文件里,下次访问直接命中 —— JSONL 的意义就在这。
630
+ const jsonlFile = jsonlPathFor(category);
631
+ let appendFd = null;
632
+ let appendedCount = 0;
633
+ let appendFailures = 0;
634
+ // 攒批再写:fs.writeSync 是同步 syscall,每目录一次会让同步调用数暴涨,
635
+ // 而同步调用本身就是"扫描期间服务卡"的一部分。攒 FLUSH_EVERY 个再写一次:
636
+ // 中断最多丢这一批(相对几万个目录可以忽略),同步调用降到 1/FLUSH_EVERY。
637
+ // 24 是拍的:再大丢得更多、再小收益不明显;有实测依据可以调,但别调成 1。
638
+ const pendingLines = [];
639
+ if (options.persist !== false) {
640
+ try {
641
+ ensureJsonlHeader(jsonlFile, category);
642
+ appendFd = fs.openSync(jsonlFile, "a");
643
+ } catch (_) {
644
+ appendFd = null; // 打不开就退回"只改内存",扫描照常
645
+ }
646
+ }
457
647
  const exclude = new Set((options.excludeDirs || []).map((s) => String(s)));
458
648
  // skipDirs:本次遍历**不下钻**的子树(绝对路径)。
459
649
  // 用途:前端「当前目录优先」时第一步已单独取过该子树,第二步请求整根时把它跳过 ⇒
@@ -461,24 +651,57 @@ async function walkWithIndex(category, root, opts) {
461
651
  const skipDirs = new Set((options.skipDirs || []).map((p) => path.resolve(String(p))));
462
652
  const images = [];
463
653
  let dirsSeen = 0;
654
+ // 已产出图片数的累计器:供进度上报用(外层 images 是在 entryOf 返回后才 push,
655
+ // 在 entryOf 里读 images.length 会永远读到上一轮的旧值)
656
+ let imagesSoFar = 0;
464
657
  let hits = 0;
465
658
  let scans = 0;
466
659
 
467
- function entryOf(dir) {
660
+ function flushPending() {
661
+ if (appendFd === null || pendingLines.length === 0) return;
662
+ try {
663
+ fs.writeSync(appendFd, pendingLines.join(""));
664
+ appendedCount += pendingLines.length;
665
+ } catch (_) {
666
+ // 写失败不中断扫描:内存里仍有,本轮返回照常;只记数便于事后发现磁盘问题
667
+ appendFailures += pendingLines.length;
668
+ }
669
+ pendingLines.length = 0;
670
+ }
671
+
672
+ // 单个目录的"查缓存 / 扫一层"都在这里收口。
673
+ // 下一步把 readdirSync/statSync 换成 fs.promises 时,只需要改这里(entryOf 变成 async、
674
+ // 调用点加 await),遍历结构与追加逻辑都不用动。
675
+ async function entryOf(dir) {
468
676
  const abs = path.resolve(dir);
469
677
  const key = dirKey(abs);
470
- const mtime = dirMtimeMs(abs);
678
+ const mtime = await dirMtimeMsAsync(abs);
471
679
  const cached = entries.get(key);
472
680
  if (cached && mtime && cached.dirMtime === mtime) {
473
681
  hits++;
474
682
  return cached;
475
683
  }
476
- const scanned = scanDirShallow(abs);
684
+ const scanned = await scanDirShallowAsync(abs);
477
685
  const entry = { k: key, dir: abs, dirMtime: scanned.dirMtime, items: scanned.items, images: scanned.images };
478
686
  if (options.persist !== false) {
479
- entries.set(key, entry); // 只在内存里改;遍历结束后一次性写盘(见函数末尾 writeAllJsonl)
687
+ entries.set(key, entry);
688
+ // 边扫边落盘:立即追加一行(不是只改内存)。
689
+ // 写失败**不中断扫描**:内存里仍有这条,本轮返回照常;只记数,便于事后发现磁盘问题。
690
+ if (appendFd !== null) {
691
+ pendingLines.push(JSON.stringify(entry) + "\n");
692
+ if (pendingLines.length >= FLUSH_EVERY) flushPending();
693
+ }
480
694
  }
481
695
  scans++;
696
+ // 进度:每完成一个目录报一次(节流在 scan-progress 里做,这里只提供事实)。
697
+ //
698
+ // 两个数量都取「此刻已确认」的值,不能用外层变量:
699
+ // · dirs 用 dirsSeen —— 调用点已先 ++,代表"已处理的目录数";
700
+ // · scanned 用累计已产出的图片数 —— 外层 images 数组要等 entryOf 返回后才 push,
701
+ // 在 entryOf 里读它是**上一轮**的旧值(第一轮恒为 0),进度会一直停在 0。
702
+ // 故这里用 imagesSoFar 累计器:扫到一个目录就把该目录的图片数加进去。
703
+ imagesSoFar += Array.isArray(scanned.images) ? scanned.images.length : 0;
704
+ bumpScan(scanSlotKey, { scanned: imagesSoFar, dirs: dirsSeen, currentPath: abs });
482
705
  return entry;
483
706
  }
484
707
 
@@ -486,11 +709,12 @@ async function walkWithIndex(category, root, opts) {
486
709
  // 又不会长时间占死事件循环(此前纯同步递归会把服务器堵到首页 HTML 都发不出去)。
487
710
  const YIELD_EVERY = 64; // 每处理 64 个目录让出一次(与 scan.js 的既有做法一致)
488
711
  const stack = [{ dir: path.resolve(String(root)), items: null, idx: 0 }];
712
+ try {
489
713
  while (stack.length) {
490
714
  const frame = stack[stack.length - 1];
491
715
  if (frame.items === null || !Array.isArray(frame.items)) {
492
716
  dirsSeen++;
493
- const entry = entryOf(frame.dir);
717
+ const entry = await entryOf(frame.dir);
494
718
  frame.items = Array.isArray(entry.items) ? entry.items : [];
495
719
  frame.idx = 0;
496
720
  if (dirsSeen % YIELD_EVERY === 0) await new Promise((r) => setImmediate(r));
@@ -510,16 +734,43 @@ async function walkWithIndex(category, root, opts) {
510
734
  }
511
735
  }
512
736
 
513
- // 遍历期间只在内存里改,收尾一次性写盘(避免每目录 open→rename 造成的句柄堆积与 O(n²) 重写)
737
+ } finally {
738
+ // 无论正常结束还是中途抛错:先把攒着的这批写掉,再关句柄
739
+ flushPending();
740
+ if (appendFd !== null) {
741
+ try { fs.closeSync(appendFd); } catch (_) { /* ignore */ }
742
+ appendFd = null;
743
+ }
744
+ }
745
+
746
+ if (appendFailures > 0) {
747
+ console.warn(`[index-store] 追加写失败 ${appendFailures} 次(分类 ${category}):磁盘问题,扫描未受影响`);
748
+ }
749
+
750
+ // 压缩:**只在遍历结束后**判断,中途压缩等于回到"全量重写"的老问题。
751
+ // 判据:文件行数超过唯一目录数的 2 倍(说明同一目录被追加了多次)。
514
752
  if (scans > 0 && options.persist !== false) {
515
753
  try {
516
- writeAllJsonl(category, entries);
754
+ const linesBefore = LINE_COUNTS.get(jsonlFile) || 0;
755
+ const totalLines = linesBefore + appendedCount;
756
+ if (totalLines > entries.size * COMPACT_LINE_RATIO) {
757
+ writeAllJsonl(category, entries); // 内部会重设 LINE_COUNTS 并失效缓存
758
+ } else {
759
+ // 没压缩:行数已因追加而变化,让缓存数字失效(下次载入时重算)
760
+ LINE_COUNTS.delete(jsonlFile);
761
+ }
517
762
  } catch (_) {
518
763
  /* 落盘失败不影响本次返回(下次访问重建即可) */
519
764
  }
520
765
  }
521
766
 
522
767
  return { images, dirsSeen, hits, scans };
768
+ } finally {
769
+ // 先收进度(强制发布最终值),再释放槽位
770
+ endScan(scanSlotKey);
771
+ // 抛错也要释放:否则槽位永久占死,之后所有分类都扫不动
772
+ releaseScanSlot();
773
+ }
523
774
  }
524
775
 
525
776
  /** 手动重建(保留但不自动跑):按目录 / 按分类 / 全量;批量导入后一次性补全用 */
@@ -554,6 +805,8 @@ module.exports = {
554
805
  writeJsonAtomic,
555
806
  dirMtimeMs,
556
807
  scanDirShallow,
808
+ dirMtimeMsAsync,
809
+ scanDirShallowAsync,
557
810
  getDirEntry,
558
811
  walkWithIndex,
559
812
  // 流式读写与路径(供回归测试与运维脚本使用;跨块多字节解码的正确性由它们保证)
@@ -0,0 +1,149 @@
1
+ // 扫描进度:内存里的实时进度表 + 节流发布。
2
+ //
3
+ // 为什么要节流:一个大根有几万个目录,每个目录都更新一次对象是没必要的分配;
4
+ // 但**不能只按目录数节流** —— 遇到一棵"空目录树"可能几十秒没有新增图片,
5
+ // 那样轮询方会以为卡死。所以心跳是独立的一条:即使进度没变,每 2 秒也发布一次。
6
+ //
7
+ // 三个触发条件(先到先发):每 N 个目录 / 心跳到期 / 扫描开始与结束(必须发)。
8
+ //
9
+ // 这个模块只碰内存:`progressSnapshot()` 不做任何 IO,端点直接返回它 ——
10
+ // 否则"查进度"本身就会变成一次扫描,把要观测的问题变成问题的一部分。
11
+
12
+ const PROGRESS_EVERY_DIRS = 50;
13
+ const PROGRESS_HEARTBEAT_MS = 2000;
14
+ /** 扫描结束后保留多久(让迟到的轮询能看到 done,而不是突然消失) */
15
+ const DONE_RETAIN_MS = 5000;
16
+
17
+ /** key -> { key, phase, scanned, dirs, currentPath, startedAt, publishedDirs, publishedAt, finishedAt, position } */
18
+ const table = new Map();
19
+
20
+ function now() {
21
+ return Date.now();
22
+ }
23
+
24
+ /** 开始扫描:立刻发布一帧(scanned=0),让轮询方马上知道"有人在扫"。 */
25
+ function startScan(key) {
26
+ const at = now();
27
+ table.set(key, {
28
+ key,
29
+ phase: "scan",
30
+ scanned: 0,
31
+ dirs: 0,
32
+ currentPath: "",
33
+ startedAt: at,
34
+ publishedDirs: 0,
35
+ publishedAt: at,
36
+ finishedAt: 0,
37
+ position: 0,
38
+ latestScanned: 0,
39
+ latestDirs: 0,
40
+ latestPath: "",
41
+ });
42
+ }
43
+
44
+ /** 排队中:让"还没开始扫"的请求也能被看到(否则用户只看到转圈)。 */
45
+ function queuedScan(key, position) {
46
+ if (table.has(key)) return;
47
+ table.set(key, {
48
+ key,
49
+ phase: "queued",
50
+ scanned: 0,
51
+ dirs: 0,
52
+ currentPath: "",
53
+ startedAt: now(),
54
+ publishedDirs: 0,
55
+ publishedAt: now(),
56
+ finishedAt: 0,
57
+ position: position || 0,
58
+ });
59
+ }
60
+
61
+ /**
62
+ * 报一次进度。是否真的更新"已发布"字段由节流决定(先到先发)。
63
+ *
64
+ * @param {string} key
65
+ * @param {{scanned:number, dirs:number, currentPath:string}} progress
66
+ */
67
+ function bumpScan(key, progress) {
68
+ const entry = table.get(key);
69
+ if (!entry) return;
70
+
71
+ // 内部先记最新事实(不对外)
72
+ entry.latestScanned = progress.scanned;
73
+ entry.latestDirs = progress.dirs;
74
+ if (progress.currentPath) entry.latestPath = progress.currentPath;
75
+
76
+ // 发布条件(先到先发):
77
+ // ① **首个目录必须立刻发布** —— 否则小规模扫描(几十个目录、几百毫秒扫完)永远等不到
78
+ // "每 50 个目录"或"2 秒心跳",进度自始至终停在 0,表现成「进度功能没生效」。
79
+ // ② 每 N 个目录发布一次(降低推送频率)
80
+ // ③ 心跳到期发布(长扫描里目录涨得慢时也要有动静)
81
+ // "开始/结束"两帧由 startScan/endScan 强制发布,不经过这里。
82
+ const isFirstPublish = entry.publishedDirs === 0 && entry.latestDirs > 0;
83
+ const byDirs = entry.latestDirs - entry.publishedDirs >= PROGRESS_EVERY_DIRS;
84
+ const byHeartbeat = now() - entry.publishedAt >= PROGRESS_HEARTBEAT_MS;
85
+ if (!isFirstPublish && !byDirs && !byHeartbeat) return;
86
+
87
+ entry.scanned = entry.latestScanned;
88
+ entry.dirs = entry.latestDirs;
89
+ if (entry.latestPath) entry.currentPath = entry.latestPath;
90
+ entry.publishedDirs = entry.latestDirs;
91
+ entry.publishedAt = now();
92
+ }
93
+
94
+ /** 扫描结束:强制发布最终值,并在 DONE_RETAIN_MS 后移除。 */
95
+ function endScan(key) {
96
+ const entry = table.get(key);
97
+ if (!entry) return;
98
+ entry.phase = "done";
99
+ entry.finishedAt = now();
100
+ // 强制发布最终值:否则轮询方会停在上一次节流发布的中间值
101
+ entry.scanned = entry.latestScanned;
102
+ entry.dirs = entry.latestDirs;
103
+ if (entry.latestPath) entry.currentPath = entry.latestPath;
104
+ entry.publishedDirs = entry.dirs;
105
+ entry.publishedAt = entry.finishedAt;
106
+
107
+ const timer = setTimeout(() => {
108
+ const current = table.get(key);
109
+ // 只有仍是"这次扫描"的 done 记录才删(期间可能有新的扫描复用同一 key)
110
+ if (current && current.finishedAt === entry.finishedAt) table.delete(key);
111
+ }, DONE_RETAIN_MS);
112
+ // 不让这个定时器拖住进程退出(测试/命令行场景)
113
+ if (typeof timer.unref === "function") timer.unref();
114
+ }
115
+
116
+ /**
117
+ * 当前进度快照(只读内存,不做任何 IO)。
118
+ *
119
+ * @returns {Array<object>} 每项 { key, phase, scanned, dirs, currentPath, elapsedMs, position }
120
+ */
121
+ function progressSnapshot() {
122
+ const at = now();
123
+ return Array.from(table.values()).map((entry) => ({
124
+ key: entry.key,
125
+ phase: entry.phase,
126
+ scanned: entry.scanned,
127
+ dirs: entry.dirs,
128
+ currentPath: entry.currentPath,
129
+ elapsedMs: Math.max(0, (entry.finishedAt || at) - entry.startedAt),
130
+ position: entry.position,
131
+ }));
132
+ }
133
+
134
+ /** 清空(测试用;生产不调用) */
135
+ function resetProgress() {
136
+ table.clear();
137
+ }
138
+
139
+ module.exports = {
140
+ PROGRESS_EVERY_DIRS,
141
+ PROGRESS_HEARTBEAT_MS,
142
+ DONE_RETAIN_MS,
143
+ startScan,
144
+ queuedScan,
145
+ bumpScan,
146
+ endScan,
147
+ progressSnapshot,
148
+ resetProgress,
149
+ };