临时完整优化

This commit is contained in:
Chen committed 2025-12-01 13:42:25 +08:00
1 parent 9e346c7d5b
commit d6b4919880
29 files changed
+5228 -400

No files matched your search

+3 -2
View File
@@ -15,15 +15,16 @@ export const libraryAPI = {
// Image API
export const imageAPI = {
search: (libraryId, params = {}) => {
search: (libraryId, params = {}, options = {}) => {
const query = new URLSearchParams({
libraryId,
...params
});
return axios.get(`${API_BASE}/image?${query}`);
return axios.get(`${API_BASE}/image?${query}`, options);
},
getCount: (libraryId) => axios.get(`${API_BASE}/image/count?libraryId=${libraryId}`),
getFolders: (libraryId) => axios.get(`${API_BASE}/image/folders?libraryId=${libraryId}`),
getCacheMeta: (libraryId) => axios.get(`${API_BASE}/image/cache-meta?libraryId=${libraryId}`),
getThumbnailUrl: (libraryId, size, filename) => `${API_BASE}/image/thumbnail/${libraryId}/${size}/${filename}`,
getOriginalUrl: (libraryId, path) => `${API_BASE}/image/original/${libraryId}/${path}`,
openInExplorer: (libraryId, path) => axios.post(`${API_BASE}/image/${libraryId}/open-file`, { path })
+469
View File
@@ -0,0 +1,469 @@
/**
* 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
@@ -0,0 +1,269 @@
/**
* 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 }
);
});
});
});
+377
View File
@@ -0,0 +1,377 @@
/**
* ImageLoadService - 图片分批加载服务
* 支持分页加载、空闲加载、缓存优先
*/
import { imageAPI } from './api';
import requestManager, { RequestType } from './requestManager';
import cacheService from './cacheService';
// 默认批次大小
const DEFAULT_BATCH_SIZE = 200;
// 空闲加载延迟(毫秒)
const IDLE_LOAD_DELAY = 500;
class ImageLoadService {
constructor() {
// 当前加载状态
this.state = {
libraryId: null,
folder: null,
images: [],
offset: 0,
total: 0,
hasMore: false,
isLoading: false,
isIdleLoading: 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;
}
}
/**
* 用户操作开始时调用,暂停空闲加载并取消所有进行中的请求
*/
onUserActionStart() {
this.pauseIdleLoading();
// 关键:取消所有正在进行的图片请求,避免阻塞新请求
requestManager.cancelAll(RequestType.IMAGES);
}
/**
* 用户操作结束时调用,恢复空闲加载
*/
onUserActionEnd() {
// 延迟恢复,避免频繁切换
setTimeout(() => {
if (this.state.hasMore && !this.state.isLoading) {
this.resumeIdleLoading();
}
}, 300);
}
/**
* 加载下一批图片
*/
async loadNextBatch(batchSize = DEFAULT_BATCH_SIZE) {
if (!this.state.hasMore || this.state.isLoading) {
return null;
}
const { libraryId, folder, offset, images } = this.state;
const requestContext = requestManager.createRequest(RequestType.IMAGES);
this.updateState({ isLoading: true });
try {
const params = {
offset,
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 newImages = response.data.images;
const allImages = [...images, ...newImages];
this.updateState({
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,
hasMore: response.data.hasMore
};
} catch (error) {
if (error.name === 'CanceledError' || error.name === 'AbortError') {
return null;
}
requestManager.error(requestContext.id);
this.updateState({ isLoading: false });
throw error;
}
}
/**
* 启动空闲加载
*/
startIdleLoading() {
if (this.idleTimer || this.idlePaused) {
return;
}
this.updateState({ isIdleLoading: true });
const loadNext = async () => {
if (this.idlePaused || !this.state.hasMore) {
this.updateState({ isIdleLoading: false });
return;
}
try {
await this.loadNextBatch();
if (this.state.hasMore && !this.idlePaused) {
// 使用 requestIdleCallback 或 setTimeout
if (typeof requestIdleCallback !== 'undefined') {
this.idleTimer = requestIdleCallback(() => {
this.idleTimer = null;
loadNext();
}, { timeout: 2000 });
} else {
this.idleTimer = setTimeout(() => {
this.idleTimer = null;
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();
}, IDLE_LOAD_DELAY);
}
/**
* 暂停空闲加载
*/
pauseIdleLoading() {
this.idlePaused = true;
this.cancelIdleLoading();
}
/**
* 恢复空闲加载
*/
resumeIdleLoading() {
this.idlePaused = false;
if (this.state.hasMore) {
this.startIdleLoading();
}
}
/**
* 取消空闲加载
*/
cancelIdleLoading() {
if (this.idleTimer) {
if (typeof cancelIdleCallback !== 'undefined') {
cancelIdleCallback(this.idleTimer);
} else {
clearTimeout(this.idleTimer);
}
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 };
}
}
// 单例实例
const imageLoadService = new ImageLoadService();
export default imageLoadService;
export { ImageLoadService, DEFAULT_BATCH_SIZE };
@@ -0,0 +1,230 @@
/**
* ImageLoadService 属性测试
*
* **Feature: library-switch-optimization, Property 4: Scroll triggers batch loading**
* **Feature: library-switch-optimization, Property 11: Batch loading updates display incrementally**
* **Validates: Requirements 2.3, 5.2**
*/
import { describe, it, expect, beforeEach, vi } from 'vitest';
import * as fc from 'fast-check';
import { ImageLoadService, DEFAULT_BATCH_SIZE } from './imageLoadService.js';
// Mock dependencies
vi.mock('./api', () => ({
imageAPI: {
search: vi.fn(),
getCacheMeta: vi.fn()
}
}));
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(() => ({
id: `req_${Date.now()}`,
signal: new AbortController().signal,
isActive: true
})),
cancelAll: vi.fn(),
isValid: vi.fn().mockReturnValue(true),
complete: vi.fn(),
error: vi.fn()
},
RequestType: {
LIBRARY: 'library',
FOLDER: 'folder',
IMAGES: 'images'
}
}));
describe('ImageLoadService', () => {
let service;
beforeEach(() => {
service = new ImageLoadService();
vi.clearAllMocks();
});
/**
* **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', () => {
fc.assert(
fc.property(
fc.integer({ min: DEFAULT_BATCH_SIZE + 1, max: 10000 }),
(totalImages) => {
// 模拟状态:已加载一批,还有更多
service.updateState({
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;
}
),
{ numRuns: 100 }
);
});
it('should set hasMore=false when all images loaded', () => {
fc.assert(
fc.property(
fc.integer({ min: 1, max: DEFAULT_BATCH_SIZE }),
(totalImages) => {
// 模拟状态:所有图片已加载
service.updateState({
images: Array(totalImages).fill({ id: 1 }),
offset: totalImages,
total: totalImages,
hasMore: false
});
return service.state.hasMore === false &&
service.state.offset === service.state.total;
}
),
{ numRuns: 100 }
);
});
});
/**
* **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', () => {
fc.assert(
fc.property(
fc.integer({ min: 0, max: 5000 }),
fc.integer({ min: 1, max: DEFAULT_BATCH_SIZE }),
(initialCount, batchSize) => {
const initialImages = Array(initialCount).fill({ id: 1 });
const newImages = Array(batchSize).fill({ id: 2 });
service.updateState({
images: initialImages,
offset: initialCount
});
const prevCount = service.state.images.length;
// 模拟追加新批次
service.updateState({
images: [...initialImages, ...newImages],
offset: initialCount + batchSize
});
const newCount = service.state.images.length;
return newCount === prevCount + batchSize;
}
),
{ 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.pauseIdleLoading();
expect(service.idlePaused).toBe(true);
service.resumeIdleLoading();
expect(service.idlePaused).toBe(false);
});
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);
});
});
});
+166
View File
@@ -0,0 +1,166 @@
/**
* RequestManager - 统一管理异步请求的生命周期
* 支持请求取消、去重、竞态条件处理
*/
// 请求类型
export const RequestType = {
LIBRARY: 'library',
FOLDER: 'folder',
IMAGES: 'images'
};
// 生成唯一 ID
let requestIdCounter = 0;
const generateRequestId = () => {
requestIdCounter += 1;
return `req_${Date.now()}_${requestIdCounter}`;
};
class RequestManager {
constructor() {
// 按类型存储活跃的请求
this.activeRequests = new Map();
// 存储所有请求上下文
this.requestContexts = new Map();
}
/**
* 创建一个新的请求上下文
* @param {string} type - 请求类型 (library/folder/images)
* @returns {RequestContext}
*/
createRequest(type) {
const id = generateRequestId();
const abortController = new AbortController();
const context = {
id,
type,
createdAt: Date.now(),
abortController,
signal: abortController.signal,
status: 'pending',
isActive: true,
cancel: () => {
if (context.isActive) {
context.isActive = false;
context.status = 'cancelled';
abortController.abort();
this.requestContexts.delete(id);
// 从活跃请求中移除
const typeRequests = this.activeRequests.get(type);
if (typeRequests) {
typeRequests.delete(id);
}
}
}
};
// 存储请求上下文
this.requestContexts.set(id, context);
// 添加到活跃请求
if (!this.activeRequests.has(type)) {
this.activeRequests.set(type, new Map());
}
this.activeRequests.get(type).set(id, context);
return context;
}
/**
* 取消指定类型的所有请求
* @param {string} type - 请求类型
*/
cancelAll(type) {
const typeRequests = this.activeRequests.get(type);
if (typeRequests) {
for (const context of typeRequests.values()) {
context.cancel();
}
typeRequests.clear();
}
}
/**
* 取消所有请求
*/
cancelAllRequests() {
for (const type of Object.values(RequestType)) {
this.cancelAll(type);
}
}
/**
* 检查请求是否仍然有效(未被取消)
* @param {string} requestId - 请求 ID
* @returns {boolean}
*/
isValid(requestId) {
const context = this.requestContexts.get(requestId);
return context ? context.isActive : false;
}
/**
* 标记请求完成
* @param {string} requestId - 请求 ID
*/
complete(requestId) {
const context = this.requestContexts.get(requestId);
if (context && context.isActive) {
context.status = 'completed';
context.isActive = false;
this.requestContexts.delete(requestId);
const typeRequests = this.activeRequests.get(context.type);
if (typeRequests) {
typeRequests.delete(requestId);
}
}
}
/**
* 标记请求错误
* @param {string} requestId - 请求 ID
*/
error(requestId) {
const context = this.requestContexts.get(requestId);
if (context && context.isActive) {
context.status = 'error';
context.isActive = false;
this.requestContexts.delete(requestId);
const typeRequests = this.activeRequests.get(context.type);
if (typeRequests) {
typeRequests.delete(requestId);
}
}
}
/**
* 获取指定类型的活跃请求数量
* @param {string} type - 请求类型
* @returns {number}
*/
getActiveCount(type) {
const typeRequests = this.activeRequests.get(type);
return typeRequests ? typeRequests.size : 0;
}
/**
* 检查是否有指定类型的活跃请求
* @param {string} type - 请求类型
* @returns {boolean}
*/
hasActiveRequests(type) {
return this.getActiveCount(type) > 0;
}
}
// 单例实例
const requestManager = new RequestManager();
export default requestManager;
export { RequestManager };
@@ -0,0 +1,232 @@
/**
* RequestManager 属性测试
* 使用 fast-check 进行属性测试
*/
import { describe, it, expect, beforeEach } from 'vitest';
import * as fc from 'fast-check';
import { RequestManager, RequestType } from './requestManager.js';
describe('RequestManager', () => {
let manager;
beforeEach(() => {
manager = new RequestManager();
});
/**
* **Feature: library-switch-optimization, Property 7: Unique request IDs**
* *For any* set of requests created by RequestManager, each request should have
* a unique ID that is different from all other request IDs.
* **Validates: Requirements 4.1**
*/
describe('Property 7: Unique request IDs', () => {
it('should generate unique IDs for all requests', () => {
fc.assert(
fc.property(
fc.integer({ min: 1, max: 100 }),
(requestCount) => {
const localManager = new RequestManager();
const ids = new Set();
for (let i = 0; i < requestCount; i++) {
const type = Object.values(RequestType)[i % 3];
const context = localManager.createRequest(type);
ids.add(context.id);
}
// 所有 ID 应该唯一
return ids.size === requestCount;
}
),
{ numRuns: 100 }
);
});
it('should generate unique IDs across different request types', () => {
fc.assert(
fc.property(
fc.array(fc.constantFrom(...Object.values(RequestType)), { minLength: 1, maxLength: 50 }),
(types) => {
const localManager = new RequestManager();
const ids = new Set();
for (const type of types) {
const context = localManager.createRequest(type);
ids.add(context.id);
}
return ids.size === types.length;
}
),
{ numRuns: 100 }
);
});
});
/**
* **Feature: library-switch-optimization, Property 8: Cancelled requests don't trigger callbacks**
* *For any* cancelled request, its completion callback should not be executed,
* and its result should not be applied to the state.
* **Validates: Requirements 4.2**
*/
describe('Property 8: Cancelled requests don\'t trigger callbacks', () => {
it('should mark cancelled requests as inactive', () => {
fc.assert(
fc.property(
fc.constantFrom(...Object.values(RequestType)),
(type) => {
const context = manager.createRequest(type);
const requestId = context.id;
// 请求应该是活跃的
expect(manager.isValid(requestId)).toBe(true);
expect(context.isActive).toBe(true);
// 取消请求
context.cancel();
// 请求应该不再有效
expect(manager.isValid(requestId)).toBe(false);
expect(context.isActive).toBe(false);
expect(context.status).toBe('cancelled');
return true;
}
),
{ numRuns: 100 }
);
});
it('should abort the AbortController signal when cancelled', () => {
fc.assert(
fc.property(
fc.constantFrom(...Object.values(RequestType)),
(type) => {
const context = manager.createRequest(type);
expect(context.signal.aborted).toBe(false);
context.cancel();
expect(context.signal.aborted).toBe(true);
return true;
}
),
{ numRuns: 100 }
);
});
it('should remove cancelled requests from active requests', () => {
fc.assert(
fc.property(
fc.constantFrom(...Object.values(RequestType)),
fc.integer({ min: 1, max: 10 }),
(type, count) => {
const localManager = new RequestManager();
const contexts = [];
// 创建多个请求
for (let i = 0; i < count; i++) {
contexts.push(localManager.createRequest(type));
}
expect(localManager.getActiveCount(type)).toBe(count);
// 取消所有请求
for (const ctx of contexts) {
ctx.cancel();
}
expect(localManager.getActiveCount(type)).toBe(0);
return true;
}
),
{ numRuns: 100 }
);
});
it('cancelAll should cancel all requests of a specific type', () => {
fc.assert(
fc.property(
fc.integer({ min: 1, max: 20 }),
(count) => {
const localManager = new RequestManager();
const contexts = [];
// 创建多个 FOLDER 类型请求
for (let i = 0; i < count; i++) {
contexts.push(localManager.createRequest(RequestType.FOLDER));
}
// 创建一个 LIBRARY 类型请求
const libraryContext = localManager.createRequest(RequestType.LIBRARY);
expect(localManager.getActiveCount(RequestType.FOLDER)).toBe(count);
expect(localManager.getActiveCount(RequestType.LIBRARY)).toBe(1);
// 取消所有 FOLDER 请求
localManager.cancelAll(RequestType.FOLDER);
// FOLDER 请求应该全部取消
expect(localManager.getActiveCount(RequestType.FOLDER)).toBe(0);
for (const ctx of contexts) {
expect(ctx.isActive).toBe(false);
expect(ctx.signal.aborted).toBe(true);
}
// LIBRARY 请求应该不受影响
expect(localManager.getActiveCount(RequestType.LIBRARY)).toBe(1);
expect(libraryContext.isActive).toBe(true);
return true;
}
),
{ numRuns: 100 }
);
});
});
describe('Request lifecycle', () => {
it('should properly track request completion', () => {
const context = manager.createRequest(RequestType.IMAGES);
const requestId = context.id;
expect(manager.isValid(requestId)).toBe(true);
manager.complete(requestId);
expect(manager.isValid(requestId)).toBe(false);
expect(context.status).toBe('completed');
});
it('should properly track request errors', () => {
const context = manager.createRequest(RequestType.IMAGES);
const requestId = context.id;
expect(manager.isValid(requestId)).toBe(true);
manager.error(requestId);
expect(manager.isValid(requestId)).toBe(false);
expect(context.status).toBe('error');
});
it('cancelAllRequests should cancel all types', () => {
manager.createRequest(RequestType.LIBRARY);
manager.createRequest(RequestType.FOLDER);
manager.createRequest(RequestType.IMAGES);
expect(manager.hasActiveRequests(RequestType.LIBRARY)).toBe(true);
expect(manager.hasActiveRequests(RequestType.FOLDER)).toBe(true);
expect(manager.hasActiveRequests(RequestType.IMAGES)).toBe(true);
manager.cancelAllRequests();
expect(manager.hasActiveRequests(RequestType.LIBRARY)).toBe(false);
expect(manager.hasActiveRequests(RequestType.FOLDER)).toBe(false);
expect(manager.hasActiveRequests(RequestType.IMAGES)).toBe(false);
});
});
});