-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
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
New websockets #2158
Conversation
… 9.0, with sans-i/o features. Requires more work.
# Conflicts: # sanic/config.py
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Looks fantastic. I will pull the branch and review some more.
Looking at this from the perspective of websockets, I'm planning to review how you handle connection termination, normal or abnormal, because this is the area where I'm least confident that websockets gives you a nice API. Fortunately you're only doing the server-side and it's more straightforward than the client side. |
Co-authored-by: Adam Hopkins <[email protected]>
Co-authored-by: Adam Hopkins <[email protected]>
Co-authored-by: Adam Hopkins <[email protected]>
@ashleysommer How is this coming? Are we going to be able to get this done this week to sneak it into the release? |
I'm still tuning a few things in websockets, especially around connection termination and error handling, so it may be safest to aim for the following Sanic release. |
Also this branch currently depends on the main branch of websockets, so I need to make a release before you can merge it. |
Good to know. Will plan accordingly |
@ashleysommer I'm working on an integration guide here: python-websockets/websockets#999 This weekend I reworked the implementation to ensure Please note the addition of the
In this case, you'd rather time out after 10 seconds than 2 hours (which I believe is the TCP timeout if you don't do anything) :-) |
@ashleysommer Any update? Are we targeting next release? |
@ashleysommer update? |
@aaugustin I spoke with @ashleysommer and he said he was hoping you'd have some of your changes released soon. Is this the case? We are hoping to target a release next month and I'd love to get this in since there are a few websocket issues to address with current implementation. |
Code & tests for what you need are OK; I'm now working on the docs. I think I can get them done and push a release by the end of August. Would that work for you? |
That would be amazing 😍 |
# Conflicts: # sanic/server.py # sanic/websocket.py # tests/test_routes.py
Incorporated other suggestions made by team
Well, I missed my "end of August" deadline for the next websockets release, but hopeful to get it done this week-end. |
Finished my big refactoring, splitting out the new websockets code into modules as described by @ahopkins above a few months ago. |
I'm not really happy with that websocket requests are handled in the sanic request handler. It still feels like that part of websockets support is kind of hacked in (because it was). At the moment, a websocket request goes:
I understand there isn't much we can do about it at this stage. All requests must be treated as HTTP requests to begin with, and they do still need to go through the router to ensure the request is handled by the correct endpoint handler. And a handshake/upgrade is only done in the handler wrapper, triggered if the handler itself is defined as a websocket handler. I wonder if we can optimize this pipeline so some extent, by attempting to upgrade the request early (if its a websocket upgrade request), maybe have a websocket-handlers-only section of the router to optimize route lookup, and skipping request-middleware altogether (does that even make sense on a websocket request?) we'd then be able to remove the websocket handler wrapper fn too, because the connection would be already upgraded. Ideally I'd like something like this:
But that is a big change |
Remove default values for deprecated websocket parameters
There's still some flake8 issues, looks like the black configuration is not quite compatible with the flake8 rules, in regard to line length. |
Great info on the benchmarks. |
227e483
to
cb495ac
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@ashleysommer Nice work on this. It looks like this is a fantastic upgrade to a constant pain point for support.
You could also benchmark sanic from a client written in websockets. You can open one or many connections from the client script. Here's a benchmarking script you can take inspiration from: https://github.com/aaugustin/websockets/blob/main/experiments/compression/client.py It's benchmarking compression, not throughput, but you get the basic structure for connecting one or several clients to a server and sending traffic. The server can either drop the traffic or echo it, as you like. To stress the server, you can also run multiple copies of the client script. For example, a 6 core machine, I'd try starting 4 clients for 1 server. Then the server will max out 1 CPU core while clients run on 4 CPU cores. This is somewhat valid as long as sanic isn't 4x faster than websockets — else you end up benchmarking the clients instead of the server :-) |
Use Optional[T] instead of union[T,None] Fix mypy type logic errors change "is not None" to truthy checks where appropriate change "is None" to falsy checks were appropriate Add more debug logging when debug mode is on Change to using sanic.logger for debug logging rather than error_logger.
Some changes including suggestions from code reviews:
|
Looks like the remaining Flake8 errors are due to line lengths on long strings (mostly in error and debug messages), but Black says those are fine. |
Black will not know how to break the lines up in the middle of a string. You will need to do that part yourself as elsewhere in the repo: Line 1011 in 1f06902
|
Add some new debug messages when websocket IO is paused and unpaused for flow control Fix websocket example to use app.static()
Final changes:
|
Finally.. all green lights |
@sanic-org/core-devs Anyone else want to do a review on this? |
🎉 |
* Remove unnecessary import in test_constants.py, which also fixes an error on win (#2180) Co-authored-by: Adam Hopkins <[email protected]> * Manually reset the buffer when streaming request body (#2183) * Remove Duplicated Dependencies and PEP 517 Support (#2173) * Remove duplicated dependencies * Specify setuptools as the tool for generating distribution (PEP 517) * Add `isort` to `dev_require` * manage all dependencies in setup.py * Execute `make pretty` * Set usedevelop to true (revert previous change) * Fix the handling of the end of a chunked request. (#2188) * Fix the handling of the end of a chunked request. * Avoid hardcoding final chunk header size. * Add some unit tests for pipeline body reading * Decode bytes for json serialization Co-authored-by: L. Kärkkäinen <[email protected]> Co-authored-by: Adam Hopkins <[email protected]> * Resolve regressions in exceptions (#2181) * Update sanic-routing to fix path issues plus lookahead / lookbehind support (#2178) * Update sanic-routing to fix path issues plus lookahead / lookbehind support * Update setup.py Co-authored-by: Adam Hopkins <[email protected]> Co-authored-by: Adam Hopkins <[email protected]> * style(app,blueprints): add some type hints (#2196) * style(app,blueprints): add some type hints * style(app): option is Any * style(blueprints): url prefix default value is ``""`` * style(app): backward compatible * style(app): backward compatible * style(blueprints): defult is None * style(app): apply code style (black) * Update some CC config (#2199) * Update README.rst * raise exception for `_static_request_handler` unknown exception; add test with custom error (#2195) Co-authored-by: n.feofanov <[email protected]> Co-authored-by: Adam Hopkins <[email protected]> * Change dumps to AnyStr (#2193) * HTTP tests (#2194) * Fix issues with after request handling in HTTP pipelining (#2201) * Clean up after a request is complete, before the next pipelined request. * Limit the size of request body consumed after handler has finished. * Linter error. * Add unit test re: bad headers Co-authored-by: L. Kärkkäinen <[email protected]> Co-authored-by: Adam Hopkins <[email protected]> Co-authored-by: Adam Hopkins <[email protected]> * Update CHANGELOG * Log remote address if available (#2207) * Log remote address if available * Add tests * Fix testing version Co-authored-by: Adam Hopkins <[email protected]> * Fixed for handling exceptions of asgi app call. (#2211) @cansarigol3megawatt Thanks for looking into this and getting the quick turnaround on this. I will 🍒 pick this into the 21.6 branch and get it out a little later tonight. * Signals Integration (#2160) * Update some tests * Resolve #2122 route decorator returning tuple * Use rc sanic-routing version * Update unit tests to <:str> * Minimal working version with some signals implemented * Add more http signals * Update ASGI and change listeners to signals * Allow for dynamic ODE signals * Allow signals to be stacked * Begin tests * Prioritize match_info on keyword argument injection * WIP on tests * Compat with signals * Work through some test coverage * Passing tests * Post linting * Setup proper resets * coverage reporting * Fixes from vltr comments * clear delayed tasks * Fix bad test * rm pycache * uncomment windows tests (#2214) * Add convenience methods to BP groups (#2209) * Fix bug where ws exceptions not being logged (#2213) * Fix bug where ws exceptions not being logged * Fix t\est * Style: add type hints (#2217) * style(routes): add_route argument, return typing * style(listeners): typing * style(views): typing as_view * style(routes): change type hint * style(listeners): change type hint * style(routes): change type hint * add some more types * Change as_view typing * Add some cleaner type annotations Co-authored-by: Adam Hopkins <[email protected]> * Add default messages to SanicExceptions (#2216) * Add default messages to SanicExceptions * Cleaner exception message setting * Copy Blueprints Implementation (#2184) * Accept header parsing (#2200) * Add some tests * docstring * Add accept matching * Add some more tests on matching * Add matching flags for wildcards * Add mathing controls to accept * Limit uvicorn 14 in testing * Add convenience for annotated handlers (#2225) * Split HttpProtocol parts into base SanicProtocol and HTTPProtocol subclass (#2229) * Split HttpProtocol parts into base SanicProtocol and HTTPProtocol subclass. * lint fixes * re-black server.py * Move server.py into its own module (#2230) * Move server.py into its own module * Change monkeypatch path on test_logging.py * Blueprint specific exception handlers (#2208) * Call abort() on sockets after close() to prevent dangling sockets (#2231) * Add ability to return Falsey but not-None from handlers (#2236) * Adds Blueprint Group exception decorator (#2238) * Add exception decorator * Added tests * Fix line too long * Static DIR and FILE resource types (#2244) * Explicit static directive for serving file or dir Co-authored-by: anbuhckr <[email protected]> Co-authored-by: anbuhckr <[email protected]> * Close HTTP loop when connection task cancelled (#2245) * Terminate loop when no transport exists * Add log when closing HTTP loop because of shutdown * Add unit test * New websockets (#2158) * First attempt at new Websockets implementation based on websockets >= 9.0, with sans-i/o features. Requires more work. * Update sanic/websocket.py Co-authored-by: Adam Hopkins <[email protected]> * Update sanic/websocket.py Co-authored-by: Adam Hopkins <[email protected]> * Update sanic/websocket.py Co-authored-by: Adam Hopkins <[email protected]> * wip, update websockets code to new Sans/IO API * Refactored new websockets impl into own modules Incorporated other suggestions made by team * Another round of work on the new websockets impl * Added websocket_timeout support (matching previous/legacy support) * Lots more comments * Incorporated suggested changes from previous round of review * Changed RuntimeError usage to ServerError * Changed SanicException usage to ServerError * Removed some redundant asserts * Change remaining asserts to ServerErrors * Fixed some timeout handling issues * Fixed websocket.close() handling, and made it more robust * Made auto_close task smarter and more error-resilient * Made fail_connection routine smarter and more error-resilient * Further new websockets impl fixes * Update compatibility with Websockets v10 * Track server connection state in a more precise way * Try to handle the shutdown process more gracefully * Add a new end_connection() helper, to use as an alterative to close() or fail_connection() * Kill the auto-close task and keepalive-timeout task when sanic is shutdown * Deprecate WEBSOCKET_READ_LIMIT and WEBSOCKET_WRITE_LIMIT configs, they are not used in this implementation. * Change a warning message to debug level Remove default values for deprecated websocket parameters * Fix flake8 errors * Fix a couple of missed failing tests * remove websocket bench from examples * Integrate suggestions from code reviews Use Optional[T] instead of union[T,None] Fix mypy type logic errors change "is not None" to truthy checks where appropriate change "is None" to falsy checks were appropriate Add more debug logging when debug mode is on Change to using sanic.logger for debug logging rather than error_logger. * Fix long line lengths of debug messages Add some new debug messages when websocket IO is paused and unpaused for flow control Fix websocket example to use app.static() * remove unused import in websocket example app * re-run isort after Flake8 fixes Co-authored-by: Adam Hopkins <[email protected]> Co-authored-by: Adam Hopkins <[email protected]> * Account for BP with exception handler but no routes (#2246) * Don't log "enabled" if auto-reload disabled (#2247) Fixes #2240 Co-authored-by: Adam Hopkins <[email protected]> * Smarter auto fallback (#2162) * Smarter auto fallback * remove config from blueprints * Add tests for error formatting * Add check for proper format * Fix some tests * Add some tests * docstring * Add accept matching * Add some more tests on matching * Fix contains bug, earlier return on MediaType eq * Add matching flags for wildcards * Add mathing controls to accept * Cleanup dev cruft * Add cleanup and resolve OSError relating to test implementation * Fix test * Fix some typos * Some fixes to the new Websockets impl (#2248) * First attempt at new Websockets implementation based on websockets >= 9.0, with sans-i/o features. Requires more work. * Update sanic/websocket.py Co-authored-by: Adam Hopkins <[email protected]> * Update sanic/websocket.py Co-authored-by: Adam Hopkins <[email protected]> * Update sanic/websocket.py Co-authored-by: Adam Hopkins <[email protected]> * wip, update websockets code to new Sans/IO API * Refactored new websockets impl into own modules Incorporated other suggestions made by team * Another round of work on the new websockets impl * Added websocket_timeout support (matching previous/legacy support) * Lots more comments * Incorporated suggested changes from previous round of review * Changed RuntimeError usage to ServerError * Changed SanicException usage to ServerError * Removed some redundant asserts * Change remaining asserts to ServerErrors * Fixed some timeout handling issues * Fixed websocket.close() handling, and made it more robust * Made auto_close task smarter and more error-resilient * Made fail_connection routine smarter and more error-resilient * Further new websockets impl fixes * Update compatibility with Websockets v10 * Track server connection state in a more precise way * Try to handle the shutdown process more gracefully * Add a new end_connection() helper, to use as an alterative to close() or fail_connection() * Kill the auto-close task and keepalive-timeout task when sanic is shutdown * Deprecate WEBSOCKET_READ_LIMIT and WEBSOCKET_WRITE_LIMIT configs, they are not used in this implementation. * Change a warning message to debug level Remove default values for deprecated websocket parameters * Fix flake8 errors * Fix a couple of missed failing tests * remove websocket bench from examples * Integrate suggestions from code reviews Use Optional[T] instead of union[T,None] Fix mypy type logic errors change "is not None" to truthy checks where appropriate change "is None" to falsy checks were appropriate Add more debug logging when debug mode is on Change to using sanic.logger for debug logging rather than error_logger. * Fix long line lengths of debug messages Add some new debug messages when websocket IO is paused and unpaused for flow control Fix websocket example to use app.static() * remove unused import in websocket example app * re-run isort after Flake8 fixes * Some fixes to the new Websockets impl Will throw WebsocketClosed exception instead of ServerException now when attempting to read or write to closed websocket, this makes it easier to catch The various ws.recv() methods now have the ability to raise CancelledError into your websocket handler Fix a niche close-socket negotiation bug Fix bug where http protocol thought the websocket never sent any response. Allow data to still send in some cases after websocket enters CLOSING state. Fix some badly formatted and badly placed comments * allow eof_received to send back data too, if the connection is in CLOSING state Co-authored-by: Adam Hopkins <[email protected]> Co-authored-by: Adam Hopkins <[email protected]> * 21.9 release docs (#2218) * Beging 21.9 release docs * Add PRs to changelog * Change deprecation version * Update logging tests * Bump version * Update changelog * Change dev install command (#2251) Co-authored-by: Zhiwei <[email protected]> Co-authored-by: L. Kärkkäinen <[email protected]> Co-authored-by: L. Kärkkäinen <[email protected]> Co-authored-by: Robert Palmer <[email protected]> Co-authored-by: Ryu JuHeon <[email protected]> Co-authored-by: gluhar2006 <[email protected]> Co-authored-by: n.feofanov <[email protected]> Co-authored-by: Néstor Pérez <[email protected]> Co-authored-by: Can Sarigol <[email protected]> Co-authored-by: Zhiwei <[email protected]> Co-authored-by: YongChan Cho <[email protected]> Co-authored-by: Zhiwei <[email protected]> Co-authored-by: Ashley Sommer <[email protected]> Co-authored-by: anbuhckr <[email protected]> Co-authored-by: anbuhckr <[email protected]>
* First attempt at new Websockets implementation based on websockets >= 9.0, with sans-i/o features. Requires more work. * Update sanic/websocket.py Co-authored-by: Adam Hopkins <[email protected]> * Update sanic/websocket.py Co-authored-by: Adam Hopkins <[email protected]> * Update sanic/websocket.py Co-authored-by: Adam Hopkins <[email protected]> * wip, update websockets code to new Sans/IO API * Refactored new websockets impl into own modules Incorporated other suggestions made by team * Another round of work on the new websockets impl * Added websocket_timeout support (matching previous/legacy support) * Lots more comments * Incorporated suggested changes from previous round of review * Changed RuntimeError usage to ServerError * Changed SanicException usage to ServerError * Removed some redundant asserts * Change remaining asserts to ServerErrors * Fixed some timeout handling issues * Fixed websocket.close() handling, and made it more robust * Made auto_close task smarter and more error-resilient * Made fail_connection routine smarter and more error-resilient * Further new websockets impl fixes * Update compatibility with Websockets v10 * Track server connection state in a more precise way * Try to handle the shutdown process more gracefully * Add a new end_connection() helper, to use as an alterative to close() or fail_connection() * Kill the auto-close task and keepalive-timeout task when sanic is shutdown * Deprecate WEBSOCKET_READ_LIMIT and WEBSOCKET_WRITE_LIMIT configs, they are not used in this implementation. * Change a warning message to debug level Remove default values for deprecated websocket parameters * Fix flake8 errors * Fix a couple of missed failing tests * remove websocket bench from examples * Integrate suggestions from code reviews Use Optional[T] instead of union[T,None] Fix mypy type logic errors change "is not None" to truthy checks where appropriate change "is None" to falsy checks were appropriate Add more debug logging when debug mode is on Change to using sanic.logger for debug logging rather than error_logger. * Fix long line lengths of debug messages Add some new debug messages when websocket IO is paused and unpaused for flow control Fix websocket example to use app.static() * remove unused import in websocket example app * re-run isort after Flake8 fixes Co-authored-by: Adam Hopkins <[email protected]> Co-authored-by: Adam Hopkins <[email protected]>
Resolves #2000
@aaugustin @ahopkins
I've spent another couple of days on it, and its now passing all of the tests, including some other demo applications I've written to stress it out.
It certainly needs cleaning up, and could probably get some efficiency improvements in places too, but otherwise I'm pretty happy with it.
This branch also incorporates another change I've written, that splits the existing
server.HttpProtocol
out into a baseSanicProtocol
class, that contains just all of the connection-handling and transport-layer stuff, andHttpProtocol
that is a subclass ofSanicProtocol
and adds the HTTP-specific handlers on top of that. I'd like the newWebSocketProtocol
to subclassSanicProtocol
but for now it still subclassesHttpProtocol
.