Debian Codegraph @

src/websockets/sync/router.py

raw
1 from __future__ import annotations
2
3 import http
4 import ssl as ssl_module
5 import urllib.parse
6 from typing import Any, Callable, Literal
7
8 from ..http11 import Request, Response
9 from ..typing import PathLike
10 from .server import Server, ServerConnection, serve
11
12
13 __all__ = ["route", "unix_route", "Router"]
14
15
16 try:
17 from werkzeug.exceptions import NotFound
18 from werkzeug.routing import Map, RequestRedirect
19
20 except ImportError:
21
22 def route(
23 url_map: Map,
24 *args: Any,
25 server_name: str | None = None,
26 ssl: ssl_module.SSLContext | Literal[True] | None = None,
27 create_router: type[Router] | None = None,
28 **kwargs: Any,
29 ) -> Server:
30 raise ImportError("route() requires werkzeug")
31
32 def unix_route(
33 url_map: Map,
34 path: PathLike | None = None,
35 **kwargs: Any,
36 ) -> Server:
37 raise ImportError("unix_route() requires werkzeug")
38
39 else:
40
41 def route(
42 url_map: Map,
43 *args: Any,
44 server_name: str | None = None,
45 ssl: ssl_module.SSLContext | Literal[True] | None = None,
46 create_router: type[Router] | None = None,
47 **kwargs: Any,
48 ) -> Server:
49 """
50 Create a WebSocket server dispatching connections to different handlers.
51
52 This feature requires the third-party library `werkzeug`_:
53
54 .. code-block:: console
55
56 $ pip install werkzeug
57
58 .. _werkzeug: https://werkzeug.palletsprojects.com/
59
60 :func:`route` accepts the same arguments as
61 :func:`~websockets.sync.server.serve`, except as described below.
62
63 The first argument is a :class:`werkzeug.routing.Map` that maps URL patterns
64 to connection handlers. In addition to the connection, handlers receive
65 parameters captured in the URL as keyword arguments.
66
67 Here's an example::
68
69
70 from websockets.sync.router import route
71 from werkzeug.routing import Map, Rule
72
73 def channel_handler(websocket, channel_id):
74 ...
75
76 url_map = Map([
77 Rule("/channel/<uuid:channel_id>", endpoint=channel_handler),
78 ...
79 ])
80
81 with route(url_map, ...) as server:
82 server.serve_forever()
83
84 Refer to the documentation of :mod:`werkzeug.routing` for details.
85
86 If you define redirects with ``Rule(..., redirect_to=...)`` in the URL map,
87 when the server runs behind a reverse proxy that modifies the ``Host``
88 header or terminates TLS, you need additional configuration:
89
90 * Set ``server_name`` to the name of the server as seen by clients. When
91 not provided, websockets uses the value of the ``Host`` header.
92
93 * Set ``ssl=True`` to generate ``wss://`` URIs without enabling TLS.
94 Under the hood, this bind the URL map with a ``url_scheme`` of
95 ``wss://`` instead of ``ws://``.
96
97 There is no need to specify ``websocket=True`` in each rule. It is added
98 automatically.
99
100 Args:
101 url_map: Mapping of URL patterns to connection handlers.
102 server_name: Name of the server as seen by clients. If :obj:`None`,
103 websockets uses the value of the ``Host`` header.
104 ssl: Configuration for enabling TLS on the connection. Set it to
105 :obj:`True` if a reverse proxy terminates TLS connections.
106 create_router: Factory for the :class:`Router` dispatching requests to
107 handlers. Set it to a wrapper or a subclass to customize routing.
108
109 """
110 url_scheme = "ws" if ssl is None else "wss"
111 if ssl is not True and ssl is not None:
112 kwargs["ssl"] = ssl
113
114 if create_router is None:
115 create_router = Router
116
117 router = create_router(url_map, server_name, url_scheme)
118
119 _process_request: (
120 Callable[
121 [ServerConnection, Request],
122 Response | None,
123 ]
124 | None
125 ) = kwargs.pop("process_request", None)
126 if _process_request is None:
127 process_request: Callable[
128 [ServerConnection, Request],
129 Response | None,
130 ] = router.route_request
131 else:
132
133 def process_request(
134 connection: ServerConnection, request: Request
135 ) -> Response | None:
136 response = _process_request(connection, request)
137 if response is not None:
138 return response
139 return router.route_request(connection, request)
140
141 return serve(router.handler, *args, process_request=process_request, **kwargs)
142
143 def unix_route(
144 url_map: Map,
145 path: PathLike | None = None,
146 **kwargs: Any,
147 ) -> Server:
148 """
149 Create a WebSocket Unix server dispatching connections to different handlers.
150
151 :func:`unix_route` combines the behaviors of :func:`route` and
152 :func:`~websockets.sync.server.unix_serve`.
153
154 Args:
155 url_map: Mapping of URL patterns to connection handlers.
156 path: File system path to the Unix socket.
157
158 """
159 return route(url_map, unix=True, path=path, **kwargs)
160
161
162 class Router:
163 """WebSocket router supporting :func:`route`."""
164
165 def __init__(
166 self,
167 url_map: Map,
168 server_name: str | None = None,
169 url_scheme: str = "ws",
170 ) -> None:
171 self.url_map = url_map
172 self.server_name = server_name
173 self.url_scheme = url_scheme
174 for rule in self.url_map.iter_rules():
175 rule.websocket = True
176
177 def get_server_name(self, connection: ServerConnection, request: Request) -> str:
178 if self.server_name is None:
179 return request.headers["Host"]
180 else:
181 return self.server_name
182
183 def redirect(self, connection: ServerConnection, url: str) -> Response:
184 response = connection.respond(http.HTTPStatus.FOUND, f"Found at {url}")
185 response.headers["Location"] = url
186 return response
187
188 def not_found(self, connection: ServerConnection) -> Response:
189 return connection.respond(http.HTTPStatus.NOT_FOUND, "Not Found")
190
191 def route_request(
192 self, connection: ServerConnection, request: Request
193 ) -> Response | None:
194 """Route incoming request."""
195 url_map_adapter = self.url_map.bind(
196 server_name=self.get_server_name(connection, request),
197 url_scheme=self.url_scheme,
198 )
199 try:
200 parsed = urllib.parse.urlparse(request.path)
201 handler, kwargs = url_map_adapter.match(
202 path_info=parsed.path,
203 query_args=parsed.query,
204 )
205 except RequestRedirect as redirect:
206 return self.redirect(connection, redirect.new_url)
207 except NotFound:
208 return self.not_found(connection)
209 connection.handler, connection.handler_kwargs = handler, kwargs
210 return None
211
212 def handler(self, connection: ServerConnection) -> None:
213 """Handle a connection."""
214 return connection.handler(connection, **connection.handler_kwargs)