failsafe-py 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
failsafe/__init__.py ADDED
@@ -0,0 +1,103 @@
1
+ """Fault tolerance and resilience policies for Python."""
2
+
3
+ from ._async import AsyncFailsafe
4
+ from ._conditions import Condition
5
+ from ._core import Execution, current_execution
6
+ from ._delays import Backoff, Delay, Fixed, Jitter, RandomDelay
7
+ from ._events import (
8
+ ExecutionCompletedEvent,
9
+ ExecutionEvent,
10
+ ScheduledRetryEvent,
11
+ StateChangedEvent,
12
+ )
13
+ from ._exceptions import (
14
+ BudgetExceeded,
15
+ BulkheadFull,
16
+ CircuitBreakerOpen,
17
+ FailsafeError,
18
+ LimitExceeded,
19
+ RateLimitExceeded,
20
+ RetriesExceeded,
21
+ ThrottleExceeded,
22
+ TimeoutExceeded,
23
+ )
24
+ from ._prioritizer import CalibratedEvent, Prioritizer, ThresholdChangedEvent
25
+ from ._sync import Failsafe
26
+ from .adaptive_limiter import AdaptiveLimiter, LimitChangedEvent, queue_prioritizer
27
+ from .adaptive_throttler import AdaptiveThrottler, throttle_prioritizer
28
+ from .budget import Budget, BudgetExceededEvent
29
+ from .bulkhead import Bulkhead
30
+ from .cache import Cache, CachePolicy, cache_key, current_cache_key
31
+ from .circuit_breaker import CircuitBreaker, Rate, Ratio
32
+ from .fallback import Fallback
33
+ from .hedge import HedgePolicy
34
+ from .priority import (
35
+ LevelTracker,
36
+ Priority,
37
+ UsageTracker,
38
+ current_level,
39
+ current_user,
40
+ level_scope,
41
+ priority_scope,
42
+ user_scope,
43
+ )
44
+ from .rate_limiter import RateLimiter
45
+ from .retry import RetryPolicy
46
+ from .timeout import Timeout
47
+
48
+ __all__ = [
49
+ "AdaptiveLimiter",
50
+ "AdaptiveThrottler",
51
+ "AsyncFailsafe",
52
+ "Backoff",
53
+ "Budget",
54
+ "BudgetExceeded",
55
+ "BudgetExceededEvent",
56
+ "Bulkhead",
57
+ "BulkheadFull",
58
+ "Cache",
59
+ "CachePolicy",
60
+ "CalibratedEvent",
61
+ "CircuitBreaker",
62
+ "CircuitBreakerOpen",
63
+ "Condition",
64
+ "Delay",
65
+ "Execution",
66
+ "ExecutionCompletedEvent",
67
+ "ExecutionEvent",
68
+ "Failsafe",
69
+ "FailsafeError",
70
+ "Fallback",
71
+ "Fixed",
72
+ "HedgePolicy",
73
+ "Jitter",
74
+ "LevelTracker",
75
+ "LimitChangedEvent",
76
+ "LimitExceeded",
77
+ "Prioritizer",
78
+ "Priority",
79
+ "RandomDelay",
80
+ "Rate",
81
+ "RateLimitExceeded",
82
+ "RateLimiter",
83
+ "Ratio",
84
+ "RetriesExceeded",
85
+ "RetryPolicy",
86
+ "ScheduledRetryEvent",
87
+ "StateChangedEvent",
88
+ "ThresholdChangedEvent",
89
+ "ThrottleExceeded",
90
+ "Timeout",
91
+ "TimeoutExceeded",
92
+ "UsageTracker",
93
+ "cache_key",
94
+ "current_cache_key",
95
+ "current_execution",
96
+ "current_level",
97
+ "current_user",
98
+ "level_scope",
99
+ "priority_scope",
100
+ "queue_prioritizer",
101
+ "throttle_prioritizer",
102
+ "user_scope",
103
+ ]
failsafe/_async.py ADDED
@@ -0,0 +1,285 @@
1
+ """The asyncio driver: services policy instructions by suspending the caller."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import functools
7
+ from collections.abc import Awaitable, Callable, Coroutine, Generator
8
+ from typing import Any, ParamSpec, TypeVar
9
+
10
+ from ._core import (
11
+ SYSTEM_CLOCK,
12
+ Acquire,
13
+ Clock,
14
+ Execution,
15
+ Hedge,
16
+ Instruction,
17
+ Invoke,
18
+ Outcome,
19
+ Policy,
20
+ Race,
21
+ Sleep,
22
+ compose,
23
+ set_current_execution,
24
+ )
25
+
26
+ __all__ = ["AsyncFailsafe"]
27
+
28
+ R = TypeVar("R")
29
+ P = ParamSpec("P")
30
+
31
+
32
+ class AsyncFailsafe:
33
+ """Executes coroutine functions under a composition of policies.
34
+
35
+ The async counterpart of [`Failsafe`][failsafe.Failsafe], with the same composition
36
+ order and the same policy objects. Policy state is shared between the two: a
37
+ circuit breaker tripped by a sync call is seen open by an async one.
38
+
39
+ Cancellation is ordinary `asyncio` cancellation. `asyncio.CancelledError`
40
+ is a `BaseException` and is never treated as a failure or retried.
41
+
42
+ The result type is inferred from the function passed to `call`.
43
+
44
+ This type is concurrency safe.
45
+
46
+ Args:
47
+ *policies: Policies, outermost first.
48
+ clock: Custom time source for delays and deadlines (e.g. for testing).
49
+ """
50
+
51
+ __slots__ = ("_chain", "_clock", "policies")
52
+
53
+ def __init__(self, *policies: Policy, clock: Clock = SYSTEM_CLOCK) -> None:
54
+ self.policies = policies
55
+ """The configured policies, outermost first."""
56
+ self._clock = clock
57
+ self._chain = compose(policies)
58
+
59
+ async def call(self, fn: Callable[P, Awaitable[R]], /, *args: P.args, **kwargs: P.kwargs) -> R:
60
+ """Execute ``fn`` under the configured policies and return its result.
61
+
62
+ The result type comes from ``fn``, and the arguments are checked against its
63
+ signature, so one composition can guard calls returning different types
64
+ without giving up either check.
65
+
66
+ Args:
67
+ fn: The coroutine function to execute. Awaited once per attempt.
68
+ *args: Positional arguments for ``fn``.
69
+ **kwargs: Keyword arguments for ``fn``.
70
+
71
+ Returns:
72
+ The result of the final attempt.
73
+
74
+ Raises:
75
+ Exception: Whatever the final attempt or the policies produce.
76
+ """
77
+ ex = Execution(self._clock)
78
+ ex.args = args
79
+ ex.kwargs = kwargs
80
+ token = set_current_execution(ex)
81
+ try:
82
+ outcome = await self._pump(self._chain(ex), ex, fn, args, kwargs)
83
+ return outcome.unwrap()
84
+ finally:
85
+ token.var.reset(token)
86
+
87
+ def __call__(self, fn: Callable[P, Awaitable[R]]) -> Callable[P, Coroutine[Any, Any, R]]:
88
+ """Decorate a coroutine function so every call runs under these policies.
89
+
90
+ The decorated function keeps its signature, name and docstring.
91
+
92
+ Example:
93
+ ```python
94
+ payments = AsyncFailsafe(retry, breaker)
95
+ @payments
96
+ async def charge(amount): ...
97
+ ```
98
+ """
99
+
100
+ @functools.wraps(fn)
101
+ async def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
102
+ return await self.call(fn, *args, **kwargs)
103
+
104
+ return wrapper
105
+
106
+ async def _pump(
107
+ self,
108
+ gen: Generator[Instruction, Any, Outcome[Any]],
109
+ ex: Execution,
110
+ fn: Callable[..., Awaitable[R]],
111
+ args: tuple[Any, ...],
112
+ kwargs: dict[str, Any],
113
+ ) -> Outcome[R]:
114
+ """Drive a policy generator to completion, servicing what it yields."""
115
+ sent: Any = None
116
+ try:
117
+ while True:
118
+ try:
119
+ instruction = gen.send(sent)
120
+ except StopIteration as stop:
121
+ outcome: Outcome[R] = stop.value
122
+ return outcome
123
+ sent = await self._service(instruction, ex, fn, args, kwargs)
124
+ finally:
125
+ # Lets policies release permits from a finally block when the driver stops
126
+ # pumping, which includes the task being cancelled mid-execution.
127
+ gen.close()
128
+
129
+ async def _service(
130
+ self,
131
+ instruction: Instruction,
132
+ ex: Execution,
133
+ fn: Callable[..., Awaitable[R]],
134
+ args: tuple[Any, ...],
135
+ kwargs: dict[str, Any],
136
+ ) -> Any:
137
+ if type(instruction) is Invoke:
138
+ try:
139
+ return Outcome(value=await fn(*args, **kwargs))
140
+ except Exception as exc: # CancelledError is a BaseException: propagates
141
+ return Outcome(exc=exc)
142
+ if type(instruction) is Sleep:
143
+ await self._clock.sleep_async(instruction.seconds)
144
+ return None
145
+ if type(instruction) is Acquire:
146
+ return await instruction.semaphore.acquire_async(instruction.timeout)
147
+ if type(instruction) is Race:
148
+ return await self._race(instruction, ex, fn, args, kwargs)
149
+ if type(instruction) is Hedge:
150
+ return await self._hedge(instruction, ex, fn, args, kwargs)
151
+ raise AssertionError(f"unknown instruction {instruction!r}")
152
+
153
+ async def _hedge(
154
+ self,
155
+ hedge: Hedge,
156
+ ex: Execution,
157
+ fn: Callable[..., Awaitable[R]],
158
+ args: tuple[Any, ...],
159
+ kwargs: dict[str, Any],
160
+ ) -> Outcome[Any]:
161
+ """Run concurrent attempts, returning the first the policy accepts.
162
+
163
+ Attempts start one at a time: each is given its delay to finish before the
164
+ next joins it. Losers are cancelled once a winner is accepted, so their I/O
165
+ stops rather than running on in the background. When no attempt is ever
166
+ accepted, the last one to finish is returned.
167
+ """
168
+ control = hedge.control
169
+ pending: set[asyncio.Task[tuple[Outcome[Any], Execution]]] = set()
170
+ hedged: set[asyncio.Task[tuple[Outcome[Any], Execution]]] = set()
171
+ last: Outcome[Any] | None = None
172
+ started = 0
173
+ more = True
174
+ try:
175
+ while True:
176
+ if more:
177
+ attempt_ex = ex if started == 0 else ex.copy_for_hedge()
178
+ started += 1
179
+ task = asyncio.ensure_future(
180
+ self._hedged_attempt(hedge.inner, attempt_ex, fn, args, kwargs)
181
+ )
182
+ pending.add(task)
183
+ if attempt_ex.is_hedge:
184
+ hedged.add(task)
185
+ delay = control.hedge_delay(ex)
186
+ more = delay is not None and control.start_hedge(ex)
187
+ else:
188
+ delay = None
189
+
190
+ timer = (
191
+ asyncio.ensure_future(self._clock.sleep_async(delay))
192
+ if more and delay is not None
193
+ else None
194
+ )
195
+ try:
196
+ while pending:
197
+ waits: set[asyncio.Future[Any]] = set(pending)
198
+ if timer is not None:
199
+ waits.add(timer)
200
+ await asyncio.wait(waits, return_when=asyncio.FIRST_COMPLETED)
201
+ for task in [t for t in pending if t.done()]:
202
+ pending.discard(task)
203
+ if task in hedged:
204
+ hedged.discard(task)
205
+ control.finish_hedge()
206
+ last, finished_ex = task.result()
207
+ accepted = control.accepts(last)
208
+ # Go times each attempt inside its own goroutine, and only
209
+ # an acceptable outcome teaches the estimate anything.
210
+ if accepted:
211
+ control.record_duration(finished_ex)
212
+ return self._won(ex, last)
213
+ if timer is not None and timer.done():
214
+ break
215
+ finally:
216
+ if timer is not None and not timer.done():
217
+ timer.cancel()
218
+ if not pending and not more:
219
+ # Nothing left to wait for and nothing acceptable arrived.
220
+ assert last is not None
221
+ return self._won(ex, last)
222
+ finally:
223
+ for task in pending:
224
+ task.cancel()
225
+ if pending:
226
+ await asyncio.gather(*pending, return_exceptions=True)
227
+ for _ in hedged:
228
+ control.finish_hedge()
229
+
230
+ async def _hedged_attempt(
231
+ self,
232
+ inner: Any,
233
+ attempt_ex: Execution,
234
+ fn: Callable[..., Awaitable[R]],
235
+ args: tuple[Any, ...],
236
+ kwargs: dict[str, Any],
237
+ ) -> tuple[Outcome[Any], Execution]:
238
+ """Pump one hedged attempt, with its own execution visible to user code.
239
+
240
+ Returns the attempt's execution alongside its outcome so the policy can time
241
+ that attempt rather than the hedged execution as a whole.
242
+ """
243
+ set_current_execution(attempt_ex)
244
+ outcome = await self._pump(inner(attempt_ex), attempt_ex, fn, args, kwargs)
245
+ return outcome, attempt_ex
246
+
247
+ @staticmethod
248
+ def _won(ex: Execution, outcome: Outcome[Any]) -> Outcome[Any]:
249
+ """Record the winning attempt's outcome on the parent execution."""
250
+ ex.last_result = outcome.value
251
+ ex.last_exception = outcome.exc
252
+ return outcome
253
+
254
+ async def _race(
255
+ self,
256
+ race: Race,
257
+ ex: Execution,
258
+ fn: Callable[..., Awaitable[R]],
259
+ args: tuple[Any, ...],
260
+ kwargs: dict[str, Any],
261
+ ) -> Outcome[Any] | None:
262
+ """Run an inner step under a deadline, returning ``None`` if it elapsed.
263
+
264
+ `asyncio.timeout` is the mechanism, not something to reimplement: it
265
+ interrupts whatever is awaiting inside the scope and exposes the absolute
266
+ deadline, which user code reads through ``Execution.remaining()``.
267
+ """
268
+ previous_deadline = ex.deadline
269
+ scope = asyncio.timeout(race.seconds)
270
+ try:
271
+ async with scope:
272
+ ex.deadline = self._deadline_from(scope.when())
273
+ return await self._pump(race.inner(ex), ex, fn, args, kwargs)
274
+ except TimeoutError:
275
+ if not scope.expired():
276
+ raise
277
+ return None
278
+ finally:
279
+ ex.deadline = previous_deadline
280
+
281
+ def _deadline_from(self, when: float | None) -> float | None:
282
+ """Translate a loop-clock deadline onto the configured clock."""
283
+ if when is None:
284
+ return None
285
+ return self._clock.now() + (when - asyncio.get_running_loop().time())
@@ -0,0 +1,166 @@
1
+ """Failure conditions: one vocabulary for every "does this result-or-error match?" filter.
2
+
3
+ Go needs four builder families (``HandleErrors``, ``HandleErrorTypes``, ``HandleResult``,
4
+ ``HandleIf``) because ``errors.Is`` is not ``errors.As`` and generics split results from
5
+ errors. `isinstance` collapses all four into one type, reused wherever Go has
6
+ a condition family: ``handle=`` and ``abort=`` on retry, ``handle=`` on fallback and the
7
+ circuit breaker.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from collections.abc import Callable, Sequence
13
+ from typing import Any, TypeAlias
14
+
15
+ __all__ = ["Condition"]
16
+
17
+ _MAX_CAUSE_DEPTH = 20
18
+
19
+
20
+ Predicate: TypeAlias = Callable[[Any, "Exception | None"], bool]
21
+
22
+ UNSET: Any = object()
23
+ """The default for every condition keyword, meaning "not configured".
24
+
25
+ A plain ``None`` default cannot serve: ``handle=None`` has to mean "a ``None`` return
26
+ is a failure", which is indistinguishable from omitting the argument otherwise.
27
+ """
28
+
29
+ Condition: TypeAlias = Any
30
+ """Anything that can decide whether an outcome is a failure.
31
+
32
+ One of:
33
+
34
+ - an exception type, matched against the exception and its ``__cause__`` chain
35
+ - a tuple or list of exception types or predicates, OR'ed together
36
+ - a callable taking ``(result, exception)`` and returning a bool
37
+ - any other value, matched against the returned value with ``==``
38
+
39
+ A value that would read as one of the above - a tuple, a list, anything callable,
40
+ including a class - needs a predicate: ``handle=lambda result, exc: result == (1, 2)``.
41
+
42
+ Typed as `Any` deliberately. Bare values are accepted, so the set of
43
+ legal arguments is "almost anything", and a union spelling that out would reject
44
+ valid code while promising a precision it cannot deliver. The constructor raises
45
+ `TypeError` on the shapes that are genuinely ambiguous.
46
+ """
47
+
48
+
49
+ def matches_exception(exc: BaseException | None, types: tuple[type[Exception], ...]) -> bool:
50
+ """Whether ``exc`` or anything it was explicitly raised from is one of ``types``.
51
+
52
+ ``errors.Is`` follows Go's ``Unwrap``; `isinstance` follows nothing, so the
53
+ chain is walked here. Only ``__cause__`` is followed, never ``__context__``: implicit
54
+ context would match exceptions raised incidentally while handling another, which Go
55
+ has no equivalent of. The walk is depth-limited and cycle-safe.
56
+
57
+ An `ExceptionGroup` matches if any of its leaves does.
58
+ """
59
+ seen: set[int] = set()
60
+ current: BaseException | None = exc
61
+ for _ in range(_MAX_CAUSE_DEPTH):
62
+ if current is None or id(current) in seen:
63
+ return False
64
+ seen.add(id(current))
65
+ if isinstance(current, types):
66
+ return True
67
+ if isinstance(current, BaseExceptionGroup) and any(
68
+ matches_exception(leaf, types) for leaf in current.exceptions
69
+ ):
70
+ return True
71
+ current = current.__cause__
72
+ return False
73
+
74
+
75
+ def _is_exception_type(item: Any) -> bool:
76
+ """Whether ``item`` is an exception class rather than a value."""
77
+ return isinstance(item, type) and issubclass(item, Exception)
78
+
79
+
80
+ def _value_predicate(expected: Any) -> tuple[Predicate, bool]:
81
+ """Match a returned value, which never inspects the exception."""
82
+ return lambda result, exc: exc is None and bool(result == expected), False
83
+
84
+
85
+ def _as_predicate(condition: Any) -> tuple[Predicate, bool]:
86
+ """Compile one condition into a predicate, and whether it inspects errors."""
87
+ if _is_exception_type(condition):
88
+ types = (condition,)
89
+ return lambda result, exc: matches_exception(exc, types), True
90
+ if isinstance(condition, (str, bytes)):
91
+ # Checked before Sequence, which a str satisfies, so it reads as one value.
92
+ return _value_predicate(condition)
93
+ if isinstance(condition, Sequence):
94
+ return _as_sequence_predicate(condition)
95
+ if callable(condition):
96
+ predicate: Predicate = condition
97
+ return predicate, True
98
+ return _value_predicate(condition)
99
+
100
+
101
+ def _as_sequence_predicate(condition: Sequence[Any]) -> tuple[Predicate, bool]:
102
+ """Compile a tuple or list of conditions, OR'ed together.
103
+
104
+ A collection means "any of these", so its members must be conditions in their own
105
+ right: exception types or predicates. A value belongs in a predicate.
106
+ """
107
+ if not condition:
108
+ raise TypeError(
109
+ "invalid condition (): an empty collection matches nothing, which is "
110
+ "never useful; omit the argument instead"
111
+ )
112
+ bare = [item for item in condition if not (_is_exception_type(item) or callable(item))]
113
+ if bare:
114
+ offender = bare[0]
115
+ raise TypeError(
116
+ f"invalid condition {condition!r}: {offender!r} is ambiguous inside a "
117
+ f"collection, which already means a set of conditions. Match it with a "
118
+ f"predicate, as lambda result, exc: result == {offender!r}."
119
+ )
120
+ compiled = [_as_predicate(item) for item in condition]
121
+ predicates = [p for p, _ in compiled]
122
+ checks_errors = any(checks for _, checks in compiled)
123
+ return (
124
+ lambda result, exc: any(predicate(result, exc) for predicate in predicates),
125
+ checks_errors,
126
+ )
127
+
128
+
129
+ class FailureConditions:
130
+ """A compiled set of conditions, evaluated as Go's ``BaseFailurePolicy`` does.
131
+
132
+ Conditions are OR'ed. The subtle rule, preserved verbatim from Go's ``errorsChecked``
133
+ flag: a result-only condition does **not** replace the default "any error is a
134
+ failure" handling, because it never inspects errors at all. Configuring
135
+ ``handle=None`` therefore leaves exceptions failing as before, while
136
+ ``handle=ValueError`` narrows failures to that type.
137
+
138
+ Compiled once at policy construction.
139
+
140
+ Args:
141
+ condition: The configured condition, or `UNSET` for Go's default.
142
+ """
143
+
144
+ __slots__ = ("_checks_errors", "_predicates")
145
+
146
+ def __init__(self, condition: Condition = UNSET) -> None:
147
+ if condition is UNSET:
148
+ self._predicates: list[Predicate] = []
149
+ self._checks_errors = False
150
+ return
151
+ predicate, checks_errors = _as_predicate(condition)
152
+ self._predicates = [predicate]
153
+ self._checks_errors = checks_errors
154
+
155
+ def __call__(self, result: Any, exc: Exception | None) -> bool:
156
+ """Whether this outcome is a failure."""
157
+ if not self._predicates:
158
+ return exc is not None
159
+ if any(predicate(result, exc) for predicate in self._predicates):
160
+ return True
161
+ return exc is not None and not self._checks_errors
162
+
163
+ @property
164
+ def configured(self) -> bool:
165
+ """Whether any condition was configured."""
166
+ return bool(self._predicates)