"""Model overload and a worker crash between commit and acknowledgment.

Run with Python 3.10 or newer: python3 08-queues-backpressure-workers.py
Uses an in-memory SQLite database and deterministic simulation, without a broker.
"""

import sqlite3
from dataclasses import dataclass


@dataclass(frozen=True)
class Tick:
    waiting: int
    shed: int
    completed: int


def simulate(
    arrivals: list[int], service_per_second: int, waiting_limit: int
) -> list[Tick]:
    """Advance one-second ticks with an empty initial queue.

    Arrivals are a batch at the start of the tick. Admission can fill service
    slots for this tick plus the bounded waiting queue. Jobs have unit cost.
    """
    waiting = 0
    result = []
    for offered in arrivals:
        available = service_per_second + waiting_limit - waiting
        admitted = min(offered, available)
        completed = min(waiting + admitted, service_per_second)
        waiting += admitted - completed
        result.append(Tick(waiting, offered - admitted, completed))
    return result


def apply_delivery(database: sqlite3.Connection, event_id: str) -> bool:
    """Update a counter once per event ID within the same database transaction."""
    with database:
        claim = database.execute(
            "INSERT INTO processed VALUES (?) ON CONFLICT DO NOTHING", (event_id,)
        )
        if claim.rowcount == 0:
            return False
        database.execute("UPDATE receipts SET total = total + 1")
    return True


def main() -> None:
    spike = [160] * 20
    unrestricted = simulate(spike, service_per_second=100, waiting_limit=10_000)
    assert unrestricted[-1].waiting == 1_200

    recovery = simulate(spike + [80] * 60, service_per_second=100, waiting_limit=10_000)
    assert recovery[-2].waiting == 20
    assert recovery[-1].waiting == 0

    bounded = simulate(spike, service_per_second=100, waiting_limit=500)
    assert bounded[7].waiting == 480
    assert bounded[8] == Tick(waiting=500, shed=40, completed=100)
    assert sum(tick.shed for tick in bounded) == 700
    assert sum(tick.completed for tick in bounded) + 500 + 700 == sum(spike)

    database = sqlite3.connect(":memory:")
    try:
        database.executescript(
            """
            CREATE TABLE processed (event_id TEXT PRIMARY KEY);
            CREATE TABLE receipts (total INTEGER NOT NULL);
            INSERT INTO receipts VALUES (0);
            """
        )
        assert apply_delivery(database, "event-17")
        # The worker crashes after commit and before acknowledging the broker.
        # On redelivery the stable ID is already in the same durable state.
        assert not apply_delivery(database, "event-17")
        assert apply_delivery(database, "event-18")
        assert database.execute("SELECT total FROM receipts").fetchone() == (2,)
    finally:
        database.close()

    print("Peak backlog: 1200 jobs. Recovery: 60 s. Bounded queue shed: 700 jobs.")
    print("Two unique deliveries changed the database despite three attempts.")

    # Try it yourself:
    # 1. Reduce the completion rate to 80 after the burst. Does the queue drain?
    # 2. Reserve 100 waiting slots for a separate priority class.
    # 3. Raise an exception after INSERT but before UPDATE and check rollback.


if __name__ == "__main__":
    main()
