foley.sources.resilience#
Graceful degradation for HTTP source adapters — throttle · backoff · circuit-break (#12).
resilient() wraps the injectable Transport DI seam
with three composed policies so a flaky or rate-limited remote source degrades
predictably instead of hammering the API or crashing a run:
throttle — a token bucket honouring the source config’s declared
rate(per_min/per_day) so foley never exceeds the published limits;backoff — exponential retry on
429/5xx(and transport exceptions), honouring aRetry-Afterheader when present (delta-seconds or an HTTP-date; a value that is negative, not finite or unreadable falls back to the backoff), up to the policy’smax_delay_s; a policy withgive_up_over_max_delayraisesRetryAfterTooLonginstead of waiting the cap (a caller with a mirrormoves on to it);
circuit-break — after N consecutive failures the breaker opens and fast-fails with
SourceUnavailablefor a cool-down window (no thundering herd).
per_host() gives each host its own wrapped transport (its own pace and breaker),
for a caller that fetches from several websites through one transport (a music
library and its Wayback mirror); pace_per_host() is that pace alone, for a
caller whose requests do not go through a transport.
All timing goes through injected clock / sleep callables (default
time.monotonic / time.sleep) so the whole thing is deterministically testable
with a fake clock and a no-op sleep — no real network, no real waiting. Stdlib-only.
Module Attributes
Seconds in a rolling rate-limit day (the |
Functions
|
Build a resilient transport from a source |
|
|
|
A transport that sends each request through its host's own transport. |
|
Wrap a |
|
The seconds a |
Classes
|
Circuit-breaker thresholds. |
|
Exponential-backoff retry policy for transient HTTP failures. |
Exceptions
|
A |
Raised when a source's circuit breaker is open or its retries are exhausted. |
- class foley.sources.resilience.BreakerPolicy(fail_threshold=5, reset_timeout_s=30.0)[source]#
Bases:
objectCircuit-breaker thresholds.
- exception foley.sources.resilience.RetryAfterTooLong(message, *, retry_after_s, max_delay_s)[source]#
Bases:
SourceUnavailableA
Retry-Afterasked for longer than the policy waits, and the policy gives up rather than wait its cap (RetryPolicy.give_up_over_max_delay).retry_after_sis what the server asked for,max_delay_sthe cap.
- class foley.sources.resilience.RetryPolicy(max_attempts=4, retry_on=(429, 500, 502, 503, 504), base_delay_s=0.5, max_delay_s=30.0, respect_retry_after=True, give_up_over_max_delay=False)[source]#
Bases:
objectExponential-backoff retry policy for transient HTTP failures.
- give_up_over_max_delay: bool = False#
a
Retry-Afterabovemax_delay_sraisesRetryAfterTooLongat once;False: it is waited atmax_delay_s.- Type:
True
- foley.sources.resilience.SECONDS_PER_DAY: float = 86400.0#
Seconds in a rolling rate-limit day (the
per_daywindow length).
Bases:
RuntimeErrorRaised when a source’s circuit breaker is open or its retries are exhausted.
- foley.sources.resilience.make_resilient_transport_from_config(config, *, base=None, **inject)[source]#
Build a resilient transport from a source
config(itsratedrives the throttle).- Parameters:
config (
dict) – ASOURCE_CONFIGdict (readsconfig['rate']and, if present,config['retry']:RetryPolicyfields).base – The base transport (default:
foley.sources.http.requests_transport()).**inject –
retry/breaker/clock/sleep/wall_clockoverrides.
- Returns:
A resilient transport wrapping
base.
- foley.sources.resilience.pace_per_host(rate, *, clock=<built-in function monotonic>, sleep=<built-in function sleep>)[source]#
wait(url): before a request tourl, wait out its host’s pace.The throttle of
resilient()(rate’sper_min;per_dayraisesSourceUnavailablepast its cap) without the transport around it, one per host, for a caller whose requests are its own (aurl -> bytesfunction). Noratewaits for nothing.>>> slept, now = [], [0.0] >>> wait = pace_per_host({"per_min": 30}, clock=lambda: now[0], sleep=slept.append) >>> for url in ("https://a.org/1", "https://b.org/1", "https://a.org/2"): ... wait(url) >>> slept [2.0]
- foley.sources.resilience.per_host(make)[source]#
A transport that sends each request through its host’s own transport.
make()builds one transport per host, on that host’s first request: aresilient()one gives each host its own throttle and circuit breaker, so a pace is kept per website and a site that fails does not trip the breaker of its mirror. The returned transport has a.reset()that resets every host’s.>>> made = [] >>> def make(): ... made.append(1) ... return lambda method, url, **kw: (method, url) >>> t = per_host(make) >>> t("GET", "https://a.org/1"), t("GET", "https://a.org/2")[1] (('GET', 'https://a.org/1'), 'https://a.org/2') >>> _ = t("GET", "https://b.org/1"); len(made) 2
- Return type:
- foley.sources.resilience.resilient(transport, *, rate=None, retry=None, breaker=None, clock=<built-in function monotonic>, sleep=<built-in function sleep>, resend_after_transport_error=True, wall_clock=<built-in function time>)[source]#
Wrap a
Transportwith throttle + backoff + circuit-break.- Parameters:
transport – The base transport callable
(method, url, *, params, headers, json).rate (
Optional[dict]) – The source config’sratedict ({'per_min':…, 'per_day':…}).retry (
Optional[RetryPolicy]) – TheRetryPolicy(default: 4 attempts on 429/5xx).breaker (
Optional[BreakerPolicy]) – TheBreakerPolicy(default: open after 5 consecutive fails).clock (
Callable[[],float]) – Monotonic time source (injected for tests).sleep (
Callable[[float],None]) – Blocking sleep (injected for tests).resend_after_transport_error (
bool) – Retry a non-GET request after a transport-level failure (timeout, reset).Falsefor a paid source: the provider may have accepted — and billed — the request before the connection failed, so re-sending would be an unauthorized second paid call. Status-coded rejections (429 / 5xx) are still retried: those are answers, not charges.wall_clock (
Callable[[],float]) – Epoch-seconds time source, for aRetry-AfterHTTP-date (injected for tests).
- Returns:
A transport with the same signature, plus a
.reset()method. RaisesSourceUnavailablewhen the breaker is open or retries are exhausted (RetryAfterTooLongwhen the policy gives up on a long wait).
- foley.sources.resilience.retry_after_seconds(raw, *, now=None)[source]#
The seconds a
Retry-Aftervalue asks to wait, orNonewhen it is unusable.rawis delta-seconds ("120") or an HTTP-date, read relative tonow(wall-clock epoch seconds; defaulttime.time()). A negative, non-finite or unreadable value, and a date in the past, areNone: the caller backs off.>>> retry_after_seconds("37"), retry_after_seconds(" 1.5 ") (37.0, 1.5) >>> retry_after_seconds("Wed, 21 Oct 2026 07:28:00 GMT", now=1792567600.0) 80.0 >>> [retry_after_seconds(v) for v in ("-5", "nan", "inf", "soon", None)] [None, None, None, None, None]