forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.ts
More file actions
305 lines (262 loc) · 8.26 KB
/
Copy pathcache.ts
File metadata and controls
305 lines (262 loc) · 8.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
/**
* Shared caching infrastructure for API data
*
* Features:
* - Typed cache entries by domain (conversations, memories, etc.)
* - Stale-while-revalidate support
* - Event-based cache invalidation
* - Request deduplication
*/
// Cache TTL constants
export const CACHE_TTL = {
SHORT: 60 * 1000, // 1 minute - user-specific frequently changing data
MEDIUM: 5 * 60 * 1000, // 5 minutes - lists that update occasionally
LONG: 60 * 60 * 1000, // 1 hour - static/reference data
} as const;
// Cache entry with metadata
interface CacheEntry<T> {
data: T;
timestamp: number;
ttl: number;
}
// In-flight request tracking for deduplication
const pendingRequests = new Map<string, Promise<unknown>>();
// Main cache storage
const cache = new Map<string, CacheEntry<unknown>>();
// Keys that should persist to sessionStorage for instant loads
const PERSISTENT_KEYS = ['memories:', 'conversations:', 'actionItems', 'folders'];
// Try to hydrate cache from sessionStorage on module load
if (typeof window !== 'undefined') {
try {
// Check if this is a page reload - if so, clear cache for fresh data
// This ensures refreshing the page always fetches fresh data from server
const navEntry = performance.getEntriesByType('navigation')[0] as
PerformanceNavigationTiming | undefined;
const isReload = navEntry?.type === 'reload';
if (isReload) {
sessionStorage.removeItem('omi_cache');
} else {
const stored = sessionStorage.getItem('omi_cache');
if (stored) {
const parsed = JSON.parse(stored) as Record<string, CacheEntry<unknown>>;
for (const [key, entry] of Object.entries(parsed)) {
// Only restore if not expired (check against original TTL)
if (Date.now() - entry.timestamp < entry.ttl) {
cache.set(key, entry);
}
}
}
}
} catch {
// Ignore parse errors
}
}
// Persist cache to sessionStorage (debounced)
let persistTimeout: ReturnType<typeof setTimeout> | null = null;
function persistCache(): void {
if (typeof window === 'undefined') return;
if (persistTimeout) clearTimeout(persistTimeout);
persistTimeout = setTimeout(() => {
try {
const toStore: Record<string, CacheEntry<unknown>> = {};
for (const [key, entry] of cache.entries()) {
// Only persist certain keys to avoid bloating storage
if (PERSISTENT_KEYS.some((pattern) => key.includes(pattern))) {
toStore[key] = entry;
}
}
sessionStorage.setItem('omi_cache', JSON.stringify(toStore));
} catch {
// Ignore storage errors (quota exceeded, etc.)
}
}, 100); // Debounce 100ms
}
// Event listeners for invalidation
type InvalidationListener = (pattern: string) => void;
const invalidationListeners = new Set<InvalidationListener>();
/**
* Get cached data
* @returns { data, isStale } or null if not in cache
*/
export function getCache<T>(key: string): { data: T; isStale: boolean } | null {
const entry = cache.get(key) as CacheEntry<T> | undefined;
if (!entry) return null;
const isStale = Date.now() - entry.timestamp > entry.ttl;
return { data: entry.data, isStale };
}
/**
* Set cache data
*/
export function setCache<T>(key: string, data: T, ttl: number = CACHE_TTL.MEDIUM): void {
cache.set(key, { data, timestamp: Date.now(), ttl });
persistCache();
}
/**
* Update cache data in place (for optimistic updates)
*/
export function updateCache<T>(key: string, updater: (data: T) => T): void {
const entry = cache.get(key) as CacheEntry<T> | undefined;
if (entry) {
entry.data = updater(entry.data);
entry.timestamp = Date.now(); // Refresh timestamp on update
persistCache();
}
}
/**
* Delete specific cache entry
*/
export function deleteCache(key: string): void {
cache.delete(key);
persistCache();
}
/**
* Invalidate cache entries matching a pattern
* @param pattern - String pattern to match against cache keys
*/
export function invalidateCache(pattern: string): void {
const keysToDelete: string[] = [];
for (const key of cache.keys()) {
if (key.includes(pattern)) {
keysToDelete.push(key);
}
}
keysToDelete.forEach((key) => cache.delete(key));
persistCache();
// Notify listeners
invalidationListeners.forEach((listener) => listener(pattern));
}
/**
* Invalidate a specific cache key (granular invalidation)
* More efficient than pattern matching when you know the exact key
* @param key - Exact cache key to invalidate
*/
export function invalidateCacheKey(key: string): void {
if (cache.has(key)) {
cache.delete(key);
persistCache();
}
}
/**
* Invalidate multiple specific cache keys (batch granular invalidation)
* @param keys - Array of exact cache keys to invalidate
*/
export function invalidateCacheKeys(keys: string[]): void {
let deleted = false;
for (const key of keys) {
if (cache.has(key)) {
cache.delete(key);
deleted = true;
}
}
if (deleted) {
persistCache();
}
}
/**
* Subscribe to cache invalidation events
* @returns Unsubscribe function
*/
export function onCacheInvalidation(listener: InvalidationListener): () => void {
invalidationListeners.add(listener);
return () => invalidationListeners.delete(listener);
}
/**
* Deduplicated fetch - prevents multiple identical requests
* If a request with the same key is already in flight, returns the existing promise
*/
export async function deduplicatedFetch<T>(
key: string,
fetcher: () => Promise<T>,
): Promise<T> {
// Check if request is already in flight
const pending = pendingRequests.get(key);
if (pending) {
return pending as Promise<T>;
}
// Start new request
const promise = fetcher().finally(() => {
pendingRequests.delete(key);
});
pendingRequests.set(key, promise);
return promise;
}
/**
* Fetch with cache - returns cached data immediately if available,
* then optionally revalidates in background
*/
export async function fetchWithCache<T>(
key: string,
fetcher: () => Promise<T>,
options: {
ttl?: number;
forceRefresh?: boolean;
onStaleData?: (data: T) => void;
} = {},
): Promise<T> {
const { ttl = CACHE_TTL.MEDIUM, forceRefresh = false, onStaleData } = options;
// Check cache first
if (!forceRefresh) {
const cached = getCache<T>(key);
if (cached) {
if (!cached.isStale) {
// Fresh data - return immediately
return cached.data;
} else if (onStaleData) {
// Stale data - return immediately and revalidate in background
onStaleData(cached.data);
// Background revalidation
deduplicatedFetch(key, fetcher)
.then((freshData) => {
setCache(key, freshData, ttl);
})
.catch(console.error);
return cached.data;
}
}
}
// Fetch fresh data
const data = await deduplicatedFetch(key, fetcher);
setCache(key, data, ttl);
return data;
}
/**
* Clear all cache entries (useful for logout)
*/
export function clearAllCache(): void {
cache.clear();
pendingRequests.clear();
if (typeof window !== 'undefined') {
try {
sessionStorage.removeItem('omi_cache');
} catch {
// Ignore storage errors
}
}
}
// Cache key generators for consistency
export const cacheKeys = {
conversations: (folderId?: string, startDate?: string, endDate?: string) =>
`conversations:${folderId || 'all'}:${startDate || ''}:${endDate || ''}`,
conversation: (id: string) => `conversation:${id}`,
screenFrames: (conversationId: string) => `screenFrames:${conversationId}`,
memories: (categories: string[]) =>
`memories:${categories.length === 0 ? 'all' : [...categories].sort().join(',')}`,
memory: (id: string) => `memory:${id}`,
recaps: (offset: number) => `recaps:${offset}`,
actionItems: () => 'actionItems',
folders: () => 'folders',
knowledgeGraph: () => 'knowledgeGraph',
search: (type: string, query: string) => `search:${type}:${query}`,
apps: (tab: string, filters?: string) => `apps:${tab}:${filters || ''}`,
goals: (includeEnded: boolean) => `goals:${includeEnded ? 'all' : 'active'}`,
scores: (date?: string) => `scores:${date || 'today'}`,
};
// Invalidation patterns for mutations
export const invalidationPatterns = {
conversations: 'conversations',
memories: 'memories',
actionItems: 'actionItems',
folders: 'folders',
apps: 'apps',
goals: 'goals',
};