Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 18 additions & 11 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,28 +9,31 @@ build/
target/

# Dependencies
node_modules/
venv/
.venv/
.env
.env.local
*.env.*
venv/
node_modules/
.mypy_cache/
.pytest_cache/
.coverage
coverage/
htmlcov/

# Logs and temp files
*.log
*.tmp
*.swp
*.swo

# Environment
.env
.env.local
*.env.*

# Editors
.vscode/
.idea/

# Coverage
coverage/
htmlcov/
.coverage

# OS
# System files
.DS_Store
Thumbs.db

Expand All @@ -53,4 +56,8 @@ Thumbs.db
*.Z
*.lz
*.lzo
*.tar.gz
*.tar.bz2
*.tar.xz
*.tar.zst
```
38 changes: 37 additions & 1 deletion apps/web/src/lib/api/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,15 @@ interface CacheEntry<T> {

const memoryStore = new Map<string, CacheEntry<unknown>>();

// Bug #PERF-4.1: 缩短清理间隔为 30 秒,更快释放过期缓存内存
setInterval(() => {
const now = Date.now();
for (const [key, entry] of memoryStore) {
if (entry.expiresAt <= now) {
memoryStore.delete(key);
}
}
}, 60_000).unref();
}, 30_000).unref();

export async function memoizeAsync<T>(
key: string,
Expand Down Expand Up @@ -60,6 +61,9 @@ export async function memoizeAsync<T>(
return value;
}

// Bug #PERF-4.2: 添加带标签的缓存,支持按标签批量失效
const keyTagsMap = new Map<string, Set<string>>(); // tag -> set of keys

async function deleteRedisKeysByPrefix(redis: Redis, prefix: string): Promise<void> {
const pattern = `${prefix}*`;
let cursor = '0';
Expand All @@ -86,3 +90,35 @@ export function invalidateCache(prefix: string): void {
}
}
}

export function memoizeWithTags<T>(
key: string,
tags: string[],
ttlMs: number,
fn: () => Promise<T>,
): Promise<T> {
const result = memoizeAsync(key, ttlMs, fn);

// 记录 key 与 tag 的关联
result.then(() => {
for (const tag of tags) {
if (!keyTagsMap.has(tag)) {
keyTagsMap.set(tag, new Set());
}
keyTagsMap.get(tag)!.add(key);
}
}).catch(() => {}); // ignore errors

return result;
}

export function invalidateCacheByTag(tag: string): void {
const keys = keyTagsMap.get(tag);
if (!keys || keys.size === 0) return;

// 失效所有关联的 key
for (const key of keys) {
invalidateCache(key);
}
keyTagsMap.delete(tag);
}
Loading
Loading