Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
123 changes: 100 additions & 23 deletions pipegate/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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:
Expand All @@ -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:
Expand Down
19 changes: 19 additions & 0 deletions pipegate/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
73 changes: 70 additions & 3 deletions pipegate/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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]:
Expand Down Expand Up @@ -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"
Expand All @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Loading
Loading