"""
Solution: health checks and draining. Lab 07's logic for scripts 03_health_checks.py and
04_deploys.py (Check.detection_range_s() in lb_config.py, and the arithmetic the lab and the
chapter use): how long a check takes to notice a frozen server, how many requests fail
meanwhile, how much traffic the servers left can carry, and whether a restart is long enough
for the check to notice at all.
"""


def detection_range(inter_s, timeout_s, fall):
    """Shortest and longest time from "server freezes" to "marked down", as (lo, hi) seconds.
    A frozen server accepts the connection and never answers, so each failed check waits out
    its timeout, and the next one starts `inter` after that: failures are one cycle
    (inter + timeout) apart. The first lands anywhere in the first cycle; then fall - 1 more."""
    cycle = inter_s + timeout_s
    return ((fall - 1) * cycle, fall * cycle)


def rise_range(inter_s, rise):
    """Shortest and longest time from "server answers again" to "marked up", as (lo, hi):
    rise passed checks in a row, inter apart, the first anywhere in the first interval."""
    return ((rise - 1) * inter_s, rise * inter_s)


def expected_failures(rate, servers, detect_s):
    """Requests sent to the frozen server before it's marked down: its share of the traffic
    (round robin: rate / servers) times the time to notice."""
    return rate / servers * detect_s


def passive_detection(server_timeout_s, error_limit, share_per_s):
    """Roughly when a passive check marks the server down: the first real request fails after
    the balancer's server timeout, and error_limit failures in a row arrive error_limit / share
    seconds of traffic later."""
    return server_timeout_s + error_limit / share_per_s


def mean_work_ms(mix):
    """Mean work per request; mix is a list of (percent, ms)."""
    return sum(w * ms for w, ms in mix) / sum(w for w, _ in mix)


def capacity(servers, slots_per_server, mix):
    """Requests a second the servers can serve: slots / mean work (one slot does one request at
    a time)."""
    return servers * slots_per_server / (mean_work_ms(mix) / 1000)


def utilization(rate, servers, slots_per_server, mix):
    """How busy the servers are: arrivals / capacity. Above 1, the lines grow without end."""
    return rate / capacity(servers, slots_per_server, mix)


def away_times(steps):
    """Seconds each server was away in a deploy: from the stop command (`stop`) to answering
    again (`started`). steps is a list of dicts with those keys, as in 04_deploys.py's log."""
    return [s["started"] - s["stop"] for s in steps]


def check_can_notice(away_s, inter_s, fall):
    """Could an active check mark a restarting server down? A refused connection fails a check
    at once, so fall failed checks need the server gone for more than (fall - 1) * inter."""
    return away_s > (fall - 1) * inter_s
