-
-
Notifications
You must be signed in to change notification settings - Fork 554
feat: improve copilot token refresh resilience #213
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,169 @@ | ||
| import consola from "consola" | ||
|
|
||
| import { getCopilotToken } from "~/services/github/get-copilot-token" | ||
|
|
||
| import { state } from "./state" | ||
|
|
||
| /** | ||
| * Singleton manager for Copilot token with automatic refresh | ||
| * All token access should go through this manager | ||
| */ | ||
| class CopilotTokenManager { | ||
| private refreshTimer: ReturnType<typeof setTimeout> | null = null | ||
| private refreshPromise: Promise<void> | null = null | ||
| private tokenExpiresAt: number = 0 | ||
| private consecutiveRefreshFailures: number = 0 | ||
|
|
||
| /** | ||
| * Get the current valid Copilot token | ||
| * Automatically refreshes if expired or about to expire | ||
| */ | ||
| async getToken(): Promise<string> { | ||
| // If no token or token is expired/expiring soon (within 60 seconds), refresh | ||
| const now = Date.now() / 1000 | ||
| if (!state.copilotToken || this.tokenExpiresAt - now < 60) { | ||
| if (!this.refreshPromise) { | ||
| this.refreshPromise = this.refreshToken().finally(() => { | ||
| this.refreshPromise = null | ||
| }) | ||
| } | ||
|
|
||
| try { | ||
| await this.refreshPromise | ||
| } catch (error) { | ||
| const nowAfterRefresh = Date.now() / 1000 | ||
| const stillValid = | ||
| Boolean(state.copilotToken) && this.tokenExpiresAt - nowAfterRefresh > 5 | ||
| if (stillValid && state.copilotToken) { | ||
| consola.warn( | ||
| "[CopilotTokenManager] Refresh failed but current token is still valid, using cached token:", | ||
| error, | ||
| ) | ||
| return state.copilotToken | ||
| } | ||
| throw error | ||
| } | ||
| } | ||
|
|
||
| if (!state.copilotToken) { | ||
| throw new Error("Failed to obtain Copilot token") | ||
| } | ||
|
|
||
| return state.copilotToken | ||
| } | ||
|
|
||
| /** | ||
| * Force refresh the token and reset the auto-refresh timer | ||
| */ | ||
| async refreshToken(): Promise<void> { | ||
| try { | ||
| consola.debug("[CopilotTokenManager] Refreshing token...") | ||
| const { token, expires_at, refresh_in } = await getCopilotToken() | ||
|
|
||
| state.copilotToken = token | ||
| this.tokenExpiresAt = expires_at | ||
|
|
||
| consola.debug("[CopilotTokenManager] Token refreshed successfully") | ||
| if (state.showToken) { | ||
| consola.info("[CopilotTokenManager] Token:", token) | ||
| } | ||
|
|
||
| this.consecutiveRefreshFailures = 0 | ||
| // Setup auto-refresh timer | ||
| this.scheduleRefresh(refresh_in) | ||
| } catch (error) { | ||
| this.consecutiveRefreshFailures += 1 | ||
| consola.error("[CopilotTokenManager] Failed to refresh token:", error) | ||
| throw error | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Schedule the next automatic refresh | ||
| */ | ||
| private scheduleRefresh(refreshIn: number): void { | ||
| // Clear existing timer | ||
| if (this.refreshTimer) { | ||
| clearTimeout(this.refreshTimer) | ||
| this.refreshTimer = null | ||
| } | ||
|
|
||
| // Schedule refresh 60 seconds before the recommended refresh time | ||
| const refreshMs = Math.min( | ||
| refreshIn * 1000, | ||
| Math.max((refreshIn - 60) * 1000, 60000), // At least 1 minute | ||
| ) | ||
|
|
||
| consola.debug( | ||
| `[CopilotTokenManager] Scheduling next refresh in ${Math.round(refreshMs / 1000)}s`, | ||
| ) | ||
|
|
||
| this.refreshTimer = setTimeout(async () => { | ||
| try { | ||
| await this.refreshToken() | ||
| } catch (error) { | ||
| consola.error( | ||
| "[CopilotTokenManager] Auto-refresh failed, scheduling background retry:", | ||
| error, | ||
| ) | ||
| this.scheduleRetryAfterFailure() | ||
| } | ||
| }, refreshMs) | ||
| } | ||
|
|
||
| private scheduleRetryAfterFailure(): void { | ||
| if (this.refreshTimer) { | ||
| clearTimeout(this.refreshTimer) | ||
| this.refreshTimer = null | ||
| } | ||
|
|
||
| const cappedFailures = Math.min(this.consecutiveRefreshFailures, 6) | ||
| const retryDelaySeconds = Math.min( | ||
| 15 * 2 ** Math.max(cappedFailures - 1, 0), | ||
| 300, | ||
| ) | ||
|
|
||
| consola.warn( | ||
| `[CopilotTokenManager] Scheduling retry after refresh failure in ${retryDelaySeconds}s`, | ||
| ) | ||
|
|
||
| this.refreshTimer = setTimeout(async () => { | ||
| try { | ||
| await this.refreshToken() | ||
| } catch (error) { | ||
| consola.error( | ||
| "[CopilotTokenManager] Retry refresh failed, will retry again:", | ||
| error, | ||
| ) | ||
| this.scheduleRetryAfterFailure() | ||
| } | ||
| }, retryDelaySeconds * 1000) | ||
| } | ||
|
|
||
| /** | ||
| * Clear the token and stop auto-refresh | ||
| * Call this when switching accounts or logging out | ||
| */ | ||
| clear(): void { | ||
| if (this.refreshTimer) { | ||
| clearTimeout(this.refreshTimer) | ||
| this.refreshTimer = null | ||
| } | ||
| this.refreshPromise = null | ||
| state.copilotToken = undefined | ||
| this.tokenExpiresAt = 0 | ||
| this.consecutiveRefreshFailures = 0 | ||
| consola.debug("[CopilotTokenManager] Token cleared") | ||
| } | ||
|
|
||
| /** | ||
| * Check if we have a valid token | ||
| */ | ||
| hasValidToken(): boolean { | ||
| const now = Date.now() / 1000 | ||
| return Boolean(state.copilotToken) && this.tokenExpiresAt - now > 60 | ||
| } | ||
| } | ||
|
|
||
| // Export singleton instance | ||
| export const copilotTokenManager = new CopilotTokenManager() | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
copilotTokenManageris exported here but not referenced anywhere else insrc/(the server startup still callssetupCopilotToken()insrc/lib/token.ts, which keeps its ownsetIntervalrefresh). If the intent of this PR is to improve refresh resilience globally, the manager needs to be integrated into the existing token setup / request paths, otherwise these new behaviors won’t take effect.