Repository navigation
Expand file tree
/
Copy pathbackground-refresh.ts
More file actions
155 lines (119 loc) · 3.53 KB
/
Copy pathbackground-refresh.ts
File metadata and controls
155 lines (119 loc) · 3.53 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
import 'server-only';
import { getFullDashboardData } from '../../lib/github';
import { syncQueue } from '../../lib/syncQueue';
// Cache is considered stale and candidate for background refresh after 10 minutes
const STALE_THRESHOLD_MS = 10 * 60 * 1000;
// Lock expires automatically after 5 minutes
const LOCK_TTL_MS = 5 * 60 * 1000;
type GlobalWithLocks = typeof globalThis & {
__backgroundRefreshLocks?: Map<
string,
{
expiresAt: number;
}
>;
};
const globalLocks =
(globalThis as GlobalWithLocks).__backgroundRefreshLocks ??
new Map<string, { expiresAt: number }>();
(globalThis as GlobalWithLocks).__backgroundRefreshLocks = globalLocks;
export class BackgroundRefresh {
private static instance: BackgroundRefresh;
private constructor() {}
public static getInstance(): BackgroundRefresh {
if (!BackgroundRefresh.instance) {
BackgroundRefresh.instance = new BackgroundRefresh();
}
return BackgroundRefresh.instance;
}
/**
* Checks whether a cached entry is stale and should trigger an async background update.
*/
public isStale(lastSyncedAt: string | undefined): boolean {
if (!lastSyncedAt) return true;
try {
const lastSyncTime = new Date(lastSyncedAt).getTime();
if (isNaN(lastSyncTime)) return true;
return Date.now() - lastSyncTime > STALE_THRESHOLD_MS;
} catch {
return true;
}
}
/**
* Generates normalized lock key.
*/
private createLockKey(username: string): string {
return username.trim().toLowerCase();
}
/**
* Attempts to acquire refresh lock.
*/
private acquireLock(username: string): boolean {
const key = this.createLockKey(username);
const existing = globalLocks.get(key);
if (existing && existing.expiresAt > Date.now()) {
return false;
}
globalLocks.set(key, {
expiresAt: Date.now() + LOCK_TTL_MS,
});
return true;
}
/**
* Releases refresh lock.
*/
private releaseLock(username: string): void {
const key = this.createLockKey(username);
globalLocks.delete(key);
}
/**
* Triggers asynchronous cache refresh.
*/
public async triggerRefresh(username: string): Promise<void> {
const sanitized = username.trim().toLowerCase();
const acquired = this.acquireLock(sanitized);
if (!acquired) {
console.info(`[BackgroundRefresh] Refresh already active for: ${sanitized}`);
return;
}
console.info(`[BackgroundRefresh] Queuing background refresh for: ${sanitized}`);
return new Promise((resolve) => {
syncQueue.enqueue(async () => {
try {
await getFullDashboardData(username, { forceRefresh: true });
console.info(
`[BackgroundRefresh] Successfully completed background refresh for: ${sanitized}`
);
} catch (err) {
console.error(`[BackgroundRefresh] Background refresh failed for: ${sanitized}`, err);
} finally {
this.releaseLock(sanitized);
resolve();
}
});
});
}
/**
* Returns whether a job is active.
*/
public isJobActive(username: string): boolean {
const key = this.createLockKey(username);
const existing = globalLocks.get(key);
if (!existing) {
return false;
}
if (existing.expiresAt <= Date.now()) {
globalLocks.delete(key);
return false;
}
return true;
}
/**
* Clears locks.
*/
public reset(): void {
globalLocks.clear();
}
}
export const backgroundRefresh = BackgroundRefresh.getInstance();
export default backgroundRefresh;