forked from NoeFabris/opencode-antigravity-auth
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrefresh-queue.ts
More file actions
320 lines (279 loc) · 8.56 KB
/
Copy pathrefresh-queue.ts
File metadata and controls
320 lines (279 loc) · 8.56 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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
/**
* Proactive Token Refresh Queue
*
* Ported from LLM-API-Key-Proxy's BackgroundRefresher.
*
* This module provides background token refresh to ensure OAuth tokens
* remain valid without blocking user requests. It periodically checks
* all accounts and refreshes tokens that are approaching expiry.
*
* Features:
* - Non-blocking background refresh (doesn't block requests)
* - Configurable refresh buffer (default: 30 minutes before expiry)
* - Configurable check interval (default: 5 minutes)
* - Serialized refresh to prevent concurrent refresh storms
* - Integrates with existing AccountManager and token refresh logic
* - Silent operation: no console output, uses structured logger
*/
import type { AccountManager, ManagedAccount } from "./accounts";
import type { PluginClient, OAuthAuthDetails } from "./types";
import { refreshAccessToken } from "./token";
import { createLogger } from "./logger";
const log = createLogger("refresh-queue");
/** Configuration for the proactive refresh queue */
export interface ProactiveRefreshConfig {
/** Enable proactive token refresh (default: true) */
enabled: boolean;
/** Seconds before expiry to trigger proactive refresh (default: 1800 = 30 minutes) */
bufferSeconds: number;
/** Interval between refresh checks in seconds (default: 300 = 5 minutes) */
checkIntervalSeconds: number;
}
export const DEFAULT_PROACTIVE_REFRESH_CONFIG: ProactiveRefreshConfig = {
enabled: true,
bufferSeconds: 1800, // 30 minutes
checkIntervalSeconds: 300, // 5 minutes
};
/** State for tracking refresh operations */
interface RefreshQueueState {
isRunning: boolean;
intervalHandle: ReturnType<typeof setInterval> | null;
isRefreshing: boolean;
lastCheckTime: number;
lastRefreshTime: number;
refreshCount: number;
errorCount: number;
}
/**
* Proactive Token Refresh Queue
*
* Runs in the background and proactively refreshes tokens before they expire.
* This ensures that user requests never block on token refresh.
*
* All logging is silent by default - uses structured logger that only outputs
* when OPENCODE_ANTIGRAVITY_CONSOLE_LOG=1 is set or TUI logging is available.
*/
export class ProactiveRefreshQueue {
private readonly config: ProactiveRefreshConfig;
private readonly client: PluginClient;
private readonly providerId: string;
private accountManager: AccountManager | null = null;
private state: RefreshQueueState = {
isRunning: false,
intervalHandle: null,
isRefreshing: false,
lastCheckTime: 0,
lastRefreshTime: 0,
refreshCount: 0,
errorCount: 0,
};
constructor(
client: PluginClient,
providerId: string,
config?: Partial<ProactiveRefreshConfig>,
) {
this.client = client;
this.providerId = providerId;
this.config = {
...DEFAULT_PROACTIVE_REFRESH_CONFIG,
...config,
};
}
/**
* Set the account manager to use for refresh operations.
* Must be called before start().
*/
setAccountManager(manager: AccountManager): void {
this.accountManager = manager;
}
/**
* Check if a token needs proactive refresh.
* Returns true if the token expires within the buffer period.
*/
needsRefresh(account: ManagedAccount): boolean {
if (!account.expires) {
// No expiry set - assume it's fine
return false;
}
const now = Date.now();
const bufferMs = this.config.bufferSeconds * 1000;
const refreshThreshold = now + bufferMs;
return account.expires <= refreshThreshold;
}
/**
* Check if a token is already expired.
*/
isExpired(account: ManagedAccount): boolean {
if (!account.expires) {
return false;
}
return account.expires <= Date.now();
}
/**
* Get all accounts that need proactive refresh.
*/
getAccountsNeedingRefresh(): ManagedAccount[] {
if (!this.accountManager) {
return [];
}
return this.accountManager.getAccounts().filter((account) => {
// Only refresh if not already expired (let the main flow handle expired tokens)
if (this.isExpired(account)) {
return false;
}
return this.needsRefresh(account);
});
}
/**
* Perform a single refresh check iteration.
* This is called periodically by the background interval.
*/
private async runRefreshCheck(): Promise<void> {
if (this.state.isRefreshing) {
// Already refreshing - skip this iteration
return;
}
if (!this.accountManager) {
return;
}
this.state.isRefreshing = true;
this.state.lastCheckTime = Date.now();
try {
const accountsToRefresh = this.getAccountsNeedingRefresh();
if (accountsToRefresh.length === 0) {
return;
}
log.debug("Found accounts needing refresh", { count: accountsToRefresh.length });
// Refresh accounts serially to avoid concurrent refresh storms
for (const account of accountsToRefresh) {
if (!this.state.isRunning) {
// Queue was stopped - abort
break;
}
try {
const auth = this.accountManager.toAuthDetails(account);
const refreshed = await this.refreshToken(auth, account);
if (refreshed) {
this.accountManager.updateFromAuth(account, refreshed);
this.state.refreshCount++;
this.state.lastRefreshTime = Date.now();
// Persist the refreshed token
try {
await this.accountManager.saveToDisk();
} catch {
// Non-fatal - token is refreshed in memory
}
}
} catch (error) {
this.state.errorCount++;
// Log but don't throw - continue with other accounts
log.warn("Failed to refresh account", {
accountIndex: account.index,
error: error instanceof Error ? error.message : String(error),
});
}
}
} finally {
this.state.isRefreshing = false;
}
}
/**
* Refresh a single token.
*/
private async refreshToken(
auth: OAuthAuthDetails,
account: ManagedAccount,
): Promise<OAuthAuthDetails | undefined> {
const minutesUntilExpiry = account.expires
? Math.round((account.expires - Date.now()) / 60000)
: "unknown";
log.debug("Proactively refreshing token", {
accountIndex: account.index,
email: account.email ?? "unknown",
minutesUntilExpiry,
});
return refreshAccessToken(auth, this.client, this.providerId);
}
/**
* Start the background refresh queue.
*/
start(): void {
if (this.state.isRunning) {
return;
}
if (!this.config.enabled) {
log.debug("Proactive refresh disabled by config");
return;
}
this.state.isRunning = true;
const intervalMs = this.config.checkIntervalSeconds * 1000;
log.debug("Started proactive refresh queue", {
checkIntervalSeconds: this.config.checkIntervalSeconds,
bufferSeconds: this.config.bufferSeconds,
});
// Run initial check after a short delay (let things settle)
setTimeout(() => {
if (this.state.isRunning) {
this.runRefreshCheck().catch((error) => {
log.error("Initial check failed", {
error: error instanceof Error ? error.message : String(error),
});
});
}
}, 5000);
// Set up periodic checks
this.state.intervalHandle = setInterval(() => {
this.runRefreshCheck().catch((error) => {
log.error("Check failed", {
error: error instanceof Error ? error.message : String(error),
});
});
}, intervalMs);
}
/**
* Stop the background refresh queue.
*/
stop(): void {
if (!this.state.isRunning) {
return;
}
this.state.isRunning = false;
if (this.state.intervalHandle) {
clearInterval(this.state.intervalHandle);
this.state.intervalHandle = null;
}
log.debug("Stopped proactive refresh queue", {
refreshCount: this.state.refreshCount,
errorCount: this.state.errorCount,
});
}
/**
* Get current queue statistics.
*/
getStats(): {
isRunning: boolean;
isRefreshing: boolean;
lastCheckTime: number;
lastRefreshTime: number;
refreshCount: number;
errorCount: number;
} {
return { ...this.state };
}
/**
* Check if the queue is currently running.
*/
isRunning(): boolean {
return this.state.isRunning;
}
}
/**
* Create a proactive refresh queue instance.
*/
export function createProactiveRefreshQueue(
client: PluginClient,
providerId: string,
config?: Partial<ProactiveRefreshConfig>,
): ProactiveRefreshQueue {
return new ProactiveRefreshQueue(client, providerId, config);
}