Skip to content

[RFC]: add callback api to WebSocketProxy #40

Open
@WSH032

Description

@WSH032

Have you discussed it?

  • I have discussed this feature request in discussions, and developers ask me directly to create an issue here.

Discussed in #39

Originally posted by IvesAwadi July 15, 2024
Thank you for the library, it's amazing so far but for some reason I can't figure out how to log incoming data from the WebSocket and also read its responses.

Describe your feature request

Add a callback function API to ReverseWebSocketProxy so that we can use the callback function to modify the messages received and sent by the client.

Is your feature request related to a problem? Please describe

Thank you for the response, I wanted to use this to modify incoming data and also modify the responses.
I basically having a client that sends WebSocket data and I want to proxy the connection to read incoming data and it's response before it's returned back to the original client. Should work similarly like the ReverseHttpProxy system but for WebSocket.

Describe the solution you'd like

Something like:

async def server_to_client_callback(
    receiver: AsyncIterator[str], sender: Callable[[str], Awaitable[None]]
):
    """Receive from the target(base_url) server and send to the client."""
    async for recv in receiver:  # Receive the message
        print(f"Received: {recv}")
        resp = f"Modified: {recv}"  # Modify the message
        await sender(resp)  # Send the message
        print(time.time)  # Do something after sending the message


@app.websocket("/{path:path}")
async def _(websocket: WebSocket):
    return await proxy.proxy(
        websocket=websocket,
        server_to_client_callback=server_to_client_callback,
    )

Describe alternatives you've considered

Or would this API be better? It would offer higher performance but be more low-level. So it wouldn't allow for background tasks after sending a message or ensuring the order of message receipt.

async def server_to_client_callback(recv: str):
    """Receive from the target(base_url) server and send to the client."""
    print(f"Received: {recv}")
    resp = f"Modified: {recv}"  # Modify the message
    return resp  # Send the message

Additional context

For the first API, it is necessary to consider exceptions and disconnections:

if an exception occurs in the proxy, what do you want the callback to receive; or conversely, if an exception occurs in the callback, what should the proxy send to the client?

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions