File size: 3,742 Bytes
8145bee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
"""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()