临时完整优化
This commit is contained in:
1 parent
9e346c7d5b
commit
d6b4919880
29 files changed
+5228
-400
No files matched your search
@@ -0,0 +1,267 @@
|
||||
/**
|
||||
* CacheManager - 后端缓存文件管理
|
||||
* 管理 .flypic/cache/ 目录下的缓存文件
|
||||
*/
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const crypto = require('crypto');
|
||||
|
||||
// 缓存版本号
|
||||
const CACHE_VERSION = 1;
|
||||
|
||||
class CacheManager {
|
||||
constructor(libraryPath) {
|
||||
this.libraryPath = libraryPath;
|
||||
this.cacheDir = path.join(libraryPath, '.flypic', 'cache');
|
||||
this.foldersDir = path.join(this.cacheDir, 'folders');
|
||||
|
||||
// 确保缓存目录存在
|
||||
this.ensureDirs();
|
||||
}
|
||||
|
||||
/**
|
||||
* 确保缓存目录存在
|
||||
*/
|
||||
ensureDirs() {
|
||||
if (!fs.existsSync(this.cacheDir)) {
|
||||
fs.mkdirSync(this.cacheDir, { recursive: true });
|
||||
}
|
||||
if (!fs.existsSync(this.foldersDir)) {
|
||||
fs.mkdirSync(this.foldersDir, { recursive: true });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成文件夹路径的哈希值(用于缓存文件名)
|
||||
*/
|
||||
hashFolder(folderPath) {
|
||||
return crypto.createHash('md5').update(folderPath || '__all__').digest('hex');
|
||||
}
|
||||
|
||||
// ==================== 素材库缓存 ====================
|
||||
|
||||
/**
|
||||
* 获取素材库缓存文件路径
|
||||
*/
|
||||
getLibraryCachePath() {
|
||||
return path.join(this.cacheDir, 'library.json');
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取素材库缓存
|
||||
* @returns {object|null}
|
||||
*/
|
||||
readLibraryCache() {
|
||||
try {
|
||||
const cachePath = this.getLibraryCachePath();
|
||||
if (!fs.existsSync(cachePath)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const content = fs.readFileSync(cachePath, 'utf-8');
|
||||
const cache = JSON.parse(content);
|
||||
|
||||
// 验证版本
|
||||
if (cache.version !== CACHE_VERSION) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return cache;
|
||||
} catch (error) {
|
||||
console.warn('Failed to read library cache:', error.message);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入素材库缓存
|
||||
* @param {object} data - { folderTree, totalCount, dbModifiedAt }
|
||||
*/
|
||||
writeLibraryCache(data) {
|
||||
try {
|
||||
const cachePath = this.getLibraryCachePath();
|
||||
const cache = {
|
||||
version: CACHE_VERSION,
|
||||
createdAt: Date.now(),
|
||||
dbModifiedAt: data.dbModifiedAt,
|
||||
totalCount: data.totalCount,
|
||||
folderTree: data.folderTree
|
||||
};
|
||||
|
||||
fs.writeFileSync(cachePath, JSON.stringify(cache), 'utf-8');
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.warn('Failed to write library cache:', error.message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 文件夹缓存 ====================
|
||||
|
||||
/**
|
||||
* 获取文件夹缓存文件路径
|
||||
*/
|
||||
getFolderCachePath(folderPath) {
|
||||
const hash = this.hashFolder(folderPath);
|
||||
return path.join(this.foldersDir, `${hash}.json`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取文件夹缓存
|
||||
* @param {string|null} folderPath
|
||||
* @returns {object|null}
|
||||
*/
|
||||
readFolderCache(folderPath) {
|
||||
try {
|
||||
const cachePath = this.getFolderCachePath(folderPath);
|
||||
if (!fs.existsSync(cachePath)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const content = fs.readFileSync(cachePath, 'utf-8');
|
||||
const cache = JSON.parse(content);
|
||||
|
||||
// 验证版本
|
||||
if (cache.version !== CACHE_VERSION) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return cache;
|
||||
} catch (error) {
|
||||
console.warn('Failed to read folder cache:', error.message);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入文件夹缓存
|
||||
* @param {string|null} folderPath
|
||||
* @param {Array} images
|
||||
* @param {number} dbModifiedAt
|
||||
*/
|
||||
writeFolderCache(folderPath, images, dbModifiedAt) {
|
||||
try {
|
||||
const cachePath = this.getFolderCachePath(folderPath);
|
||||
|
||||
// 精简图片数据
|
||||
const slimImages = images.map(img => ({
|
||||
id: img.id,
|
||||
path: img.path,
|
||||
filename: img.filename,
|
||||
width: img.width,
|
||||
height: img.height,
|
||||
thumbnail_path: img.thumbnail_path,
|
||||
file_type: img.file_type,
|
||||
created_at: img.created_at,
|
||||
format: img.format
|
||||
}));
|
||||
|
||||
const cache = {
|
||||
version: CACHE_VERSION,
|
||||
folder: folderPath || '__all__',
|
||||
cachedAt: Date.now(),
|
||||
dbModifiedAt,
|
||||
imageCount: images.length,
|
||||
images: slimImages
|
||||
};
|
||||
|
||||
fs.writeFileSync(cachePath, JSON.stringify(cache), 'utf-8');
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.warn('Failed to write folder cache:', error.message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 缓存清理 ====================
|
||||
|
||||
/**
|
||||
* 删除素材库缓存
|
||||
*/
|
||||
deleteLibraryCache() {
|
||||
try {
|
||||
const cachePath = this.getLibraryCachePath();
|
||||
if (fs.existsSync(cachePath)) {
|
||||
fs.unlinkSync(cachePath);
|
||||
}
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.warn('Failed to delete library cache:', error.message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除文件夹缓存
|
||||
*/
|
||||
deleteFolderCache(folderPath) {
|
||||
try {
|
||||
const cachePath = this.getFolderCachePath(folderPath);
|
||||
if (fs.existsSync(cachePath)) {
|
||||
fs.unlinkSync(cachePath);
|
||||
}
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.warn('Failed to delete folder cache:', error.message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除所有缓存
|
||||
*/
|
||||
clearAllCache() {
|
||||
try {
|
||||
// 删除素材库缓存
|
||||
this.deleteLibraryCache();
|
||||
|
||||
// 删除所有文件夹缓存
|
||||
if (fs.existsSync(this.foldersDir)) {
|
||||
const files = fs.readdirSync(this.foldersDir);
|
||||
for (const file of files) {
|
||||
fs.unlinkSync(path.join(this.foldersDir, file));
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.warn('Failed to clear all cache:', error.message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取缓存统计信息
|
||||
*/
|
||||
getCacheStats() {
|
||||
try {
|
||||
const stats = {
|
||||
hasLibraryCache: fs.existsSync(this.getLibraryCachePath()),
|
||||
folderCacheCount: 0,
|
||||
totalSize: 0
|
||||
};
|
||||
|
||||
if (fs.existsSync(this.foldersDir)) {
|
||||
const files = fs.readdirSync(this.foldersDir);
|
||||
stats.folderCacheCount = files.length;
|
||||
|
||||
for (const file of files) {
|
||||
const filePath = path.join(this.foldersDir, file);
|
||||
const fileStat = fs.statSync(filePath);
|
||||
stats.totalSize += fileStat.size;
|
||||
}
|
||||
}
|
||||
|
||||
if (stats.hasLibraryCache) {
|
||||
const libCacheStat = fs.statSync(this.getLibraryCachePath());
|
||||
stats.totalSize += libCacheStat.size;
|
||||
}
|
||||
|
||||
return stats;
|
||||
} catch (error) {
|
||||
return { hasLibraryCache: false, folderCacheCount: 0, totalSize: 0 };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = CacheManager;
|
||||
@@ -0,0 +1,201 @@
|
||||
/**
|
||||
* CacheManager 属性测试
|
||||
* **Feature: library-switch-optimization, Property 12: Cache file creation after full load**
|
||||
* **Feature: library-switch-optimization, Property 16: Folder cache creation**
|
||||
* **Validates: Requirements 6.1, 7.1**
|
||||
*/
|
||||
const { describe, it, expect, beforeEach, afterEach } = require('vitest');
|
||||
const fc = require('fast-check');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const os = require('os');
|
||||
const CacheManager = require('./cacheManager');
|
||||
|
||||
describe('CacheManager', () => {
|
||||
let testDir;
|
||||
let cacheManager;
|
||||
|
||||
beforeEach(() => {
|
||||
// 创建临时测试目录
|
||||
testDir = fs.mkdtempSync(path.join(os.tmpdir(), 'flypic-test-'));
|
||||
cacheManager = new CacheManager(testDir);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
// 清理测试目录
|
||||
fs.rmSync(testDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
/**
|
||||
* **Property 12: Cache file creation after full load**
|
||||
* *For any* library that completes full image loading, a cache file should
|
||||
* exist in the .flypic/cache directory.
|
||||
*/
|
||||
describe('Property 12: Cache file creation after full load', () => {
|
||||
it('should create library cache file when writeLibraryCache is called', () => {
|
||||
fc.assert(
|
||||
fc.property(
|
||||
fc.integer({ min: 0, max: 100000 }),
|
||||
fc.integer({ min: 0, max: Date.now() }),
|
||||
(totalCount, dbModifiedAt) => {
|
||||
const data = {
|
||||
folderTree: [],
|
||||
totalCount,
|
||||
dbModifiedAt
|
||||
};
|
||||
|
||||
cacheManager.writeLibraryCache(data);
|
||||
|
||||
const cachePath = cacheManager.getLibraryCachePath();
|
||||
return fs.existsSync(cachePath);
|
||||
}
|
||||
),
|
||||
{ numRuns: 50 }
|
||||
);
|
||||
});
|
||||
|
||||
it('should persist library cache data correctly', () => {
|
||||
fc.assert(
|
||||
fc.property(
|
||||
fc.integer({ min: 0, max: 100000 }),
|
||||
fc.integer({ min: 0, max: Date.now() }),
|
||||
(totalCount, dbModifiedAt) => {
|
||||
const data = {
|
||||
folderTree: [{ path: 'test', name: 'test', children: [] }],
|
||||
totalCount,
|
||||
dbModifiedAt
|
||||
};
|
||||
|
||||
cacheManager.writeLibraryCache(data);
|
||||
const cache = cacheManager.readLibraryCache();
|
||||
|
||||
return cache !== null &&
|
||||
cache.totalCount === totalCount &&
|
||||
cache.dbModifiedAt === dbModifiedAt &&
|
||||
cache.folderTree.length === 1;
|
||||
}
|
||||
),
|
||||
{ numRuns: 50 }
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* **Property 16: Folder cache creation**
|
||||
* *For any* folder whose images are fully loaded, a separate cache file
|
||||
* should be created for that folder.
|
||||
*/
|
||||
describe('Property 16: Folder cache creation', () => {
|
||||
it('should create folder cache file when writeFolderCache is called', () => {
|
||||
fc.assert(
|
||||
fc.property(
|
||||
fc.string({ minLength: 1, maxLength: 50 }),
|
||||
fc.integer({ min: 0, max: Date.now() }),
|
||||
(folderPath, dbModifiedAt) => {
|
||||
const images = [
|
||||
{ id: 1, path: 'img1.jpg', filename: 'img1.jpg', width: 100, height: 100 }
|
||||
];
|
||||
|
||||
cacheManager.writeFolderCache(folderPath, images, dbModifiedAt);
|
||||
|
||||
const cachePath = cacheManager.getFolderCachePath(folderPath);
|
||||
return fs.existsSync(cachePath);
|
||||
}
|
||||
),
|
||||
{ numRuns: 50 }
|
||||
);
|
||||
});
|
||||
|
||||
it('should create separate cache files for different folders', () => {
|
||||
fc.assert(
|
||||
fc.property(
|
||||
fc.array(fc.string({ minLength: 1, maxLength: 20 }), { minLength: 2, maxLength: 10 }),
|
||||
(folders) => {
|
||||
const uniqueFolders = [...new Set(folders)];
|
||||
const dbModifiedAt = Date.now();
|
||||
const images = [{ id: 1, path: 'img.jpg', filename: 'img.jpg', width: 100, height: 100 }];
|
||||
|
||||
for (const folder of uniqueFolders) {
|
||||
cacheManager.writeFolderCache(folder, images, dbModifiedAt);
|
||||
}
|
||||
|
||||
// 每个文件夹应该有独立的缓存文件
|
||||
const cacheFiles = new Set();
|
||||
for (const folder of uniqueFolders) {
|
||||
const cachePath = cacheManager.getFolderCachePath(folder);
|
||||
if (fs.existsSync(cachePath)) {
|
||||
cacheFiles.add(cachePath);
|
||||
}
|
||||
}
|
||||
|
||||
return cacheFiles.size === uniqueFolders.length;
|
||||
}
|
||||
),
|
||||
{ numRuns: 50 }
|
||||
);
|
||||
});
|
||||
|
||||
it('should persist folder cache data correctly', () => {
|
||||
fc.assert(
|
||||
fc.property(
|
||||
fc.string({ minLength: 1, maxLength: 50 }),
|
||||
fc.integer({ min: 1, max: 100 }),
|
||||
fc.integer({ min: 0, max: Date.now() }),
|
||||
(folderPath, imageCount, dbModifiedAt) => {
|
||||
const images = Array.from({ length: imageCount }, (_, i) => ({
|
||||
id: i + 1,
|
||||
path: `img${i}.jpg`,
|
||||
filename: `img${i}.jpg`,
|
||||
width: 100,
|
||||
height: 100,
|
||||
thumbnail_path: `thumb${i}.webp`,
|
||||
file_type: 'image',
|
||||
created_at: Date.now(),
|
||||
format: 'jpg'
|
||||
}));
|
||||
|
||||
cacheManager.writeFolderCache(folderPath, images, dbModifiedAt);
|
||||
const cache = cacheManager.readFolderCache(folderPath);
|
||||
|
||||
return cache !== null &&
|
||||
cache.imageCount === imageCount &&
|
||||
cache.images.length === imageCount &&
|
||||
cache.dbModifiedAt === dbModifiedAt;
|
||||
}
|
||||
),
|
||||
{ numRuns: 50 }
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Cache deletion', () => {
|
||||
it('should delete library cache', () => {
|
||||
cacheManager.writeLibraryCache({ folderTree: [], totalCount: 100, dbModifiedAt: Date.now() });
|
||||
expect(fs.existsSync(cacheManager.getLibraryCachePath())).toBe(true);
|
||||
|
||||
cacheManager.deleteLibraryCache();
|
||||
expect(fs.existsSync(cacheManager.getLibraryCachePath())).toBe(false);
|
||||
});
|
||||
|
||||
it('should delete folder cache', () => {
|
||||
const folder = 'test-folder';
|
||||
cacheManager.writeFolderCache(folder, [], Date.now());
|
||||
expect(fs.existsSync(cacheManager.getFolderCachePath(folder))).toBe(true);
|
||||
|
||||
cacheManager.deleteFolderCache(folder);
|
||||
expect(fs.existsSync(cacheManager.getFolderCachePath(folder))).toBe(false);
|
||||
});
|
||||
|
||||
it('should clear all cache', () => {
|
||||
cacheManager.writeLibraryCache({ folderTree: [], totalCount: 100, dbModifiedAt: Date.now() });
|
||||
cacheManager.writeFolderCache('folder1', [], Date.now());
|
||||
cacheManager.writeFolderCache('folder2', [], Date.now());
|
||||
|
||||
cacheManager.clearAllCache();
|
||||
|
||||
expect(fs.existsSync(cacheManager.getLibraryCachePath())).toBe(false);
|
||||
expect(fs.existsSync(cacheManager.getFolderCachePath('folder1'))).toBe(false);
|
||||
expect(fs.existsSync(cacheManager.getFolderCachePath('folder2'))).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
+134
-118
@@ -1,14 +1,15 @@
|
||||
const chokidar = require('chokidar');
|
||||
const { Worker } = require('worker_threads');
|
||||
const path = require('path');
|
||||
const { getLibrary } = require('./config');
|
||||
const { syncLibrary, applyChangesFromEvents } = require('./scanner');
|
||||
const { applyChangesFromEvents } = require('./scanner');
|
||||
const dbPool = require('../database/dbPool');
|
||||
|
||||
class FileWatcher {
|
||||
constructor() {
|
||||
this.watchers = new Map(); // libraryId -> watcher
|
||||
this.workers = new Map(); // libraryId -> Worker
|
||||
this.debounceTimers = new Map(); // libraryId -> { timer, forceRebuildFolders }
|
||||
this.changeBuffers = new Map(); // libraryId -> { filesAdded, filesChanged, filesRemoved, dirsAdded, dirsRemoved }
|
||||
this.ioRef = null; // Socket.IO 引用
|
||||
}
|
||||
|
||||
// 获取或创建变更缓冲区
|
||||
@@ -36,10 +37,13 @@ class FileWatcher {
|
||||
);
|
||||
}
|
||||
|
||||
// 启动监控
|
||||
// 启动监控(使用 Worker Thread,不阻塞主线程)
|
||||
watch(libraryId, io) {
|
||||
// 保存 io 引用
|
||||
this.ioRef = io;
|
||||
|
||||
// 如果已经在监控,先停止
|
||||
if (this.watchers.has(libraryId)) {
|
||||
if (this.workers.has(libraryId)) {
|
||||
this.unwatch(libraryId);
|
||||
}
|
||||
|
||||
@@ -56,137 +60,149 @@ class FileWatcher {
|
||||
} catch (error) {
|
||||
const errorMsg = `Cannot access library path: ${library.path} - ${error.message}`;
|
||||
console.error(errorMsg);
|
||||
console.error('提示:在飞牛 fnOS 上,请确保在应用设置中授予了文件夹访问权限');
|
||||
throw new Error(errorMsg);
|
||||
}
|
||||
|
||||
console.log(`Starting file watcher for library: ${library.name} (${library.path})`);
|
||||
console.log(`[FileWatcher] Starting worker for: ${library.name} (${library.path})`);
|
||||
|
||||
// 监控所有文件(使用通配符)
|
||||
const pattern = '**/*.*';
|
||||
|
||||
// 创建监控器(监控所有文件和文件夹)
|
||||
const watcher = chokidar.watch([pattern, '**/'], {
|
||||
cwd: library.path,
|
||||
ignored: [
|
||||
'**/node_modules/**',
|
||||
'**/.git/**',
|
||||
'**/.flypic/**', // 忽略自己的缓存目录
|
||||
'**/.*' // 忽略隐藏文件
|
||||
],
|
||||
persistent: true,
|
||||
ignoreInitial: true, // 忽略初始扫描
|
||||
usePolling: false, // 不使用轮询,减少 CPU 占用
|
||||
awaitWriteFinish: {
|
||||
stabilityThreshold: 1000, // 文件稳定 1 秒后触发,确保复制完成
|
||||
pollInterval: 200
|
||||
// 创建 Worker Thread
|
||||
const workerPath = path.join(__dirname, 'fileWatcherWorker.js');
|
||||
const worker = new Worker(workerPath, {
|
||||
workerData: {
|
||||
libraryPath: library.path,
|
||||
libraryName: library.name
|
||||
}
|
||||
});
|
||||
|
||||
// 防抖处理:多个文件变化合并为一次同步(自适应时长)
|
||||
const debouncedSync = (forceRebuildFolders = false) => {
|
||||
const buf = this._getBuffer(libraryId);
|
||||
const changeCount = this._bufferCount(buf);
|
||||
// 处理 Worker 消息
|
||||
worker.on('message', (msg) => {
|
||||
this._handleWorkerMessage(libraryId, library, msg);
|
||||
});
|
||||
|
||||
// 清除之前的定时器
|
||||
if (this.debounceTimers.has(libraryId)) {
|
||||
const oldTimer = this.debounceTimers.get(libraryId);
|
||||
clearTimeout(oldTimer.timer);
|
||||
// 聚合 forceRebuildFolders 标记
|
||||
forceRebuildFolders = forceRebuildFolders || oldTimer.forceRebuildFolders;
|
||||
worker.on('error', (error) => {
|
||||
console.error(`[FileWatcher] Worker error for ${library.name}:`, error);
|
||||
});
|
||||
|
||||
worker.on('exit', (code) => {
|
||||
if (code !== 0) {
|
||||
console.error(`[FileWatcher] Worker exited with code ${code} for ${library.name}`);
|
||||
}
|
||||
this.workers.delete(libraryId);
|
||||
});
|
||||
|
||||
// 自适应防抖时间:更快响应
|
||||
let debounceMs = 2000;
|
||||
if (changeCount <= 1) debounceMs = 800; // 单文件 0.8 秒
|
||||
else if (changeCount <= 5) debounceMs = 1000; // 少量 1 秒
|
||||
else if (changeCount <= 20) debounceMs = 1500;
|
||||
else if (changeCount <= 100) debounceMs = 2000;
|
||||
else debounceMs = 3000; // 大批量 3 秒
|
||||
this.workers.set(libraryId, worker);
|
||||
}
|
||||
|
||||
const timer = setTimeout(async () => {
|
||||
const snapshot = this._getBuffer(libraryId);
|
||||
// 清空缓冲区(开始新一轮累计)
|
||||
this.changeBuffers.set(libraryId, {
|
||||
filesAdded: new Set(),
|
||||
filesChanged: new Set(),
|
||||
filesRemoved: new Set(),
|
||||
dirsAdded: new Set(),
|
||||
dirsRemoved: new Set()
|
||||
});
|
||||
// 处理 Worker 发来的消息
|
||||
_handleWorkerMessage(libraryId, library, msg) {
|
||||
switch (msg.type) {
|
||||
case 'add':
|
||||
this._getBuffer(libraryId).filesAdded.add(msg.path);
|
||||
this._debouncedSync(libraryId, library);
|
||||
break;
|
||||
case 'unlink':
|
||||
this._getBuffer(libraryId).filesRemoved.add(msg.path);
|
||||
this._debouncedSync(libraryId, library);
|
||||
break;
|
||||
case 'change':
|
||||
this._getBuffer(libraryId).filesChanged.add(msg.path);
|
||||
this._debouncedSync(libraryId, library);
|
||||
break;
|
||||
case 'addDir':
|
||||
this._getBuffer(libraryId).dirsAdded.add(msg.path);
|
||||
this._debouncedSync(libraryId, library, true);
|
||||
break;
|
||||
case 'unlinkDir':
|
||||
this._getBuffer(libraryId).dirsRemoved.add(msg.path);
|
||||
this._debouncedSync(libraryId, library, true);
|
||||
break;
|
||||
case 'ready':
|
||||
console.log(`[FileWatcher] Ready for: ${library.name}`);
|
||||
break;
|
||||
case 'error':
|
||||
console.error(`[FileWatcher] Error for ${library.name}:`, msg.message);
|
||||
break;
|
||||
case 'closed':
|
||||
console.log(`[FileWatcher] Closed for: ${library.name}`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// 从连接池获取数据库连接
|
||||
const db = dbPool.acquire(library.path);
|
||||
// 防抖同步
|
||||
_debouncedSync(libraryId, library, forceRebuildFolders = false) {
|
||||
const buf = this._getBuffer(libraryId);
|
||||
const changeCount = this._bufferCount(buf);
|
||||
|
||||
try {
|
||||
const total = this._bufferCount(snapshot);
|
||||
let results;
|
||||
// 清除之前的定时器
|
||||
if (this.debounceTimers.has(libraryId)) {
|
||||
const oldTimer = this.debounceTimers.get(libraryId);
|
||||
clearTimeout(oldTimer.timer);
|
||||
forceRebuildFolders = forceRebuildFolders || oldTimer.forceRebuildFolders;
|
||||
}
|
||||
|
||||
// 始终使用基于事件的快速同步(不再调用 syncLibrary)
|
||||
results = await applyChangesFromEvents(library.path, db, {
|
||||
filesAdded: Array.from(snapshot.filesAdded),
|
||||
filesChanged: Array.from(snapshot.filesChanged),
|
||||
filesRemoved: Array.from(snapshot.filesRemoved),
|
||||
dirsAdded: Array.from(snapshot.dirsAdded),
|
||||
dirsRemoved: Array.from(snapshot.dirsRemoved)
|
||||
});
|
||||
// 自适应防抖时间
|
||||
let debounceMs = 2000;
|
||||
if (changeCount <= 1) debounceMs = 800;
|
||||
else if (changeCount <= 5) debounceMs = 1000;
|
||||
else if (changeCount <= 20) debounceMs = 1500;
|
||||
else if (changeCount <= 100) debounceMs = 2000;
|
||||
else debounceMs = 3000;
|
||||
|
||||
// 通过 Socket.IO 通知前端
|
||||
io.emit('scanComplete', { libraryId, results });
|
||||
console.log(`Sync complete for ${library.name}:`, results);
|
||||
} catch (error) {
|
||||
console.error(`Sync error for ${library.name}:`, error);
|
||||
io.emit('scanError', { libraryId, error: error.message });
|
||||
} finally {
|
||||
// 释放数据库连接(不关闭,复用)
|
||||
dbPool.release(library.path);
|
||||
}
|
||||
|
||||
this.debounceTimers.delete(libraryId);
|
||||
}, debounceMs);
|
||||
|
||||
this.debounceTimers.set(libraryId, { timer, forceRebuildFolders });
|
||||
};
|
||||
|
||||
// 监听文件和文件夹变化(写入缓冲,统一合并处理)
|
||||
watcher
|
||||
.on('add', (filePath) => {
|
||||
this._getBuffer(libraryId).filesAdded.add(filePath);
|
||||
debouncedSync();
|
||||
})
|
||||
.on('unlink', (filePath) => {
|
||||
this._getBuffer(libraryId).filesRemoved.add(filePath);
|
||||
debouncedSync();
|
||||
})
|
||||
.on('change', (filePath) => {
|
||||
this._getBuffer(libraryId).filesChanged.add(filePath);
|
||||
debouncedSync();
|
||||
})
|
||||
.on('addDir', (dirPath) => {
|
||||
this._getBuffer(libraryId).dirsAdded.add(dirPath);
|
||||
debouncedSync(true); // 强制重建文件夹结构
|
||||
})
|
||||
.on('unlinkDir', (dirPath) => {
|
||||
this._getBuffer(libraryId).dirsRemoved.add(dirPath);
|
||||
debouncedSync(true); // 强制重建文件夹结构
|
||||
})
|
||||
.on('error', (error) => {
|
||||
console.error(`Watcher error for ${library.name}:`, error);
|
||||
})
|
||||
.on('ready', () => {
|
||||
console.log(`File watcher ready for: ${library.name}`);
|
||||
const timer = setTimeout(async () => {
|
||||
const snapshot = this._getBuffer(libraryId);
|
||||
// 清空缓冲区
|
||||
this.changeBuffers.set(libraryId, {
|
||||
filesAdded: new Set(),
|
||||
filesChanged: new Set(),
|
||||
filesRemoved: new Set(),
|
||||
dirsAdded: new Set(),
|
||||
dirsRemoved: new Set()
|
||||
});
|
||||
|
||||
this.watchers.set(libraryId, watcher);
|
||||
const db = dbPool.acquire(library.path);
|
||||
|
||||
try {
|
||||
const results = await applyChangesFromEvents(library.path, db, {
|
||||
filesAdded: Array.from(snapshot.filesAdded),
|
||||
filesChanged: Array.from(snapshot.filesChanged),
|
||||
filesRemoved: Array.from(snapshot.filesRemoved),
|
||||
dirsAdded: Array.from(snapshot.dirsAdded),
|
||||
dirsRemoved: Array.from(snapshot.dirsRemoved)
|
||||
});
|
||||
|
||||
if (this.ioRef) {
|
||||
this.ioRef.emit('scanComplete', { libraryId, results });
|
||||
}
|
||||
console.log(`[FileWatcher] Sync complete for ${library.name}:`, results);
|
||||
} catch (error) {
|
||||
console.error(`[FileWatcher] Sync error for ${library.name}:`, error);
|
||||
if (this.ioRef) {
|
||||
this.ioRef.emit('scanError', { libraryId, error: error.message });
|
||||
}
|
||||
} finally {
|
||||
dbPool.release(library.path);
|
||||
}
|
||||
|
||||
this.debounceTimers.delete(libraryId);
|
||||
}, debounceMs);
|
||||
|
||||
this.debounceTimers.set(libraryId, { timer, forceRebuildFolders });
|
||||
}
|
||||
|
||||
// 停止监控
|
||||
unwatch(libraryId) {
|
||||
const watcher = this.watchers.get(libraryId);
|
||||
if (watcher) {
|
||||
watcher.close();
|
||||
this.watchers.delete(libraryId);
|
||||
console.log(`Stopped file watcher for library: ${libraryId}`);
|
||||
const worker = this.workers.get(libraryId);
|
||||
if (worker) {
|
||||
// 发送关闭命令给 Worker
|
||||
worker.postMessage({ type: 'close' });
|
||||
// 给 Worker 一些时间优雅关闭,然后强制终止
|
||||
setTimeout(() => {
|
||||
if (this.workers.has(libraryId)) {
|
||||
worker.terminate();
|
||||
this.workers.delete(libraryId);
|
||||
}
|
||||
}, 1000);
|
||||
console.log(`[FileWatcher] Stopping worker for: ${libraryId}`);
|
||||
}
|
||||
|
||||
// 清除防抖定时器
|
||||
@@ -204,19 +220,19 @@ class FileWatcher {
|
||||
|
||||
// 停止所有监控
|
||||
unwatchAll() {
|
||||
for (const libraryId of this.watchers.keys()) {
|
||||
for (const libraryId of this.workers.keys()) {
|
||||
this.unwatch(libraryId);
|
||||
}
|
||||
}
|
||||
|
||||
// 获取监控状态
|
||||
isWatching(libraryId) {
|
||||
return this.watchers.has(libraryId);
|
||||
return this.workers.has(libraryId);
|
||||
}
|
||||
|
||||
// 获取所有正在监控的库
|
||||
getWatchedLibraries() {
|
||||
return Array.from(this.watchers.keys());
|
||||
return Array.from(this.workers.keys());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* File Watcher Worker - 在独立线程中运行 chokidar
|
||||
* 避免文件监控初始化阻塞主线程的事件循环
|
||||
*/
|
||||
const { parentPort, workerData } = require('worker_threads');
|
||||
const chokidar = require('chokidar');
|
||||
|
||||
const { libraryPath, libraryName } = workerData;
|
||||
|
||||
console.log(`[Worker] Starting chokidar for: ${libraryName}`);
|
||||
|
||||
// 创建监控器
|
||||
const watcher = chokidar.watch(['**/*.*', '**/'], {
|
||||
cwd: libraryPath,
|
||||
ignored: [
|
||||
'**/node_modules/**',
|
||||
'**/.git/**',
|
||||
'**/.flypic/**',
|
||||
'**/.*'
|
||||
],
|
||||
persistent: true,
|
||||
ignoreInitial: true,
|
||||
usePolling: false,
|
||||
awaitWriteFinish: {
|
||||
stabilityThreshold: 1000,
|
||||
pollInterval: 200
|
||||
}
|
||||
});
|
||||
|
||||
// 监听事件并发送到主线程
|
||||
watcher
|
||||
.on('add', (filePath) => {
|
||||
parentPort.postMessage({ type: 'add', path: filePath });
|
||||
})
|
||||
.on('unlink', (filePath) => {
|
||||
parentPort.postMessage({ type: 'unlink', path: filePath });
|
||||
})
|
||||
.on('change', (filePath) => {
|
||||
parentPort.postMessage({ type: 'change', path: filePath });
|
||||
})
|
||||
.on('addDir', (dirPath) => {
|
||||
parentPort.postMessage({ type: 'addDir', path: dirPath });
|
||||
})
|
||||
.on('unlinkDir', (dirPath) => {
|
||||
parentPort.postMessage({ type: 'unlinkDir', path: dirPath });
|
||||
})
|
||||
.on('error', (error) => {
|
||||
parentPort.postMessage({ type: 'error', message: error.message });
|
||||
})
|
||||
.on('ready', () => {
|
||||
console.log(`[Worker] File watcher ready for: ${libraryName}`);
|
||||
parentPort.postMessage({ type: 'ready' });
|
||||
});
|
||||
|
||||
// 监听主线程的关闭命令
|
||||
parentPort.on('message', (msg) => {
|
||||
if (msg.type === 'close') {
|
||||
console.log(`[Worker] Closing watcher for: ${libraryName}`);
|
||||
watcher.close().then(() => {
|
||||
parentPort.postMessage({ type: 'closed' });
|
||||
process.exit(0);
|
||||
});
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user