luckfun233 commited on
Commit ·
04c88a2
1
Parent(s): 766bd1c
feat: Add jitter and random offset to token refresh intervals for better distribution
Browse files- internal/auth/request.go +15 -2
internal/auth/request.go
CHANGED
|
@@ -5,6 +5,7 @@ import (
|
|
| 5 |
"crypto/sha256"
|
| 6 |
"encoding/hex"
|
| 7 |
"errors"
|
|
|
|
| 8 |
"net/http"
|
| 9 |
"strings"
|
| 10 |
"sync"
|
|
@@ -329,16 +330,28 @@ func (r *Resolver) shouldForceRefresh(accountID string) bool {
|
|
| 329 |
r.tokenRefreshedAt[accountID] = now
|
| 330 |
return false
|
| 331 |
}
|
| 332 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 333 |
}
|
| 334 |
|
| 335 |
func (r *Resolver) markTokenRefreshedNow(accountID string) {
|
| 336 |
if strings.TrimSpace(accountID) == "" {
|
| 337 |
return
|
| 338 |
}
|
|
|
|
|
|
|
|
|
|
| 339 |
r.mu.Lock()
|
| 340 |
defer r.mu.Unlock()
|
| 341 |
-
r.tokenRefreshedAt[accountID] = time.Now()
|
| 342 |
}
|
| 343 |
|
| 344 |
func (r *Resolver) clearTokenRefreshMark(accountID string) {
|
|
|
|
| 5 |
"crypto/sha256"
|
| 6 |
"encoding/hex"
|
| 7 |
"errors"
|
| 8 |
+
"math/rand"
|
| 9 |
"net/http"
|
| 10 |
"strings"
|
| 11 |
"sync"
|
|
|
|
| 330 |
r.tokenRefreshedAt[accountID] = now
|
| 331 |
return false
|
| 332 |
}
|
| 333 |
+
// Add jitter: ±15% random variation to avoid all accounts refreshing at the same time.
|
| 334 |
+
// For a 6h interval, this gives a range of ~5h06m to ~6h54m.
|
| 335 |
+
baseInterval := time.Duration(intervalHours) * time.Hour
|
| 336 |
+
jitterRange := baseInterval / 10 // ±10% → total range is 80%-120% of base
|
| 337 |
+
jitter := time.Duration(rand.Int63n(int64(2*jitterRange+1))) - jitterRange
|
| 338 |
+
effectiveInterval := baseInterval + jitter
|
| 339 |
+
if effectiveInterval < time.Hour {
|
| 340 |
+
effectiveInterval = time.Hour
|
| 341 |
+
}
|
| 342 |
+
return now.Sub(last) >= effectiveInterval
|
| 343 |
}
|
| 344 |
|
| 345 |
func (r *Resolver) markTokenRefreshedNow(accountID string) {
|
| 346 |
if strings.TrimSpace(accountID) == "" {
|
| 347 |
return
|
| 348 |
}
|
| 349 |
+
// Add a random offset (0-30min) to spread out future refreshes across accounts.
|
| 350 |
+
// This prevents all accounts from refreshing at the same wall-clock time.
|
| 351 |
+
offset := time.Duration(rand.Int63n(int64(30*time.Minute)))
|
| 352 |
r.mu.Lock()
|
| 353 |
defer r.mu.Unlock()
|
| 354 |
+
r.tokenRefreshedAt[accountID] = time.Now().Add(-offset)
|
| 355 |
}
|
| 356 |
|
| 357 |
func (r *Resolver) clearTokenRefreshMark(accountID string) {
|