"""Simulate DNS expiry and HTTP edge caching with a deterministic clock.

Run with Python 3.10 or newer: python3 05-networking-http-dns-cdn.py
Uses only the standard library and sends no network requests.
"""

from dataclasses import dataclass


@dataclass
class Resolver:
    address: str
    expires_at: int = 0
    cached_address: str = ""

    def resolve(self, now: int, ttl: int) -> str:
        if now >= self.expires_at:
            self.cached_address = self.address
            self.expires_at = now + ttl
        return self.cached_address


@dataclass(frozen=True)
class Response:
    body: str
    etag: str
    max_age: int
    stale_if_error: int
    shared: bool = True


@dataclass
class Origin:
    responses: dict[tuple[str, str], Response]
    available: bool = True
    requests: int = 0

    def fetch(self, key: tuple[str, str], validator: str | None) -> Response | None:
        self.requests += 1
        if not self.available:
            raise TimeoutError("Origin response deadline expired")
        response = self.responses[key]
        # None stands for a 304 with unchanged policy and validator metadata.
        return None if response.etag == validator else response


@dataclass(frozen=True)
class CachedEntry:
    response: Response
    stored_at: int


class Edge:
    def __init__(self, origin: Origin):
        self.origin = origin
        self.entries: dict[tuple[str, str], CachedEntry] = {}

    def get(self, path: str, language: str, now: int) -> tuple[str, str]:
        # A single HTTPS authority is assumed. The caller supplies a
        # normalized, supported language. Private routes bypass shared lookup.
        key = (path, language)
        previous = None if path == "/me" else self.entries.get(key)
        if previous:
            age = now - previous.stored_at
            if age < previous.response.max_age:
                return "HIT", previous.response.body

        validator = previous.response.etag if previous else None
        try:
            response = self.origin.fetch(key, validator)
        except TimeoutError:
            if previous:
                policy = previous.response
                stale_by = now - previous.stored_at - policy.max_age
                if policy.stale_if_error > 0 and stale_by <= policy.stale_if_error:
                    return "STALE", policy.body
            raise

        if response is None:
            assert previous is not None
            self.entries[key] = CachedEntry(previous.response, now)
            return "REVALIDATED", previous.response.body

        if response.shared and path != "/me":
            self.entries[key] = CachedEntry(response, now)
        else:
            self.entries.pop(key, None)
        return "MISS", response.body


def main() -> None:
    resolver = Resolver("192.0.2.10")
    assert resolver.resolve(now=0, ttl=60) == "192.0.2.10"
    resolver.address = "192.0.2.20"
    assert resolver.resolve(now=30, ttl=15) == "192.0.2.10"
    assert resolver.resolve(now=60, ttl=15) == "192.0.2.20"

    origin = Origin({
        ("/schedule", "en"): Response("Doors open at 9", '"en-v1"', 30, 60),
        ("/schedule", "fr"): Response("Ouverture à 9 h", '"fr-v1"', 30, 60),
        ("/me", "en"): Response("Your registration", '"private"', 0, 0, shared=False),
    })
    edge = Edge(origin)

    assert edge.get("/schedule", "en", 0) == ("MISS", "Doors open at 9")
    assert edge.get("/schedule", "en", 10) == ("HIT", "Doors open at 9")
    assert origin.requests == 1
    assert edge.get("/schedule", "fr", 10) == ("MISS", "Ouverture à 9 h")
    assert edge.get("/schedule", "en", 30) == ("REVALIDATED", "Doors open at 9")
    origin.responses[("/schedule", "en")] = Response(
        "Doors open at 10", '"en-v2"', 30, 60
    )
    assert edge.get("/schedule", "en", 60) == ("MISS", "Doors open at 10")

    edge.get("/me", "en", 60)
    assert ("/me", "en") not in edge.entries

    origin.available = False
    assert edge.get("/schedule", "en", 150) == ("STALE", "Doors open at 10")
    try:
        edge.get("/schedule", "en", 151)
    except TimeoutError:
        pass
    else:
        raise AssertionError("Expired stale response should not be served")

    print("DNS expiry, edge variants, validation, and bounded stale checks passed.")

    # Try it yourself:
    # 1. Add a second resolver that cached the old address at t=25 and
    #    compare its first observation of the new address.
    # 2. Start with an empty edge during the outage. Which requests can succeed?
    # 3. Remove language from the key and write an assertion that fails when
    #    a French reader receives the English schedule.


if __name__ == "__main__":
    main()
