"""
Practice: deadlocks and connection pools. Lab 05's logic for scripts 02_deadlocks.py and
05_pool_deadlock.py (bank.lock_order, and the arithmetic behind the tables): the order a transfer
locks its rows in, finding a cycle of waiting the way Postgres's deadlock check does, what a
deadlock costs under load, and when a pool of connections can wait for itself.

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


def lock_order(src, dst, ordered):
    """The order a transfer from `src` to `dst` locks the two account rows.
    ordered=False: request order, the sender first (src, dst).
    ordered=True: lowest account number first, whichever way the money goes."""
    return tuple(sorted((src, dst))) if ordered else (src, dst)


def find_cycle(waits_for):
    """`waits_for` maps each waiting transaction to the one holding the lock it wants,
    e.g. {"A": "B", "B": "A"}. Return the transactions in a cycle, starting from the
    first one found by following the arrows from each key in order, as a list
    (["A", "B"]); return [] if nobody is waiting in a circle.
    This is the question Postgres's deadlock check answers after deadlock_timeout."""
    for start in waits_for:
        path, seen = [], {}
        node = start
        while node in waits_for and node not in seen:
            seen[node] = len(path)
            path.append(node)
            node = waits_for[node]
        if node in seen:
            return path[seen[node]:]
    return []


def transfers_locking(pairs, ordered):
    """Each transfer in `pairs` ((src, dst) tuples) holds its first row and waits for its
    second, all at the same moment. Build the waits-for map {transfer index: index of the
    transfer holding the row it wants} and return find_cycle() of it. Rows are taken in
    lock_order(); if two transfers want the same first row, the earlier one (lower index)
    gets it and the later one waits for it, holding nothing."""
    holder, waits_for, firsts = {}, {}, []
    for i, (s, d) in enumerate(pairs):
        first, second = lock_order(s, d, ordered)
        if first in holder:
            waits_for[i] = holder[first]           # waits for its first row, holds nothing
            firsts.append(None)
        else:
            holder[first] = i
            firsts.append((first, second))
    for i, fs in enumerate(firsts):
        if fs is not None and fs[1] in holder and holder[fs[1]] != i:
            waits_for[i] = holder[fs[1]]
    return find_cycle(waits_for)


def deadlocks_in_progress(deadlocks, deadlock_timeout_s, seconds):
    """On average, how many deadlocks were going on at any moment: each one lasts about
    deadlock_timeout, so deadlocks x timeout ÷ the run's length."""
    return deadlocks * deadlock_timeout_s / seconds


def per_transfer(deadlocks, transfers):
    """Deadlocks per transfer, as a fraction."""
    return deadlocks / transfers


def hang_threshold(pool_size, connections_per_request=2):
    """The fewest requests at once that can hang a pool for good, when each request takes
    its connections one at a time and holds them until it has them all. They're stuck
    once every connection is held and nobody has all they need: each can hold at most
    connections_per_request - 1. A request that needs one connection can't hang it:
    return math.inf."""
    if connections_per_request <= 1:
        return math.inf
    return math.ceil(pool_size / (connections_per_request - 1))


def burst(requests, pool_size, connections_per_request=2):
    """Model of 05's Exercise 1: `requests` arrive together and each takes one connection
    while any are free. Then, repeatedly, a request that can get all the connections it
    still needs takes them, finishes and frees everything it held; waiting requests then
    take their first connection. Return how many finish."""
    free = pool_size
    held = []                                      # connections held by each started request
    waiting = requests
    while waiting and free:
        held.append(1)
        free -= 1
        waiting -= 1
    done = 0
    while True:
        i = next((k for k, h in enumerate(held) if connections_per_request - h <= free), None)
        if i is None:
            return done
        free += held.pop(i)
        done += 1
        while waiting and free:
            held.append(1)
            free -= 1
            waiting -= 1


def failed_share(finished, errors):
    """Of the requests that got an answer, the share that were errors."""
    return errors / (finished + errors)


def implied_hold_ms(connections, per_second):
    """Little's law (Chapter 1) turned around: with every connection busy, each request
    holds one for connections ÷ throughput. In ms."""
    return 1000 * connections / per_second
