Module

asgi.ws_bridge

WebSocket ASGI bridge — translates between WSProtocol events and ASGI.

Builds ASGIwebsocketscope dicts and creates the async receive/send callables for WebSocket ASGI apps.

ASGI WebSocket lifecycle:

1. App receives ``websocket.connect``
2. App sends ``websocket.accept`` (or ``websocket.close`` to reject)
3. App receives ``websocket.receive`` messages
4. App sends ``websocket.send`` messages
5. Either side sends ``websocket.close`` / receives ``websocket.disconnect``

Functions

build_ws_scope 4 dict[str, Any]
Build an ASGI WebSocket scope dict from the upgrade request.
def build_ws_scope(request: RequestReceived, config: ServerConfig, client: tuple[str, int], server: tuple[str, int]) -> dict[str, Any]
Parameters
Name Type Description
request RequestReceived

The parsed HTTP upgrade request.

config ServerConfig

Server configuration.

client tuple[str, int]

Client (host, port) tuple.

server tuple[str, int]

Server (host, port) tuple.

Returns
dict[str, Any]
create_ws_receive 1 Receive
Create an ASGI receive callable for WebSocket. The worker pushes WebSocket eve…
def create_ws_receive(events: asyncio.Queue[dict[str, Any]]) -> Receive

Create an ASGI receive callable for WebSocket.

The worker pushes WebSocket events into the queue. The ASGI app consumes them viareceive().

Parameters
Name Type Description
events asyncio.Queue[dict[str, Any]]

Queue of ASGI WebSocket event dicts.

Returns
Receive
create_ws_send 5 Send
Create an ASGI send callable for WebSocket. Handles ``websocket.accept``, ``we…
def create_ws_send(writer: asyncio.StreamWriter, ws_protocol: WSProtocol, ws_key: bytes, *, accept_event: asyncio.Event, close_event: asyncio.Event) -> Send

Create an ASGI send callable for WebSocket.

Handleswebsocket.accept, websocket.send, and websocket.closemessages from the ASGI app.

Parameters
Name Type Description
writer asyncio.StreamWriter

Asyncio stream writer for the connection.

ws_protocol WSProtocol

The WSProtocol instance for WebSocket framing.

ws_key bytes

The Sec-WebSocket-Key from the client's upgrade request.

accept_event asyncio.Event

Set when the app sendswebsocket.accept.

close_event asyncio.Event

Set when the app sendswebsocket.close.

Returns
Send