|
2 | 2 |
|
3 | 3 | require 'spec_helper' |
4 | 4 |
|
5 | | -RETRYABLE_ERROR_LABEL = 'RetryableError' |
6 | | -SYSTEM_OVERLOADED_ERROR = 'SystemOverloadedError' |
7 | | - |
8 | | -def system_overloaded_error?(error) |
9 | | - error.respond_to?(:label?) && error.label?(SYSTEM_OVERLOADED_ERROR) |
10 | | -end |
| 5 | +describe 'backpressure examples' do |
| 6 | + RETRYABLE_ERROR_LABEL = 'RetryableError' |
| 7 | + SYSTEM_OVERLOADED_ERROR = 'SystemOverloadedError' |
| 8 | + BASE_BACKOFF_MS = 100 |
| 9 | + MAX_BACKOFF_MS = 10_000 |
11 | 10 |
|
12 | | -BASE_BACKOFF_MS = 100 |
13 | | -MAX_BACKOFF_MS = 10_000 |
| 11 | + def system_overloaded_error?(error) |
| 12 | + error.respond_to?(:label?) && error.label?(SYSTEM_OVERLOADED_ERROR) |
| 13 | + end |
14 | 14 |
|
15 | | -def calculate_exponential_backoff(attempt) |
16 | | - rand * [ MAX_BACKOFF_MS, BASE_BACKOFF_MS * (2**(attempt - 1)) ].min |
17 | | -end |
| 15 | + def calculate_exponential_backoff(attempt) |
| 16 | + rand * [ MAX_BACKOFF_MS, BASE_BACKOFF_MS * (2**(attempt - 1)) ].min |
| 17 | + end |
18 | 18 |
|
19 | | -def with_retries(max_attempts: 2) |
20 | | - max_attempts.times do |attempt| |
21 | | - is_retry = attempt > 0 |
22 | | - if is_retry |
23 | | - delay = calculate_exponential_backoff(attempt) |
24 | | - sleep(delay / 1000.0) |
25 | | - end |
26 | | - begin |
27 | | - return yield |
28 | | - rescue StandardError => e |
29 | | - is_retryable_overload_error = system_overloaded_error?(e) && e.label?(RETRYABLE_ERROR_LABEL) |
30 | | - can_retry = is_retryable_overload_error && attempt + 1 < max_attempts |
31 | | - raise e unless can_retry |
| 19 | + def with_retries(max_attempts: 2) |
| 20 | + max_attempts.times do |attempt| |
| 21 | + is_retry = attempt > 0 |
| 22 | + if is_retry |
| 23 | + delay = calculate_exponential_backoff(attempt) |
| 24 | + sleep(delay / 1000.0) |
| 25 | + end |
| 26 | + begin |
| 27 | + return yield |
| 28 | + rescue StandardError => e |
| 29 | + is_retryable_overload_error = system_overloaded_error?(e) && e.label?(RETRYABLE_ERROR_LABEL) |
| 30 | + can_retry = is_retryable_overload_error && attempt + 1 < max_attempts |
| 31 | + raise e unless can_retry |
| 32 | + end |
32 | 33 | end |
33 | 34 | end |
34 | | -end |
35 | | - |
36 | | -describe 'backpressure examples' do |
37 | 35 | describe '#system_overloaded_error?' do |
38 | 36 | it 'returns true for an error with the SystemOverloadedError label' do |
39 | 37 | error = Mongo::Error.new('overloaded') |
|
0 commit comments