"""
Practice: what a cache buys and how it breaks. Lab 08's logic for scripts 01_hit_ratio.py,
02_cache_speedup.py and 04_stampede.py (cache_sim.py, cache_metrics.py and
service/cache_logic.py): the best hit ratio a cache can get, LRU and LFU eviction, the
database's share of the load, half-second steps of a stampede, TTL jitter and early refresh.

Fill in the TODOs, then run the tests:
    pytest test_cache_practice.py        (locally)
or press "Run tests" on the chapter page.
"""
import math
from collections import OrderedDict


def top_share(n, s, k):
    """The share of requests the k most popular of n items get, when the item ranked r is asked
    for in proportion to 1 / r**s (a Zipf distribution). The best any cache of k items can do."""
    # TODO
    raise NotImplementedError


def lru_hits(stream, capacity, warmup=0):
    """Run a stream of keys through a cache that throws out the least recently used key when
    full (cache-aside: a miss puts the key in). Return the hits after the first `warmup` requests."""
    # TODO
    raise NotImplementedError


def lfu_hits(stream, capacity, warmup=0):
    """Same, but throw out the least frequently used key; on a tie, the least recently used of
    those. A new key starts with a count of 1."""
    # TODO
    raise NotImplementedError


def db_reads_per_s(rate, hit_ratio):
    """Reads a second that reach the database: only the misses."""
    # TODO
    raise NotImplementedError


def half_second_steps(rates_100ms):
    """Average each 5 bins of 100 ms into half-second steps."""
    # TODO
    raise NotImplementedError


def jittered_ttl(ttl_ms, jitter, u):
    """TTL jitter: ttl_ms times a factor spread evenly over [1 - jitter, 1 + jitter].
    u in [0, 1] picks the factor (0 gives the shortest, 1 the longest). Round to whole ms, at
    least 1. Raise ValueError unless 0 <= jitter < 1."""
    # TODO
    raise NotImplementedError


def xfetch_should_refresh(delta_s, expiry, now, beta, u):
    """Early refresh (XFetch): refresh now if now - delta_s * beta * ln(u) >= expiry.
    delta_s: how long the last recompute took. u: a random number in (0, 1]."""
    # TODO
    raise NotImplementedError


def recomputes_per_expiry(recomputes, seconds, ttl_s):
    """Recomputes divided by the number of expiries in a run: seconds / ttl_s, rounded, at least 1."""
    # TODO
    raise NotImplementedError
