修复内存溢出问题

This commit is contained in:
2025-09-19 01:25:30 +08:00
parent 803cc100be
commit 9674740c0d
13 changed files with 1085 additions and 337 deletions

View File

@@ -3,6 +3,10 @@ import { Project, Generation, Asset } from '../types';
const CACHE_PREFIX = 'nano-banana';
const CACHE_VERSION = '1.0';
// 限制缓存项目数量
const MAX_CACHED_ITEMS = 50;
// 限制缓存最大年龄 (3天)
const MAX_CACHE_AGE = 3 * 24 * 60 * 60 * 1000;
export class CacheService {
private static getKey(type: string, id: string): string {
@@ -11,6 +15,8 @@ export class CacheService {
// Project caching
static async saveProject(project: Project): Promise<void> {
// 在保存新项目之前,清理旧缓存
await this.clearOldCache();
await set(this.getKey('project', project.id), project);
}
@@ -33,6 +39,8 @@ export class CacheService {
// Asset caching (for offline access)
static async cacheAsset(asset: Asset, data: Blob): Promise<void> {
// 在保存新资产之前,清理旧缓存
await this.clearOldCache();
await set(this.getKey('asset', asset.id), {
asset,
data,
@@ -47,6 +55,8 @@ export class CacheService {
// Generation metadata caching
static async cacheGeneration(generation: Generation): Promise<void> {
// 在保存新生成记录之前,清理旧缓存
await this.clearOldCache();
await set(this.getKey('generation', generation.id), generation);
}
@@ -55,17 +65,55 @@ export class CacheService {
}
// Clear old cache entries
static async clearOldCache(maxAge: number = 7 * 24 * 60 * 60 * 1000): Promise<void> {
static async clearOldCache(maxAge: number = MAX_CACHE_AGE): Promise<void> {
const allKeys = await keys();
const now = Date.now();
// 收集需要删除的键
const keysToDelete: string[] = [];
const validCachedItems: Array<{key: string, cachedAt: number}> = [];
for (const key of allKeys) {
if (typeof key === 'string' && key.startsWith(CACHE_PREFIX)) {
const cached = await get(key);
if (cached?.cachedAt && (now - cached.cachedAt) > maxAge) {
await del(key);
if (cached?.cachedAt) {
// 检查是否过期
if ((now - cached.cachedAt) > maxAge) {
keysToDelete.push(key);
} else {
validCachedItems.push({key, cachedAt: cached.cachedAt});
}
}
}
}
// 如果有效项目数量超过限制,删除最旧的项目
if (validCachedItems.length > MAX_CACHED_ITEMS) {
// 按时间排序,最旧的在前面
validCachedItems.sort((a, b) => a.cachedAt - b.cachedAt);
// 计算需要删除的数量
const excessCount = validCachedItems.length - MAX_CACHED_ITEMS;
// 添加最旧的项目到删除列表
for (let i = 0; i < excessCount; i++) {
keysToDelete.push(validCachedItems[i].key);
}
}
// 执行删除
for (const key of keysToDelete) {
await del(key);
}
}
// 清空所有缓存
static async clearAllCache(): Promise<void> {
const allKeys = await keys();
const cacheKeys = allKeys.filter(key =>
typeof key === 'string' && key.startsWith(CACHE_PREFIX)
);
for (const key of cacheKeys) {
await del(key);
}
}
}