| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import logging |
| 4 |
import typing as t |
| 5 |
|
| 6 |
from .retry import RetryCheck, RetryCheckFlags, RetryCheckResult, RetryContext |
| 7 |
|
| 8 |
log = logging.getLogger(__name__) |
| 9 |
|
| 10 |
|
| 11 |
class RetryCheckRunner: |
| 12 |
""" |
| 13 |
A RetryCheckRunner is an object responsible for running retry checks over the |
| 14 |
lifetime of a request. Unlike the checks or the retry context, the runner persists |
| 15 |
between retries. It can therefore implement special logic for checks like "only try |
| 16 |
this check once". |
| 17 |
|
| 18 |
Its primary responsibility is to answer the question "should_retry(context)?" with a |
| 19 |
boolean. |
| 20 |
|
| 21 |
It takes as its input a list of checks. Checks may be paired with flags to indicate |
| 22 |
their configuration options. When not paired with flags, the flags are taken to be |
| 23 |
"NONE". |
| 24 |
|
| 25 |
Supported flags: |
| 26 |
|
| 27 |
``RUN_ONCE`` |
| 28 |
The check will run at most once for a given request. Once it has run, it is |
| 29 |
recorded as "has_run" and will not be run again on that request. |
| 30 |
""" |
| 31 |
|
| 32 |
# check configs: a list of pairs, (check, flags) |
| 33 |
# a check without flags is assumed to have flags=NONE |
| 34 |
def __init__(self, checks: t.Iterable[RetryCheck]) -> None: |
| 35 |
self._checks: list[RetryCheck] = [] |
| 36 |
self._check_data: dict[RetryCheck, dict[str, t.Any]] = {} |
| 37 |
for check in checks: |
| 38 |
self._checks.append(check) |
| 39 |
self._check_data[check] = {} |
| 40 |
|
| 41 |
def should_retry(self, context: RetryContext) -> bool: |
| 42 |
for check in self._checks: |
| 43 |
flags = getattr(check, "_retry_check_flags", RetryCheckFlags.NONE) |
| 44 |
|
| 45 |
if flags & RetryCheckFlags.RUN_ONCE: |
| 46 |
if self._check_data[check].get("has_run"): |
| 47 |
continue |
| 48 |
else: |
| 49 |
self._check_data[check]["has_run"] = True |
| 50 |
|
| 51 |
result = check(context) |
| 52 |
log.debug( # try to get name but don't fail if it's not a function... |
| 53 |
"ran retry check (%s) => %s", getattr(check, "__name__", check), result |
| 54 |
) |
| 55 |
if result is RetryCheckResult.no_decision: |
| 56 |
continue |
| 57 |
elif result is RetryCheckResult.do_not_retry: |
| 58 |
return False |
| 59 |
else: |
| 60 |
return True |
| 61 |
|
| 62 |
# fallthrough: don't retry any request which isn't marked for retry |
| 63 |
return False |