pygemstone 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pygemstone/__init__.py +71 -0
- pygemstone/__main__.py +100 -0
- pygemstone/appsync.py +393 -0
- pygemstone/auth.py +202 -0
- pygemstone/client.py +416 -0
- pygemstone/const.py +47 -0
- pygemstone/device.py +66 -0
- pygemstone/errors.py +40 -0
- pygemstone/models.py +648 -0
- pygemstone/py.typed +0 -0
- pygemstone-0.0.1.dist-info/METADATA +150 -0
- pygemstone-0.0.1.dist-info/RECORD +16 -0
- pygemstone-0.0.1.dist-info/WHEEL +5 -0
- pygemstone-0.0.1.dist-info/entry_points.txt +2 -0
- pygemstone-0.0.1.dist-info/licenses/LICENSE +21 -0
- pygemstone-0.0.1.dist-info/top_level.txt +1 -0
pygemstone/__init__.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""pygemstone — Python client for Gemstone Lights permanent Christmas lights."""
|
|
2
|
+
|
|
3
|
+
from .appsync import AppSyncClient
|
|
4
|
+
from .auth import GemstoneAuth, TokenSet
|
|
5
|
+
from .client import GemstoneClient
|
|
6
|
+
from .device import Device
|
|
7
|
+
from .errors import (
|
|
8
|
+
GemstoneApiError,
|
|
9
|
+
GemstoneAuthError,
|
|
10
|
+
GemstoneConnectionError,
|
|
11
|
+
GemstoneError,
|
|
12
|
+
GemstoneNotFoundError,
|
|
13
|
+
GemstoneValueError,
|
|
14
|
+
)
|
|
15
|
+
from .models import Device as DeviceRecord
|
|
16
|
+
from .models import (
|
|
17
|
+
AccountProfile,
|
|
18
|
+
Announcement,
|
|
19
|
+
DeviceState,
|
|
20
|
+
DownloadableFolder,
|
|
21
|
+
DownloadablePattern,
|
|
22
|
+
EventCategory,
|
|
23
|
+
EventsScheduleWindow,
|
|
24
|
+
EventsSettings,
|
|
25
|
+
Folder,
|
|
26
|
+
FolderPattern,
|
|
27
|
+
HomeGroup,
|
|
28
|
+
HomeGroupUser,
|
|
29
|
+
Pattern,
|
|
30
|
+
SubscribedEvent,
|
|
31
|
+
Swatch,
|
|
32
|
+
SwatchColor,
|
|
33
|
+
Timer,
|
|
34
|
+
TimerData,
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
__version__ = "0.0.1"
|
|
38
|
+
|
|
39
|
+
__all__ = [
|
|
40
|
+
"GemstoneClient",
|
|
41
|
+
"GemstoneAuth",
|
|
42
|
+
"AppSyncClient",
|
|
43
|
+
"TokenSet",
|
|
44
|
+
"Device",
|
|
45
|
+
"DeviceRecord",
|
|
46
|
+
"DeviceState",
|
|
47
|
+
"HomeGroup",
|
|
48
|
+
"Pattern",
|
|
49
|
+
"AccountProfile",
|
|
50
|
+
"Announcement",
|
|
51
|
+
"DownloadableFolder",
|
|
52
|
+
"DownloadablePattern",
|
|
53
|
+
"EventCategory",
|
|
54
|
+
"EventsScheduleWindow",
|
|
55
|
+
"EventsSettings",
|
|
56
|
+
"Folder",
|
|
57
|
+
"FolderPattern",
|
|
58
|
+
"HomeGroupUser",
|
|
59
|
+
"SubscribedEvent",
|
|
60
|
+
"Swatch",
|
|
61
|
+
"SwatchColor",
|
|
62
|
+
"Timer",
|
|
63
|
+
"TimerData",
|
|
64
|
+
"GemstoneError",
|
|
65
|
+
"GemstoneAuthError",
|
|
66
|
+
"GemstoneApiError",
|
|
67
|
+
"GemstoneConnectionError",
|
|
68
|
+
"GemstoneNotFoundError",
|
|
69
|
+
"GemstoneValueError",
|
|
70
|
+
"__version__",
|
|
71
|
+
]
|
pygemstone/__main__.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""Tiny CLI for manual smoke-testing pygemstone.
|
|
2
|
+
|
|
3
|
+
Usage:
|
|
4
|
+
|
|
5
|
+
python -m pygemstone login # verify credentials work
|
|
6
|
+
python -m pygemstone list # list home groups + devices
|
|
7
|
+
python -m pygemstone state <DSN> # print currentlyPlaying for a device
|
|
8
|
+
python -m pygemstone on <DSN> # turn a device on
|
|
9
|
+
python -m pygemstone off <DSN> # turn a device off
|
|
10
|
+
python -m pygemstone introspect # dump the AppSync GraphQL schema
|
|
11
|
+
# (json on stdout)
|
|
12
|
+
|
|
13
|
+
Credentials come from ``$GEMSTONE_EMAIL`` and ``$GEMSTONE_PASSWORD``
|
|
14
|
+
or, if absent, a ``.env`` file in the current directory.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import asyncio
|
|
20
|
+
import json
|
|
21
|
+
import os
|
|
22
|
+
import sys
|
|
23
|
+
|
|
24
|
+
from .client import GemstoneClient
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _load_env() -> tuple[str, str]:
|
|
28
|
+
email = os.environ.get("GEMSTONE_EMAIL")
|
|
29
|
+
password = os.environ.get("GEMSTONE_PASSWORD")
|
|
30
|
+
if not (email and password):
|
|
31
|
+
try:
|
|
32
|
+
from dotenv import load_dotenv
|
|
33
|
+
|
|
34
|
+
load_dotenv()
|
|
35
|
+
except ImportError:
|
|
36
|
+
pass
|
|
37
|
+
email = os.environ.get("GEMSTONE_EMAIL")
|
|
38
|
+
password = os.environ.get("GEMSTONE_PASSWORD")
|
|
39
|
+
if not (email and password):
|
|
40
|
+
print(
|
|
41
|
+
"Missing GEMSTONE_EMAIL / GEMSTONE_PASSWORD in environment.",
|
|
42
|
+
file=sys.stderr,
|
|
43
|
+
)
|
|
44
|
+
sys.exit(2)
|
|
45
|
+
return email, password
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
async def _run(argv: list[str]) -> int:
|
|
49
|
+
if not argv:
|
|
50
|
+
print(__doc__, file=sys.stderr)
|
|
51
|
+
return 2
|
|
52
|
+
cmd, rest = argv[0], argv[1:]
|
|
53
|
+
email, password = _load_env()
|
|
54
|
+
async with GemstoneClient(email, password) as gc:
|
|
55
|
+
await gc.login()
|
|
56
|
+
if cmd == "login":
|
|
57
|
+
tokens = gc.auth.tokens
|
|
58
|
+
assert tokens is not None
|
|
59
|
+
print(f"OK, access token expires at {tokens.expires_at:.0f}")
|
|
60
|
+
return 0
|
|
61
|
+
if cmd == "list":
|
|
62
|
+
for group in await gc.homegroups():
|
|
63
|
+
print(f"[{group.id}] {group.name} (role={group.role})")
|
|
64
|
+
for dev in await gc.devices(group.id):
|
|
65
|
+
print(f" {dev.id} {dev.name} fw={dev.firmware}")
|
|
66
|
+
return 0
|
|
67
|
+
if cmd == "state" and rest:
|
|
68
|
+
state = await gc.device_state(rest[0])
|
|
69
|
+
pat = state.pattern
|
|
70
|
+
print(
|
|
71
|
+
f"on={state.on_state} "
|
|
72
|
+
f"pattern={(pat.name if pat else None)!r} "
|
|
73
|
+
f"updated={state.last_updated_at}"
|
|
74
|
+
)
|
|
75
|
+
return 0
|
|
76
|
+
if cmd in ("on", "off") and rest:
|
|
77
|
+
tx = await gc.set_on_state(rest[0], cmd == "on")
|
|
78
|
+
print(f"OK tx={tx}")
|
|
79
|
+
return 0
|
|
80
|
+
if cmd == "introspect":
|
|
81
|
+
schema = await gc.introspect_schema()
|
|
82
|
+
if not schema:
|
|
83
|
+
print(
|
|
84
|
+
"Introspection returned no data — the operator may have "
|
|
85
|
+
"disabled it on this AppSync API.",
|
|
86
|
+
file=sys.stderr,
|
|
87
|
+
)
|
|
88
|
+
return 1
|
|
89
|
+
print(json.dumps(schema, indent=2))
|
|
90
|
+
return 0
|
|
91
|
+
print(__doc__, file=sys.stderr)
|
|
92
|
+
return 2
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def main() -> None: # pragma: no cover - entry point
|
|
96
|
+
sys.exit(asyncio.run(_run(sys.argv[1:])))
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
if __name__ == "__main__": # pragma: no cover
|
|
100
|
+
main()
|
pygemstone/appsync.py
ADDED
|
@@ -0,0 +1,393 @@
|
|
|
1
|
+
"""AppSync GraphQL HTTP + real-time WebSocket transport.
|
|
2
|
+
|
|
3
|
+
.. warning::
|
|
4
|
+
|
|
5
|
+
**Experimental — parked.** Two mitmproxy WireGuard captures of the
|
|
6
|
+
official iOS app (``com.gemstone.lights`` 0.6.03, amplify-flutter
|
|
7
|
+
2.6.5) show that the app **never opens a GraphQL connection** —
|
|
8
|
+
even across logout/login, device control, and live state changes.
|
|
9
|
+
All real-time state propagation observed in the wild happens via
|
|
10
|
+
REST polling of ``/deviceControl/currentlyPlaying``. The only
|
|
11
|
+
AppSync traffic seen is two unauthenticated ``GET /ping``
|
|
12
|
+
healthchecks per session.
|
|
13
|
+
|
|
14
|
+
Consequently the AppSync auth scheme used by the AppSync API
|
|
15
|
+
(if any) is unknown. All four Cognito JWT auth modes
|
|
16
|
+
(``Authorization: <id_token>``, ``Authorization: Bearer <id_token>``,
|
|
17
|
+
and the same with the access token) return HTTP 401
|
|
18
|
+
``UnauthorizedException``. Cognito Identity Pool (AWS_IAM) is
|
|
19
|
+
ruled out — no ``cognito-identity.us-west-2.amazonaws.com`` traffic
|
|
20
|
+
was seen during a fresh login.
|
|
21
|
+
|
|
22
|
+
This module is kept as scaffolding (transport, protocol, tests) so
|
|
23
|
+
if Gemstone ever flips real-time on, we can finish wiring it once
|
|
24
|
+
a successful subscription handshake is captured.
|
|
25
|
+
|
|
26
|
+
The Gemstone Lights cloud exposes an AWS AppSync GraphQL endpoint for
|
|
27
|
+
push-based state propagation. This module wraps both surfaces:
|
|
28
|
+
|
|
29
|
+
* :meth:`AppSyncClient.query` — POST GraphQL queries / mutations over
|
|
30
|
+
HTTPS to the regular ``appsync-api`` host.
|
|
31
|
+
* :meth:`AppSyncClient.subscribe` — open a real-time subscription over
|
|
32
|
+
the ``graphql-ws`` WebSocket protocol on the ``appsync-realtime-api``
|
|
33
|
+
host and yield event payloads.
|
|
34
|
+
|
|
35
|
+
The WebSocket protocol implemented here is the one documented by AWS
|
|
36
|
+
for AppSync real-time subscriptions:
|
|
37
|
+
|
|
38
|
+
1. Connect to ``wss://{realtime-host}/graphql?header=<b64>&payload=e30=``
|
|
39
|
+
with ``Sec-WebSocket-Protocol: graphql-ws``.
|
|
40
|
+
2. Send ``{"type":"connection_init"}``; expect ``connection_ack``.
|
|
41
|
+
3. Send ``{"id":<uuid>,"type":"start","payload":{"data":<json>,
|
|
42
|
+
"extensions":{"authorization":{...}}}}``; expect ``start_ack``.
|
|
43
|
+
4. Receive ``{"type":"data","id":...,"payload":{"data":{...}}}``
|
|
44
|
+
events; ``ka`` keepalives are ignored; ``complete`` ends the
|
|
45
|
+
subscription.
|
|
46
|
+
5. Send ``{"id":<uuid>,"type":"stop"}`` to unsubscribe.
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
from __future__ import annotations
|
|
50
|
+
|
|
51
|
+
import base64
|
|
52
|
+
import json
|
|
53
|
+
import logging
|
|
54
|
+
import uuid
|
|
55
|
+
from contextlib import asynccontextmanager
|
|
56
|
+
from typing import Any, AsyncIterator
|
|
57
|
+
from urllib.parse import urlparse
|
|
58
|
+
|
|
59
|
+
import aiohttp
|
|
60
|
+
|
|
61
|
+
from .auth import GemstoneAuth
|
|
62
|
+
from .const import APPSYNC_API_URL, APPSYNC_REALTIME_URL, USER_AGENT
|
|
63
|
+
from .errors import GemstoneApiError, GemstoneConnectionError
|
|
64
|
+
|
|
65
|
+
logger = logging.getLogger(__name__)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
_GRAPHQL_WS_PROTOCOL = "graphql-ws"
|
|
69
|
+
|
|
70
|
+
# Standard GraphQL introspection query. Trimmed to the parts we care
|
|
71
|
+
# about so the response is a couple of hundred KB at most; sufficient
|
|
72
|
+
# to recover every type, field, argument, and (crucially) subscription.
|
|
73
|
+
INTROSPECTION_QUERY = """
|
|
74
|
+
query IntrospectionQuery {
|
|
75
|
+
__schema {
|
|
76
|
+
queryType { name }
|
|
77
|
+
mutationType { name }
|
|
78
|
+
subscriptionType { name }
|
|
79
|
+
types {
|
|
80
|
+
kind
|
|
81
|
+
name
|
|
82
|
+
description
|
|
83
|
+
fields(includeDeprecated: true) {
|
|
84
|
+
name
|
|
85
|
+
description
|
|
86
|
+
args {
|
|
87
|
+
name
|
|
88
|
+
description
|
|
89
|
+
type { ...TypeRef }
|
|
90
|
+
defaultValue
|
|
91
|
+
}
|
|
92
|
+
type { ...TypeRef }
|
|
93
|
+
isDeprecated
|
|
94
|
+
deprecationReason
|
|
95
|
+
}
|
|
96
|
+
inputFields {
|
|
97
|
+
name
|
|
98
|
+
description
|
|
99
|
+
type { ...TypeRef }
|
|
100
|
+
defaultValue
|
|
101
|
+
}
|
|
102
|
+
interfaces { ...TypeRef }
|
|
103
|
+
enumValues(includeDeprecated: true) {
|
|
104
|
+
name
|
|
105
|
+
description
|
|
106
|
+
isDeprecated
|
|
107
|
+
deprecationReason
|
|
108
|
+
}
|
|
109
|
+
possibleTypes { ...TypeRef }
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
fragment TypeRef on __Type {
|
|
115
|
+
kind
|
|
116
|
+
name
|
|
117
|
+
ofType {
|
|
118
|
+
kind
|
|
119
|
+
name
|
|
120
|
+
ofType {
|
|
121
|
+
kind
|
|
122
|
+
name
|
|
123
|
+
ofType {
|
|
124
|
+
kind
|
|
125
|
+
name
|
|
126
|
+
ofType {
|
|
127
|
+
kind
|
|
128
|
+
name
|
|
129
|
+
ofType {
|
|
130
|
+
kind
|
|
131
|
+
name
|
|
132
|
+
ofType {
|
|
133
|
+
kind
|
|
134
|
+
name
|
|
135
|
+
ofType { kind name }
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
""".strip()
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _encode_auth_header(api_host: str, auth_token: str) -> str:
|
|
147
|
+
"""Base64-encode the JSON header object used in the WS query string."""
|
|
148
|
+
obj = {"host": api_host, "Authorization": auth_token}
|
|
149
|
+
raw = json.dumps(obj, separators=(",", ":")).encode("utf-8")
|
|
150
|
+
return base64.urlsafe_b64encode(raw).decode("ascii")
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _ws_connect_url(
|
|
154
|
+
realtime_url: str, api_host: str, auth_token: str
|
|
155
|
+
) -> str:
|
|
156
|
+
"""Build the AppSync real-time WebSocket connect URL."""
|
|
157
|
+
header_b64 = _encode_auth_header(api_host, auth_token)
|
|
158
|
+
payload_b64 = base64.urlsafe_b64encode(b"{}").decode("ascii")
|
|
159
|
+
sep = "&" if "?" in realtime_url else "?"
|
|
160
|
+
return f"{realtime_url}{sep}header={header_b64}&payload={payload_b64}"
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
class AppSyncClient:
|
|
164
|
+
"""GraphQL client for Gemstone's AppSync endpoint.
|
|
165
|
+
|
|
166
|
+
Reuses the host :class:`pygemstone.client.GemstoneClient`'s
|
|
167
|
+
:class:`aiohttp.ClientSession` and shares its :class:`GemstoneAuth`
|
|
168
|
+
so tokens refresh transparently.
|
|
169
|
+
"""
|
|
170
|
+
|
|
171
|
+
def __init__(
|
|
172
|
+
self,
|
|
173
|
+
auth: GemstoneAuth,
|
|
174
|
+
session: aiohttp.ClientSession,
|
|
175
|
+
*,
|
|
176
|
+
api_url: str = APPSYNC_API_URL,
|
|
177
|
+
realtime_url: str = APPSYNC_REALTIME_URL,
|
|
178
|
+
) -> None:
|
|
179
|
+
self._auth = auth
|
|
180
|
+
self._session = session
|
|
181
|
+
self._api_url = api_url
|
|
182
|
+
self._realtime_url = realtime_url
|
|
183
|
+
self._api_host = urlparse(api_url).netloc
|
|
184
|
+
|
|
185
|
+
async def _auth_token(self) -> str:
|
|
186
|
+
"""The Cognito id_token used by AppSync user-pool auth.
|
|
187
|
+
|
|
188
|
+
AppSync's ``AMAZON_COGNITO_USER_POOLS`` auth mode expects the
|
|
189
|
+
Cognito **id token** (not access token) in the ``Authorization``
|
|
190
|
+
header, with no ``Bearer`` prefix.
|
|
191
|
+
"""
|
|
192
|
+
tokens = await self._auth.ensure_fresh()
|
|
193
|
+
return tokens.id_token
|
|
194
|
+
|
|
195
|
+
async def query(
|
|
196
|
+
self,
|
|
197
|
+
query: str,
|
|
198
|
+
*,
|
|
199
|
+
variables: dict[str, Any] | None = None,
|
|
200
|
+
operation_name: str | None = None,
|
|
201
|
+
) -> dict[str, Any]:
|
|
202
|
+
"""Run a GraphQL query or mutation over HTTPS.
|
|
203
|
+
|
|
204
|
+
Returns the ``data`` field of the GraphQL response. Raises
|
|
205
|
+
:class:`GemstoneApiError` on HTTP errors or if the response
|
|
206
|
+
contains a non-empty ``errors`` list.
|
|
207
|
+
"""
|
|
208
|
+
token = await self._auth_token()
|
|
209
|
+
body: dict[str, Any] = {"query": query}
|
|
210
|
+
if variables is not None:
|
|
211
|
+
body["variables"] = variables
|
|
212
|
+
if operation_name is not None:
|
|
213
|
+
body["operationName"] = operation_name
|
|
214
|
+
headers = {
|
|
215
|
+
"Authorization": token,
|
|
216
|
+
"User-Agent": USER_AGENT,
|
|
217
|
+
"Accept": "application/json",
|
|
218
|
+
"Content-Type": "application/json",
|
|
219
|
+
"Host": self._api_host,
|
|
220
|
+
}
|
|
221
|
+
try:
|
|
222
|
+
async with self._session.post(
|
|
223
|
+
self._api_url, json=body, headers=headers
|
|
224
|
+
) as resp:
|
|
225
|
+
text = await resp.text()
|
|
226
|
+
if resp.status >= 400:
|
|
227
|
+
raise GemstoneApiError(resp.status, text)
|
|
228
|
+
payload = json.loads(text) if text else {}
|
|
229
|
+
except aiohttp.ClientError as exc:
|
|
230
|
+
raise GemstoneConnectionError(f"AppSync POST failed: {exc}") from exc
|
|
231
|
+
errors = payload.get("errors") or []
|
|
232
|
+
if errors:
|
|
233
|
+
raise GemstoneApiError(
|
|
234
|
+
200, json.dumps(errors), message="GraphQL error"
|
|
235
|
+
)
|
|
236
|
+
data: dict[str, Any] = payload.get("data") or {}
|
|
237
|
+
return data
|
|
238
|
+
|
|
239
|
+
async def introspect(self) -> dict[str, Any]:
|
|
240
|
+
"""Dump the AppSync schema via the standard introspection query.
|
|
241
|
+
|
|
242
|
+
Will return an empty dict (and log a warning) if the operator
|
|
243
|
+
has disabled introspection on this AppSync API. In that case,
|
|
244
|
+
the only way to discover subscription names is a fresh
|
|
245
|
+
mitmproxy capture of the official app while a subscription is
|
|
246
|
+
active.
|
|
247
|
+
"""
|
|
248
|
+
try:
|
|
249
|
+
return await self.query(INTROSPECTION_QUERY)
|
|
250
|
+
except GemstoneApiError as exc:
|
|
251
|
+
logger.warning("AppSync introspection failed: %s", exc)
|
|
252
|
+
return {}
|
|
253
|
+
|
|
254
|
+
@asynccontextmanager
|
|
255
|
+
async def subscribe(
|
|
256
|
+
self,
|
|
257
|
+
query: str,
|
|
258
|
+
*,
|
|
259
|
+
variables: dict[str, Any] | None = None,
|
|
260
|
+
operation_name: str | None = None,
|
|
261
|
+
handshake_timeout: float = 15.0,
|
|
262
|
+
) -> AsyncIterator[AsyncIterator[dict[str, Any]]]:
|
|
263
|
+
"""Open a real-time subscription, yielding an async iterator of events.
|
|
264
|
+
|
|
265
|
+
Usage::
|
|
266
|
+
|
|
267
|
+
sub = "subscription OnUpdate($id: ID!) { onUpdate(id: $id) { ... } }"
|
|
268
|
+
async with gc.appsync.subscribe(sub, variables={"id": dev}) as events:
|
|
269
|
+
async for event in events:
|
|
270
|
+
print(event) # GraphQL `data` field of each push
|
|
271
|
+
|
|
272
|
+
The iterator ends cleanly when the server sends ``complete``;
|
|
273
|
+
:class:`GemstoneApiError` is raised on protocol errors.
|
|
274
|
+
"""
|
|
275
|
+
token = await self._auth_token()
|
|
276
|
+
url = _ws_connect_url(self._realtime_url, self._api_host, token)
|
|
277
|
+
sub_id = str(uuid.uuid4())
|
|
278
|
+
try:
|
|
279
|
+
async with self._session.ws_connect(
|
|
280
|
+
url, protocols=(_GRAPHQL_WS_PROTOCOL,)
|
|
281
|
+
) as ws:
|
|
282
|
+
await _ws_handshake(ws, handshake_timeout)
|
|
283
|
+
await _ws_start(
|
|
284
|
+
ws,
|
|
285
|
+
sub_id,
|
|
286
|
+
query,
|
|
287
|
+
variables,
|
|
288
|
+
operation_name,
|
|
289
|
+
self._api_host,
|
|
290
|
+
token,
|
|
291
|
+
handshake_timeout,
|
|
292
|
+
)
|
|
293
|
+
try:
|
|
294
|
+
yield _ws_iterate(ws, sub_id)
|
|
295
|
+
finally:
|
|
296
|
+
if not ws.closed:
|
|
297
|
+
try:
|
|
298
|
+
await ws.send_json({"id": sub_id, "type": "stop"})
|
|
299
|
+
except Exception: # noqa: BLE001 - best-effort cleanup
|
|
300
|
+
pass
|
|
301
|
+
except aiohttp.ClientError as exc:
|
|
302
|
+
raise GemstoneConnectionError(
|
|
303
|
+
f"AppSync WS connect failed: {exc}"
|
|
304
|
+
) from exc
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
async def _ws_handshake(
|
|
308
|
+
ws: aiohttp.ClientWebSocketResponse, timeout: float
|
|
309
|
+
) -> None:
|
|
310
|
+
await ws.send_json({"type": "connection_init"})
|
|
311
|
+
msg = await ws.receive_json(timeout=timeout)
|
|
312
|
+
if msg.get("type") != "connection_ack":
|
|
313
|
+
raise GemstoneApiError(
|
|
314
|
+
0,
|
|
315
|
+
json.dumps(msg),
|
|
316
|
+
message=f"unexpected AppSync handshake reply: {msg.get('type')}",
|
|
317
|
+
)
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
async def _ws_start(
|
|
321
|
+
ws: aiohttp.ClientWebSocketResponse,
|
|
322
|
+
sub_id: str,
|
|
323
|
+
query: str,
|
|
324
|
+
variables: dict[str, Any] | None,
|
|
325
|
+
operation_name: str | None,
|
|
326
|
+
api_host: str,
|
|
327
|
+
token: str,
|
|
328
|
+
timeout: float,
|
|
329
|
+
) -> None:
|
|
330
|
+
inner: dict[str, Any] = {"query": query}
|
|
331
|
+
if variables is not None:
|
|
332
|
+
inner["variables"] = variables
|
|
333
|
+
if operation_name is not None:
|
|
334
|
+
inner["operationName"] = operation_name
|
|
335
|
+
await ws.send_json(
|
|
336
|
+
{
|
|
337
|
+
"id": sub_id,
|
|
338
|
+
"type": "start",
|
|
339
|
+
"payload": {
|
|
340
|
+
"data": json.dumps(inner, separators=(",", ":")),
|
|
341
|
+
"extensions": {
|
|
342
|
+
"authorization": {
|
|
343
|
+
"host": api_host,
|
|
344
|
+
"Authorization": token,
|
|
345
|
+
}
|
|
346
|
+
},
|
|
347
|
+
},
|
|
348
|
+
}
|
|
349
|
+
)
|
|
350
|
+
while True:
|
|
351
|
+
msg = await ws.receive_json(timeout=timeout)
|
|
352
|
+
kind = msg.get("type")
|
|
353
|
+
if kind == "start_ack":
|
|
354
|
+
return
|
|
355
|
+
if kind == "error":
|
|
356
|
+
raise GemstoneApiError(
|
|
357
|
+
0, json.dumps(msg.get("payload")), message="AppSync start error"
|
|
358
|
+
)
|
|
359
|
+
if kind in ("ka", "connection_ack"):
|
|
360
|
+
continue
|
|
361
|
+
raise GemstoneApiError(
|
|
362
|
+
0, json.dumps(msg), message=f"unexpected start reply: {kind}"
|
|
363
|
+
)
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
async def _ws_iterate(
|
|
367
|
+
ws: aiohttp.ClientWebSocketResponse, sub_id: str
|
|
368
|
+
) -> AsyncIterator[dict[str, Any]]:
|
|
369
|
+
async for msg in ws:
|
|
370
|
+
if msg.type != aiohttp.WSMsgType.TEXT:
|
|
371
|
+
continue
|
|
372
|
+
try:
|
|
373
|
+
data = json.loads(msg.data)
|
|
374
|
+
except json.JSONDecodeError:
|
|
375
|
+
continue
|
|
376
|
+
kind = data.get("type")
|
|
377
|
+
if kind == "ka":
|
|
378
|
+
continue
|
|
379
|
+
if data.get("id") and data["id"] != sub_id:
|
|
380
|
+
# Ignore traffic for any other subscription multiplexed on
|
|
381
|
+
# the same WS (we don't currently open multiple, but be
|
|
382
|
+
# safe).
|
|
383
|
+
continue
|
|
384
|
+
if kind == "complete":
|
|
385
|
+
return
|
|
386
|
+
if kind == "error":
|
|
387
|
+
raise GemstoneApiError(
|
|
388
|
+
0,
|
|
389
|
+
json.dumps(data.get("payload")),
|
|
390
|
+
message="AppSync subscription error",
|
|
391
|
+
)
|
|
392
|
+
if kind == "data":
|
|
393
|
+
yield (data.get("payload") or {}).get("data") or {}
|