#!/usr/bin/env python3
# H3 client for repro.cfg, needs aioquic (pip install aioquic).
#
# First sends a normal GET to check the setup. Then sends a POST whose HEADERS,
# DATA and trailers HEADERS frames all go out, but the stream is never closed
# (no STREAM FIN). Finally checks whether haproxy still answers a GET.
#
# usage: python3 repro.py [host:port]       (default 127.0.0.1:8443)
# exit:  0 haproxy stopped answering after the trailers, 1 still answering,
#        2 baseline GET failed
import asyncio, ssl, sys

from aioquic.asyncio.client import connect
from aioquic.asyncio.protocol import QuicConnectionProtocol
from aioquic.h3.connection import H3_ALPN, H3Connection
from aioquic.h3.events import DataReceived, HeadersReceived
from aioquic.quic.configuration import QuicConfiguration

host, port = (sys.argv[1] if len(sys.argv) > 1 else "127.0.0.1:8443").rsplit(":", 1)
port = int(port)


class Client(QuicConnectionProtocol):
    def __init__(self, *a, **k):
        super().__init__(*a, **k)
        self.h3 = H3Connection(self._quic)
        self.done = {}

    def quic_event_received(self, ev):
        for e in self.h3.handle_event(ev):
            if isinstance(e, (HeadersReceived, DataReceived)) and e.stream_ended:
                if e.stream_id in self.done:
                    self.done[e.stream_id].set()

    def headers(self, method):
        return [(b":method", method), (b":scheme", b"https"), (b":authority", b"localhost"),
                (b":path", b"/")]

    async def get(self):
        sid = self._quic.get_next_available_stream_id()
        self.done[sid] = asyncio.Event()
        self.h3.send_headers(sid, self.headers(b"GET"), end_stream=True)
        self.transmit()
        await asyncio.wait_for(self.done[sid].wait(), 3)

    def post_trailers_no_fin(self):
        sid = self._quic.get_next_available_stream_id()
        self.h3.send_headers(sid, self.headers(b"POST"))
        self.h3.send_data(sid, b"hello", end_stream=False)
        self.h3.send_headers(sid, [(b"x-trailer", b"1")], end_stream=False)
        self.transmit()


async def get_ok():
    cfg = QuicConfiguration(is_client=True, alpn_protocols=H3_ALPN, verify_mode=ssl.CERT_NONE)
    try:
        async with asyncio.timeout(5):
            async with connect(host, port, configuration=cfg, create_protocol=Client) as c:
                await c.get()
        return True
    except (TimeoutError, ConnectionError):
        return False


async def main():
    asyncio.get_running_loop().set_exception_handler(lambda loop, ctx: None)
    if not await get_ok():
        print("baseline: GET failed, check that haproxy runs repro.cfg")
        return 2
    print("baseline: GET answered")
    cfg = QuicConfiguration(is_client=True, alpn_protocols=H3_ALPN, verify_mode=ssl.CERT_NONE)
    async with connect(host, port, configuration=cfg, create_protocol=Client) as c:
        c.post_trailers_no_fin()
        print("sent: POST with HEADERS + DATA + trailers HEADERS, no FIN")
        await asyncio.sleep(1)
    if await get_ok():
        print("after: GET answered, haproxy is fine")
        return 1
    print("after: GET not answered, haproxy is gone")
    return 0

sys.exit(asyncio.run(main()))
