Debian Codegraph @

src/websockets/trio/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, Awaitable, Callable, Literal
7
8 import trio
9
10 from ..http11 import Request, Response
11 from .server import Server, ServerConnection, serve
12
13
14 __all__ = ["route", "Router"]
15
16
17 try:
18 from werkzeug.exceptions import NotFound
19 from werkzeug.routing import Map, RequestRedirect
20
21 except ImportError:
22
23 async def route(
24 url_map: Map,
25 *args: Any,
26 server_name: str | None = None,
27 ssl: ssl_module.SSLContext | Literal[True] | None = None,
28 create_router: type[Router] | None = None,
29 task_status: trio.TaskStatus[Server] = trio.TASK_STATUS_IGNORED,
30 **kwargs: Any,
31 ) -> None:
32 raise ImportError("route() requires werkzeug")
33
34 else:
35
36 async def route(
37 url_map: Map,
38 *args: Any,
39 server_name: str | None = None,
40 ssl: ssl_module.SSLContext | Literal[True] | None = None,
41 create_router: type[Router] | None = None,
42 task_status: trio.TaskStatus[Server] = trio.TASK_STATUS_IGNORED,
43 **kwargs: Any,
44 ) -> None:
45 """
46 Create a WebSocket server dispatching connections to different handlers.
47
48 This feature requires the third-party library `werkzeug`_:
49
50 .. code-block:: console
51
52 $ pip install werkzeug
53
54 .. _werkzeug: https://werkzeug.palletsprojects.com/
55
56 :func:`route` accepts the same arguments as
57 :func:`~websockets.trio.server.serve`, except as described below.
58
59 The first argument is a :class:`werkzeug.routing.Map` that maps URL patterns
60 to connection handlers. In addition to the connection, handlers receive
61 parameters captured in the URL as keyword arguments.
62
63 Here's an example::
64
65 from websockets.trio.router import route
66 from werkzeug.routing import Map, Rule
67
68 async def channel_handler(websocket, channel_id):
69 ...
70
71 url_map = Map([
72 Rule("/channel/<uuid:channel_id>", endpoint=channel_handler),
73 ...
74 ])
75
76 # set this event to exit the server
77 stop = trio.Event()
78
79 with trio.open_nursery() as nursery:
80 server = await nursery.start(route, url_map, ...)
81 async with server:
82 await stop.wait()
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 task_status: For compatibility with :meth:`nursery.start
109 <trio.Nursery.start>`.
110
111 """
112 url_scheme = "ws" if ssl is None else "wss"
113 if ssl is not True and ssl is not None:
114 kwargs["ssl"] = ssl
115
116 if create_router is None:
117 create_router = Router
118
119 router = create_router(url_map, server_name, url_scheme)
120
121 _process_request: (
122 Callable[
123 [ServerConnection, Request],
124 Awaitable[Response | None] | Response | None,
125 ]
126 | None
127 ) = kwargs.pop("process_request", None)
128 if _process_request is None:
129 process_request: Callable[
130 [ServerConnection, Request],
131 Awaitable[Response | None] | Response | None,
132 ] = router.route_request
133 else:
134
135 async def process_request(
136 connection: ServerConnection,
137 request: Request,
138 ) -> Response | None:
139 response = _process_request(connection, request)
140 if isinstance(response, Awaitable):
141 response = await response
142 if response is not None:
143 return response
144 return router.route_request(connection, request)
145
146 return await serve(
147 router.handler,
148 *args,
149 process_request=process_request,
150 task_status=task_status,
151 **kwargs,
152 )
153
154
155 class Router:
156 """WebSocket router supporting :func:`route`."""
157
158 def __init__(
159 self,
160 url_map: Map,
161 server_name: str | None = None,
162 url_scheme: str = "ws",
163 ) -> None:
164 self.url_map = url_map
165 self.server_name = server_name
166 self.url_scheme = url_scheme
167 for rule in self.url_map.iter_rules():
168 rule.websocket = True
169
170 def get_server_name(self, connection: ServerConnection, request: Request) -> str:
171 if self.server_name is None:
172 return request.headers["Host"]
173 else:
174 return self.server_name
175
176 def redirect(self, connection: ServerConnection, url: str) -> Response:
177 response = connection.respond(http.HTTPStatus.FOUND, f"Found at {url}")
178 response.headers["Location"] = url
179 return response
180
181 def not_found(self, connection: ServerConnection) -> Response:
182 return connection.respond(http.HTTPStatus.NOT_FOUND, "Not Found")
183
184 def route_request(
185 self, connection: ServerConnection, request: Request
186 ) -> Response | None:
187 """Route incoming request."""
188 url_map_adapter = self.url_map.bind(
189 server_name=self.get_server_name(connection, request),
190 url_scheme=self.url_scheme,
191 )
192 try:
193 parsed = urllib.parse.urlparse(request.path)
194 handler, kwargs = url_map_adapter.match(
195 path_info=parsed.path,
196 query_args=parsed.query,
197 )
198 except RequestRedirect as redirect:
199 return self.redirect(connection, redirect.new_url)
200 except NotFound:
201 return self.not_found(connection)
202 connection.handler, connection.handler_kwargs = handler, kwargs
203 return None
204
205 async def handler(self, connection: ServerConnection) -> None:
206 """Handle a connection."""
207 return await connection.handler(connection, **connection.handler_kwargs)