forked from instantlyeasy/claude-code-sdk-ts
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathretry-strategies.js
More file actions
331 lines (270 loc) · 9.37 KB
/
retry-strategies.js
File metadata and controls
331 lines (270 loc) · 9.37 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
#!/usr/bin/env node
/**
* Retry Strategies Example
*
* This example demonstrates various retry strategies available in the SDK,
* including exponential backoff, linear retry, and Fibonacci sequences.
*
* Use cases:
* - Handling transient network failures
* - Managing rate limits gracefully
* - Building resilient API integrations
*/
import {
claude,
createRetryExecutor,
createExponentialRetryExecutor,
createLinearRetryExecutor,
createFibonacciRetryExecutor,
withRetry
} from '../../../dist/index.js';
async function retryStrategiesExample() {
console.log('🔄 Retry Strategies Example\n');
// Example 1: Basic retry with exponential backoff
console.log('1. Exponential Backoff Retry');
console.log('----------------------------\n');
const exponentialRetry = createExponentialRetryExecutor({
maxAttempts: 4,
initialDelay: 1000, // Start with 1 second
multiplier: 2, // Double the delay each time
maxDelay: 10000, // Cap at 10 seconds
jitter: true // Add randomization to prevent thundering herd
});
try {
let attemptCount = 0;
const result = await exponentialRetry.execute(async () => {
attemptCount++;
console.log(`📍 Attempt ${attemptCount}`);
// Simulate failures for first 2 attempts
if (attemptCount < 3) {
throw new Error('Simulated transient error');
}
return await claude()
.withModel('sonnet')
.query('Say "Success after retry!"')
.asText();
}, {
onRetry: (attempt, error, nextDelay) => {
console.log(`⏳ Retry ${attempt} in ${nextDelay}ms after: ${error.message}`);
}
});
console.log('✅ Result:', result);
console.log('📊 Stats:', exponentialRetry.getStats());
} catch (error) {
console.log('❌ Failed after all retries:', error.message);
}
// Example 2: Linear retry for predictable delays
console.log('\n\n2. Linear Retry Strategy');
console.log('------------------------\n');
const linearRetry = createLinearRetryExecutor({
maxAttempts: 3,
delay: 2000, // Fixed 2 second delay between attempts
jitter: false // No randomization
});
try {
const startTime = Date.now();
const result = await linearRetry.execute(async () => {
const elapsed = Math.floor((Date.now() - startTime) / 1000);
console.log(`📍 Attempting at T+${elapsed}s`);
// Succeed on second attempt
if (linearRetry.getStats().totalAttempts > 1) {
return 'Linear retry success!';
}
throw new Error('Need one more try');
});
console.log('✅ Result:', result);
} catch (error) {
console.log('❌ Linear retry failed:', error.message);
}
// Example 3: Fibonacci retry for gradual backoff
console.log('\n\n3. Fibonacci Retry Strategy');
console.log('---------------------------\n');
const fibonacciRetry = createFibonacciRetryExecutor({
maxAttempts: 5,
initialDelay: 1000, // 1 second
maxDelay: 8000 // Cap at 8 seconds
});
console.log('Fibonacci sequence delays: 1s, 1s, 2s, 3s, 5s...\n');
try {
let previousDelay = 0;
await fibonacciRetry.execute(async () => {
throw new Error('Always fail to show sequence');
}, {
onRetry: (attempt, error, nextDelay) => {
const sequence = attempt === 1 ? 1 : previousDelay;
console.log(`🔢 Fibonacci attempt ${attempt}: waiting ${nextDelay}ms`);
previousDelay = nextDelay;
}
});
} catch (error) {
console.log('✅ Fibonacci sequence demonstrated');
}
// Example 4: Using withRetry helper function
console.log('\n\n4. WithRetry Helper Function');
console.log('----------------------------\n');
try {
// Simple retry wrapper with custom configuration
const result = await withRetry(
async () => {
return await claude()
.withModel('sonnet')
.query('Write a haiku about persistence')
.asText();
},
{
maxAttempts: 3,
strategy: 'exponential',
initialDelay: 500,
shouldRetry: (error, attempt) => {
// Custom retry logic - only retry on specific errors
const retryableErrors = ['network_error', 'timeout_error', 'rate_limit_error'];
const errorType = error.type || 'unknown';
console.log(`🤔 Checking if should retry: ${errorType}`);
return retryableErrors.includes(errorType) && attempt < 3;
}
}
);
console.log('✅ Result with retry helper:');
console.log(result);
} catch (error) {
console.log('❌ WithRetry failed:', error.message);
}
// Example 5: Advanced retry with circuit breaker pattern
console.log('\n\n5. Circuit Breaker Pattern');
console.log('--------------------------\n');
class CircuitBreaker {
constructor(retryExecutor, options = {}) {
this.retryExecutor = retryExecutor;
this.failureThreshold = options.failureThreshold || 3;
this.resetTimeout = options.resetTimeout || 30000; // 30 seconds
this.state = 'CLOSED'; // CLOSED, OPEN, HALF_OPEN
this.failures = 0;
this.lastFailureTime = null;
}
async execute(fn) {
// Check if circuit should be reset
if (this.state === 'OPEN' &&
Date.now() - this.lastFailureTime > this.resetTimeout) {
console.log('🔄 Circuit breaker: Moving to HALF_OPEN');
this.state = 'HALF_OPEN';
}
// If circuit is open, fail fast
if (this.state === 'OPEN') {
throw new Error('Circuit breaker is OPEN - failing fast');
}
try {
const result = await this.retryExecutor.execute(fn);
// Success - reset the circuit
if (this.state === 'HALF_OPEN') {
console.log('✅ Circuit breaker: Success in HALF_OPEN, closing circuit');
this.state = 'CLOSED';
this.failures = 0;
}
return result;
} catch (error) {
this.failures++;
this.lastFailureTime = Date.now();
if (this.failures >= this.failureThreshold) {
console.log('🚫 Circuit breaker: Opening circuit after', this.failures, 'failures');
this.state = 'OPEN';
}
throw error;
}
}
getState() {
return {
state: this.state,
failures: this.failures,
lastFailureTime: this.lastFailureTime
};
}
}
// Create circuit breaker with exponential retry
const breaker = new CircuitBreaker(
createExponentialRetryExecutor({ maxAttempts: 2, initialDelay: 1000 }),
{ failureThreshold: 2, resetTimeout: 5000 }
);
// Simulate multiple failures to open the circuit
for (let i = 0; i < 4; i++) {
try {
await breaker.execute(async () => {
throw new Error('Service unavailable');
});
} catch (error) {
console.log(`❌ Request ${i + 1} failed:`, error.message);
console.log(' Circuit state:', breaker.getState().state);
}
// Small delay between requests
await new Promise(resolve => setTimeout(resolve, 500));
}
console.log('\n⏳ Waiting for circuit reset timeout...');
await new Promise(resolve => setTimeout(resolve, 5500));
// Try again after reset
try {
await breaker.execute(async () => {
console.log('✅ Service recovered!');
return 'Success after circuit reset';
});
} catch (error) {
console.log('❌ Still failing:', error.message);
}
// Example 6: Retry with telemetry
console.log('\n\n6. Retry with Telemetry');
console.log('-----------------------\n');
const telemetryRetry = createRetryExecutor({
maxAttempts: 3,
initialDelay: 1000
});
// Track retry metrics
const metrics = {
attempts: [],
totalDuration: 0,
finalStatus: null
};
const startTime = Date.now();
try {
await telemetryRetry.execute(
async () => {
const attemptStart = Date.now();
const attemptNumber = metrics.attempts.length + 1;
try {
// Simulate work
await new Promise(resolve => setTimeout(resolve, 200));
if (attemptNumber < 2) {
throw new Error('Simulated failure');
}
return 'Success with telemetry';
} finally {
metrics.attempts.push({
number: attemptNumber,
duration: Date.now() - attemptStart,
timestamp: new Date().toISOString()
});
}
},
{
onRetry: (attempt, error, delay) => {
console.log(`📈 Telemetry: Retry ${attempt}, delay ${delay}ms`);
}
}
);
metrics.finalStatus = 'success';
} catch (error) {
metrics.finalStatus = 'failure';
}
metrics.totalDuration = Date.now() - startTime;
console.log('\n📊 Retry Telemetry Report:');
console.log('- Total attempts:', metrics.attempts.length);
console.log('- Total duration:', metrics.totalDuration, 'ms');
console.log('- Final status:', metrics.finalStatus);
console.log('- Attempt details:');
metrics.attempts.forEach(attempt => {
console.log(` - Attempt ${attempt.number}: ${attempt.duration}ms`);
});
console.log('\n✨ Retry strategies examples completed!');
}
// Error handling wrapper
retryStrategiesExample().catch(error => {
console.error('Fatal error:', error);
process.exit(1);
});