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

New websockets #2158

Merged
merged 22 commits into from
Sep 29, 2021
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
190ce7b
First attempt at new Websockets implementation based on websockets >=…
ashleysommer Jun 8, 2021
4b814ec
Merge remote-tracking branch 'origin/main' into new_websockets
ashleysommer Jun 9, 2021
4e9d984
Update sanic/websocket.py
ashleysommer Jun 16, 2021
2c8f750
Update sanic/websocket.py
ashleysommer Jun 16, 2021
e2d0198
Update sanic/websocket.py
ashleysommer Jun 16, 2021
e6379ea
Merge remote-tracking branch 'origin/main' into new_websockets
ashleysommer Aug 31, 2021
98785e7
Merge remote-tracking branch 'ashleysommer_github/new_websockets' int…
ashleysommer Sep 1, 2021
cc2082c
wip, update websockets code to new Sans/IO API
ashleysommer Sep 1, 2021
e687517
Merge branch 'main' into new_websockets
ashleysommer Sep 1, 2021
2436780
Refactored new websockets impl into own modules
ashleysommer Sep 1, 2021
b24e914
Merge remote-tracking branch 'origin/main' into new_websockets
ashleysommer Sep 15, 2021
aea3538
Another round of work on the new websockets impl
ashleysommer Sep 15, 2021
13d49b8
Further new websockets impl fixes
ashleysommer Sep 15, 2021
5f6cc06
Change a warning message to debug level
ashleysommer Sep 23, 2021
37d462a
Fix flake8 errors
ashleysommer Sep 23, 2021
cb495ac
Fix a couple of missed failing tests
ashleysommer Sep 23, 2021
955d515
remove websocket bench from examples
ashleysommer Sep 26, 2021
19c98b9
Integrate suggestions from code reviews
ashleysommer Sep 26, 2021
cd26e00
Merge branch 'main' into new_websockets
ahopkins Sep 27, 2021
791b693
Fix long line lengths of debug messages
ashleysommer Sep 28, 2021
f264477
remove unused import in websocket example app
ashleysommer Sep 28, 2021
2162854
re-run isort after Flake8 fixes
ashleysommer Sep 28, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
15 changes: 2 additions & 13 deletions sanic/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,8 @@
from sanic.server import serve, serve_multiple, serve_single
from sanic.signals import Signal, SignalRouter
from sanic.touchup import TouchUp, TouchUpMeta
from sanic.websocket import ConnectionClosed, WebSocketProtocol
from sanic.server.protocols.websocket_protocol import WebSocketProtocol
from sanic.server.websockets.impl import ConnectionClosed


class Sanic(BaseSanic, metaclass=TouchUpMeta):
Expand Down Expand Up @@ -871,23 +872,11 @@ async def handle_request(self, request: Request): # no cov
async def _websocket_handler(
self, handler, request, *args, subprotocols=None, **kwargs
):
request.app = self
if not getattr(handler, "__blueprintname__", False):
request._name = handler.__name__
else:
request._name = (
getattr(handler, "__blueprintname__", "") + handler.__name__
)

pass

if self.asgi:
ws = request.transport.get_websocket_connection()
await ws.accept(subprotocols)
else:
protocol = request.transport.get_protocol()
protocol.app = self

ws = await protocol.websocket_handshake(request, subprotocols)

# schedule the application handler
Expand Down
2 changes: 1 addition & 1 deletion sanic/asgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from sanic.models.asgi import ASGIReceive, ASGIScope, ASGISend, MockTransport
from sanic.request import Request
from sanic.server import ConnInfo
from sanic.websocket import WebSocketConnection
from sanic.server.websockets.connection import WebSocketConnection


class Lifespan:
Expand Down
2 changes: 0 additions & 2 deletions sanic/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@
"REQUEST_MAX_SIZE": 100000000, # 100 megabytes
"REQUEST_TIMEOUT": 60, # 60 seconds
"RESPONSE_TIMEOUT": 60, # 60 seconds
"WEBSOCKET_MAX_QUEUE": 32,
"WEBSOCKET_MAX_SIZE": 2 ** 20, # 1 megabyte
"WEBSOCKET_PING_INTERVAL": 20,
"WEBSOCKET_PING_TIMEOUT": 20,
Expand All @@ -62,7 +61,6 @@ class Config(dict):
REQUEST_MAX_SIZE: int
REQUEST_TIMEOUT: int
RESPONSE_TIMEOUT: int
WEBSOCKET_MAX_QUEUE: int
WEBSOCKET_MAX_SIZE: int
WEBSOCKET_PING_INTERVAL: int
WEBSOCKET_PING_TIMEOUT: int
Expand Down
7 changes: 5 additions & 2 deletions sanic/mixins/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,8 +121,11 @@ def decorator(handler):
"Expected either string or Iterable of host strings, "
"not %s" % host
)

if isinstance(subprotocols, (list, tuple, set)):
if isinstance(subprotocols, list):
# Ordered subprotocols, maintain order
subprotocols = tuple(subprotocols)
if isinstance(subprotocols, set):
ahopkins marked this conversation as resolved.
Show resolved Hide resolved
# subprotocol is unordered, keep it unordered
subprotocols = frozenset(subprotocols)

route = FutureRoute(
Expand Down
2 changes: 1 addition & 1 deletion sanic/models/asgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from typing import Any, Awaitable, Callable, MutableMapping, Optional, Union

from sanic.exceptions import InvalidUsage
from sanic.websocket import WebSocketConnection
from sanic.server.websockets.connection import WebSocketConnection


ASGIScope = MutableMapping[str, Any]
Expand Down
113 changes: 113 additions & 0 deletions sanic/server/protocols/websocket_protocol.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
from typing import (
Optional,
Union,
Sequence,
TYPE_CHECKING
)

from httptools import HttpParserUpgrade # type: ignore
from websockets.server import ServerConnection
from websockets.connection import OPEN, CLOSING, CLOSED

from sanic.exceptions import SanicException
from sanic.server import HttpProtocol
from sanic.log import error_logger
from ..websockets.impl import WebsocketImplProtocol

if TYPE_CHECKING:
from websockets import http11

class WebSocketProtocol(HttpProtocol):
def __init__(
self,
*args,
websocket_timeout=10,
websocket_max_size=None,
websocket_max_queue=None,
websocket_read_limit=2 ** 16,
websocket_write_limit=2 ** 16,
websocket_ping_interval=20,
websocket_ping_timeout=20,
**kwargs,
):
super().__init__(*args, **kwargs)
self.websocket = None # type: Union[None, WebsocketImplProtocol]
ahopkins marked this conversation as resolved.
Show resolved Hide resolved
# self.app = None
ahopkins marked this conversation as resolved.
Show resolved Hide resolved
self.websocket_timeout = websocket_timeout
self.websocket_max_size = websocket_max_size
if websocket_max_queue is not None and int(websocket_max_queue) > 0:
error_logger.warning(DeprecationWarning("websocket_max_queue is no longer used. No websocket message queueing is implemented."))
self.websocket_read_limit = websocket_read_limit
self.websocket_write_limit = websocket_write_limit
self.websocket_ping_interval = websocket_ping_interval
self.websocket_ping_timeout = websocket_ping_timeout

def connection_lost(self, exc):
if self.websocket is not None:
ahopkins marked this conversation as resolved.
Show resolved Hide resolved
self.websocket.connection_lost(exc)
super().connection_lost(exc)

def data_received(self, data):
if self.websocket is not None:
ahopkins marked this conversation as resolved.
Show resolved Hide resolved
self.websocket.data_received(data)
else:
# Pass it to HttpProtocol handler first
# That will (hopefully) upgrade it to a websocket.
super().data_received(data)

def eof_received(self) -> Optional[bool]:
if self.websocket is not None:
return self.websocket.eof_received()
else:
return False

def close(self, timeout: Optional[float] = None):
# Called by HttpProtocol at the end of connection_task
# If we've upgraded to websocket, we do our own closing
if self.websocket is not None:
self.websocket.fail_connection(1001)
else:
super().close()

def close_if_idle(self):
# Called by Sanic Server when shutting down
# If we've upgraded to websocket, shut it down
if self.websocket is not None:
if self.websocket.connection.state in (CLOSING, CLOSED):
return True
else:
return self.websocket.fail_connection(1001)
else:
return super().close_if_idle()

async def websocket_handshake(self, request, subprotocols=Optional[Sequence[str]]):
# let the websockets package do the handshake with the client
headers = {"Upgrade": "websocket", "Connection": "Upgrade"}
try:
if subprotocols is not None:
# subprotocols can be a set or frozenset, but ServerConnection needs a list
subprotocols = list(subprotocols)
ws_conn = ServerConnection(max_size=self.websocket_max_size, subprotocols=subprotocols,
state=OPEN, logger=error_logger)
resp: "http11.Response" = ws_conn.accept(request)
ahopkins marked this conversation as resolved.
Show resolved Hide resolved
except Exception as exc:
msg = (
"Failed to open a WebSocket connection.\n"
"See server log for more information.\n"
)
raise SanicException(msg, status_code=500)
ahopkins marked this conversation as resolved.
Show resolved Hide resolved
if 100 <= resp.status_code <= 299:
rbytes = b"".join([b"HTTP/1.1 ", b'%d' % resp.status_code, b" ", resp.reason_phrase.encode("utf-8"), b"\r\n"])
ahopkins marked this conversation as resolved.
Show resolved Hide resolved
for k, v in resp.headers.items():
rbytes += k.encode("utf-8") + b": " + v.encode("utf-8") + b"\r\n"
if resp.body:
rbytes += b"\r\n" + resp.body + b"\r\n"
rbytes += b"\r\n"
await super().send(rbytes)
ahopkins marked this conversation as resolved.
Show resolved Hide resolved
else:
raise SanicException(resp.body, resp.status_code)

self.websocket = WebsocketImplProtocol(ws_conn, ping_interval=self.websocket_ping_interval, ping_timeout=self.websocket_ping_timeout)
loop = request.transport.loop if hasattr(request, "transport") and hasattr(request.transport, "loop") else None
await self.websocket.connection_made(self, loop=loop)
return self.websocket
3 changes: 1 addition & 2 deletions sanic/server/runners.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ def serve(
coros = []
for conn in connections:
if hasattr(conn, "websocket") and conn.websocket:
coros.append(conn.websocket.close_connection())
coros.append(conn.websocket.close(code=1001))
else:
conn.abort()

Expand Down Expand Up @@ -278,7 +278,6 @@ def _build_protocol_kwargs(
if hasattr(protocol, "websocket_handshake"):
return {
"websocket_max_size": config.WEBSOCKET_MAX_SIZE,
"websocket_max_queue": config.WEBSOCKET_MAX_QUEUE,
"websocket_read_limit": config.WEBSOCKET_READ_LIMIT,
"websocket_write_limit": config.WEBSOCKET_WRITE_LIMIT,
"websocket_ping_timeout": config.WEBSOCKET_PING_TIMEOUT,
Expand Down
Empty file.
70 changes: 70 additions & 0 deletions sanic/server/websockets/connection.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
from typing import Optional, List, Callable, Awaitable, Union, Dict, MutableMapping, Any

ASIMessage = MutableMapping[str, Any]

class WebSocketConnection:
"""
This is for ASGI Connections.
It provides an interface similar to WebsocketProtocol, but
sends/receives over an ASGI connection.
"""
# TODO
# - Implement ping/pong
ahopkins marked this conversation as resolved.
Show resolved Hide resolved

def __init__(
self,
send: Callable[[ASIMessage], Awaitable[None]],
receive: Callable[[], Awaitable[ASIMessage]],
subprotocols: Optional[List[str]] = None,
) -> None:
self._send = send
self._receive = receive
self._subprotocols = subprotocols or []

async def send(self, data: Union[str, bytes], *args, **kwargs) -> None:
message: Dict[str, Union[str, bytes]] = {"type": "websocket.send"}
ahopkins marked this conversation as resolved.
Show resolved Hide resolved

if isinstance(data, bytes):
message.update({"bytes": data})
else:
message.update({"text": str(data)})

await self._send(message)

async def recv(self, *args, **kwargs) -> Optional[str]:
message = await self._receive()

if message["type"] == "websocket.receive":
return message["text"]
elif message["type"] == "websocket.disconnect":
pass

return None

receive = recv

async def accept(self, subprotocols: Optional[List[str]] = None) -> None:
subprotocol = None
if subprotocols:
for subp in subprotocols:
if subp in self.subprotocols:
subprotocol = subp
break

await self._send(
{
"type": "websocket.accept",
"subprotocol": subprotocol,
}
)

async def close(self, code: int = 1000, reason: str = "") -> None:
pass

@property
def subprotocols(self):
return self._subprotocols

@subprotocols.setter
def subprotocols(self, subprotocols: Optional[List[str]] = None):
self._subprotocols = subprotocols or []