diff --git a/pipegate/client.py b/pipegate/client.py index bc7556e..4f9319a 100644 --- a/pipegate/client.py +++ b/pipegate/client.py @@ -2,16 +2,36 @@ import asyncio import base64 +import functools import sys +import uuid import httpx import orjson from websockets.asyncio.client import ClientConnection, connect -from .schemas import BufferGateRequest, BufferGateResponse +from .schemas import BufferGateChunk, BufferGateRequest, BufferGateResponse _BACKOFF_BASE: float = 1.0 _BACKOFF_MAX: float = 60.0 +# No read timeout: a server-sent event stream is idle between events for as +# long as it likes. Until the head is sent a request has as long as the +# server waits for it; after that the server cancels a stream whose caller +# went away. +_TIMEOUT = httpx.Timeout(5.0, read=None) +_HEAD_TIMEOUT_S = 300.0 +# Not passed on with a streamed body: it is re-framed by the server. +_STREAM_DROP_HEADERS = { + "content-length", + "content-encoding", + "transfer-encoding", + "connection", +} + + +def _is_stream(response: httpx.Response) -> bool: + content_type: str = response.headers.get("content-type", "") + return content_type.startswith("text/event-stream") async def handle_request( @@ -20,33 +40,77 @@ async def handle_request( http_client: httpx.AsyncClient, ws_client: ClientConnection, ) -> None: + streaming = False try: - response = await http_client.request( - method=request.method, - url=f"{target}/{request.url_path}", - headers=orjson.loads(request.headers), - params=orjson.loads(request.url_query), - content=base64.b64decode(request.body) if request.body else b"", - ) - payload = BufferGateResponse( - correlation_id=request.correlation_id, - headers=orjson.dumps(dict(response.headers)).decode(), - body=base64.b64encode(response.content).decode(), - status_code=response.status_code, - ) + async with ( + asyncio.timeout(_HEAD_TIMEOUT_S) as deadline, + http_client.stream( + method=request.method, + url=f"{target}/{request.url_path}", + headers=orjson.loads(request.headers), + params=orjson.loads(request.url_query), + content=base64.b64decode(request.body) if request.body else b"", + timeout=_TIMEOUT, + ) as response, + ): + if not _is_stream(response): + body = await response.aread() + payload = BufferGateResponse( + correlation_id=request.correlation_id, + headers=orjson.dumps(dict(response.headers)).decode(), + body=base64.b64encode(body).decode(), + status_code=response.status_code, + ) + await ws_client.send(payload.model_dump_json()) + return + + # Server-sent events: the head now, then each piece as it comes. + headers = { + k: v + for k, v in response.headers.items() + if k.lower() not in _STREAM_DROP_HEADERS + } + await ws_client.send( + BufferGateResponse( + correlation_id=request.correlation_id, + headers=orjson.dumps(headers).decode(), + body="", + status_code=response.status_code, + stream=True, + ).model_dump_json() + ) + streaming = True + deadline.reschedule(None) + async for piece in response.aiter_bytes(): + await ws_client.send( + BufferGateChunk( + correlation_id=request.correlation_id, + body=base64.b64encode(piece).decode(), + ).model_dump_json() + ) + await ws_client.send( + BufferGateChunk( + correlation_id=request.correlation_id, done=True + ).model_dump_json() + ) + except asyncio.CancelledError: + raise except Exception as e: print( f"Error processing request {request.correlation_id}: {e}", file=sys.stderr, ) - payload = BufferGateResponse( - correlation_id=request.correlation_id, - headers="{}", - body="", - status_code=504, + reply: BufferGateResponse | BufferGateChunk = ( + BufferGateChunk(correlation_id=request.correlation_id, done=True) + if streaming + else BufferGateResponse( + correlation_id=request.correlation_id, + headers="{}", + body="", + status_code=504, + ) ) - - await ws_client.send(payload.model_dump_json()) + await ws_client.send(reply.model_dump_json()) async def main(target_url: str, server_url: str) -> None: @@ -71,16 +135,29 @@ async def main(target_url: str, server_url: str) -> None: ): print("Connected.") attempt = 0 + # Requests in flight, so the server can cancel a stream. + tasks: dict[uuid.UUID, asyncio.Task[None]] = {} async with asyncio.TaskGroup() as tg: while True: try: message = await ws_client.recv() - request = BufferGateRequest.model_validate_json(message) - tg.create_task( + data = orjson.loads(message) + if data.get("kind") == "cancel": + cid = uuid.UUID(data["correlation_id"]) + if cancelled := tasks.pop(cid, None): + cancelled.cancel() + continue + request = BufferGateRequest.model_validate(data) + task = tg.create_task( handle_request( target_url, request, http_client, ws_client ) ) + tasks[request.correlation_id] = task + # Called with the task: pop(cid, task) forgets it. + task.add_done_callback( + functools.partial(tasks.pop, request.correlation_id) + ) except asyncio.CancelledError: raise except Exception as e: diff --git a/pipegate/schemas.py b/pipegate/schemas.py index f3da7e2..5e5171d 100644 --- a/pipegate/schemas.py +++ b/pipegate/schemas.py @@ -31,6 +31,25 @@ class BufferGateResponse(BaseModel): headers: str body: str status_code: int + # True: the body follows in BufferGateChunk messages (server-sent events), + # and `body` here is empty. + stream: bool = False + + +class BufferGateChunk(BaseModel): + """A piece of a streamed response body; `done` ends the stream.""" + + kind: Literal["chunk"] = "chunk" + correlation_id: uuid.UUID + body: str = "" + done: bool = False + + +class BufferGateCancel(BaseModel): + """Server to client: the caller went away, stop streaming this response.""" + + kind: Literal["cancel"] = "cancel" + correlation_id: uuid.UUID class JWTPayload(BaseModel): diff --git a/pipegate/server.py b/pipegate/server.py index 4f8bf3b..8af9712 100644 --- a/pipegate/server.py +++ b/pipegate/server.py @@ -18,10 +18,13 @@ WebSocket, WebSocketDisconnect, ) +from fastapi.responses import StreamingResponse from pydantic import ValidationError from .auth import verify_token from .schemas import ( + BufferGateCancel, + BufferGateChunk, BufferGateRequest, BufferGateResponse, Methods, @@ -32,8 +35,11 @@ def create_app() -> FastAPI: - buffers: dict[str, asyncio.Queue[BufferGateRequest]] = {} + buffers: dict[str, asyncio.Queue[BufferGateRequest | BufferGateCancel]] = {} futures: dict[uuid.UUID, asyncio.Future[BufferGateResponse]] = {} + # Streamed bodies in flight: correlation id -> (connection id, pieces). + # None in the queue ends the body. + streams: dict[uuid.UUID, tuple[str, asyncio.Queue[bytes | None]]] = {} @asynccontextmanager async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]: @@ -114,6 +120,9 @@ async def handle_http_request( finally: futures.pop(correlation_id, None) + if response.stream: + return stream_body(connection_id, correlation_id, response, request.method) + response_content = ( b"" if request.method == "HEAD" @@ -125,6 +134,43 @@ async def handle_http_request( status_code=response.status_code, ) + def stream_body( + connection_id: str, + correlation_id: uuid.UUID, + head: BufferGateResponse, + method: str, + ) -> Response: + """The body of a streamed response, piece by piece as the client sends + it. If the caller goes away first, the client is told to stop.""" + headers = orjson.loads(head.headers) if head.headers else {} + + def cancel() -> None: + if streams.pop(correlation_id, None) is None: + return + queue = buffers.get(connection_id) + if queue is not None: + with contextlib.suppress(asyncio.QueueFull): + queue.put_nowait(BufferGateCancel(correlation_id=correlation_id)) + + if method == "HEAD": + cancel() + return Response(headers=headers, status_code=head.status_code) + + async def pieces() -> AsyncGenerator[bytes, None]: + entry = streams.get(correlation_id) + if entry is None: + return + try: + while (piece := await entry[1].get()) is not None: + yield piece + streams.pop(correlation_id, None) + finally: + cancel() + + return StreamingResponse( + pieces(), status_code=head.status_code, headers=headers + ) + @app.websocket("/") async def handle_websocket( websocket: WebSocket, @@ -155,15 +201,32 @@ async def receive() -> None: while True: message_text = await websocket.receive_text() try: - message = BufferGateResponse.model_validate_json(message_text) + data = orjson.loads(message_text) + if isinstance(data, dict) and data.get("kind") == "chunk": + chunk = BufferGateChunk.model_validate(data) + entry = streams.get(chunk.correlation_id) + if entry is not None: + if chunk.body: + entry[1].put_nowait(base64.b64decode(chunk.body)) + if chunk.done: + entry[1].put_nowait(None) + continue + message = BufferGateResponse.model_validate(data) future = futures.get(message.correlation_id) if future and not future.done(): + # Ready before the caller resumes, so no piece + # that follows the head is lost. + if message.stream: + streams[message.correlation_id] = ( + connection_id, + asyncio.Queue(), + ) future.set_result(message) else: logger.warning( "No pending future for: %s", message.correlation_id ) - except ValidationError as ve: + except (ValidationError, orjson.JSONDecodeError) as ve: logger.warning("Invalid message format: %s", ve) except WebSocketDisconnect: pass @@ -198,5 +261,9 @@ async def send() -> None: logger.info("WebSocket disconnected: %s", connection_id) buffers.pop(connection_id, None) + # Streams through this tunnel end with it. + for owner, pieces in list(streams.values()): + if owner == connection_id: + pieces.put_nowait(None) return app diff --git a/tests/test_client.py b/tests/test_client.py index a5ec0e2..2a3cdf6 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -4,13 +4,19 @@ import base64 import contextlib import uuid +from collections.abc import AsyncIterator from unittest.mock import AsyncMock, patch import httpx import orjson from pipegate.client import handle_request, main -from pipegate.schemas import BufferGateRequest, BufferGateResponse +from pipegate.schemas import ( + BufferGateCancel, + BufferGateChunk, + BufferGateRequest, + BufferGateResponse, +) class TestHandleRequest: @@ -147,3 +153,94 @@ async def side_effect(*a: object, **kw: object) -> None: await main("http://localhost:9000", "ws://fake:8000/conn") assert call_count >= 2 + + +class TestStreaming: + def _request(self) -> BufferGateRequest: + return BufferGateRequest( + correlation_id=uuid.uuid4(), + url_path="stream", + url_query=orjson.dumps([]).decode(), + method="GET", + headers=orjson.dumps({}).decode(), + body="", + ) + + async def test_event_stream_is_sent_as_head_and_pieces(self) -> None: + ws = AsyncMock() + request = self._request() + + async def events() -> AsyncIterator[bytes]: + yield b"data: 1\n\n" + yield b"data: 2\n\n" + + def handler(req: httpx.Request) -> httpx.Response: + return httpx.Response( + 200, + headers={"content-type": "text/event-stream", "content-length": "18"}, + content=events(), + ) + + async with httpx.AsyncClient( + transport=httpx.MockTransport(handler) + ) as http_client: + await handle_request("http://localhost:9000", request, http_client, ws) + + sent = [orjson.loads(c.args[0]) for c in ws.send.call_args_list] + head = BufferGateResponse.model_validate(sent[0]) + assert head.stream and head.status_code == 200 and head.body == "" + assert "content-length" not in orjson.loads(head.headers) + chunks = [BufferGateChunk.model_validate(m) for m in sent[1:]] + assert b"".join(base64.b64decode(c.body) for c in chunks) == ( + b"data: 1\n\ndata: 2\n\n" + ) + assert [c.done for c in chunks] == [False, False, True] + + async def test_cancel_stops_a_stream(self) -> None: + request = self._request() + cancel = BufferGateCancel(correlation_id=request.correlation_id) + started = asyncio.Event() + stopped = asyncio.Event() + + async def endless() -> AsyncIterator[bytes]: + try: + while True: + started.set() + yield b"data: tick\n\n" + await asyncio.sleep(0.01) + finally: + stopped.set() + + def handler(req: httpx.Request) -> httpx.Response: + return httpx.Response( + 200, headers={"content-type": "text/event-stream"}, content=endless() + ) + + sent: list[str] = [] + inbox: asyncio.Queue[str] = asyncio.Queue() + await inbox.put(request.model_dump_json()) + + ws = AsyncMock() + ws.recv.side_effect = inbox.get + ws.send.side_effect = sent.append + connect_cm = AsyncMock() + connect_cm.__aenter__.return_value = ws + connect_cm.__aexit__.return_value = False + real_client = httpx.AsyncClient + + def mock_client(*a: object, **kw: object) -> httpx.AsyncClient: + return real_client(transport=httpx.MockTransport(handler)) + + with ( + patch("pipegate.client.connect", return_value=connect_cm), + patch("pipegate.client.httpx.AsyncClient", side_effect=mock_client), + ): + task = asyncio.create_task(main("http://localhost:9000", "ws://fake/")) + await asyncio.wait_for(started.wait(), 2) + await inbox.put(cancel.model_dump_json()) + await asyncio.wait_for(stopped.wait(), 2) + task.cancel() + with contextlib.suppress(asyncio.CancelledError): + await task + + assert BufferGateResponse.model_validate_json(sent[0]).stream diff --git a/tests/test_server.py b/tests/test_server.py index 0fd5cb0..d9eb0b5 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -11,7 +11,12 @@ from fastapi import FastAPI from httpx import ASGITransport, AsyncClient, Response -from pipegate.schemas import BufferGateRequest, BufferGateResponse, Settings +from pipegate.schemas import ( + BufferGateChunk, + BufferGateRequest, + BufferGateResponse, + Settings, +) from pipegate.server import create_app from .conftest import make_token @@ -484,3 +489,96 @@ async def test_send_uses_captured_queue_not_dict_lookup( assert not received_from_replacement, ( "send() read from a replacement queue — it must use the captured queue ref" ) + + +# --------------------------------------------------------------------------- +# Streamed responses (server-sent events) +# --------------------------------------------------------------------------- + + +async def _ws_stream( + app: FastAPI, + connection_id: str, + *, + pieces: list[bytes], + finish: str, +) -> Response: + """HTTP -> WS forward -> streamed head and pieces -> HTTP. finish is + "done" (the client ends the body) or "disconnect" (the tunnel drops).""" + token = make_token(connection_id) + transport = ASGITransport(app=app) + async with AsyncClient(transport=transport, base_url="http://test") as client: + + async def ws_client() -> None: + scope: dict[str, object] = { + "type": "websocket", + "asgi": {"version": "3.0"}, + "http_version": "1.1", + "path": "/", + "query_string": f"token={token}".encode(), + "headers": [], + } + inbox: asyncio.Queue[dict[str, object]] = asyncio.Queue() + outbox: asyncio.Queue[dict[str, object]] = asyncio.Queue() + await inbox.put({"type": "websocket.connect"}) + app_task = asyncio.create_task( + app(scope, inbox.get, outbox.put), # type: ignore[arg-type] + ) + assert (await asyncio.wait_for(outbox.get(), 5))[ + "type" + ] == "websocket.accept" + msg = await asyncio.wait_for(outbox.get(), 5) + cid = json.loads(cast(str, msg["text"]))["correlation_id"] + + async def say(model: BufferGateResponse | BufferGateChunk) -> None: + await inbox.put( + {"type": "websocket.receive", "text": model.model_dump_json()} + ) + + await say( + BufferGateResponse( + correlation_id=cid, + headers=orjson.dumps( + {"content-type": "text/event-stream"} + ).decode(), + body="", + status_code=200, + stream=True, + ) + ) + for piece in pieces: + await say( + BufferGateChunk( + correlation_id=cid, body=base64.b64encode(piece).decode() + ) + ) + if finish == "done": + await say(BufferGateChunk(correlation_id=cid, done=True)) + await asyncio.sleep(0.05) + await inbox.put({"type": "websocket.disconnect"}) + with contextlib.suppress(Exception): + await asyncio.wait_for(app_task, timeout=2) + + ws_task = asyncio.create_task(ws_client()) + await asyncio.sleep(0.01) + resp = await asyncio.wait_for(client.get(f"/{connection_id}/stream"), 10) + await ws_task + return resp + + +class TestStreaming: + async def test_pieces_reach_the_caller_in_order(self, connection_id: str) -> None: + pieces = [b"event: init\ndata: {}\n\n", b"data: 1\n\n", b"data: 2\n\n"] + resp = await _ws_stream( + _make_app(), connection_id, pieces=pieces, finish="done" + ) + assert resp.status_code == 200 + assert resp.headers["content-type"].startswith("text/event-stream") + assert resp.content == b"".join(pieces) + + async def test_stream_ends_when_the_tunnel_drops(self, connection_id: str) -> None: + app = _make_app() + resp = await _ws_stream( + app, connection_id, pieces=[b"data: 1\n\n"], finish="disconnect" + ) + assert resp.content == b"data: 1\n\n"