-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathretry.py
More file actions
143 lines (103 loc) · 3.78 KB
/
Copy pathretry.py
File metadata and controls
143 lines (103 loc) · 3.78 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
"""Retry logic with exponential backoff and jitter."""
from __future__ import annotations
import asyncio
import random
import time
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Callable, TypeVar
from .errors import HawkAPIError, RateLimitError
if TYPE_CHECKING:
from collections.abc import Awaitable
T = TypeVar("T")
@dataclass
class RetryConfig:
"""Configuration for retry behavior."""
max_retries: int = 3
initial_backoff: float = 0.5
max_backoff: float = 30.0
multiplier: float = 2.0
retryable_statuses: set[int] = field(default_factory=lambda: {429, 500, 502, 503, 504})
DEFAULT_RETRY_CONFIG = RetryConfig()
def _compute_backoff(attempt: int, config: RetryConfig) -> float:
"""Compute backoff duration with exponential growth and jitter."""
backoff = config.initial_backoff * (config.multiplier**attempt)
backoff = min(backoff, config.max_backoff)
# Add jitter: random value between 0 and backoff
jitter = random.uniform(0, backoff * 0.5)
return backoff + jitter
def _is_retryable(error: Exception, config: RetryConfig) -> bool:
"""Determine if an error is retryable based on config."""
if isinstance(error, HawkAPIError):
return error.status_code in config.retryable_statuses
return False
async def with_retry(
fn: Callable[[], Awaitable[T]],
config: RetryConfig | None = None,
) -> T:
"""Execute an async function with retry logic.
Uses exponential backoff with jitter. Respects Retry-After header
on 429 responses.
Args:
fn: Async callable to execute.
config: Retry configuration. Uses DEFAULT_RETRY_CONFIG if None.
Returns:
The result of fn() on success.
Raises:
The last exception if all retries are exhausted.
"""
if config is None:
config = DEFAULT_RETRY_CONFIG
last_error: Exception | None = None
for attempt in range(config.max_retries + 1):
try:
return await fn()
except Exception as e:
last_error = e
if attempt >= config.max_retries:
break
if not _is_retryable(e, config):
break
# Respect Retry-After header for rate limit errors
if isinstance(e, RateLimitError) and e.retry_after is not None:
wait = e.retry_after
else:
wait = _compute_backoff(attempt, config)
await asyncio.sleep(wait)
if last_error is None:
raise HawkAPIError("Retry logic failed unexpectedly: no error recorded", status_code=0)
raise last_error
def with_retry_sync(
fn: Callable[[], T],
config: RetryConfig | None = None,
) -> T:
"""Execute a sync function with retry logic.
Uses exponential backoff with jitter. Respects Retry-After header
on 429 responses.
Args:
fn: Callable to execute.
config: Retry configuration. Uses DEFAULT_RETRY_CONFIG if None.
Returns:
The result of fn() on success.
Raises:
The last exception if all retries are exhausted.
"""
if config is None:
config = DEFAULT_RETRY_CONFIG
last_error: Exception | None = None
for attempt in range(config.max_retries + 1):
try:
return fn()
except Exception as e:
last_error = e
if attempt >= config.max_retries:
break
if not _is_retryable(e, config):
break
if isinstance(e, RateLimitError) and e.retry_after is not None:
wait = e.retry_after
else:
wait = _compute_backoff(attempt, config)
time.sleep(wait)
if last_error is None:
raise HawkAPIError("Retry logic failed unexpectedly: no error recorded", status_code=0)
raise last_error