forked from facebook/sapling
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGitHubCache.ts
More file actions
72 lines (63 loc) · 1.91 KB
/
GitHubCache.ts
File metadata and controls
72 lines (63 loc) · 1.91 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
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
type CacheEntry<T = unknown> = {
data: T;
timestamp: number;
ttlMs: number;
};
/**
* Simple in-memory TTL cache for GitHub API responses.
* Supports stale-while-revalidate pattern via getStale().
* Clears on server restart (no disk persistence).
*/
export class GitHubCache {
private store = new Map<string, CacheEntry>();
/** Get data if cache hit and not expired. Returns undefined if miss or expired. */
get<T = unknown>(key: string): T | undefined {
const entry = this.store.get(key);
if (entry == null) {
return undefined;
}
if (Date.now() - entry.timestamp > entry.ttlMs) {
return undefined;
}
return entry.data as T;
}
/** Get data even if expired (for stale-while-revalidate). Returns undefined only on miss. */
getStale<T = unknown>(key: string): T | undefined {
const entry = this.store.get(key);
return entry != null ? (entry.data as T) : undefined;
}
/** Store data with a TTL in milliseconds. */
set<T = unknown>(key: string, data: T, ttlMs: number): void {
this.store.set(key, {data, timestamp: Date.now(), ttlMs});
}
/** Check if a key is expired or missing. */
isExpired(key: string): boolean {
const entry = this.store.get(key);
if (entry == null) {
return true;
}
return Date.now() - entry.timestamp > entry.ttlMs;
}
/** Remove a specific key. */
invalidate(key: string): void {
this.store.delete(key);
}
/** Remove all entries whose key starts with the given prefix. */
invalidateByPrefix(prefix: string): void {
for (const key of this.store.keys()) {
if (key.startsWith(prefix)) {
this.store.delete(key);
}
}
}
/** Remove all entries. */
clear(): void {
this.store.clear();
}
}