-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathretries.py
More file actions
176 lines (140 loc) · 5.43 KB
/
Copy pathretries.py
File metadata and controls
176 lines (140 loc) · 5.43 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
"""Ready-made retry strategies and retry creators."""
from __future__ import annotations
import math
import random
import re
from dataclasses import dataclass, field
from enum import StrEnum
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from collections.abc import Callable
Numeric = int | float
# region Jitter
class JitterStrategy(StrEnum):
"""
Jitter strategies are used to introduce noise when attempting to retry
an invoke. We introduce noise to prevent a thundering-herd effect where
a group of accesses (e.g. invokes) happen at once.
Jitter is meant to be used to spread operations across time.
members:
:NONE: No jitter; use the exact calculated delay
:FULL: Full jitter; random delay between 0 and calculated delay
:HALF: Half jitter; random delay between 0.5x and 1.0x of the calculated delay
"""
NONE = "NONE"
FULL = "FULL"
HALF = "HALF"
def compute_jitter(self, delay) -> float:
match self:
case JitterStrategy.NONE:
return 0
case JitterStrategy.HALF:
return random.random() * 0.5 + 0.5 # noqa: S311
case _: # default is FULL
return random.random() * delay # noqa: S311
# endregion Jitter
@dataclass
class RetryDecision:
"""Decision about whether to retry a step and with what delay."""
should_retry: bool
delay_seconds: int
@classmethod
def retry(cls, delay_seconds: int) -> RetryDecision:
"""Create a retry decision."""
return cls(should_retry=True, delay_seconds=delay_seconds)
@classmethod
def no_retry(cls) -> RetryDecision:
"""Create a no-retry decision."""
return cls(should_retry=False, delay_seconds=0)
@dataclass
class RetryStrategyConfig:
max_attempts: int = 3 # "infinite", practically
initial_delay_seconds: int = 5
max_delay_seconds: int = 300 # 5 minutes
backoff_rate: Numeric = 2.0
jitter_strategy: JitterStrategy = field(default=JitterStrategy.FULL)
retryable_errors: list[str | re.Pattern] = field(
default_factory=lambda: [re.compile(r".*")]
)
retryable_error_types: list[type[Exception]] = field(default_factory=list)
def create_retry_strategy(
config: RetryStrategyConfig,
) -> Callable[[Exception, int], RetryDecision]:
if config is None:
config = RetryStrategyConfig()
def retry_strategy(error: Exception, attempts_made: int) -> RetryDecision:
# Check if we've exceeded max attempts
if attempts_made >= config.max_attempts:
return RetryDecision.no_retry()
# Check if error is retryable based on error message
is_retryable_error_message = any(
pattern.search(str(error))
if isinstance(pattern, re.Pattern)
else pattern in str(error)
for pattern in config.retryable_errors
)
# Check if error is retryable based on error type
is_retryable_error_type = any(
isinstance(error, error_type) for error_type in config.retryable_error_types
)
if not is_retryable_error_message and not is_retryable_error_type:
return RetryDecision.no_retry()
# Calculate delay with exponential backoff
delay = min(
config.initial_delay_seconds * (config.backoff_rate ** (attempts_made - 1)),
config.max_delay_seconds,
)
delay_with_jitter = delay + config.jitter_strategy.compute_jitter(delay)
delay_with_jitter = math.ceil(delay_with_jitter)
final_delay = max(1, delay_with_jitter)
return RetryDecision.retry(round(final_delay))
return retry_strategy
class RetryPresets:
"""Default retry presets."""
@classmethod
def none(cls) -> Callable[[Exception, int], RetryDecision]:
"""No retries."""
return create_retry_strategy(RetryStrategyConfig(max_attempts=1))
@classmethod
def default(cls) -> Callable[[Exception, int], RetryDecision]:
"""Default retries, will be used automatically if retryConfig is missing"""
return create_retry_strategy(
RetryStrategyConfig(
max_attempts=6,
initial_delay_seconds=5,
max_delay_seconds=60,
backoff_rate=2,
jitter_strategy=JitterStrategy.FULL,
)
)
@classmethod
def transient(cls) -> Callable[[Exception, int], RetryDecision]:
"""Quick retries for transient errors"""
return create_retry_strategy(
RetryStrategyConfig(
max_attempts=3, backoff_rate=2, jitter_strategy=JitterStrategy.HALF
)
)
@classmethod
def resource_availability(cls) -> Callable[[Exception, int], RetryDecision]:
"""Longer retries for resource availability"""
return create_retry_strategy(
RetryStrategyConfig(
max_attempts=5,
initial_delay_seconds=5,
max_delay_seconds=300,
backoff_rate=2,
)
)
@classmethod
def critical(cls) -> Callable[[Exception, int], RetryDecision]:
"""Aggressive retries for critical operations"""
return create_retry_strategy(
RetryStrategyConfig(
max_attempts=10,
initial_delay_seconds=1,
max_delay_seconds=60,
backoff_rate=1.5,
jitter_strategy=JitterStrategy.NONE,
)
)