|
| 1 | +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | +from functools import lru_cache |
| 4 | +from typing import Any, Literal |
| 5 | + |
| 6 | +from ..exceptions import RetryError |
| 7 | +from ..interfaces import retries as retries_interface |
| 8 | +from ..retries import ( |
| 9 | + ExponentialBackoffJitterType, |
| 10 | + ExponentialRetryBackoffStrategy, |
| 11 | + RetryStrategyOptions, |
| 12 | + SimpleRetryToken, |
| 13 | + StandardRetryQuota, |
| 14 | + StandardRetryToken, |
| 15 | +) |
| 16 | +from .interfaces.retries import RetryStrategy |
| 17 | + |
| 18 | +RetryStrategyType = Literal["simple", "standard"] |
| 19 | + |
| 20 | + |
| 21 | +class RetryStrategyResolver: |
| 22 | + """Retry strategy resolver that caches retry strategies based on configuration options. |
| 23 | +
|
| 24 | + This resolver caches retry strategy instances based on their configuration to reuse existing |
| 25 | + instances of RetryStrategy with the same settings. Uses LRU cache for thread-safe caching. |
| 26 | + """ |
| 27 | + |
| 28 | + async def resolve_retry_strategy( |
| 29 | + self, *, retry_strategy: RetryStrategy | RetryStrategyOptions | None |
| 30 | + ) -> RetryStrategy: |
| 31 | + """Resolve a retry strategy from the provided options, using cache when possible. |
| 32 | +
|
| 33 | + :param retry_strategy: An explicitly configured retry strategy or options for creating one. |
| 34 | + """ |
| 35 | + if isinstance(retry_strategy, RetryStrategy): |
| 36 | + return retry_strategy |
| 37 | + elif retry_strategy is None: |
| 38 | + retry_strategy = RetryStrategyOptions() |
| 39 | + elif not isinstance(retry_strategy, RetryStrategyOptions): # type: ignore[reportUnnecessaryIsInstance] |
| 40 | + raise TypeError( |
| 41 | + f"retry_strategy must be RetryStrategy, RetryStrategyOptions, or None, " |
| 42 | + f"got {type(retry_strategy).__name__}" |
| 43 | + ) |
| 44 | + return self._create_retry_strategy( |
| 45 | + retry_strategy.retry_mode, retry_strategy.max_attempts |
| 46 | + ) |
| 47 | + |
| 48 | + @lru_cache |
| 49 | + def _create_retry_strategy( |
| 50 | + self, retry_mode: RetryStrategyType, max_attempts: int | None |
| 51 | + ) -> RetryStrategy: |
| 52 | + kwargs = {"max_attempts": max_attempts} |
| 53 | + filtered_kwargs: dict[str, Any] = { |
| 54 | + k: v for k, v in kwargs.items() if v is not None |
| 55 | + } |
| 56 | + match retry_mode: |
| 57 | + case "simple": |
| 58 | + return SimpleRetryStrategy(**filtered_kwargs) |
| 59 | + case "standard": |
| 60 | + return StandardRetryStrategy(**filtered_kwargs) |
| 61 | + case _: |
| 62 | + raise ValueError(f"Unknown retry mode: {retry_mode}") |
| 63 | + |
| 64 | + |
| 65 | +class SimpleRetryStrategy: |
| 66 | + def __init__( |
| 67 | + self, |
| 68 | + *, |
| 69 | + backoff_strategy: retries_interface.RetryBackoffStrategy | None = None, |
| 70 | + max_attempts: int = 5, |
| 71 | + ): |
| 72 | + """Retry strategy that simply invokes the given backoff strategy. |
| 73 | +
|
| 74 | + :param backoff_strategy: The backoff strategy used by returned tokens to compute |
| 75 | + the retry delay. Defaults to :py:class:`ExponentialRetryBackoffStrategy`. |
| 76 | +
|
| 77 | + :param max_attempts: Upper limit on total number of attempts made, including |
| 78 | + initial attempt and retries. |
| 79 | + """ |
| 80 | + self.backoff_strategy = backoff_strategy or ExponentialRetryBackoffStrategy() |
| 81 | + self.max_attempts = max_attempts |
| 82 | + |
| 83 | + async def acquire_initial_retry_token( |
| 84 | + self, *, token_scope: str | None = None |
| 85 | + ) -> SimpleRetryToken: |
| 86 | + """Create a base retry token for the start of a request. |
| 87 | +
|
| 88 | + :param token_scope: This argument is ignored by this retry strategy. |
| 89 | + """ |
| 90 | + retry_delay = self.backoff_strategy.compute_next_backoff_delay(0) |
| 91 | + return SimpleRetryToken(retry_count=0, retry_delay=retry_delay) |
| 92 | + |
| 93 | + async def refresh_retry_token_for_retry( |
| 94 | + self, |
| 95 | + *, |
| 96 | + token_to_renew: retries_interface.RetryToken, |
| 97 | + error: Exception, |
| 98 | + ) -> SimpleRetryToken: |
| 99 | + """Replace an existing retry token from a failed attempt with a new token. |
| 100 | +
|
| 101 | + This retry strategy always returns a token until the attempt count stored in |
| 102 | + the new token exceeds the ``max_attempts`` value. |
| 103 | +
|
| 104 | + :param token_to_renew: The token used for the previous failed attempt. |
| 105 | + :param error: The error that triggered the need for a retry. |
| 106 | + :raises RetryError: If no further retry attempts are allowed. |
| 107 | + """ |
| 108 | + if isinstance(error, retries_interface.ErrorRetryInfo) and error.is_retry_safe: |
| 109 | + retry_count = token_to_renew.retry_count + 1 |
| 110 | + if retry_count >= self.max_attempts: |
| 111 | + raise RetryError( |
| 112 | + f"Reached maximum number of allowed attempts: {self.max_attempts}" |
| 113 | + ) from error |
| 114 | + retry_delay = self.backoff_strategy.compute_next_backoff_delay(retry_count) |
| 115 | + return SimpleRetryToken(retry_count=retry_count, retry_delay=retry_delay) |
| 116 | + else: |
| 117 | + raise RetryError(f"Error is not retryable: {error}") from error |
| 118 | + |
| 119 | + async def record_success(self, *, token: retries_interface.RetryToken) -> None: |
| 120 | + """Not used by this retry strategy.""" |
| 121 | + |
| 122 | + def __deepcopy__(self, memo: Any) -> "SimpleRetryStrategy": |
| 123 | + return self |
| 124 | + |
| 125 | + |
| 126 | +class StandardRetryStrategy: |
| 127 | + def __init__( |
| 128 | + self, |
| 129 | + *, |
| 130 | + backoff_strategy: retries_interface.RetryBackoffStrategy | None = None, |
| 131 | + max_attempts: int = 3, |
| 132 | + retry_quota: StandardRetryQuota | None = None, |
| 133 | + ): |
| 134 | + """Standard retry strategy using truncated binary exponential backoff |
| 135 | + with full jitter. |
| 136 | +
|
| 137 | + :param backoff_strategy: The backoff strategy used by returned tokens to compute |
| 138 | + the retry delay. Defaults to :py:class:`ExponentialRetryBackoffStrategy`. |
| 139 | +
|
| 140 | + :param max_attempts: Upper limit on total number of attempts made, including |
| 141 | + initial attempt and retries. |
| 142 | +
|
| 143 | + :param retry_quota: The retry quota to use for managing retry capacity. Defaults |
| 144 | + to a new :py:class:`StandardRetryQuota` instance. |
| 145 | + """ |
| 146 | + if max_attempts < 0: |
| 147 | + raise ValueError( |
| 148 | + f"max_attempts must be a non-negative integer, got {max_attempts}" |
| 149 | + ) |
| 150 | + |
| 151 | + self.backoff_strategy = backoff_strategy or ExponentialRetryBackoffStrategy( |
| 152 | + backoff_scale_value=1, |
| 153 | + max_backoff=20, |
| 154 | + jitter_type=ExponentialBackoffJitterType.FULL, |
| 155 | + ) |
| 156 | + self.max_attempts = max_attempts |
| 157 | + self._retry_quota = retry_quota or StandardRetryQuota() |
| 158 | + |
| 159 | + async def acquire_initial_retry_token( |
| 160 | + self, *, token_scope: str | None = None |
| 161 | + ) -> StandardRetryToken: |
| 162 | + """Create a base retry token for the start of a request. |
| 163 | +
|
| 164 | + :param token_scope: This argument is ignored by this retry strategy. |
| 165 | + """ |
| 166 | + retry_delay = self.backoff_strategy.compute_next_backoff_delay(0) |
| 167 | + return StandardRetryToken(retry_count=0, retry_delay=retry_delay) |
| 168 | + |
| 169 | + async def refresh_retry_token_for_retry( |
| 170 | + self, |
| 171 | + *, |
| 172 | + token_to_renew: retries_interface.RetryToken, |
| 173 | + error: Exception, |
| 174 | + ) -> StandardRetryToken: |
| 175 | + """Replace an existing retry token from a failed attempt with a new token. |
| 176 | +
|
| 177 | + This retry strategy always returns a token until the attempt count stored in |
| 178 | + the new token exceeds the ``max_attempts`` value. |
| 179 | +
|
| 180 | + :param token_to_renew: The token used for the previous failed attempt. |
| 181 | + :param error: The error that triggered the need for a retry. |
| 182 | + :raises RetryError: If no further retry attempts are allowed. |
| 183 | + """ |
| 184 | + if not isinstance(token_to_renew, StandardRetryToken): |
| 185 | + raise TypeError( |
| 186 | + f"StandardRetryStrategy requires StandardRetryToken, got {type(token_to_renew).__name__}" |
| 187 | + ) |
| 188 | + |
| 189 | + if isinstance(error, retries_interface.ErrorRetryInfo) and error.is_retry_safe: |
| 190 | + retry_count = token_to_renew.retry_count + 1 |
| 191 | + if retry_count >= self.max_attempts: |
| 192 | + raise RetryError( |
| 193 | + f"Reached maximum number of allowed attempts: {self.max_attempts}" |
| 194 | + ) from error |
| 195 | + |
| 196 | + # Acquire additional quota for this retry attempt |
| 197 | + # (may raise a RetryError if none is available) |
| 198 | + quota_acquired = self._retry_quota.acquire(error=error) |
| 199 | + |
| 200 | + if error.retry_after is not None: |
| 201 | + retry_delay = error.retry_after |
| 202 | + else: |
| 203 | + retry_delay = self.backoff_strategy.compute_next_backoff_delay( |
| 204 | + retry_count |
| 205 | + ) |
| 206 | + |
| 207 | + return StandardRetryToken( |
| 208 | + retry_count=retry_count, |
| 209 | + retry_delay=retry_delay, |
| 210 | + quota_acquired=quota_acquired, |
| 211 | + ) |
| 212 | + else: |
| 213 | + raise RetryError(f"Error is not retryable: {error}") from error |
| 214 | + |
| 215 | + async def record_success(self, *, token: retries_interface.RetryToken) -> None: |
| 216 | + """Release retry quota back based on the amount consumed by the last retry. |
| 217 | +
|
| 218 | + :param token: The token used for the previous successful attempt. |
| 219 | + """ |
| 220 | + if not isinstance(token, StandardRetryToken): |
| 221 | + raise TypeError( |
| 222 | + f"StandardRetryStrategy requires StandardRetryToken, got {type(token).__name__}" |
| 223 | + ) |
| 224 | + self._retry_quota.release(release_amount=token.quota_acquired) |
| 225 | + |
| 226 | + def __deepcopy__(self, memo: Any) -> "StandardRetryStrategy": |
| 227 | + return self |
0 commit comments