Skip to content

Commit 6ed2ae1

Browse files
authored
fix: clean up cache by removing stale keys (#252)
* refactor: Extract flags cache key generation. * feat: Remove stale cache keys for flags.
1 parent 3733323 commit 6ed2ae1

File tree

1 file changed

+20
-6
lines changed

1 file changed

+20
-6
lines changed

packages/sdk/src/core/flags/flags-manager.ts

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,14 @@ export class CoreFlagsManager implements FlagsManager {
106106
};
107107
}
108108

109+
private removeStaleKeys(validCacheKeys: Set<string>): void {
110+
for (const key of this.cache.keys()) {
111+
if (!validCacheKeys.has(key)) {
112+
this.cache.delete(key);
113+
}
114+
}
115+
}
116+
109117
private async initialize(): Promise<void> {
110118
// Load from persistent storage first (instant hydration)
111119
if (!this.config.skipStorage && this.storage) {
@@ -294,16 +302,22 @@ export class CoreFlagsManager implements FlagsManager {
294302
const apiUrl = this.config.apiUrl ?? "https://api.databuddy.cc";
295303
const params = buildQueryParams(this.config, user);
296304

305+
const ttl = this.config.cacheTtl ?? 60_000;
306+
const staleTime = this.config.staleTime ?? ttl / 2;
307+
297308
try {
298309
const flags = await fetchAllFlagsApi(apiUrl, params);
310+
const flagCacheEntries = Object.entries(flags).map(([key, result]) => ({
311+
cacheKey: getCacheKey(key, user ?? this.config.user),
312+
cacheEntry: createCacheEntry(result, ttl, staleTime),
313+
}));
299314

300-
// Update cache with all flags
301-
const ttl = this.config.cacheTtl ?? 60_000;
302-
const staleTime = this.config.staleTime ?? ttl / 2;
315+
this.removeStaleKeys(
316+
new Set(flagCacheEntries.map(({ cacheKey }) => cacheKey))
317+
);
303318

304-
for (const [key, result] of Object.entries(flags)) {
305-
const cacheKey = getCacheKey(key, user ?? this.config.user);
306-
this.cache.set(cacheKey, createCacheEntry(result, ttl, staleTime));
319+
for (const { cacheKey, cacheEntry } of flagCacheEntries) {
320+
this.cache.set(cacheKey, cacheEntry);
307321
}
308322

309323
this.ready = true;

0 commit comments

Comments
 (0)