Send ASGI websocket messages, ensuring valid state transitions.
(self, message: Message)
| 57 | raise RuntimeError('Cannot call "receive" once a disconnect message has been received.') |
| 58 | |
| 59 | async def send(self, message: Message) -> None: |
| 60 | """ |
| 61 | Send ASGI websocket messages, ensuring valid state transitions. |
| 62 | """ |
| 63 | if self.application_state == WebSocketState.CONNECTING: |
| 64 | message_type = message["type"] |
| 65 | if message_type not in {"websocket.accept", "websocket.close", "websocket.http.response.start"}: |
| 66 | raise RuntimeError( |
| 67 | 'Expected ASGI message "websocket.accept", "websocket.close" or "websocket.http.response.start", ' |
| 68 | f"but got {message_type!r}" |
| 69 | ) |
| 70 | if message_type == "websocket.close": |
| 71 | self.application_state = WebSocketState.DISCONNECTED |
| 72 | elif message_type == "websocket.http.response.start": |
| 73 | self.application_state = WebSocketState.RESPONSE |
| 74 | else: |
| 75 | self.application_state = WebSocketState.CONNECTED |
| 76 | await self._send(message) |
| 77 | elif self.application_state == WebSocketState.CONNECTED: |
| 78 | message_type = message["type"] |
| 79 | if message_type not in {"websocket.send", "websocket.close"}: |
| 80 | raise RuntimeError( |
| 81 | f'Expected ASGI message "websocket.send" or "websocket.close", but got {message_type!r}' |
| 82 | ) |
| 83 | if message_type == "websocket.close": |
| 84 | self.application_state = WebSocketState.DISCONNECTED |
| 85 | try: |
| 86 | await self._send(message) |
| 87 | except OSError: |
| 88 | self.application_state = WebSocketState.DISCONNECTED |
| 89 | raise WebSocketDisconnect(code=1006) |
| 90 | elif self.application_state == WebSocketState.RESPONSE: |
| 91 | message_type = message["type"] |
| 92 | if message_type != "websocket.http.response.body": |
| 93 | raise RuntimeError(f'Expected ASGI message "websocket.http.response.body", but got {message_type!r}') |
| 94 | if not message.get("more_body", False): |
| 95 | self.application_state = WebSocketState.DISCONNECTED |
| 96 | await self._send(message) |
| 97 | else: |
| 98 | raise RuntimeError('Cannot call "send" once a close message has been sent.') |
| 99 | |
| 100 | async def accept( |
| 101 | self, |