清理多余优化

This commit is contained in:
Chen committed 2025-12-01 13:58:53 +08:00
1 parent d6b4919880
commit 3272593199
15 files changed
+30 -1790

No files matched your search

-193
View File
@@ -1,193 +0,0 @@
/**
* 缓存 API 路由
* 管理素材库和文件夹的缓存数据
*/
const express = require('express');
const router = express.Router();
const CacheManager = require('../utils/cacheManager');
const dbPool = require('../database/dbPool');
const { getLibrary } = require('../utils/config');
/**
* 获取素材库缓存
* GET /api/cache/library/:libraryId
*/
router.get('/library/:libraryId', (req, res) => {
try {
const { libraryId } = req.params;
const library = getLibrary(libraryId);
if (!library) {
return res.status(404).json({ error: 'Library not found' });
}
const cacheManager = new CacheManager(library.path);
const cache = cacheManager.readLibraryCache();
if (!cache) {
return res.status(404).json({ error: 'Cache not found' });
}
res.json(cache);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
/**
* 保存素材库缓存
* POST /api/cache/library/:libraryId
*/
router.post('/library/:libraryId', (req, res) => {
try {
const { libraryId } = req.params;
const { folderTree, totalCount, dbModifiedAt } = req.body;
const library = getLibrary(libraryId);
if (!library) {
return res.status(404).json({ error: 'Library not found' });
}
const cacheManager = new CacheManager(library.path);
const success = cacheManager.writeLibraryCache({
folderTree,
totalCount,
dbModifiedAt
});
if (success) {
res.json({ success: true });
} else {
res.status(500).json({ error: 'Failed to write cache' });
}
} catch (error) {
res.status(500).json({ error: error.message });
}
});
/**
* 获取文件夹缓存
* GET /api/cache/folder/:libraryId
* Query: folder (可选,不传则获取全部图片缓存)
*/
router.get('/folder/:libraryId', (req, res) => {
try {
const { libraryId } = req.params;
const { folder } = req.query;
const library = getLibrary(libraryId);
if (!library) {
return res.status(404).json({ error: 'Library not found' });
}
const cacheManager = new CacheManager(library.path);
const cache = cacheManager.readFolderCache(folder || null);
if (!cache) {
return res.status(404).json({ error: 'Folder cache not found' });
}
// 验证缓存是否过期
const db = dbPool.acquire(library.path);
try {
const dbModifiedAt = db.getLastModified();
if (cache.dbModifiedAt < dbModifiedAt) {
// 缓存过期
return res.status(410).json({
error: 'Cache stale',
cacheModifiedAt: cache.dbModifiedAt,
dbModifiedAt
});
}
res.json(cache);
} finally {
dbPool.release(library.path);
}
} catch (error) {
res.status(500).json({ error: error.message });
}
});
/**
* 保存文件夹缓存
* POST /api/cache/folder/:libraryId
*/
router.post('/folder/:libraryId', (req, res) => {
try {
const { libraryId } = req.params;
const { folder, images } = req.body;
const library = getLibrary(libraryId);
if (!library) {
return res.status(404).json({ error: 'Library not found' });
}
// 获取当前数据库修改时间
const db = dbPool.acquire(library.path);
let dbModifiedAt;
try {
dbModifiedAt = db.getLastModified();
} finally {
dbPool.release(library.path);
}
const cacheManager = new CacheManager(library.path);
const success = cacheManager.writeFolderCache(folder || null, images, dbModifiedAt);
if (success) {
res.json({ success: true, dbModifiedAt });
} else {
res.status(500).json({ error: 'Failed to write cache' });
}
} catch (error) {
res.status(500).json({ error: error.message });
}
});
/**
* 删除素材库所有缓存
* DELETE /api/cache/library/:libraryId
*/
router.delete('/library/:libraryId', (req, res) => {
try {
const { libraryId } = req.params;
const library = getLibrary(libraryId);
if (!library) {
return res.status(404).json({ error: 'Library not found' });
}
const cacheManager = new CacheManager(library.path);
cacheManager.clearAllCache();
res.json({ success: true });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
/**
* 获取缓存统计信息
* GET /api/cache/stats/:libraryId
*/
router.get('/stats/:libraryId', (req, res) => {
try {
const { libraryId } = req.params;
const library = getLibrary(libraryId);
if (!library) {
return res.status(404).json({ error: 'Library not found' });
}
const cacheManager = new CacheManager(library.path);
const stats = cacheManager.getCacheStats();
res.json(stats);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
module.exports = router;
-36
View File
@@ -7,18 +7,8 @@ const dbPool = require('../database/dbPool');
const { generateThumbnail } = require('../utils/thumbnail');
const { getLibrary } = require('../utils/config');
// 请求计数器(用于调试)
let requestCounter = 0;
let lastRequestTime = 0;
// Get images with search and filters (supports pagination)
router.get('/', (req, res) => {
const requestId = ++requestCounter;
const startTime = Date.now();
const timeSinceLastRequest = lastRequestTime ? startTime - lastRequestTime : 0;
lastRequestTime = startTime;
console.log(`[Image API #${requestId}] START folder=${req.query.folder || 'all'} offset=${req.query.offset || 0} | gap=${timeSinceLastRequest}ms`);
try {
const { libraryId, keywords, folder, formats, minSize, maxSize, startDate, endDate, offset, limit } = req.query;
@@ -31,10 +21,8 @@ router.get('/', (req, res) => {
return res.status(404).json({ error: 'Library not found' });
}
const acquireStart = Date.now();
// 使用连接池获取数据库连接
const db = dbPool.acquire(library.path);
const acquireTime = Date.now() - acquireStart;
try {
const filters = {};
@@ -54,14 +42,7 @@ router.get('/', (req, res) => {
};
}
const queryStart = Date.now();
const result = db.searchImages(keywords || '', filters, pagination);
const queryTime = Date.now() - queryStart;
const totalTime = Date.now() - startTime;
// 性能日志
console.log(`[Image API #${requestId}] END folder=${folder || 'all'} | acquire=${acquireTime}ms | query=${queryTime}ms | total=${totalTime}ms | count=${pagination ? result.images.length : result.length}`);
// 如果使用分页,返回分页格式;否则保持向后兼容
if (pagination) {
@@ -112,8 +93,6 @@ router.get('/cache-meta', (req, res) => {
// Get total image count
router.get('/count', (req, res) => {
const startTime = Date.now();
console.log(`[Image API] /count START`);
try {
const { libraryId } = req.query;
@@ -126,16 +105,10 @@ router.get('/count', (req, res) => {
return res.status(404).json({ error: 'Library not found' });
}
const acquireStart = Date.now();
const db = dbPool.acquire(library.path);
const acquireTime = Date.now() - acquireStart;
try {
const queryStart = Date.now();
const row = db.db.prepare('SELECT COUNT(*) as count FROM images').get();
const queryTime = Date.now() - queryStart;
const duration = Date.now() - startTime;
console.log(`[Image API] /count END | acquire=${acquireTime}ms | query=${queryTime}ms | total=${duration}ms | count=${row.count}`);
res.json({ count: row.count });
} finally {
dbPool.release(library.path);
@@ -147,8 +120,6 @@ router.get('/count', (req, res) => {
// Get folders
router.get('/folders', (req, res) => {
const startTime = Date.now();
console.log(`[Image API] /folders START`);
try {
const { libraryId } = req.query;
@@ -161,17 +132,10 @@ router.get('/folders', (req, res) => {
return res.status(404).json({ error: 'Library not found' });
}
// 使用连接池
const acquireStart = Date.now();
const db = dbPool.acquire(library.path);
const acquireTime = Date.now() - acquireStart;
try {
const queryStart = Date.now();
const folders = db.getFolderTree();
const queryTime = Date.now() - queryStart;
const duration = Date.now() - startTime;
console.log(`[Image API] /folders END | acquire=${acquireTime}ms | query=${queryTime}ms | total=${duration}ms | count=${folders.length}`);
res.json({ folders });
} finally {
dbPool.release(library.path);
+2 -17
View File
@@ -111,8 +111,6 @@ router.delete('/:id', async (req, res) => {
const fileWatcher = require('../utils/fileWatcher');
const scanManager = require('../utils/scanManager');
console.log(`[Delete] Cleaning up library: ${library.name}`);
// 1. 停止扫描并清理状态
scanManager.clearState(id);
@@ -128,8 +126,6 @@ router.delete('/:id', async (req, res) => {
// 删除索引
removeLibrary(id);
console.log(`✅ Library removed: ${library.name}`);
res.json({
message: 'Library removed successfully',
path: library.path
@@ -154,21 +150,16 @@ router.post('/:id/set-current', async (req, res) => {
if (oldLibraryId && oldLibraryId !== id) {
const oldLibrary = config.libraries.find(lib => lib.id === oldLibraryId);
if (oldLibrary) {
console.log(`[Switch] Cleaning up old library: ${oldLibrary.name}`);
// 1. 停止扫描(如果正在进行),但保留暂停状态以便恢复
// 1. 停止扫描(如果正在进行),但保留暂停状态以便恢复
if (scanManager.isScanning(oldLibraryId)) {
const state = scanManager.getState(oldLibraryId);
if (state.abortController) {
state.abortController.aborted = true;
}
// 不调用 completeScan,让扫描自己暂停并保留待处理文件
console.log(` ⏸️ Pausing scan (will preserve state)`);
}
// 3. 关闭数据库连接
// 2. 关闭数据库连接
dbPool.close(oldLibrary.path);
console.log(` ⏹️ Closed database`);
}
}
@@ -176,7 +167,6 @@ router.post('/:id/set-current', async (req, res) => {
setCurrentLibrary(id);
const newLibrary = config.libraries.find(lib => lib.id === id);
console.log(`[Switch] Switched to library: ${newLibrary?.name}`);
// 预热新数据库连接(避免第一个查询时才创建连接)
if (newLibrary) {
@@ -184,7 +174,6 @@ router.post('/:id/set-current', async (req, res) => {
// 执行一个简单查询来预热缓存
try {
db.db.prepare('SELECT 1').get();
console.log(`[Switch] Database connection warmed up`);
} catch (e) {
// 忽略预热错误
}
@@ -228,18 +217,14 @@ router.post('/:id/release', (req, res) => {
return res.status(404).json({ error: 'Library not found' });
}
console.log(`[Release] Releasing resources for library: ${library.name}`);
// 1. 关闭数据库连接
const dbPool = require('../database/dbPool');
dbPool.close(library.path);
console.log(`[Release] Database connection closed`);
// 2. 停止文件监控
const fileWatcher = req.app.get('fileWatcher');
if (fileWatcher && fileWatcher.isWatching(id)) {
fileWatcher.unwatch(id);
console.log(`[Release] File watcher stopped`);
}
res.json({
-2
View File
@@ -3,7 +3,6 @@ const router = express.Router();
// Start watching a library
router.post('/start/:libraryId', (req, res) => {
const startTime = Date.now();
try {
const { libraryId } = req.params;
const fileWatcher = req.app.get('fileWatcher');
@@ -20,7 +19,6 @@ router.post('/start/:libraryId', (req, res) => {
setImmediate(() => {
try {
fileWatcher.watch(libraryId, io);
console.log(`[Watch] Started in ${Date.now() - startTime}ms`);
} catch (watchError) {
console.error(`Failed to start file watching for ${libraryId}:`, watchError.message);
}
-3
View File
@@ -49,13 +49,10 @@ const libraryRouter = require('./routes/library');
const imageRouter = require('./routes/image');
const scanRouter = require('./routes/scan');
const watchRouter = require('./routes/watch');
const cacheRouter = require('./routes/cache');
app.use('/api/library', libraryRouter);
app.use('/api/image', imageRouter);
app.use('/api/scan', scanRouter);
app.use('/api/watch', watchRouter);
app.use('/api/cache', cacheRouter);
// Serve static files (production)
if (FRONTEND_DIST) {
-267
View File
@@ -1,267 +0,0 @@
/**
* 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;
-201
View File
@@ -1,201 +0,0 @@
/**
* 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);
});
});
});
-4
View File
@@ -52,12 +52,8 @@ function Header() {
// 启动文件监控
watchAPI.start(currentLibraryId)
.then(() => {
console.log('✅ 文件监控已启动(实时检测文件变化)');
})
.catch(error => {
console.error('启动文件监控失败:', error);
console.error('提示:在飞牛 fnOS 上,请确保在应用设置中授予了文件夹访问权限');
});
// 清理:关闭监控
+1 -4
View File
@@ -175,13 +175,10 @@ function ImageWaterfall() {
);
workerRef.current.onmessage = (e) => {
const { rows, requestId, duration, imageCount } = e.data;
const { rows, requestId } = e.data;
// 只处理最新的请求结果
if (requestId === requestIdRef.current) {
setWorkerRows(rows);
if (imageCount > 500) {
console.log(`📐 Worker layout: ${imageCount} images in ${duration.toFixed(1)}ms`);
}
}
};
}
+3 -22
View File
@@ -14,9 +14,7 @@ function MainContent() {
filters,
selectedFolder,
setImages,
setTotalImageCount,
scanProgress,
scanStartTime,
imageLoadingState
} = useStore();
@@ -24,10 +22,6 @@ function MainContent() {
const currentRequestContextRef = useRef(null);
// 文件夹切换防抖
const debounceTimerRef = useRef(null);
const [isLoadingImages, setIsLoadingImages] = useState(false);
// 使用 ref 追踪上次的 libraryId
const lastLibraryIdRef = useRef(null);
// 扫描控制
const [scanPaused, setScanPaused] = useState(false);
const [isStoppingOrResuming, setIsStoppingOrResuming] = useState(false);
@@ -59,7 +53,6 @@ function MainContent() {
// 如果没有选中文件夹且没有搜索条件,显示 Dashboard
if (!selectedFolder && !searchKeywords && filters.formats.length === 0) {
setImages([]);
setIsLoadingImages(false);
useStore.getState().setImageLoadingState({
isLoading: false,
loadedCount: 0,
@@ -78,7 +71,6 @@ function MainContent() {
currentRequestContextRef.current = requestContext;
// 设置加载状态
setIsLoadingImages(true);
useStore.getState().setImageLoadingState({
isLoading: true,
loadedCount: 0,
@@ -93,23 +85,16 @@ function MainContent() {
if (searchKeywords) params.keywords = searchKeywords;
if (filters.formats?.length > 0) params.formats = filters.formats.join(',');
const startTime = Date.now();
console.log(`📂 Loading folder: ${selectedFolder || 'all'} [reqId=${requestContext.id}] [pending=${requestManager.getActiveCount(RequestType.IMAGES)}]`);
const response = await imageAPI.search(currentLibraryId, params, {
signal: requestContext.signal
});
const networkTime = Date.now() - startTime;
// 检查请求是否被取消(使用 requestManager 检查)
// 检查请求是否被取消
if (!requestManager.isValid(requestContext.id)) {
console.log(`⏹️ Request cancelled [reqId=${requestContext.id}]`);
return;
}
const { images, total, hasMore } = response.data;
console.log(`✅ Loaded ${images.length}/${total} images | network=${networkTime}ms [reqId=${requestContext.id}]`);
// 标记请求完成
requestManager.complete(requestContext.id);
@@ -138,7 +123,6 @@ function MainContent() {
} finally {
// 只有当请求仍然有效时才更新状态
if (requestManager.isValid(requestContext.id) || requestContext.status === 'completed') {
setIsLoadingImages(false);
currentRequestContextRef.current = null;
}
}
@@ -159,13 +143,10 @@ function MainContent() {
// 立即清空图片,让 UI 快速响应
setImages([]);
// 使用防抖避免快速连续点击(150ms 足够过滤掉快速点击)
// 使用防抖避免快速连续点击
debounceTimerRef.current = setTimeout(() => {
loadImages();
}, 150);
// 更新 lastLibraryIdRef(文件夹加载已在 Sidebar 中处理)
lastLibraryIdRef.current = currentLibraryId;
}, 50);
return () => {
if (debounceTimerRef.current) {
-1
View File
@@ -3,7 +3,6 @@ import { Folder, Search, ChevronRight, ChevronDown, X, Trash2, ChevronsRight, Ch
import useStore from '../store/useStore';
import { libraryAPI, scanAPI, imageAPI } from '../services/api';
import requestManager, { RequestType } from '../services/requestManager';
import cacheService from '../services/cacheService';
import imageLoadService from '../services/imageLoadService';
// 检查素材库是否有暂停的扫描
-469
View File
@@ -1,469 +0,0 @@
/**
* CacheService - 前端缓存服务
* 管理素材库和文件夹的图片元数据缓存
*/
import { imageAPI } from './api';
// 缓存版本号,用于处理缓存格式升级
const CACHE_VERSION = 1;
// IndexedDB 数据库名称
const DB_NAME = 'flypic_cache';
const DB_VERSION = 1;
// 存储名称
const STORE_LIBRARY = 'library_cache';
const STORE_FOLDER = 'folder_cache';
// LRU 缓存最大文件夹数量
const MAX_FOLDER_CACHE = 50;
class CacheService {
constructor() {
this.db = null;
this.dbReady = this.initDB();
// 文件夹访问时间记录(用于 LRU)
this.folderAccessTimes = new Map();
}
/**
* 初始化 IndexedDB
*/
async initDB() {
return new Promise((resolve, reject) => {
const request = indexedDB.open(DB_NAME, DB_VERSION);
request.onerror = () => {
console.error('Failed to open IndexedDB:', request.error);
reject(request.error);
};
request.onsuccess = () => {
this.db = request.result;
resolve(this.db);
};
request.onupgradeneeded = (event) => {
const db = event.target.result;
// 素材库缓存存储
if (!db.objectStoreNames.contains(STORE_LIBRARY)) {
db.createObjectStore(STORE_LIBRARY, { keyPath: 'libraryId' });
}
// 文件夹缓存存储
if (!db.objectStoreNames.contains(STORE_FOLDER)) {
const folderStore = db.createObjectStore(STORE_FOLDER, { keyPath: 'cacheKey' });
folderStore.createIndex('libraryId', 'libraryId', { unique: false });
folderStore.createIndex('accessedAt', 'accessedAt', { unique: false });
}
};
});
}
/**
* 确保数据库已就绪
*/
async ensureDB() {
if (!this.db) {
await this.dbReady;
}
return this.db;
}
/**
* 生成文件夹缓存键
*/
getFolderCacheKey(libraryId, folder) {
return `${libraryId}:${folder || '__all__'}`;
}
// ==================== 素材库缓存 ====================
/**
* 获取素材库缓存
* @param {string} libraryId
* @returns {Promise<LibraryCache|null>}
*/
async getLibraryCache(libraryId) {
try {
const db = await this.ensureDB();
return new Promise((resolve, reject) => {
const tx = db.transaction(STORE_LIBRARY, 'readonly');
const store = tx.objectStore(STORE_LIBRARY);
const request = store.get(libraryId);
request.onsuccess = () => {
const cache = request.result;
if (cache && cache.version === CACHE_VERSION) {
resolve(cache);
} else {
resolve(null);
}
};
request.onerror = () => reject(request.error);
});
} catch (error) {
console.warn('Failed to get library cache:', error);
return null;
}
}
/**
* 保存素材库缓存
* @param {string} libraryId
* @param {object} data - { folders, totalCount, dbModifiedAt }
*/
async saveLibraryCache(libraryId, data) {
try {
const db = await this.ensureDB();
return new Promise((resolve, reject) => {
const tx = db.transaction(STORE_LIBRARY, 'readwrite');
const store = tx.objectStore(STORE_LIBRARY);
const cache = {
libraryId,
version: CACHE_VERSION,
createdAt: Date.now(),
dbModifiedAt: data.dbModifiedAt,
totalCount: data.totalCount,
folders: data.folders
};
const request = store.put(cache);
request.onsuccess = () => resolve();
request.onerror = () => reject(request.error);
});
} catch (error) {
console.warn('Failed to save library cache:', error);
}
}
/**
* 验证素材库缓存是否有效
* @param {string} libraryId
* @returns {Promise<CacheValidation>}
*/
async validateLibraryCache(libraryId) {
try {
const cache = await this.getLibraryCache(libraryId);
if (!cache) {
return { isValid: false, reason: 'not_found' };
}
// 从后端获取当前数据库修改时间
const response = await imageAPI.getCacheMeta(libraryId);
const currentDbModifiedAt = response.data.dbModifiedAt;
if (cache.dbModifiedAt >= currentDbModifiedAt) {
return {
isValid: true,
cache,
dbModifiedAt: currentDbModifiedAt,
cacheModifiedAt: cache.dbModifiedAt
};
} else {
return {
isValid: false,
reason: 'stale',
dbModifiedAt: currentDbModifiedAt,
cacheModifiedAt: cache.dbModifiedAt
};
}
} catch (error) {
console.warn('Failed to validate library cache:', error);
return { isValid: false, reason: 'error' };
}
}
// ==================== 文件夹缓存 ====================
/**
* 获取文件夹缓存
* @param {string} libraryId
* @param {string|null} folder
* @returns {Promise<FolderCache|null>}
*/
async getFolderCache(libraryId, folder) {
try {
const db = await this.ensureDB();
const cacheKey = this.getFolderCacheKey(libraryId, folder);
return new Promise((resolve, reject) => {
const tx = db.transaction(STORE_FOLDER, 'readwrite');
const store = tx.objectStore(STORE_FOLDER);
const request = store.get(cacheKey);
request.onsuccess = () => {
const cache = request.result;
if (cache && cache.version === CACHE_VERSION) {
// 更新访问时间
cache.accessedAt = Date.now();
store.put(cache);
this.folderAccessTimes.set(cacheKey, cache.accessedAt);
resolve(cache);
} else {
resolve(null);
}
};
request.onerror = () => reject(request.error);
});
} catch (error) {
console.warn('Failed to get folder cache:', error);
return null;
}
}
/**
* 保存文件夹缓存
* @param {string} libraryId
* @param {string|null} folder
* @param {Array} images
* @param {number} dbModifiedAt
*/
async saveFolderCache(libraryId, folder, images, dbModifiedAt) {
try {
const db = await this.ensureDB();
const cacheKey = this.getFolderCacheKey(libraryId, folder);
const now = Date.now();
// 先检查是否需要 LRU 驱逐(全局检查)
await this.evictIfNeeded(null, true);
return new Promise((resolve, reject) => {
const tx = db.transaction(STORE_FOLDER, 'readwrite');
const store = tx.objectStore(STORE_FOLDER);
// 精简图片数据,只保留必要字段
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 = {
cacheKey,
libraryId,
folder: folder || '__all__',
version: CACHE_VERSION,
cachedAt: now,
accessedAt: now,
dbModifiedAt,
imageCount: images.length,
images: slimImages
};
const request = store.put(cache);
request.onsuccess = () => {
this.folderAccessTimes.set(cacheKey, now);
resolve();
};
request.onerror = () => reject(request.error);
});
} catch (error) {
console.warn('Failed to save folder cache:', error);
}
}
/**
* LRU 驱逐:如果缓存数量超过阈值,删除最久未访问的缓存
* @param {string} libraryId - 当前素材库ID(可选,如果提供则只检查该素材库)
* @param {boolean} global - 是否检查全局缓存数量
*/
async evictIfNeeded(libraryId, global = false) {
try {
const db = await this.ensureDB();
return new Promise((resolve, reject) => {
const tx = db.transaction(STORE_FOLDER, 'readwrite');
const store = tx.objectStore(STORE_FOLDER);
// 获取所有缓存或特定素材库的缓存
let request;
if (global || !libraryId) {
request = store.getAll();
} else {
const index = store.index('libraryId');
request = index.getAll(libraryId);
}
request.onsuccess = () => {
const caches = request.result;
if (caches.length >= MAX_FOLDER_CACHE) {
// 按访问时间排序(最旧的在前)
caches.sort((a, b) => (a.accessedAt || 0) - (b.accessedAt || 0));
// 计算需要删除的数量:保留 MAX_FOLDER_CACHE - 1 个,为新缓存腾出空间
const deleteCount = caches.length - MAX_FOLDER_CACHE + 1;
const toDelete = caches.slice(0, deleteCount);
console.log(`🗑️ LRU eviction: removing ${toDelete.length} folder caches`);
for (const cache of toDelete) {
store.delete(cache.cacheKey);
this.folderAccessTimes.delete(cache.cacheKey);
}
}
resolve();
};
request.onerror = () => reject(request.error);
});
} catch (error) {
console.warn('Failed to evict cache:', error);
}
}
/**
* 获取当前缓存统计信息
* @returns {Promise<{libraryCount: number, folderCount: number, totalSize: number}>}
*/
async getCacheStats() {
try {
const db = await this.ensureDB();
const libraryCount = await new Promise((resolve, reject) => {
const tx = db.transaction(STORE_LIBRARY, 'readonly');
const store = tx.objectStore(STORE_LIBRARY);
const request = store.count();
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
const folderCount = await new Promise((resolve, reject) => {
const tx = db.transaction(STORE_FOLDER, 'readonly');
const store = tx.objectStore(STORE_FOLDER);
const request = store.count();
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
return { libraryCount, folderCount };
} catch (error) {
console.warn('Failed to get cache stats:', error);
return { libraryCount: 0, folderCount: 0 };
}
}
/**
* 获取最近访问的文件夹缓存列表
* @param {number} limit - 返回数量限制
* @returns {Promise<Array<{cacheKey: string, folder: string, accessedAt: number}>>}
*/
async getRecentFolderCaches(limit = 10) {
try {
const db = await this.ensureDB();
return new Promise((resolve, reject) => {
const tx = db.transaction(STORE_FOLDER, 'readonly');
const store = tx.objectStore(STORE_FOLDER);
const index = store.index('accessedAt');
// 使用游标从最新到最旧遍历
const results = [];
const request = index.openCursor(null, 'prev');
request.onsuccess = (event) => {
const cursor = event.target.result;
if (cursor && results.length < limit) {
const cache = cursor.value;
results.push({
cacheKey: cache.cacheKey,
libraryId: cache.libraryId,
folder: cache.folder,
accessedAt: cache.accessedAt,
imageCount: cache.imageCount
});
cursor.continue();
} else {
resolve(results);
}
};
request.onerror = () => reject(request.error);
});
} catch (error) {
console.warn('Failed to get recent folder caches:', error);
return [];
}
}
// ==================== 缓存失效 ====================
/**
* 清除素材库的所有缓存
* @param {string} libraryId
*/
async invalidateLibrary(libraryId) {
try {
const db = await this.ensureDB();
// 删除素材库缓存
await new Promise((resolve, reject) => {
const tx = db.transaction(STORE_LIBRARY, 'readwrite');
const store = tx.objectStore(STORE_LIBRARY);
const request = store.delete(libraryId);
request.onsuccess = () => resolve();
request.onerror = () => reject(request.error);
});
// 删除该素材库的所有文件夹缓存
await new Promise((resolve, reject) => {
const tx = db.transaction(STORE_FOLDER, 'readwrite');
const store = tx.objectStore(STORE_FOLDER);
const index = store.index('libraryId');
const request = index.getAllKeys(libraryId);
request.onsuccess = () => {
const keys = request.result;
for (const key of keys) {
store.delete(key);
this.folderAccessTimes.delete(key);
}
resolve();
};
request.onerror = () => reject(request.error);
});
} catch (error) {
console.warn('Failed to invalidate library cache:', error);
}
}
/**
* 清除特定文件夹的缓存
* @param {string} libraryId
* @param {string|null} folder
*/
async invalidateFolder(libraryId, folder) {
try {
const db = await this.ensureDB();
const cacheKey = this.getFolderCacheKey(libraryId, folder);
return new Promise((resolve, reject) => {
const tx = db.transaction(STORE_FOLDER, 'readwrite');
const store = tx.objectStore(STORE_FOLDER);
const request = store.delete(cacheKey);
request.onsuccess = () => {
this.folderAccessTimes.delete(cacheKey);
resolve();
};
request.onerror = () => reject(request.error);
});
} catch (error) {
console.warn('Failed to invalidate folder cache:', error);
}
}
}
// 单例实例
const cacheService = new CacheService();
export default cacheService;
export { CacheService, MAX_FOLDER_CACHE };
-269
View File
@@ -1,269 +0,0 @@
/**
* CacheService 属性测试
* 使用 fast-check 进行属性测试
*
* 注意:这些测试需要模拟 IndexedDB,在 Node 环境下使用 fake-indexeddb
*/
import { describe, it, expect, beforeEach, vi } from 'vitest';
import * as fc from 'fast-check';
// 模拟缓存验证逻辑(不依赖 IndexedDB 的纯函数测试)
describe('Cache Validation Logic', () => {
/**
* **Feature: library-switch-optimization, Property 14: Cache validation compares timestamps**
* *For any* cache validation operation, the system should compare the cache's
* dbModifiedAt timestamp with the current database modification timestamp.
* **Validates: Requirements 6.3**
*/
describe('Property 14: Cache validation compares timestamps', () => {
// 纯函数:验证缓存是否有效
const isCacheValid = (cacheTimestamp, dbTimestamp) => {
return cacheTimestamp >= dbTimestamp;
};
it('should return true when cache timestamp >= db timestamp', () => {
fc.assert(
fc.property(
fc.integer({ min: 0, max: Number.MAX_SAFE_INTEGER }),
fc.integer({ min: 0, max: Number.MAX_SAFE_INTEGER }),
(cacheTs, dbTs) => {
// 确保 cacheTs >= dbTs
const adjustedCacheTs = Math.max(cacheTs, dbTs);
return isCacheValid(adjustedCacheTs, dbTs) === true;
}
),
{ numRuns: 100 }
);
});
it('should return false when cache timestamp < db timestamp', () => {
fc.assert(
fc.property(
fc.integer({ min: 0, max: Number.MAX_SAFE_INTEGER - 1 }),
fc.integer({ min: 1, max: Number.MAX_SAFE_INTEGER }),
(cacheTs, offset) => {
// 确保 dbTs > cacheTs
const dbTs = cacheTs + offset;
if (dbTs > Number.MAX_SAFE_INTEGER) return true; // 跳过溢出情况
return isCacheValid(cacheTs, dbTs) === false;
}
),
{ numRuns: 100 }
);
});
it('should handle equal timestamps as valid', () => {
fc.assert(
fc.property(
fc.integer({ min: 0, max: Number.MAX_SAFE_INTEGER }),
(timestamp) => {
return isCacheValid(timestamp, timestamp) === true;
}
),
{ numRuns: 100 }
);
});
});
/**
* **Feature: library-switch-optimization, Property 15: Stale cache triggers reload**
* *For any* cache where dbModifiedAt < current database modification timestamp,
* the cache should be invalidated and data should be reloaded from database.
* **Validates: Requirements 6.4**
*/
describe('Property 15: Stale cache triggers reload', () => {
// 模拟缓存验证结果
const validateCache = (cacheTimestamp, dbTimestamp) => {
if (cacheTimestamp === null) {
return { isValid: false, reason: 'not_found' };
}
if (cacheTimestamp >= dbTimestamp) {
return { isValid: true };
}
return { isValid: false, reason: 'stale' };
};
it('should mark cache as stale when db is newer', () => {
fc.assert(
fc.property(
fc.integer({ min: 0, max: Number.MAX_SAFE_INTEGER - 1 }),
fc.integer({ min: 1, max: 1000000 }),
(cacheTs, offset) => {
const dbTs = cacheTs + offset;
if (dbTs > Number.MAX_SAFE_INTEGER) return true;
const result = validateCache(cacheTs, dbTs);
return result.isValid === false && result.reason === 'stale';
}
),
{ numRuns: 100 }
);
});
it('should mark cache as valid when cache is newer or equal', () => {
fc.assert(
fc.property(
fc.integer({ min: 0, max: Number.MAX_SAFE_INTEGER }),
fc.integer({ min: 0, max: 1000000 }),
(dbTs, offset) => {
const cacheTs = dbTs + offset;
if (cacheTs > Number.MAX_SAFE_INTEGER) return true;
const result = validateCache(cacheTs, dbTs);
return result.isValid === true;
}
),
{ numRuns: 100 }
);
});
it('should return not_found when cache is null', () => {
fc.assert(
fc.property(
fc.integer({ min: 0, max: Number.MAX_SAFE_INTEGER }),
(dbTs) => {
const result = validateCache(null, dbTs);
return result.isValid === false && result.reason === 'not_found';
}
),
{ numRuns: 100 }
);
});
});
});
describe('LRU Cache Eviction Logic', () => {
/**
* **Feature: library-switch-optimization, Property 18: LRU cache eviction**
* *For any* state where folder cache count exceeds the maximum threshold,
* the least recently used folder cache should be evicted first.
* **Validates: Requirements 7.4**
*/
describe('Property 18: LRU cache eviction', () => {
// 模拟 LRU 缓存
class MockLRUCache {
constructor(maxSize) {
this.maxSize = maxSize;
this.cache = new Map();
}
get(key) {
if (this.cache.has(key)) {
const value = this.cache.get(key);
// 移到末尾(最近使用)
this.cache.delete(key);
this.cache.set(key, { ...value, accessedAt: Date.now() });
return value;
}
return null;
}
set(key, value) {
// 如果已存在,先删除
if (this.cache.has(key)) {
this.cache.delete(key);
}
// 如果超过容量,删除最旧的
while (this.cache.size >= this.maxSize) {
const oldestKey = this.cache.keys().next().value;
this.cache.delete(oldestKey);
}
this.cache.set(key, { ...value, accessedAt: Date.now() });
}
size() {
return this.cache.size;
}
has(key) {
return this.cache.has(key);
}
}
it('should never exceed max size', () => {
fc.assert(
fc.property(
fc.integer({ min: 1, max: 20 }),
fc.array(fc.string(), { minLength: 1, maxLength: 50 }),
(maxSize, keys) => {
const cache = new MockLRUCache(maxSize);
for (const key of keys) {
cache.set(key, { data: key });
}
return cache.size() <= maxSize;
}
),
{ numRuns: 100 }
);
});
it('should evict oldest items first', () => {
fc.assert(
fc.property(
fc.integer({ min: 2, max: 10 }),
(maxSize) => {
const cache = new MockLRUCache(maxSize);
// 添加 maxSize 个项目
for (let i = 0; i < maxSize; i++) {
cache.set(`key${i}`, { data: i });
}
// 访问第一个项目(使其成为最近使用)
cache.get('key0');
// 添加新项目,应该驱逐 key1(最旧的未访问项)
cache.set('newKey', { data: 'new' });
// key0 应该还在(因为刚访问过)
// key1 应该被驱逐
return cache.has('key0') && !cache.has('key1') && cache.has('newKey');
}
),
{ numRuns: 100 }
);
});
it('should keep recently accessed items', () => {
fc.assert(
fc.property(
fc.integer({ min: 3, max: 10 }),
fc.integer({ min: 0, max: 9 }),
(maxSize, accessIndex) => {
const cache = new MockLRUCache(maxSize);
const safeAccessIndex = accessIndex % maxSize;
// 添加 maxSize 个项目
for (let i = 0; i < maxSize; i++) {
cache.set(`key${i}`, { data: i });
}
// 访问指定索引的项目(使其成为最近使用)
cache.get(`key${safeAccessIndex}`);
// 只添加一个新项目来触发一次驱逐
cache.set('newKey', { data: 'new' });
// 被访问的项目应该还在(因为它是最近访问的)
// 除非它是 key0(最早添加的),在这种情况下它会被移到末尾
// 所以被驱逐的应该是最早添加且未被访问的项目
const accessedItemExists = cache.has(`key${safeAccessIndex}`);
// 如果访问的是 key0,那么 key1 应该被驱逐
// 如果访问的是其他 key,那么 key0 应该被驱逐
if (safeAccessIndex === 0) {
return accessedItemExists && !cache.has('key1');
} else {
return accessedItemExists && !cache.has('key0');
}
}
),
{ numRuns: 100 }
);
});
});
});
+11 -209
View File
@@ -1,10 +1,9 @@
/**
* ImageLoadService - 图片分批加载服务
* 支持分页加载、空闲加载、缓存优先
* 支持分页加载、空闲加载
*/
import { imageAPI } from './api';
import requestManager, { RequestType } from './requestManager';
import cacheService from './cacheService';
// 默认批次大小
const DEFAULT_BATCH_SIZE = 200;
@@ -22,164 +21,13 @@ class ImageLoadService {
offset: 0,
total: 0,
hasMore: false,
isLoading: false,
isIdleLoading: false
isLoading: false
};
// 空闲加载定时器
this.idleTimer = null;
// 空闲加载是否暂停
this.idlePaused = false;
// 状态变化回调
this.onStateChange = null;
}
/**
* 设置状态变化回调
*/
setOnStateChange(callback) {
this.onStateChange = callback;
}
/**
* 更新状态并通知
*/
updateState(updates) {
this.state = { ...this.state, ...updates };
if (this.onStateChange) {
this.onStateChange(this.state);
}
}
/**
* 重置状态
*/
reset() {
this.cancelIdleLoading();
this.state = {
libraryId: null,
folder: null,
images: [],
offset: 0,
total: 0,
hasMore: false,
isLoading: false,
isIdleLoading: false
};
}
/**
* 加载文件夹的第一批图片
* @param {string} libraryId
* @param {string|null} folder
* @param {object} options - { batchSize, useCache }
*/
async loadInitialBatch(libraryId, folder, options = {}) {
const { batchSize = DEFAULT_BATCH_SIZE, useCache = true } = options;
// 暂停并取消之前的空闲加载
this.pauseIdleLoading();
// 取消之前的请求
requestManager.cancelAll(RequestType.IMAGES);
// 更新状态
this.updateState({
libraryId,
folder,
images: [],
offset: 0,
total: 0,
hasMore: false,
isLoading: true
});
// 尝试从缓存加载
if (useCache) {
try {
const cachedData = await cacheService.getFolderCache(libraryId, folder);
if (cachedData) {
// 验证缓存是否有效
const metaResponse = await imageAPI.getCacheMeta(libraryId);
const dbModifiedAt = metaResponse.data.dbModifiedAt;
if (cachedData.dbModifiedAt >= dbModifiedAt) {
// 缓存有效,直接使用
console.log(`📦 Using cached data for folder: ${folder || 'all'}`);
this.updateState({
images: cachedData.images,
offset: cachedData.images.length,
total: cachedData.imageCount,
hasMore: false,
isLoading: false
});
return {
images: cachedData.images,
total: cachedData.imageCount,
hasMore: false,
fromCache: true
};
} else {
// 缓存过期,清除
await cacheService.invalidateFolder(libraryId, folder);
}
}
} catch (error) {
console.warn('Cache check failed:', error);
}
}
// 从 API 加载
const requestContext = requestManager.createRequest(RequestType.IMAGES);
try {
const params = {
offset: 0,
limit: batchSize
};
if (folder) {
params.folder = folder;
}
const response = await imageAPI.search(libraryId, params, {
signal: requestContext.signal
});
// 检查请求是否仍然有效
if (!requestManager.isValid(requestContext.id)) {
return null;
}
const { images, total, hasMore } = response.data;
this.updateState({
images,
offset: images.length,
total,
hasMore,
isLoading: false
});
requestManager.complete(requestContext.id);
// 如果还有更多数据,启动空闲加载
if (hasMore) {
this.startIdleLoading();
} else {
// 加载完成,保存到缓存
this.saveToCacheAsync(libraryId, folder, images);
}
return { images, total, hasMore, fromCache: false };
} catch (error) {
if (error.name === 'CanceledError' || error.name === 'AbortError') {
return null;
}
requestManager.error(requestContext.id);
this.updateState({ isLoading: false });
throw error;
}
}
/**
@@ -187,7 +35,6 @@ class ImageLoadService {
*/
onUserActionStart() {
this.pauseIdleLoading();
// 关键:取消所有正在进行的图片请求,避免阻塞新请求
requestManager.cancelAll(RequestType.IMAGES);
}
@@ -195,7 +42,6 @@ class ImageLoadService {
* 用户操作结束时调用,恢复空闲加载
*/
onUserActionEnd() {
// 延迟恢复,避免频繁切换
setTimeout(() => {
if (this.state.hasMore && !this.state.isLoading) {
this.resumeIdleLoading();
@@ -214,16 +60,11 @@ class ImageLoadService {
const { libraryId, folder, offset, images } = this.state;
const requestContext = requestManager.createRequest(RequestType.IMAGES);
this.updateState({ isLoading: true });
this.state.isLoading = true;
try {
const params = {
offset,
limit: batchSize
};
if (folder) {
params.folder = folder;
}
const params = { offset, limit: batchSize };
if (folder) params.folder = folder;
const response = await imageAPI.search(libraryId, params, {
signal: requestContext.signal
@@ -236,21 +77,17 @@ class ImageLoadService {
const newImages = response.data.images;
const allImages = [...images, ...newImages];
this.updateState({
this.state = {
...this.state,
images: allImages,
offset: allImages.length,
total: response.data.total,
hasMore: response.data.hasMore,
isLoading: false
});
};
requestManager.complete(requestContext.id);
// 如果加载完成,保存到缓存
if (!response.data.hasMore) {
this.saveToCacheAsync(libraryId, folder, allImages);
}
return {
images: newImages,
total: response.data.total,
@@ -260,9 +97,8 @@ class ImageLoadService {
if (error.name === 'CanceledError' || error.name === 'AbortError') {
return null;
}
requestManager.error(requestContext.id);
this.updateState({ isLoading: false });
this.state.isLoading = false;
throw error;
}
}
@@ -271,23 +107,15 @@ class ImageLoadService {
* 启动空闲加载
*/
startIdleLoading() {
if (this.idleTimer || this.idlePaused) {
return;
}
this.updateState({ isIdleLoading: true });
if (this.idleTimer || this.idlePaused) return;
const loadNext = async () => {
if (this.idlePaused || !this.state.hasMore) {
this.updateState({ isIdleLoading: false });
return;
}
if (this.idlePaused || !this.state.hasMore) return;
try {
await this.loadNextBatch();
if (this.state.hasMore && !this.idlePaused) {
// 使用 requestIdleCallback 或 setTimeout
if (typeof requestIdleCallback !== 'undefined') {
this.idleTimer = requestIdleCallback(() => {
this.idleTimer = null;
@@ -299,16 +127,12 @@ class ImageLoadService {
loadNext();
}, IDLE_LOAD_DELAY);
}
} else {
this.updateState({ isIdleLoading: false });
}
} catch (error) {
console.error('Idle loading error:', error);
this.updateState({ isIdleLoading: false });
}
};
// 延迟启动空闲加载
this.idleTimer = setTimeout(() => {
this.idleTimer = null;
loadNext();
@@ -345,28 +169,6 @@ class ImageLoadService {
}
this.idleTimer = null;
}
this.updateState({ isIdleLoading: false });
}
/**
* 异步保存到缓存(不阻塞主流程)
*/
async saveToCacheAsync(libraryId, folder, images) {
try {
const metaResponse = await imageAPI.getCacheMeta(libraryId);
const dbModifiedAt = metaResponse.data.dbModifiedAt;
await cacheService.saveFolderCache(libraryId, folder, images, dbModifiedAt);
console.log(`💾 Cached ${images.length} images for folder: ${folder || 'all'}`);
} catch (error) {
console.warn('Failed to save cache:', error);
}
}
/**
* 获取当前加载状态
*/
getState() {
return { ...this.state };
}
}
+13 -93
View File
@@ -17,14 +17,6 @@ vi.mock('./api', () => ({
}
}));
vi.mock('./cacheService', () => ({
default: {
getFolderCache: vi.fn().mockResolvedValue(null),
saveFolderCache: vi.fn().mockResolvedValue(undefined),
invalidateFolder: vi.fn().mockResolvedValue(undefined)
}
}));
vi.mock('./requestManager', () => ({
default: {
createRequest: vi.fn(() => ({
@@ -54,8 +46,6 @@ describe('ImageLoadService', () => {
/**
* **Property 4: Scroll triggers batch loading**
* *For any* folder with more images than the initial batch size,
* scrolling to the bottom should trigger loading of the next batch.
*/
describe('Property 4: Scroll triggers batch loading', () => {
it('should set hasMore=true when total exceeds loaded count', () => {
@@ -63,13 +53,13 @@ describe('ImageLoadService', () => {
fc.property(
fc.integer({ min: DEFAULT_BATCH_SIZE + 1, max: 10000 }),
(totalImages) => {
// 模拟状态:已加载一批,还有更多
service.updateState({
service.state = {
...service.state,
images: Array(DEFAULT_BATCH_SIZE).fill({ id: 1 }),
offset: DEFAULT_BATCH_SIZE,
total: totalImages,
hasMore: true
});
};
return service.state.hasMore === true &&
service.state.offset < service.state.total;
@@ -84,13 +74,13 @@ describe('ImageLoadService', () => {
fc.property(
fc.integer({ min: 1, max: DEFAULT_BATCH_SIZE }),
(totalImages) => {
// 模拟状态:所有图片已加载
service.updateState({
service.state = {
...service.state,
images: Array(totalImages).fill({ id: 1 }),
offset: totalImages,
total: totalImages,
hasMore: false
});
};
return service.state.hasMore === false &&
service.state.offset === service.state.total;
@@ -103,8 +93,6 @@ describe('ImageLoadService', () => {
/**
* **Property 11: Batch loading updates display incrementally**
* *For any* batch load completion, the displayed image count should
* increase by the batch size (or remaining count if less).
*/
describe('Property 11: Batch loading updates display incrementally', () => {
it('should increment image count by batch size', () => {
@@ -116,18 +104,19 @@ describe('ImageLoadService', () => {
const initialImages = Array(initialCount).fill({ id: 1 });
const newImages = Array(batchSize).fill({ id: 2 });
service.updateState({
service.state = {
...service.state,
images: initialImages,
offset: initialCount
});
};
const prevCount = service.state.images.length;
// 模拟追加新批次
service.updateState({
service.state = {
...service.state,
images: [...initialImages, ...newImages],
offset: initialCount + batchSize
});
};
const newCount = service.state.images.length;
@@ -137,78 +126,11 @@ describe('ImageLoadService', () => {
{ numRuns: 100 }
);
});
it('should handle partial batch at end', () => {
fc.assert(
fc.property(
fc.integer({ min: 1, max: DEFAULT_BATCH_SIZE - 1 }),
(remainingCount) => {
const total = DEFAULT_BATCH_SIZE + remainingCount;
const initialImages = Array(DEFAULT_BATCH_SIZE).fill({ id: 1 });
const remainingImages = Array(remainingCount).fill({ id: 2 });
service.updateState({
images: initialImages,
offset: DEFAULT_BATCH_SIZE,
total,
hasMore: true
});
// 模拟加载最后一批(不足一个完整批次)
service.updateState({
images: [...initialImages, ...remainingImages],
offset: total,
total,
hasMore: false
});
return service.state.images.length === total &&
service.state.hasMore === false;
}
),
{ numRuns: 100 }
);
});
});
describe('State management', () => {
it('should reset state correctly', () => {
service.updateState({
libraryId: 'test',
folder: 'folder',
images: [{ id: 1 }],
offset: 100,
total: 1000,
hasMore: true,
isLoading: true
});
service.reset();
expect(service.state.libraryId).toBe(null);
expect(service.state.folder).toBe(null);
expect(service.state.images).toHaveLength(0);
expect(service.state.offset).toBe(0);
expect(service.state.total).toBe(0);
expect(service.state.hasMore).toBe(false);
expect(service.state.isLoading).toBe(false);
});
it('should notify on state change', () => {
const callback = vi.fn();
service.setOnStateChange(callback);
service.updateState({ isLoading: true });
expect(callback).toHaveBeenCalledWith(expect.objectContaining({
isLoading: true
}));
});
});
describe('Idle loading control', () => {
it('should pause and resume idle loading', () => {
service.updateState({ hasMore: true, isIdleLoading: true });
service.state.hasMore = true;
service.pauseIdleLoading();
expect(service.idlePaused).toBe(true);
@@ -219,12 +141,10 @@ describe('ImageLoadService', () => {
it('should cancel idle loading', () => {
service.idleTimer = setTimeout(() => {}, 10000);
service.updateState({ isIdleLoading: true });
service.cancelIdleLoading();
expect(service.idleTimer).toBe(null);
expect(service.state.isIdleLoading).toBe(false);
});
});
});