-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstability.go
More file actions
239 lines (214 loc) · 6.31 KB
/
Copy pathstability.go
File metadata and controls
239 lines (214 loc) · 6.31 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
package main
import (
"fmt"
"math"
"math/rand"
"net/http"
"sync"
"time"
)
// StabilityStatus tracks the overall system stability.
type StabilityStatus struct {
IsHealthy bool `json:"is_healthy"`
Uptime string `json:"uptime"`
StartTime time.Time `json:"start_time"`
TotalRequests int64 `json:"total_requests"`
TotalErrors int64 `json:"total_errors"`
TotalRetries int64 `json:"total_retries"`
TotalFailovers int64 `json:"total_failovers"`
ConsecutiveErrs int `json:"consecutive_errors"`
LastErrAt time.Time `json:"last_error_at"`
LastRetryAt time.Time `json:"last_retry_at"`
LastFailoverAt time.Time `json:"last_failover_at"`
}
// StabilityManager handles error recovery, retries, and failover logic.
type StabilityManager struct {
mu sync.RWMutex
status StabilityStatus
cfg *ConfigStore
rng *rand.Rand
}
// NewStabilityManager creates a new stability manager.
func NewStabilityManager(cfg *ConfigStore) *StabilityManager {
return &StabilityManager{
cfg: cfg,
rng: rand.New(rand.NewSource(time.Now().UnixNano())),
status: StabilityStatus{
IsHealthy: true,
StartTime: time.Now(),
},
}
}
// RecordRequest records a request outcome.
func (sm *StabilityManager) RecordRequest(success bool) {
sm.mu.Lock()
defer sm.mu.Unlock()
sm.status.TotalRequests++
if success {
sm.status.ConsecutiveErrs = 0
sm.status.IsHealthy = true
} else {
sm.status.TotalErrors++
sm.status.ConsecutiveErrs++
sm.status.LastErrAt = time.Now()
// If 5+ consecutive errors, mark as degraded
if sm.status.ConsecutiveErrs >= 5 {
sm.status.IsHealthy = false
}
}
}
// RecordRetry records a retry attempt.
func (sm *StabilityManager) RecordRetry() {
sm.mu.Lock()
defer sm.mu.Unlock()
sm.status.TotalRetries++
sm.status.LastRetryAt = time.Now()
}
// RecordFailover records a failover event.
func (sm *StabilityManager) RecordFailover() {
sm.mu.Lock()
defer sm.mu.Unlock()
sm.status.TotalFailovers++
sm.status.LastFailoverAt = time.Now()
}
// GetStatus returns a copy of the current stability status.
func (sm *StabilityManager) GetStatus() StabilityStatus {
sm.mu.RLock()
defer sm.mu.RUnlock()
s := sm.status
s.Uptime = time.Since(s.StartTime).Truncate(time.Second).String()
return s
}
// RetryWithBackoff executes a function with exponential backoff retry logic.
// Returns the HTTP response and the provider index that succeeded.
func (sm *StabilityManager) RetryWithBackoff(fn func(providerIdx int) (*http.Response, error)) (*http.Response, int, error) {
appCfg := sm.cfg.Get()
if !appCfg.AutoRetry {
// No retry - just try active provider
_, ok := sm.cfg.GetActiveProvider()
if !ok {
return nil, 0, fmt.Errorf("no providers configured")
}
idx := appCfg.ActiveIdx
resp, err := fn(idx)
if err == nil {
sm.RecordRequest(true)
} else {
sm.RecordRequest(false)
}
return resp, idx, err
}
maxRetries := appCfg.RetryMax
if maxRetries <= 0 {
maxRetries = 3
}
// Try active provider first, then retry with backoff
for attempt := 0; attempt < maxRetries; attempt++ {
// Read active index fresh each attempt (may have changed due to failover)
currentCfg := sm.cfg.Get()
if len(currentCfg.Providers) == 0 {
return nil, 0, fmt.Errorf("no providers configured")
}
idx := currentCfg.ActiveIdx
if idx < 0 || idx >= len(currentCfg.Providers) {
idx = 0
}
resp, err := fn(idx)
if err == nil {
if resp.StatusCode < 500 {
sm.RecordRequest(resp.StatusCode < 400)
return resp, idx, nil
}
// Close the body of failed attempts (5xx status codes) to prevent connection leak
resp.Body.Close()
sm.RecordRequest(false)
} else {
sm.RecordRequest(false)
}
// Calculate backoff with jitter
if attempt < maxRetries-1 {
backoff := sm.calcBackoff(attempt)
sm.RecordRetry()
time.Sleep(backoff)
}
}
// All retries exhausted — try failover if enabled
if appCfg.Failover {
return sm.tryFailover(fn)
}
return nil, 0, fmt.Errorf("all retries exhausted for provider %s", appCfg.Providers[appCfg.ActiveIdx].Name)
}
// tryFailover attempts to use alternative providers.
func (sm *StabilityManager) tryFailover(fn func(providerIdx int) (*http.Response, error)) (*http.Response, int, error) {
appCfg := sm.cfg.Get()
activeIdx := appCfg.ActiveIdx
// Sort providers by priority, skip active
type provIdx struct {
Provider
idx int
}
var alternatives []provIdx
for i, p := range appCfg.Providers {
if i != activeIdx && p.Status != "offline" {
alternatives = append(alternatives, provIdx{p, i})
}
}
// Sort by priority
for i := 0; i < len(alternatives); i++ {
for j := i + 1; j < len(alternatives); j++ {
if alternatives[j].Priority < alternatives[i].Priority {
alternatives[i], alternatives[j] = alternatives[j], alternatives[i]
}
}
}
for _, alt := range alternatives {
resp, err := fn(alt.idx)
if err == nil && resp.StatusCode < 500 {
// Failover succeeded — switch active provider
sm.cfg.SetActiveProvider(alt.idx)
sm.RecordFailover()
sm.RecordRequest(true)
return resp, alt.idx, nil
}
sm.RecordRequest(false)
}
return nil, 0, fmt.Errorf("all providers failed including failover")
}
// calcBackoff calculates exponential backoff with jitter.
func (sm *StabilityManager) calcBackoff(attempt int) time.Duration {
// Base: 1s, then 2s, 4s, 8s... with jitter
base := time.Duration(math.Pow(2, float64(attempt))) * time.Second
jitter := time.Duration(sm.rng.Int63n(int64(base / 2)))
return base + jitter
}
// ShouldRetry checks if an error is retryable.
func ShouldRetry(statusCode int) bool {
switch statusCode {
case http.StatusTooManyRequests, // 429
http.StatusInternalServerError, // 500
http.StatusBadGateway, // 502
http.StatusServiceUnavailable, // 503
http.StatusGatewayTimeout: // 504
return true
default:
return false
}
}
// Uptime returns the time since the server started.
func (sm *StabilityManager) Uptime() time.Duration {
sm.mu.RLock()
defer sm.mu.RUnlock()
return time.Since(sm.status.StartTime)
}
// IsHealthy checks if the system is currently healthy.
func (sm *StabilityManager) IsHealthy() bool {
sm.mu.RLock()
defer sm.mu.RUnlock()
return sm.status.IsHealthy
}
// ErrorCount returns total error count.
func (sm *StabilityManager) ErrorCount() int64 {
sm.mu.RLock()
defer sm.mu.RUnlock()
return sm.status.TotalErrors
}