forked from datadvance/DjangoChannelsGraphqlWs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransport.py
187 lines (155 loc) · 6.73 KB
/
transport.py
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
# Copyright (C) DATADVANCE, 2010-2021
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""GraphQL WebSocket client transports."""
import asyncio
import json
from typing import Optional
import aiohttp
from . import graphql_ws_consumer
class GraphqlWsTransport:
"""Transport interface for the `GraphqlWsClient`."""
# Default timeout for the WebSocket messages.
TIMEOUT: float = 60.0
async def connect(self, timeout: Optional[float] = None) -> None:
"""Connect to the server."""
raise NotImplementedError()
async def send(self, message: dict) -> None:
"""Send message."""
raise NotImplementedError()
async def receive(self, timeout: Optional[float] = None) -> dict:
"""Receive message."""
raise NotImplementedError()
async def disconnect(self, timeout: Optional[float] = None) -> None:
"""Disconnect from the server."""
raise NotImplementedError()
async def wait_disconnect(self, timeout: Optional[float] = None) -> None:
"""Wait server to close the connection."""
raise NotImplementedError()
class GraphqlWsTransportAiohttp(GraphqlWsTransport):
"""Transport based on AIOHTTP WebSocket client.
Args:
url: WebSocket GraphQL endpoint.
cookies: HTTP request cookies.
headers: HTTP request headers.
"""
def __init__(self, url, cookies=None, headers=None):
"""Constructor. See class description for details."""
# Server URL.
self._url = url
# HTTP cookies.
self._cookies = cookies
# HTTP headers.
self._headers = headers
# AIOHTTP connection.
self._connection = None
# A task which processes incoming messages.
self._message_processor = None
# A queue for incoming messages.
self._incoming_messages = asyncio.Queue()
async def connect(self, timeout: Optional[float] = None) -> None:
"""Establish a connection with the WebSocket server.
Returns:
`(True, <chosen-subprotocol>)` if connection accepted.
`(False, None)` if connection rejected.
"""
connected = asyncio.Event()
self._message_processor = asyncio.ensure_future(
self._process_messages(connected, timeout or self.TIMEOUT)
)
await asyncio.wait(
[connected.wait(), self._message_processor],
return_when=asyncio.FIRST_COMPLETED,
)
if self._message_processor.done():
# Make sure to raise an exception from the task.
self._message_processor.result()
raise RuntimeError(f"Failed to connect to the server: {self._url}!")
async def send(self, message: dict) -> None:
"""Send message."""
assert self._connection is not None, "Client is not connected!"
await self._connection.send_str(json.dumps(message))
async def receive(self, timeout: Optional[float] = None) -> dict:
"""Wait and receive a message from the WebSocket connection.
Method fails if the connection closes.
Returns:
The message received as a `dict`.
"""
# Make sure there's no an exception to raise from the task.
if self._message_processor.done():
self._message_processor.result()
# Wait and receive the message.
try:
payload = await asyncio.wait_for(
self._incoming_messages.get(), timeout or self.TIMEOUT
)
assert isinstance(payload, str), "Non-string data received!"
return dict(json.loads(payload))
except asyncio.TimeoutError as ex:
# See if we have another error to raise inside.
if self._message_processor.done():
self._message_processor.result()
raise ex
async def disconnect(self, timeout: Optional[float] = None) -> None:
"""Close the connection gracefully."""
await self._connection.close(code=1000)
try:
await asyncio.wait_for(
asyncio.shield(self._message_processor), timeout or self.TIMEOUT
)
self._message_processor.result()
except asyncio.TimeoutError:
pass
finally:
if not self._message_processor.done():
self._message_processor.cancel()
try:
await self._message_processor
except asyncio.CancelledError:
pass
async def wait_disconnect(self, timeout: Optional[float] = None) -> None:
"""Wait server to close the connection."""
raise NotImplementedError()
async def _process_messages(self, connected, timeout):
"""Process messages coming from the connection.
Args:
connected: Event for reporting that connection established.
timeout: Connection timeout in seconds.
"""
session = aiohttp.ClientSession(cookies=self._cookies, headers=self._headers)
async with session as session:
connection = session.ws_connect(
self._url,
protocols=[graphql_ws_consumer.GRAPHQL_WS_SUBPROTOCOL],
timeout=timeout,
)
async with connection as self._connection:
if (
self._connection.protocol
!= graphql_ws_consumer.GRAPHQL_WS_SUBPROTOCOL
):
raise RuntimeError(
f"Server uses wrong subprotocol: {self._connection.protocol}!"
)
connected.set()
async for msg in self._connection:
await self._incoming_messages.put(msg.data)
if msg.type == aiohttp.WSMsgType.CLOSED:
break