-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathretry.go
More file actions
344 lines (288 loc) · 8.53 KB
/
retry.go
File metadata and controls
344 lines (288 loc) · 8.53 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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
// Retry Logic and Circuit Breaker Module
// Copy this to: /Users/alexis/Public/github-repos/devops-sdk/retry.go
// Provides resilient HTTP client operations with retries and circuit breaker
package sdk
import (
"fmt"
"log"
"os"
"strings"
"sync"
"time"
)
// RetryConfig configures retry behavior
type RetryConfig struct {
MaxAttempts int // Maximum number of retry attempts
InitialDelay time.Duration // Initial delay between retries
MaxDelay time.Duration // Maximum delay between retries
Multiplier float64 // Backoff multiplier (exponential)
RetryableErrors []string // List of retryable error patterns
}
// DefaultRetryConfig provides sensible defaults
var DefaultRetryConfig = RetryConfig{
MaxAttempts: 3,
InitialDelay: 100 * time.Millisecond,
MaxDelay: 30 * time.Second,
Multiplier: 2.0,
RetryableErrors: []string{
"connection refused",
"timeout",
"temporary failure",
"service unavailable",
},
}
// CircuitBreaker implements the circuit breaker pattern
type CircuitBreaker struct {
maxFailures int
resetTimeout time.Duration
state CircuitState
failures int
lastFailTime time.Time
mu sync.RWMutex
logger *log.Logger
}
// CircuitState represents the circuit breaker state
type CircuitState int
const (
StateClosed CircuitState = iota // Normal operation
StateOpen // Circuit is open, rejecting requests
StateHalfOpen // Testing if service recovered
)
// NewCircuitBreaker creates a new circuit breaker
func NewCircuitBreaker(maxFailures int, resetTimeout time.Duration, logger *log.Logger) *CircuitBreaker {
return &CircuitBreaker{
maxFailures: maxFailures,
resetTimeout: resetTimeout,
state: StateClosed,
logger: logger,
}
}
// Execute runs the operation through the circuit breaker
func (cb *CircuitBreaker) Execute(operation func() error) error {
if !cb.canAttempt() {
return fmt.Errorf("circuit breaker is OPEN")
}
err := operation()
if err != nil {
cb.recordFailure()
return err
}
cb.recordSuccess()
return nil
}
// canAttempt checks if we can attempt the operation
func (cb *CircuitBreaker) canAttempt() bool {
cb.mu.RLock()
defer cb.mu.RUnlock()
switch cb.state {
case StateClosed:
return true
case StateOpen:
// Check if enough time has passed to try again
if time.Since(cb.lastFailTime) > cb.resetTimeout {
cb.mu.RUnlock()
cb.mu.Lock()
cb.state = StateHalfOpen
cb.mu.Unlock()
cb.mu.RLock()
return true
}
return false
case StateHalfOpen:
return true
}
return false
}
// recordFailure records a failed attempt
func (cb *CircuitBreaker) recordFailure() {
cb.mu.Lock()
defer cb.mu.Unlock()
cb.failures++
cb.lastFailTime = time.Now()
if cb.failures >= cb.maxFailures {
cb.state = StateOpen
if cb.logger != nil {
cb.logger.Printf("⚠️ Circuit breaker OPENED after %d failures", cb.failures)
}
}
}
// recordSuccess records a successful attempt
func (cb *CircuitBreaker) recordSuccess() {
cb.mu.Lock()
defer cb.mu.Unlock()
if cb.state == StateHalfOpen {
cb.state = StateClosed
if cb.logger != nil {
cb.logger.Printf("✓ Circuit breaker CLOSED - service recovered")
}
}
cb.failures = 0
}
// GetState returns the current circuit breaker state
func (cb *CircuitBreaker) GetState() CircuitState {
cb.mu.RLock()
defer cb.mu.RUnlock()
return cb.state
}
// RetryableClient wraps operations with retry logic and circuit breaker
type RetryableClient struct {
config RetryConfig
circuitBreaker *CircuitBreaker
logger *log.Logger
}
// NewRetryableClient creates a new client with retry capabilities
func NewRetryableClient(config RetryConfig, logger *log.Logger) *RetryableClient {
return &RetryableClient{
config: config,
circuitBreaker: NewCircuitBreaker(5, 60*time.Second, logger),
logger: logger,
}
}
// ExecuteWithRetry executes an operation with retry logic and circuit breaker
func (rc *RetryableClient) ExecuteWithRetry(operationName string, operation func() error) error {
return rc.circuitBreaker.Execute(func() error {
return rc.retryWithBackoff(operationName, operation)
})
}
// retryWithBackoff implements exponential backoff retry logic
func (rc *RetryableClient) retryWithBackoff(operationName string, operation func() error) error {
var lastErr error
delay := rc.config.InitialDelay
for attempt := 1; attempt <= rc.config.MaxAttempts; attempt++ {
if rc.logger != nil && attempt > 1 {
rc.logger.Printf("🔄 Retry %d/%d for %s (after %v delay)",
attempt-1, rc.config.MaxAttempts-1, operationName, delay)
}
lastErr = operation()
if lastErr == nil {
if rc.logger != nil && attempt > 1 {
rc.logger.Printf("✓ %s succeeded after %d attempts", operationName, attempt)
}
return nil
}
// Check if error is retryable
if !rc.isRetryable(lastErr) {
if rc.logger != nil {
rc.logger.Printf("✗ %s failed with non-retryable error: %v", operationName, lastErr)
}
return lastErr
}
// Don't sleep after the last attempt
if attempt < rc.config.MaxAttempts {
if rc.logger != nil {
rc.logger.Printf("⏳ Waiting %v before retry %d/%d",
delay, attempt, rc.config.MaxAttempts-1)
}
time.Sleep(delay)
// Calculate next delay with exponential backoff
delay = time.Duration(float64(delay) * rc.config.Multiplier)
if delay > rc.config.MaxDelay {
delay = rc.config.MaxDelay
}
}
}
if rc.logger != nil {
rc.logger.Printf("✗ %s failed after %d attempts: %v",
operationName, rc.config.MaxAttempts, lastErr)
}
return fmt.Errorf("%s failed after %d attempts: %w",
operationName, rc.config.MaxAttempts, lastErr)
}
// isRetryable checks if an error should trigger a retry
func (rc *RetryableClient) isRetryable(err error) bool {
if err == nil {
return false
}
errMsg := err.Error()
for _, pattern := range rc.config.RetryableErrors {
if strings.Contains(errMsg, pattern) {
return true
}
}
return false
}
// ============================================================================
// INTEGRATION WITH CONFIGHHUB CLIENT
// ============================================================================
// Add these methods to ConfigHubClient:
/*
// Add to ConfigHubClient struct:
type ConfigHubClient struct {
// ... existing fields ...
retryClient *RetryableClient
}
// Modify NewConfigHubClient:
func NewConfigHubClient(apiURL, token string, logger *log.Logger) *ConfigHubClient {
return &ConfigHubClient{
APIBaseURL: apiURL,
Token: token,
HTTPClient: &http.Client{Timeout: 30 * time.Second},
Logger: logger,
retryClient: NewRetryableClient(DefaultRetryConfig, logger),
}
}
// Example usage in CreateUnit:
func (c *ConfigHubClient) CreateUnit(spaceID uuid.UUID, req CreateUnitRequest) (*Unit, error) {
var unit *Unit
var err error
err = c.retryClient.ExecuteWithRetry("CreateUnit", func() error {
unit, err = c.createUnitOnce(spaceID, req)
return err
})
return unit, err
}
// createUnitOnce is the actual implementation (no retry logic)
func (c *ConfigHubClient) createUnitOnce(spaceID uuid.UUID, req CreateUnitRequest) (*Unit, error) {
// ... existing implementation ...
}
*/
// ============================================================================
// USAGE EXAMPLES
// ============================================================================
// Example 1: Simple retry
func ExampleRetryWithBackoff() {
logger := log.New(os.Stdout, "[RETRY] ", log.LstdFlags)
client := NewRetryableClient(DefaultRetryConfig, logger)
err := client.ExecuteWithRetry("Database connection", func() error {
// Your operation here
return nil
})
if err != nil {
log.Printf("Operation failed: %v", err)
}
}
// Example 2: Circuit breaker
func ExampleCircuitBreaker() {
logger := log.New(os.Stdout, "[CB] ", log.LstdFlags)
cb := NewCircuitBreaker(3, 30*time.Second, logger)
for i := 0; i < 10; i++ {
err := cb.Execute(func() error {
// Your operation here
return fmt.Errorf("service unavailable")
})
if err != nil {
log.Printf("Attempt %d failed: %v", i+1, err)
}
time.Sleep(time.Second)
}
}
// Example 3: Custom retry configuration
func ExampleCustomRetryConfig() {
customConfig := RetryConfig{
MaxAttempts: 5,
InitialDelay: 200 * time.Millisecond,
MaxDelay: 10 * time.Second,
Multiplier: 1.5,
RetryableErrors: []string{
"network error",
"timeout",
"connection reset",
},
}
logger := log.New(os.Stdout, "[CUSTOM] ", log.LstdFlags)
client := NewRetryableClient(customConfig, logger)
client.ExecuteWithRetry("Custom operation", func() error {
// Your operation
return nil
})
}