Functional Weave
Code in Python

monitor.burn-rate@1.0.0

impl/python.py

1,396 bytes · the Python implementation · view raw

def _whole(value: object) -> bool:
    return isinstance(value, int) and not isinstance(value, bool)


def burn_rate(target_basis_points: int, total_events: int, bad_events: int) -> int:
    """How fast an SLO's error budget is burning, in thousandths: the window's
    error rate divided by the error rate the SLO allows. 1000 spends exactly
    the budget over the SLO period; 14400 (14.4x) spends 2% of a 30-day
    budget in one hour."""
    if not _whole(target_basis_points) or target_basis_points < 1 or target_basis_points > 9999:
        raise ValueError("targetBasisPoints must be a whole number from 1 to 9999 (10000 leaves no error budget), received %s" % (target_basis_points,))
    if not _whole(total_events) or total_events < 0:
        raise ValueError("totalEvents must be a whole number of at least 0, received %s" % (total_events,))
    if not _whole(bad_events) or bad_events < 0:
        raise ValueError("badEvents must be a whole number of at least 0, received %s" % (bad_events,))
    if bad_events > total_events:
        raise ValueError("badEvents must not exceed totalEvents: %d > %d" % (bad_events, total_events))
    # An empty window has no error rate; 0 keeps an alert quiet rather than failing it.
    if total_events == 0:
        return 0
    n = bad_events * 10000 * 1000
    d = total_events * (10000 - target_basis_points)
    return (2 * n + d) // (2 * d)