"""Enforce sticky step, cost and elapsed-time limits for one browser run.""" from decimal import Decimal, DecimalException import math import time _DEFAULT_STEPS = 25 class BreakerOpen(RuntimeError): """Stop a run after a limit or an unknown cost.""" def _amount(value): if isinstance(value, bool) or not isinstance(value, (int, float, Decimal)): return None try: amount = Decimal(str(value)) except (DecimalException, ValueError, OverflowError): return None return amount if amount.is_finite() and amount >= 0 else None class Breaker: """Raise before further work once any run limit opens the breaker.""" def __init__(self, steps=_DEFAULT_STEPS, usd=0.50, minutes=15, *, clock=None): if isinstance(steps, bool) or not isinstance(steps, int) or steps <= 0: raise ValueError("Run step limit is invalid.") cost_limit, time_limit = _amount(usd), _amount(minutes) if cost_limit is None or cost_limit <= 0: raise ValueError("Run cost limit is invalid.") if time_limit is None or time_limit <= 0: raise ValueError("Run time limit is invalid.") try: seconds = float(time_limit * 60) except (DecimalException, ValueError, OverflowError): raise ValueError("Run time limit is invalid.") from None if not math.isfinite(seconds) or seconds <= 0: raise ValueError("Run time limit is invalid.") self.step_limit = steps self.usd_limit = cost_limit self.steps_taken = 0 self._spent = Decimal(0) self._clock = time.monotonic if clock is None else clock self._reason = None self._last_time = self._now() self.started_at = self._last_time self._seconds = seconds @property def spent_usd(self): return float(self._spent) @property def is_open(self): return self._reason is not None def _open(self, reason): self._reason = self._reason or reason raise BreakerOpen(self._reason) from None def _now(self): try: value = self._clock() if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value): self._open("Run clock is unavailable.") return value except Exception: self._open("Run clock is unavailable.") def check(self): """Check all limits before dispatching or accepting more work.""" if self._reason is not None: raise BreakerOpen(self._reason) now = self._now() if now < self._last_time: self._open("Run clock is unavailable.") self._last_time = now if now - self.started_at >= self._seconds: self._open("Run time limit reached.") if self.steps_taken > self.step_limit: self._open("Run step limit reached.") if self._spent >= self.usd_limit: self._open("Run cost limit reached.") def cancel(self): """Stop the executor at its next boundary without retaining caller text.""" self._reason = self._reason or "Run cancelled." def step(self): """Count one step and reject the first step beyond the limit.""" self.check() self.steps_taken += 1 self.check() def charge(self, cost=None): """Record a known nonnegative USD cost and reject unknown pricing.""" self.check() amount = _amount(cost) if amount is None: self._open("Run cost is unknown.") try: self._spent += amount except DecimalException: self._open("Run cost is unknown.") self.check()