Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add callback api to WebSocketProxy #41

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open

Conversation

WSH032
Copy link
Owner

@WSH032 WSH032 commented Jul 21, 2024

  • bump typing_extensions from 4.5.0 to 4.12.0
  • explicitly add anyio as a dependency
  • fix docs host typo
  • fix broken httpx authentication docs link
  • refactor tool_4_test_fixture to factory to support testing different ws apps

Summary

Close: #40

example

proxy server

from contextlib import asynccontextmanager
from typing import AsyncIterator

from fastapi import FastAPI
from fastapi_proxy_lib.core.websocket import (
    CallbackPipeContextType,
    ReverseWebSocketProxy,
)
from httpx import AsyncClient
from starlette.websockets import WebSocket

proxy = ReverseWebSocketProxy(AsyncClient(), base_url="ws://echo.websocket.events/")


async def client_to_server_callback(pipe_context: CallbackPipeContextType[str]) -> None:
    with pipe_context as (sender, receiver):
        async for message in receiver:
            print(f"Received from client: {message}")
            await sender.send(f"CTS:{message}")
    print("client_to_server_callback end")


async def server_to_client_callback(
    pipe_context: CallbackPipeContextType[str],
) -> None:
    with pipe_context as (sender, receiver):
        async for message in receiver:
            print(f"Received from server: {message}")
            await sender.send("STC:{message}")
    print("server_to_client_callback end")


@asynccontextmanager
async def close_proxy_event(_: FastAPI) -> AsyncIterator[None]:
    """Close proxy."""
    yield
    await proxy.aclose()


app = FastAPI(lifespan=close_proxy_event)


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


# Then run shell: `uvicorn <your_py>:app --host 127.0.0.1 --port 8000`
# visit the app: `ws://127.0.0.1:8000/`
# you can establish websocket connection with `ws://echo.websocket.events`

client

from httpx_ws import aconnect_ws

async with aconnect_ws('ws://127.0.0.1:8000/') as ws:
    message = await ws.receive_text()
    print(f"Received: {message}")

    await ws.send_text('Hello, World!')

    message = await ws.receive_text()
    print(f"Received: {message}")

Checklist

  • I've read CONTRIBUTING.md.
  • I understand that this PR may be closed in case there was no previous discussion. (This doesn't apply to typos!)
  • I've added a test for each change that was introduced, and I tried as much as possible to make a single atomic change.
  • I've updated the documentation accordingly.

Copy link

codecov bot commented Jul 21, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 97.13%. Comparing base (977d9c1) to head (bda8b06).
Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main      #41      +/-   ##
==========================================
+ Coverage   96.74%   97.13%   +0.39%     
==========================================
  Files           9        9              
  Lines         461      524      +63     
  Branches       67       74       +7     
==========================================
+ Hits          446      509      +63     
  Misses          9        9              
  Partials        6        6              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@WSH032 WSH032 changed the title feat: add callback api to WebSocket feat: add callback api to WebSocketProxy Jul 21, 2024
@WSH032

This comment was marked as resolved.

@IvesAwadi

This comment was marked as resolved.

@WSH032
Copy link
Owner Author

WSH032 commented Jul 22, 2024

I just found a bug. The current implementation only supports a strict one-receive-one-send mode within a single loop. If this pattern is violated, such as multiple receives and one send, one receive and multiple sends, or sending before receiving within a single loop, it will result in a deadlock.

async def callback(ctx: CallbackPipeContextType[str]) -> None:
    with ctx as (sender, receiver):
        # multiple receives and one send, dead lock!
        await receiver.receive()
        await receiver.receive()
        await sender.send("foo")

async def callback(ctx: CallbackPipeContextType[str]) -> None:
    with ctx as (sender, receiver):
        # one receive and multiple sends, dead lock!
        async for message in receiver:
            await sender.send("foo")
            await sender.send("bar")

async def callback(ctx: CallbackPipeContextType[str]) -> None:
    with ctx as (sender, receiver):
        # sending before receiving, dead lock!
        await sender.send("foo")
        async for message in receiver:
            await sender.send(message)

Unfortunately, we can't resolve this issue until the underlying logic is rewritten using anyio and memory-object-streams.

There is already a PR for anyio: #34. However, this PR still has many issues, and I currently don't have time to merge it.


Edit:

I just created an issue to track this bug. #42

- bump `typing_extensions` from `4.5.0` to `4.12.0`
- explicitly add `anyio` as a dependency
- fix docs `host` typo
- test message modification using `callback` under normal conditions
- test WebSocket closing when `callback` encounters an exception
- fix broken `httpx` authentication docs link
Comment on lines +123 to +137
## Modify WebSocket message

In some cases, you might want to modify the content of the messages that the WebSocket proxy receives and sends to the client and target server.

In version `0.2.0` of `fastapi-proxy-lib`, we introduced a [`callback API`][fastapi_proxy_lib.core.websocket.ReverseWebSocketProxy.proxy] for `WebSocketProxy` to allow you to do this.

See example: [ReverseWebSocketProxy#with-callback][fastapi_proxy_lib.core.websocket.ReverseWebSocketProxy--with-callback]

Also:

- RFC: [#40](https://github.com/WSH032/fastapi-proxy-lib/issues/40)
- PR: [#41](https://github.com/WSH032/fastapi-proxy-lib/pull/41)

!!!example
The current implementation still has some defects. Read the [callback-implementation][fastapi_proxy_lib.core.websocket.BaseWebSocketProxy.send_request_to_target--callback-implementation] section, or you might accidentally shoot yourself in the foot.
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@IvesAwadi What do you think of this description? Can you provide some specific use cases? This way, I can add them to the documentation.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@IvesAwadi What do you think of this description? Can you provide some specific use cases? This way, I can add them to the documentation.

The description is good and makes sense, took a bit to respond to this (had some issues with my email.)

@WSH032
Copy link
Owner Author

WSH032 commented Jul 23, 2024

@IvesAwadi. This PR is completed. Do you think there are any areas that need improvement? If not, I will merge this PR tomorrow.

As a non-native English speaker, I’m unsure about the quality of the API documentation (including inline docstrings). I would greatly appreciate any suggestions for improvement.

If you want to preview the documentation in advance, you can follow the instructions in the CONTRIBUTING.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[RFC]: add callback api to WebSocketProxy
2 participants