summaryrefslogtreecommitdiff
path: root/venv/lib/python3.11/site-packages/litestar/connection/websocket.py
blob: 0c7bc04404b6e6d1b2596c50ad851246a8dbe142 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
from __future__ import annotations

from typing import TYPE_CHECKING, Any, AsyncGenerator, Generic, Literal, cast, overload

from litestar.connection.base import (
    ASGIConnection,
    AuthT,
    StateT,
    UserT,
    empty_receive,
    empty_send,
)
from litestar.datastructures.headers import Headers
from litestar.exceptions import WebSocketDisconnect
from litestar.serialization import decode_json, decode_msgpack, default_serializer, encode_json, encode_msgpack
from litestar.status_codes import WS_1000_NORMAL_CLOSURE

__all__ = ("WebSocket",)


if TYPE_CHECKING:
    from litestar.handlers.websocket_handlers import WebsocketRouteHandler  # noqa: F401
    from litestar.types import Message, Serializer, WebSocketScope
    from litestar.types.asgi_types import (
        Receive,
        ReceiveMessage,
        Scope,
        Send,
        WebSocketAcceptEvent,
        WebSocketCloseEvent,
        WebSocketDisconnectEvent,
        WebSocketMode,
        WebSocketReceiveEvent,
        WebSocketSendEvent,
    )

DISCONNECT_MESSAGE = "connection is disconnected"


class WebSocket(Generic[UserT, AuthT, StateT], ASGIConnection["WebsocketRouteHandler", UserT, AuthT, StateT]):
    """The Litestar WebSocket class."""

    __slots__ = ("connection_state",)

    scope: WebSocketScope  # pyright: ignore
    """The ASGI scope attached to the connection."""
    receive: Receive
    """The ASGI receive function."""
    send: Send
    """The ASGI send function."""

    def __init__(self, scope: Scope, receive: Receive = empty_receive, send: Send = empty_send) -> None:
        """Initialize ``WebSocket``.

        Args:
            scope: The ASGI connection scope.
            receive: The ASGI receive function.
            send: The ASGI send function.
        """
        super().__init__(scope, self.receive_wrapper(receive), self.send_wrapper(send))
        self.connection_state: Literal["init", "connect", "receive", "disconnect"] = "init"

    def receive_wrapper(self, receive: Receive) -> Receive:
        """Wrap ``receive`` to set 'self.connection_state' and validate events.

        Args:
            receive: The ASGI receive function.

        Returns:
            An ASGI receive function.
        """

        async def wrapped_receive() -> ReceiveMessage:
            if self.connection_state == "disconnect":
                raise WebSocketDisconnect(detail=DISCONNECT_MESSAGE)
            message = await receive()
            if message["type"] == "websocket.connect":
                self.connection_state = "connect"
            elif message["type"] == "websocket.receive":
                self.connection_state = "receive"
            else:
                self.connection_state = "disconnect"
            return message

        return wrapped_receive

    def send_wrapper(self, send: Send) -> Send:
        """Wrap ``send`` to ensure that state is not disconnected.

        Args:
            send: The ASGI send function.

        Returns:
            An ASGI send function.
        """

        async def wrapped_send(message: Message) -> None:
            if self.connection_state == "disconnect":
                raise WebSocketDisconnect(detail=DISCONNECT_MESSAGE)  # pragma: no cover
            await send(message)

        return wrapped_send

    async def accept(
        self,
        subprotocols: str | None = None,
        headers: Headers | dict[str, Any] | list[tuple[bytes, bytes]] | None = None,
    ) -> None:
        """Accept the incoming connection. This method should be called before receiving data.

        Args:
            subprotocols: Websocket sub-protocol to use.
            headers: Headers to set on the data sent.

        Returns:
            None
        """
        if self.connection_state == "init":
            await self.receive()
            _headers: list[tuple[bytes, bytes]] = headers if isinstance(headers, list) else []

            if isinstance(headers, dict):
                _headers = Headers(headers=headers).to_header_list()

            if isinstance(headers, Headers):
                _headers = headers.to_header_list()

            event: WebSocketAcceptEvent = {
                "type": "websocket.accept",
                "subprotocol": subprotocols,
                "headers": _headers,
            }
            await self.send(event)

    async def close(self, code: int = WS_1000_NORMAL_CLOSURE, reason: str | None = None) -> None:
        """Send an 'websocket.close' event.

        Args:
            code: Status code.
            reason: Reason for closing the connection

        Returns:
            None
        """
        event: WebSocketCloseEvent = {"type": "websocket.close", "code": code, "reason": reason or ""}
        await self.send(event)

    @overload
    async def receive_data(self, mode: Literal["text"]) -> str: ...

    @overload
    async def receive_data(self, mode: Literal["binary"]) -> bytes: ...

    async def receive_data(self, mode: WebSocketMode) -> str | bytes:
        """Receive an 'websocket.receive' event and returns the data stored on it.

        Args:
            mode: The respective event key to use.

        Returns:
            The event's data.
        """
        if self.connection_state == "init":
            await self.accept()
        event = cast("WebSocketReceiveEvent | WebSocketDisconnectEvent", await self.receive())
        if event["type"] == "websocket.disconnect":
            raise WebSocketDisconnect(detail="disconnect event", code=event["code"])
        return event.get("text") or "" if mode == "text" else event.get("bytes") or b""

    @overload
    def iter_data(self, mode: Literal["text"]) -> AsyncGenerator[str, None]: ...

    @overload
    def iter_data(self, mode: Literal["binary"]) -> AsyncGenerator[bytes, None]: ...

    async def iter_data(self, mode: WebSocketMode = "text") -> AsyncGenerator[str | bytes, None]:
        """Continuously receive data and yield it

        Args:
            mode: Socket mode to use. Either ``text`` or ``binary``
        """
        try:
            while True:
                yield await self.receive_data(mode)
        except WebSocketDisconnect:
            pass

    async def receive_text(self) -> str:
        """Receive data as text.

        Returns:
            A string.
        """
        return await self.receive_data(mode="text")

    async def receive_bytes(self) -> bytes:
        """Receive data as bytes.

        Returns:
            A byte-string.
        """
        return await self.receive_data(mode="binary")

    async def receive_json(self, mode: WebSocketMode = "text") -> Any:
        """Receive data and decode it as JSON.

        Args:
            mode: Either ``text`` or ``binary``.

        Returns:
            An arbitrary value
        """
        data = await self.receive_data(mode=mode)
        return decode_json(value=data, type_decoders=self.route_handler.resolve_type_decoders())

    async def receive_msgpack(self) -> Any:
        """Receive data and decode it as MessagePack.

        Note that since MessagePack is a binary format, this method will always receive
        data in ``binary`` mode.

        Returns:
            An arbitrary value
        """
        data = await self.receive_data(mode="binary")
        return decode_msgpack(value=data, type_decoders=self.route_handler.resolve_type_decoders())

    async def iter_json(self, mode: WebSocketMode = "text") -> AsyncGenerator[Any, None]:
        """Continuously receive data and yield it, decoding it as JSON in the process.

        Args:
            mode: Socket mode to use. Either ``text`` or ``binary``
        """
        async for data in self.iter_data(mode):
            yield decode_json(value=data, type_decoders=self.route_handler.resolve_type_decoders())

    async def iter_msgpack(self) -> AsyncGenerator[Any, None]:
        """Continuously receive data and yield it, decoding it as MessagePack in the
        process.

        Note that since MessagePack is a binary format, this method will always receive
        data in ``binary`` mode.

        """
        async for data in self.iter_data(mode="binary"):
            yield decode_msgpack(value=data, type_decoders=self.route_handler.resolve_type_decoders())

    async def send_data(self, data: str | bytes, mode: WebSocketMode = "text", encoding: str = "utf-8") -> None:
        """Send a 'websocket.send' event.

        Args:
            data: Data to send.
            mode: The respective event key to use.
            encoding: Encoding to use when converting bytes / str.

        Returns:
            None
        """
        if self.connection_state == "init":  # pragma: no cover
            await self.accept()
        event: WebSocketSendEvent = {"type": "websocket.send", "bytes": None, "text": None}
        if mode == "binary":
            event["bytes"] = data if isinstance(data, bytes) else data.encode(encoding)
        else:
            event["text"] = data if isinstance(data, str) else data.decode(encoding)
        await self.send(event)

    @overload
    async def send_text(self, data: bytes, encoding: str = "utf-8") -> None: ...

    @overload
    async def send_text(self, data: str) -> None: ...

    async def send_text(self, data: str | bytes, encoding: str = "utf-8") -> None:
        """Send data using the ``text`` key of the send event.

        Args:
            data: Data to send
            encoding: Encoding to use for binary data.

        Returns:
            None
        """
        await self.send_data(data=data, encoding=encoding)

    @overload
    async def send_bytes(self, data: bytes) -> None: ...

    @overload
    async def send_bytes(self, data: str, encoding: str = "utf-8") -> None: ...

    async def send_bytes(self, data: str | bytes, encoding: str = "utf-8") -> None:
        """Send data using the ``bytes`` key of the send event.

        Args:
            data: Data to send
            encoding: Encoding to use for binary data.

        Returns:
            None
        """
        await self.send_data(data=data, mode="binary", encoding=encoding)

    async def send_json(
        self,
        data: Any,
        mode: WebSocketMode = "text",
        encoding: str = "utf-8",
        serializer: Serializer = default_serializer,
    ) -> None:
        """Send data as JSON.

        Args:
            data: A value to serialize.
            mode: Either ``text`` or ``binary``.
            encoding: Encoding to use for binary data.
            serializer: A serializer function.

        Returns:
            None
        """
        await self.send_data(data=encode_json(data, serializer), mode=mode, encoding=encoding)

    async def send_msgpack(
        self,
        data: Any,
        encoding: str = "utf-8",
        serializer: Serializer = default_serializer,
    ) -> None:
        """Send data as MessagePack.

        Note that since MessagePack is a binary format, this method will always send
        data in ``binary`` mode.

        Args:
            data: A value to serialize.
            encoding: Encoding to use for binary data.
            serializer: A serializer function.

        Returns:
            None
        """
        await self.send_data(data=encode_msgpack(data, serializer), mode="binary", encoding=encoding)