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

Add WebSocketsSansIOProtocol #2540

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion docs/deployment.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ Options:
--loop [auto|asyncio|uvloop] Event loop implementation. [default: auto]
--http [auto|h11|httptools] HTTP protocol implementation. [default:
auto]
--ws [auto|none|websockets|wsproto]
--ws [auto|none|websockets|websockets-sansio|wsproto]
WebSocket protocol implementation.
[default: auto]
--ws-max-size INTEGER WebSocket max size message in bytes
Expand Down
2 changes: 1 addition & 1 deletion docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ Options:
--loop [auto|asyncio|uvloop] Event loop implementation. [default: auto]
--http [auto|h11|httptools] HTTP protocol implementation. [default:
auto]
--ws [auto|none|websockets|wsproto]
--ws [auto|none|websockets|websockets-sansio|wsproto]
WebSocket protocol implementation.
[default: auto]
--ws-max-size INTEGER WebSocket max size message in bytes
Expand Down
3 changes: 3 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,9 @@ filterwarnings = [
"ignore:Uvicorn's native WSGI implementation is deprecated.*:DeprecationWarning",
"ignore: 'cgi' is deprecated and slated for removal in Python 3.13:DeprecationWarning",
"ignore: remove second argument of ws_handler:DeprecationWarning:websockets",
"ignore: websockets.legacy is deprecated.*:DeprecationWarning",
"ignore: websockets.server.WebSocketServerProtocol is deprecated.*:DeprecationWarning",
"ignore: websockets.client.connect is deprecated.*:DeprecationWarning",
]

[tool.coverage.run]
Expand Down
4 changes: 2 additions & 2 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -233,9 +233,9 @@ def unused_tcp_port() -> int:
marks=pytest.mark.skipif(not importlib.util.find_spec("wsproto"), reason="wsproto not installed."),
id="wsproto",
),
pytest.param("uvicorn.protocols.websockets.websockets_impl:WebSocketProtocol", id="websockets"),
pytest.param(
"uvicorn.protocols.websockets.websockets_impl:WebSocketProtocol",
id="websockets",
"uvicorn.protocols.websockets.websockets_sansio_impl:WebSocketsSansIOProtocol", id="websockets-sansio"
),
]
)
Expand Down
10 changes: 6 additions & 4 deletions tests/middleware/test_logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,9 @@ async def app(scope: Scope, receive: ASGIReceiveCallable, send: ASGISendCallable
await send({"type": "http.response.body", "body": b"", "more_body": False})


async def test_trace_logging(caplog: pytest.LogCaptureFixture, logging_config, unused_tcp_port: int):
async def test_trace_logging(
caplog: pytest.LogCaptureFixture, logging_config: dict[str, typing.Any], unused_tcp_port: int
):
config = Config(
app=app,
log_level="trace",
Expand Down Expand Up @@ -91,8 +93,8 @@ async def test_trace_logging_on_http_protocol(http_protocol_cls, caplog, logging

async def test_trace_logging_on_ws_protocol(
ws_protocol_cls: WSProtocol,
caplog,
logging_config,
caplog: pytest.LogCaptureFixture,
logging_config: dict[str, typing.Any],
unused_tcp_port: int,
):
async def websocket_app(scope: Scope, receive: ASGIReceiveCallable, send: ASGISendCallable):
Expand All @@ -104,7 +106,7 @@ async def websocket_app(scope: Scope, receive: ASGIReceiveCallable, send: ASGISe
elif message["type"] == "websocket.disconnect":
break

async def open_connection(url):
async def open_connection(url: str):
async with websockets.client.connect(url) as websocket:
return websocket.open
Copy link
Contributor

Choose a reason for hiding this comment

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

return websocket.state is websockets.protocol.State.OPEN

Cf. https://websockets.readthedocs.io/en/stable/howto/upgrade.html#open-and-closed


Expand Down
1 change: 1 addition & 0 deletions tests/middleware/test_proxy_headers.py
Original file line number Diff line number Diff line change
Expand Up @@ -465,6 +465,7 @@ async def websocket_app(scope: Scope, receive: ASGIReceiveCallable, send: ASGISe
host, port = scope["client"]
await send({"type": "websocket.accept"})
await send({"type": "websocket.send", "text": f"{scheme}://{host}:{port}"})
await send({"type": "websocket.close"})

app_with_middleware = ProxyHeadersMiddleware(websocket_app, trusted_hosts="*")
config = Config(
Expand Down
18 changes: 11 additions & 7 deletions tests/protocols/test_websocket.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
import httpx
import pytest
import websockets
import websockets.asyncio
import websockets.asyncio.client
import websockets.client
import websockets.exceptions
from typing_extensions import TypedDict
Expand Down Expand Up @@ -601,12 +603,9 @@ async def app(scope: Scope, receive: ASGIReceiveCallable, send: ASGISendCallable
await send_accept_task.wait()
disconnect_message = await receive() # type: ignore

response: httpx.Response | None = None

async def websocket_session(uri: str):
nonlocal response
async with httpx.AsyncClient() as client:
response = await client.get(
await client.get(
f"http://127.0.0.1:{unused_tcp_port}",
headers={
"upgrade": "websocket",
Expand All @@ -623,9 +622,6 @@ async def websocket_session(uri: str):
send_accept_task.set()
await asyncio.sleep(0.1)

assert response is not None
assert response.status_code == 500, response.text
assert response.text == "Internal Server Error"
assert disconnect_message == {"type": "websocket.disconnect", "code": 1006}
await task

Expand Down Expand Up @@ -920,6 +916,9 @@ async def websocket_session(url: str):
async def test_server_reject_connection_with_invalid_msg(
ws_protocol_cls: WSProtocol, http_protocol_cls: HTTPProtocol, unused_tcp_port: int
):
if ws_protocol_cls.__name__ == "WebSocketsSansIOProtocol":
pytest.skip("WebSocketsSansIOProtocol sends both start and body messages in one message.")

async def app(scope: Scope, receive: ASGIReceiveCallable, send: ASGISendCallable):
assert scope["type"] == "websocket"
assert "extensions" in scope and "websocket.http.response" in scope["extensions"]
Expand Down Expand Up @@ -951,6 +950,9 @@ async def websocket_session(url: str):
async def test_server_reject_connection_with_missing_body(
ws_protocol_cls: WSProtocol, http_protocol_cls: HTTPProtocol, unused_tcp_port: int
):
if ws_protocol_cls.__name__ == "WebSocketsSansIOProtocol":
pytest.skip("WebSocketsSansIOProtocol sends both start and body messages in one message.")

async def app(scope: Scope, receive: ASGIReceiveCallable, send: ASGISendCallable):
assert scope["type"] == "websocket"
assert "extensions" in scope and "websocket.http.response" in scope["extensions"]
Expand Down Expand Up @@ -986,6 +988,8 @@ async def test_server_multiple_websocket_http_response_start_events(
The server should raise an exception if it sends multiple
websocket.http.response.start events.
"""
if ws_protocol_cls.__name__ == "WebSocketsSansIOProtocol":
pytest.skip("WebSocketsSansIOProtocol sends both start and body messages in one message.")
exception_message: str | None = None

async def app(scope: Scope, receive: ASGIReceiveCallable, send: ASGISendCallable):
Expand Down
3 changes: 2 additions & 1 deletion uvicorn/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
from uvicorn.middleware.wsgi import WSGIMiddleware

HTTPProtocolType = Literal["auto", "h11", "httptools"]
WSProtocolType = Literal["auto", "none", "websockets", "wsproto"]
WSProtocolType = Literal["auto", "none", "websockets", "websockets-sansio", "wsproto"]
LifespanType = Literal["auto", "on", "off"]
LoopSetupType = Literal["none", "auto", "asyncio", "uvloop"]
InterfaceType = Literal["auto", "asgi3", "asgi2", "wsgi"]
Expand All @@ -47,6 +47,7 @@
"auto": "uvicorn.protocols.websockets.auto:AutoWebSocketsProtocol",
"none": None,
"websockets": "uvicorn.protocols.websockets.websockets_impl:WebSocketProtocol",
"websockets-sansio": "uvicorn.protocols.websockets.websockets_sansio_impl:WebSocketsSansIOProtocol",
"wsproto": "uvicorn.protocols.websockets.wsproto_impl:WSProtocol",
}
LIFESPAN: dict[LifespanType, str] = {
Expand Down
Loading
Loading