Skip to content

Commit 77a6a1b

Browse files
fatelove42claude
andcommitted
fix: initialize tracksCacheBytes on startup to enforce cache limit (#1951)
Previously, tracksCacheBytes was initialized to 0 and only updated when entering the settings page. This caused the cache limit to not work until the user manually opened settings. Now the cache size is calculated from the database on app startup, ensuring cache cleanup triggers correctly. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
1 parent c47d009 commit 77a6a1b

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

src/utils/db.js

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,46 @@ db.version(1).stores({
3030

3131
let tracksCacheBytes = 0;
3232

33+
// 等待 settings 可用
34+
async function waitForSettingsReady(timeoutMs = 5000) {
35+
const interval = 100;
36+
const maxTries = Math.ceil(timeoutMs / interval);
37+
let tries = 0;
38+
while (
39+
(store.state == null ||
40+
store.state.settings == null ||
41+
store.state.settings.cacheLimit === undefined) &&
42+
tries < maxTries
43+
) {
44+
await new Promise(resolve => setTimeout(resolve, interval));
45+
tries++;
46+
}
47+
return store.state && store.state.settings;
48+
}
49+
50+
// 初始化现有缓存总大小,确保应用启动时能正确判断并清理超限缓存
51+
async function initTracksCacheBytes() {
52+
if (!process.env.IS_ELECTRON) return;
53+
try {
54+
await waitForSettingsReady();
55+
const all = await db.trackSources.toArray();
56+
tracksCacheBytes = all.reduce(
57+
(sum, t) => sum + (t?.source?.byteLength || 0),
58+
0
59+
);
60+
console.debug(
61+
'[debug][db.js] initTracksCacheBytes, total bytes:',
62+
tracksCacheBytes
63+
);
64+
deleteExcessCache();
65+
} catch (err) {
66+
console.debug('[debug][db.js] initTracksCacheBytes failed', err);
67+
}
68+
}
69+
70+
// 模块加载时触发初始化
71+
initTracksCacheBytes();
72+
3373
async function deleteExcessCache() {
3474
if (
3575
store.state.settings.cacheLimit === false ||

0 commit comments

Comments
 (0)