-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathbackground_refresh.go
More file actions
168 lines (144 loc) · 5.23 KB
/
background_refresh.go
File metadata and controls
168 lines (144 loc) · 5.23 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
package cliauth
import (
"fmt"
"os"
"time"
)
var (
// Start refresh attempts this duration before token expiration
defaultTimeStartBeforeTokenExpiration = 5 * time.Minute
// Check context cancellation this frequently while waiting
defaultTimeBetweenContextCheck = time.Second
// Retry interval on refresh failures
defaultTimeBetweenTries = 2 * time.Minute
)
// continuousRefreshToken continuously refreshes the CLI provider token in the background.
// It monitors token expiration and automatically refreshes before the token expires.
//
// The goroutine terminates when:
// - The context is canceled
// - A non-retryable error occurs
//
// To terminate this routine, cancel the context in flow.refreshContext.
func continuousRefreshToken(flow *CLIProviderFlow) {
refresher := &continuousTokenRefresher{
flow: flow,
timeStartBeforeTokenExpiration: defaultTimeStartBeforeTokenExpiration,
timeBetweenContextCheck: defaultTimeBetweenContextCheck,
timeBetweenTries: defaultTimeBetweenTries,
}
err := refresher.continuousRefreshToken()
fmt.Fprintf(os.Stderr, "CLI provider token refreshing terminated: %v\n", err)
}
type continuousTokenRefresher struct {
flow *CLIProviderFlow
timeStartBeforeTokenExpiration time.Duration
timeBetweenContextCheck time.Duration
timeBetweenTries time.Duration
}
// continuousRefreshToken runs the main background refresh loop.
// It waits until the token is close to expiring, then refreshes it.
// Always returns with a non-nil error (indicating why it terminated).
func (r *continuousTokenRefresher) continuousRefreshToken() error {
// Compute initial refresh timestamp
startRefreshTimestamp := r.getNextRefreshTimestamp()
for {
// Wait until it's time to refresh (or context is canceled)
err := r.waitUntilTimestamp(startRefreshTimestamp)
if err != nil {
return err
}
// Check if context was canceled
err = r.flow.refreshContext.Err()
if err != nil {
return fmt.Errorf("context canceled: %w", err)
}
// Attempt to refresh the token
ok, err := r.refreshToken()
if err != nil {
return fmt.Errorf("refresh token: %w", err)
}
if !ok {
// Refresh failed (but is retryable), try again later
startRefreshTimestamp = time.Now().Add(r.timeBetweenTries)
continue
}
// Refresh succeeded, compute next refresh time
startRefreshTimestamp = r.getNextRefreshTimestamp()
}
}
// getNextRefreshTimestamp calculates when the next token refresh should start.
// Returns now if token is already expired, otherwise returns expiry time minus safety margin.
func (r *continuousTokenRefresher) getNextRefreshTimestamp() time.Time {
r.flow.tokenMutex.RLock()
expiresAt := r.flow.creds.SessionExpiresAt
r.flow.tokenMutex.RUnlock()
// If no expiry time set, check again in 5 minutes
if expiresAt.IsZero() {
return time.Now().Add(5 * time.Minute)
}
// If already expired, refresh immediately
if time.Now().After(expiresAt) {
return time.Now()
}
// Schedule refresh before expiration (with safety margin)
return expiresAt.Add(-r.timeStartBeforeTokenExpiration)
}
// waitUntilTimestamp blocks until the target timestamp is reached or context is canceled.
// Periodically checks if the context has been canceled.
func (r *continuousTokenRefresher) waitUntilTimestamp(timestamp time.Time) error {
for time.Now().Before(timestamp) {
// Check if context was canceled
err := r.flow.refreshContext.Err()
if err != nil {
return fmt.Errorf("context canceled during wait: %w", err)
}
// Sleep briefly before checking again
time.Sleep(r.timeBetweenContextCheck)
}
return nil
}
// refreshToken attempts to refresh the access token.
// Returns:
// - (true, nil) if refresh succeeded
// - (false, nil) if refresh failed but should be retried (e.g., network error)
// - (false, err) if refresh failed and should not be retried (e.g., invalid refresh token)
func (r *continuousTokenRefresher) refreshToken() (bool, error) {
// Acquire write lock for refresh
r.flow.tokenMutex.Lock()
defer r.flow.tokenMutex.Unlock()
// Double-check if refresh is still needed (another goroutine might have refreshed)
if !IsTokenExpired(r.flow.creds) {
return true, nil
}
// Attempt refresh
err := RefreshTokenWithClient(r.flow.creds, r.flow.httpClient)
if err == nil {
return true, nil
}
// Check if error is retryable
// Network errors, 5xx errors are retryable
// 4xx errors (invalid refresh token) are not retryable
errStr := err.Error()
// Non-retryable errors (invalid refresh token, auth errors)
if contains(errStr, "status 400") || contains(errStr, "status 401") ||
contains(errStr, "status 403") || contains(errStr, "refresh token is empty") {
return false, fmt.Errorf("token refresh failed (non-retryable): %w", err)
}
// Retryable errors (network issues, 5xx errors)
return false, nil
}
// contains checks if a string contains a substring
func contains(s, substr string) bool {
return len(s) >= len(substr) && (s == substr || len(s) > len(substr) &&
(s[:len(substr)] == substr || s[len(s)-len(substr):] == substr ||
containsMiddle(s, substr)))
}
func containsMiddle(s, substr string) bool {
for i := 0; i <= len(s)-len(substr); i++ {
if s[i:i+len(substr)] == substr {
return true
}
}
return false
}