macss-modular-api-graphql-client 0.4.7__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.
- macss_modular_api_graphql_client-0.4.7.dist-info/METADATA +62 -0
- macss_modular_api_graphql_client-0.4.7.dist-info/RECORD +6 -0
- macss_modular_api_graphql_client-0.4.7.dist-info/WHEEL +5 -0
- macss_modular_api_graphql_client-0.4.7.dist-info/top_level.txt +1 -0
- modular_api_graphql_client/__init__.py +37 -0
- modular_api_graphql_client/client.py +524 -0
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: macss-modular-api-graphql-client
|
|
3
|
+
Version: 0.4.7
|
|
4
|
+
Summary: Official MACSS outbound GraphQL client for Python.
|
|
5
|
+
Author: ccisne.dev
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/macss-dev/modular_api
|
|
8
|
+
Project-URL: Repository, https://github.com/macss-dev/modular_api/tree/main/code/py/modular_api_graphql_client
|
|
9
|
+
Project-URL: Issues, https://github.com/macss-dev/modular_api/issues
|
|
10
|
+
Project-URL: Documentation, https://github.com/macss-dev/modular_api/tree/main/code/py/modular_api_graphql_client#readme
|
|
11
|
+
Keywords: macss,graphql,client
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
|
|
19
|
+
Classifier: Typing :: Typed
|
|
20
|
+
Requires-Python: >=3.11
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
Provides-Extra: dev
|
|
23
|
+
Requires-Dist: pytest>=8.0; extra == "dev"
|
|
24
|
+
|
|
25
|
+
# macss-modular-api-graphql-client
|
|
26
|
+
|
|
27
|
+
Official MACSS outbound GraphQL client for Python.
|
|
28
|
+
|
|
29
|
+
## Quick start
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
from modular_api_graphql_client import GraphqlRequest, ServiceClientConfig, graphql_client
|
|
33
|
+
|
|
34
|
+
result = graphql_client(
|
|
35
|
+
config=ServiceClientConfig(
|
|
36
|
+
service_id="users-graphql",
|
|
37
|
+
base_url="https://api.example.test",
|
|
38
|
+
redacted_summary="users-graphql@example",
|
|
39
|
+
default_headers={"accept": "application/json"},
|
|
40
|
+
),
|
|
41
|
+
request=GraphqlRequest(
|
|
42
|
+
operation_id="users.query",
|
|
43
|
+
document="query GetUsers { users { id } }",
|
|
44
|
+
operation_name="GetUsers",
|
|
45
|
+
),
|
|
46
|
+
decoder=lambda value: dict(value or {}),
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
if result.is_success:
|
|
50
|
+
print(result.value.data)
|
|
51
|
+
print(result.value.errors)
|
|
52
|
+
else:
|
|
53
|
+
print(result.failure.message)
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
## Current slice
|
|
57
|
+
|
|
58
|
+
- query-only GraphQL POST requests to `/graphql`
|
|
59
|
+
- normalized `GraphqlResponse[T]` with `data`, `errors`, `extensions`, and metadata
|
|
60
|
+
- persistent `GraphqlClient`
|
|
61
|
+
- one-shot `graphql_client()` helper
|
|
62
|
+
- transport failures kept separate from GraphQL error envelopes
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
modular_api_graphql_client/__init__.py,sha256=KyJVf1U7mVkuPUh0TRR_n3OSihXBecLtCLdpbK0NGkw,826
|
|
2
|
+
modular_api_graphql_client/client.py,sha256=5DLSxgnhyLg9aML2bFuiQaZoPkWpr3Gny0Spa9GZTHk,18016
|
|
3
|
+
macss_modular_api_graphql_client-0.4.7.dist-info/METADATA,sha256=H1Bid3-OEzPMGUfKoJn0YUNPMNcUnURj2akxgpHFhcU,2151
|
|
4
|
+
macss_modular_api_graphql_client-0.4.7.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
5
|
+
macss_modular_api_graphql_client-0.4.7.dist-info/top_level.txt,sha256=78g_jErjYngNMm4ggxMgN-DVD6B-9a8Frx7Wc9GwtnM,27
|
|
6
|
+
macss_modular_api_graphql_client-0.4.7.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
modular_api_graphql_client
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Public package exports for modular_api_graphql_client."""
|
|
2
|
+
|
|
3
|
+
from .client import (
|
|
4
|
+
GraphqlClient,
|
|
5
|
+
GraphqlError,
|
|
6
|
+
GraphqlErrorLocation,
|
|
7
|
+
GraphqlRequest,
|
|
8
|
+
GraphqlResponse,
|
|
9
|
+
ServiceClientConfig,
|
|
10
|
+
ServiceClientDescription,
|
|
11
|
+
ServiceFailure,
|
|
12
|
+
ServiceFailureCategory,
|
|
13
|
+
ServiceOperation,
|
|
14
|
+
ServiceResponseMetadata,
|
|
15
|
+
ServiceResult,
|
|
16
|
+
ServiceRetryPolicy,
|
|
17
|
+
ServiceTelemetryHooks,
|
|
18
|
+
graphql_client,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
__all__ = [
|
|
22
|
+
"GraphqlClient",
|
|
23
|
+
"GraphqlError",
|
|
24
|
+
"GraphqlErrorLocation",
|
|
25
|
+
"GraphqlRequest",
|
|
26
|
+
"GraphqlResponse",
|
|
27
|
+
"ServiceClientConfig",
|
|
28
|
+
"ServiceClientDescription",
|
|
29
|
+
"ServiceFailure",
|
|
30
|
+
"ServiceFailureCategory",
|
|
31
|
+
"ServiceOperation",
|
|
32
|
+
"ServiceResponseMetadata",
|
|
33
|
+
"ServiceResult",
|
|
34
|
+
"ServiceRetryPolicy",
|
|
35
|
+
"ServiceTelemetryHooks",
|
|
36
|
+
"graphql_client",
|
|
37
|
+
]
|
|
@@ -0,0 +1,524 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import socket
|
|
5
|
+
import time
|
|
6
|
+
import urllib.error
|
|
7
|
+
import urllib.parse
|
|
8
|
+
import urllib.request
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from enum import Enum
|
|
11
|
+
from typing import Any, Callable, Generic, Mapping, TypeVar, cast
|
|
12
|
+
|
|
13
|
+
T = TypeVar("T")
|
|
14
|
+
_MISSING = object()
|
|
15
|
+
|
|
16
|
+
GraphqlDecoder = Callable[[object | None], T]
|
|
17
|
+
ServiceAuthProvider = Callable[["ServiceOperation"], Mapping[str, str]]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True, slots=True)
|
|
21
|
+
class ServiceRetryPolicy:
|
|
22
|
+
max_attempts: int = 1
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True, slots=True)
|
|
26
|
+
class ServiceTelemetryHooks:
|
|
27
|
+
on_started: Callable[["ServiceOperation"], None] | None = None
|
|
28
|
+
on_completed: Callable[["ServiceOperation", "ServiceResult[object]"], None] | None = None
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(frozen=True, slots=True)
|
|
32
|
+
class ServiceClientConfig:
|
|
33
|
+
service_id: str
|
|
34
|
+
base_url: str
|
|
35
|
+
redacted_summary: str
|
|
36
|
+
default_headers: Mapping[str, str] = field(default_factory=dict)
|
|
37
|
+
auth_provider: ServiceAuthProvider | None = None
|
|
38
|
+
timeout: float | None = None
|
|
39
|
+
retry_policy: ServiceRetryPolicy | None = None
|
|
40
|
+
user_agent: str | None = None
|
|
41
|
+
telemetry_hooks: ServiceTelemetryHooks | None = None
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass(frozen=True, slots=True)
|
|
45
|
+
class ServiceOperation:
|
|
46
|
+
transport_id: str
|
|
47
|
+
operation_id: str
|
|
48
|
+
headers: Mapping[str, str] = field(default_factory=dict)
|
|
49
|
+
method: str | None = None
|
|
50
|
+
path: str | None = None
|
|
51
|
+
query: Mapping[str, object] | None = None
|
|
52
|
+
body: object | None = None
|
|
53
|
+
document: str | None = None
|
|
54
|
+
variables: Mapping[str, object] | None = None
|
|
55
|
+
operation_name: str | None = None
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class GraphqlRequest(ServiceOperation):
|
|
59
|
+
def __init__(
|
|
60
|
+
self,
|
|
61
|
+
*,
|
|
62
|
+
operation_id: str,
|
|
63
|
+
document: str,
|
|
64
|
+
headers: Mapping[str, str] | None = None,
|
|
65
|
+
variables: Mapping[str, object] | None = None,
|
|
66
|
+
operation_name: str | None = None,
|
|
67
|
+
path: str = "/graphql",
|
|
68
|
+
) -> None:
|
|
69
|
+
super().__init__(
|
|
70
|
+
transport_id="graphql",
|
|
71
|
+
operation_id=operation_id,
|
|
72
|
+
headers={} if headers is None else dict(headers),
|
|
73
|
+
method="POST",
|
|
74
|
+
path=path,
|
|
75
|
+
document=document,
|
|
76
|
+
variables=None if variables is None else dict(variables),
|
|
77
|
+
operation_name=operation_name,
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@dataclass(frozen=True, slots=True)
|
|
82
|
+
class ServiceResponseMetadata:
|
|
83
|
+
status_code: int
|
|
84
|
+
headers: Mapping[str, str]
|
|
85
|
+
transport_id: str
|
|
86
|
+
duration: float
|
|
87
|
+
request_id: str | None = None
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class ServiceFailureCategory(str, Enum):
|
|
91
|
+
TRANSPORT = "transport"
|
|
92
|
+
TIMEOUT = "timeout"
|
|
93
|
+
AUTH = "auth"
|
|
94
|
+
RATE_LIMIT = "rate_limit"
|
|
95
|
+
PROTOCOL = "protocol"
|
|
96
|
+
DECODE = "decode"
|
|
97
|
+
GRAPHQL = "graphql"
|
|
98
|
+
UNEXPECTED = "unexpected"
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@dataclass(frozen=True, slots=True)
|
|
102
|
+
class ServiceFailure:
|
|
103
|
+
category: ServiceFailureCategory
|
|
104
|
+
code: str
|
|
105
|
+
message: str
|
|
106
|
+
retryable: bool
|
|
107
|
+
status_code: int | None = None
|
|
108
|
+
transport_id: str | None = None
|
|
109
|
+
details: object | None = None
|
|
110
|
+
cause_summary: str | None = None
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class ServiceResult(Generic[T]):
|
|
114
|
+
def __init__(
|
|
115
|
+
self,
|
|
116
|
+
value: object = _MISSING,
|
|
117
|
+
failure: ServiceFailure | None = None,
|
|
118
|
+
) -> None:
|
|
119
|
+
self._value = value
|
|
120
|
+
self._failure = failure
|
|
121
|
+
|
|
122
|
+
@classmethod
|
|
123
|
+
def success(cls, value: T) -> ServiceResult[T]:
|
|
124
|
+
return cls(value=value)
|
|
125
|
+
|
|
126
|
+
@classmethod
|
|
127
|
+
def from_failure(cls, failure: ServiceFailure) -> ServiceResult[T]:
|
|
128
|
+
return cls(failure=failure)
|
|
129
|
+
|
|
130
|
+
@property
|
|
131
|
+
def is_success(self) -> bool:
|
|
132
|
+
return self._failure is None
|
|
133
|
+
|
|
134
|
+
@property
|
|
135
|
+
def is_failure(self) -> bool:
|
|
136
|
+
return self._failure is not None
|
|
137
|
+
|
|
138
|
+
@property
|
|
139
|
+
def value(self) -> T:
|
|
140
|
+
if self._failure is not None or self._value is _MISSING:
|
|
141
|
+
raise RuntimeError("ServiceResult does not contain a success value.")
|
|
142
|
+
return cast(T, self._value)
|
|
143
|
+
|
|
144
|
+
@property
|
|
145
|
+
def failure(self) -> ServiceFailure:
|
|
146
|
+
if self._failure is None:
|
|
147
|
+
raise RuntimeError("ServiceResult does not contain a failure value.")
|
|
148
|
+
return self._failure
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
@dataclass(frozen=True, slots=True)
|
|
152
|
+
class ServiceClientDescription:
|
|
153
|
+
service_id: str
|
|
154
|
+
transport_id: str
|
|
155
|
+
base_url: str
|
|
156
|
+
redacted_summary: str
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
@dataclass(frozen=True, slots=True)
|
|
160
|
+
class GraphqlErrorLocation:
|
|
161
|
+
line: int
|
|
162
|
+
column: int
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
@dataclass(frozen=True, slots=True)
|
|
166
|
+
class GraphqlError:
|
|
167
|
+
message: str
|
|
168
|
+
path: list[object] = field(default_factory=list)
|
|
169
|
+
locations: list[GraphqlErrorLocation] = field(default_factory=list)
|
|
170
|
+
extensions: dict[str, object] | None = None
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
@dataclass(frozen=True, slots=True)
|
|
174
|
+
class GraphqlResponse(Generic[T]):
|
|
175
|
+
data: T | None
|
|
176
|
+
errors: list[GraphqlError]
|
|
177
|
+
metadata: ServiceResponseMetadata
|
|
178
|
+
extensions: dict[str, object] | None = None
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
class GraphqlClient:
|
|
182
|
+
def __init__(self, config: ServiceClientConfig) -> None:
|
|
183
|
+
self._config = config
|
|
184
|
+
self._opener = urllib.request.build_opener()
|
|
185
|
+
self._closed = False
|
|
186
|
+
|
|
187
|
+
def describe(self) -> ServiceClientDescription:
|
|
188
|
+
return ServiceClientDescription(
|
|
189
|
+
service_id=self._config.service_id,
|
|
190
|
+
transport_id="graphql",
|
|
191
|
+
base_url=self._config.base_url,
|
|
192
|
+
redacted_summary=self._config.redacted_summary,
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
def execute(
|
|
196
|
+
self,
|
|
197
|
+
request: GraphqlRequest,
|
|
198
|
+
*,
|
|
199
|
+
decoder: GraphqlDecoder[T] | None = None,
|
|
200
|
+
) -> ServiceResult[GraphqlResponse[T]]:
|
|
201
|
+
if self._closed:
|
|
202
|
+
return ServiceResult.from_failure(
|
|
203
|
+
ServiceFailure(
|
|
204
|
+
category=ServiceFailureCategory.UNEXPECTED,
|
|
205
|
+
code="client_closed",
|
|
206
|
+
message="The GraphQL client is already closed.",
|
|
207
|
+
retryable=False,
|
|
208
|
+
transport_id="graphql",
|
|
209
|
+
)
|
|
210
|
+
)
|
|
211
|
+
|
|
212
|
+
if _is_mutation_document(request.document or ""):
|
|
213
|
+
return ServiceResult.from_failure(
|
|
214
|
+
ServiceFailure(
|
|
215
|
+
category=ServiceFailureCategory.GRAPHQL,
|
|
216
|
+
code="mutation_not_supported",
|
|
217
|
+
message="GraphQL mutations are not supported in v1.",
|
|
218
|
+
retryable=False,
|
|
219
|
+
transport_id="graphql",
|
|
220
|
+
)
|
|
221
|
+
)
|
|
222
|
+
|
|
223
|
+
if self._config.telemetry_hooks and self._config.telemetry_hooks.on_started:
|
|
224
|
+
self._config.telemetry_hooks.on_started(request)
|
|
225
|
+
|
|
226
|
+
started_at = time.monotonic()
|
|
227
|
+
result: ServiceResult[GraphqlResponse[T]]
|
|
228
|
+
|
|
229
|
+
try:
|
|
230
|
+
headers = self._build_headers(request)
|
|
231
|
+
payload: dict[str, object] = {"query": request.document or ""}
|
|
232
|
+
if request.variables is not None:
|
|
233
|
+
payload["variables"] = dict(request.variables)
|
|
234
|
+
if request.operation_name is not None:
|
|
235
|
+
payload["operationName"] = request.operation_name
|
|
236
|
+
|
|
237
|
+
http_request = urllib.request.Request(
|
|
238
|
+
_resolve_url(self._config.base_url, request.path or "/graphql"),
|
|
239
|
+
data=_encode_body(payload, headers),
|
|
240
|
+
headers=headers,
|
|
241
|
+
method="POST",
|
|
242
|
+
)
|
|
243
|
+
|
|
244
|
+
with self._opener.open(http_request, timeout=self._config.timeout) as response:
|
|
245
|
+
status_code = getattr(response, "status", response.getcode())
|
|
246
|
+
response_text = response.read().decode("utf-8")
|
|
247
|
+
header_map = _headers_to_record(response.headers)
|
|
248
|
+
envelope = _decode_envelope(response_text, response.headers.get_content_type())
|
|
249
|
+
if isinstance(envelope, ServiceFailure):
|
|
250
|
+
result = ServiceResult.from_failure(envelope)
|
|
251
|
+
else:
|
|
252
|
+
decoded = _decode_data(envelope.get("data"), decoder)
|
|
253
|
+
if isinstance(decoded, ServiceFailure):
|
|
254
|
+
result = ServiceResult.from_failure(decoded)
|
|
255
|
+
else:
|
|
256
|
+
result = ServiceResult.success(
|
|
257
|
+
GraphqlResponse(
|
|
258
|
+
data=decoded,
|
|
259
|
+
errors=_parse_errors(envelope.get("errors")),
|
|
260
|
+
extensions=_parse_extensions(envelope.get("extensions")),
|
|
261
|
+
metadata=ServiceResponseMetadata(
|
|
262
|
+
status_code=status_code,
|
|
263
|
+
headers=header_map,
|
|
264
|
+
transport_id="graphql",
|
|
265
|
+
duration=time.monotonic() - started_at,
|
|
266
|
+
request_id=header_map.get("x-request-id"),
|
|
267
|
+
),
|
|
268
|
+
)
|
|
269
|
+
)
|
|
270
|
+
except urllib.error.HTTPError as error:
|
|
271
|
+
details = error.read().decode("utf-8")
|
|
272
|
+
result = ServiceResult.from_failure(
|
|
273
|
+
ServiceFailure(
|
|
274
|
+
category=_category_for_status(error.code),
|
|
275
|
+
code=_code_for_status(error.code),
|
|
276
|
+
message=details if details else f"HTTP request failed with status {error.code}.",
|
|
277
|
+
retryable=_is_retryable_status(error.code),
|
|
278
|
+
status_code=error.code,
|
|
279
|
+
transport_id="http",
|
|
280
|
+
details=details if details else None,
|
|
281
|
+
)
|
|
282
|
+
)
|
|
283
|
+
except urllib.error.URLError as error:
|
|
284
|
+
reason = error.reason
|
|
285
|
+
if isinstance(reason, (TimeoutError, socket.timeout)):
|
|
286
|
+
result = ServiceResult.from_failure(
|
|
287
|
+
ServiceFailure(
|
|
288
|
+
category=ServiceFailureCategory.TIMEOUT,
|
|
289
|
+
code="timeout",
|
|
290
|
+
message="The HTTP request timed out.",
|
|
291
|
+
retryable=True,
|
|
292
|
+
transport_id="http",
|
|
293
|
+
cause_summary=str(reason),
|
|
294
|
+
)
|
|
295
|
+
)
|
|
296
|
+
else:
|
|
297
|
+
result = ServiceResult.from_failure(
|
|
298
|
+
ServiceFailure(
|
|
299
|
+
category=ServiceFailureCategory.TRANSPORT,
|
|
300
|
+
code="transport_error",
|
|
301
|
+
message="The HTTP request failed to reach the remote service.",
|
|
302
|
+
retryable=True,
|
|
303
|
+
transport_id="http",
|
|
304
|
+
cause_summary=str(reason),
|
|
305
|
+
)
|
|
306
|
+
)
|
|
307
|
+
except (TimeoutError, socket.timeout) as error:
|
|
308
|
+
result = ServiceResult.from_failure(
|
|
309
|
+
ServiceFailure(
|
|
310
|
+
category=ServiceFailureCategory.TIMEOUT,
|
|
311
|
+
code="timeout",
|
|
312
|
+
message="The HTTP request timed out.",
|
|
313
|
+
retryable=True,
|
|
314
|
+
transport_id="http",
|
|
315
|
+
cause_summary=str(error),
|
|
316
|
+
)
|
|
317
|
+
)
|
|
318
|
+
except Exception as error: # noqa: BLE001
|
|
319
|
+
result = ServiceResult.from_failure(
|
|
320
|
+
ServiceFailure(
|
|
321
|
+
category=ServiceFailureCategory.UNEXPECTED,
|
|
322
|
+
code="unexpected_error",
|
|
323
|
+
message="The GraphQL request failed unexpectedly.",
|
|
324
|
+
retryable=False,
|
|
325
|
+
transport_id="graphql",
|
|
326
|
+
cause_summary=str(error),
|
|
327
|
+
)
|
|
328
|
+
)
|
|
329
|
+
|
|
330
|
+
if self._config.telemetry_hooks and self._config.telemetry_hooks.on_completed:
|
|
331
|
+
self._config.telemetry_hooks.on_completed(request, cast(ServiceResult[object], result))
|
|
332
|
+
return result
|
|
333
|
+
|
|
334
|
+
def close(self) -> ServiceResult[None]:
|
|
335
|
+
self._closed = True
|
|
336
|
+
return ServiceResult.success(None)
|
|
337
|
+
|
|
338
|
+
def _build_headers(self, request: GraphqlRequest) -> dict[str, str]:
|
|
339
|
+
headers = {
|
|
340
|
+
**dict(self._config.default_headers),
|
|
341
|
+
**dict(request.headers),
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
if self._config.auth_provider is not None:
|
|
345
|
+
headers.update(dict(self._config.auth_provider(request)))
|
|
346
|
+
|
|
347
|
+
if self._config.user_agent is not None and "User-Agent" not in headers and "user-agent" not in headers:
|
|
348
|
+
headers["User-Agent"] = self._config.user_agent
|
|
349
|
+
|
|
350
|
+
return headers
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def graphql_client(
|
|
354
|
+
*,
|
|
355
|
+
config: ServiceClientConfig,
|
|
356
|
+
request: GraphqlRequest,
|
|
357
|
+
decoder: GraphqlDecoder[T] | None = None,
|
|
358
|
+
) -> ServiceResult[GraphqlResponse[T]]:
|
|
359
|
+
client = GraphqlClient(config)
|
|
360
|
+
try:
|
|
361
|
+
return client.execute(request, decoder=decoder)
|
|
362
|
+
finally:
|
|
363
|
+
client.close()
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def _resolve_url(base_url: str, path: str) -> str:
|
|
367
|
+
base = urllib.parse.urlsplit(base_url)
|
|
368
|
+
path_segments = [segment for segment in base.path.split("/") if segment]
|
|
369
|
+
path_segments.extend(segment for segment in path.lstrip("/").split("/") if segment)
|
|
370
|
+
normalized_path = "/" + "/".join(path_segments)
|
|
371
|
+
return urllib.parse.urlunsplit((base.scheme, base.netloc, normalized_path, "", ""))
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def _encode_body(body: object | None, headers: dict[str, str]) -> bytes | None:
|
|
375
|
+
if body is None:
|
|
376
|
+
return None
|
|
377
|
+
|
|
378
|
+
if "Content-Type" not in headers and "content-type" not in headers:
|
|
379
|
+
headers["Content-Type"] = "application/json"
|
|
380
|
+
|
|
381
|
+
return json.dumps(body).encode("utf-8")
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def _headers_to_record(headers: Any) -> dict[str, str]:
|
|
385
|
+
return {key.lower(): value for key, value in headers.items()}
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def _decode_envelope(body: str, content_type: str | None) -> dict[str, object | None] | ServiceFailure:
|
|
389
|
+
if body == "":
|
|
390
|
+
return ServiceFailure(
|
|
391
|
+
category=ServiceFailureCategory.GRAPHQL,
|
|
392
|
+
code="invalid_graphql_response",
|
|
393
|
+
message="The GraphQL response must be a JSON object envelope.",
|
|
394
|
+
retryable=False,
|
|
395
|
+
transport_id="graphql",
|
|
396
|
+
)
|
|
397
|
+
|
|
398
|
+
if not _looks_like_json(content_type, body):
|
|
399
|
+
return ServiceFailure(
|
|
400
|
+
category=ServiceFailureCategory.GRAPHQL,
|
|
401
|
+
code="invalid_graphql_response",
|
|
402
|
+
message="The GraphQL response must be a JSON object envelope.",
|
|
403
|
+
retryable=False,
|
|
404
|
+
transport_id="graphql",
|
|
405
|
+
)
|
|
406
|
+
|
|
407
|
+
try:
|
|
408
|
+
decoded = json.loads(body)
|
|
409
|
+
except json.JSONDecodeError as error:
|
|
410
|
+
return ServiceFailure(
|
|
411
|
+
category=ServiceFailureCategory.DECODE,
|
|
412
|
+
code="invalid_json",
|
|
413
|
+
message="The HTTP response body is not valid JSON.",
|
|
414
|
+
retryable=False,
|
|
415
|
+
transport_id="http",
|
|
416
|
+
cause_summary=str(error),
|
|
417
|
+
)
|
|
418
|
+
|
|
419
|
+
if not isinstance(decoded, dict):
|
|
420
|
+
return ServiceFailure(
|
|
421
|
+
category=ServiceFailureCategory.GRAPHQL,
|
|
422
|
+
code="invalid_graphql_response",
|
|
423
|
+
message="The GraphQL response must be a JSON object envelope.",
|
|
424
|
+
retryable=False,
|
|
425
|
+
transport_id="graphql",
|
|
426
|
+
)
|
|
427
|
+
|
|
428
|
+
return cast(dict[str, object | None], decoded)
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
def _looks_like_json(content_type: str | None, body: str) -> bool:
|
|
432
|
+
if content_type is not None:
|
|
433
|
+
normalized = content_type.lower()
|
|
434
|
+
if normalized == "application/json" or normalized.endswith("+json"):
|
|
435
|
+
return True
|
|
436
|
+
|
|
437
|
+
trimmed = body.lstrip()
|
|
438
|
+
return trimmed.startswith("{") or trimmed.startswith("[")
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
def _decode_data(
|
|
442
|
+
value: object | None,
|
|
443
|
+
decoder: GraphqlDecoder[T] | None,
|
|
444
|
+
) -> T | None | ServiceFailure:
|
|
445
|
+
if decoder is None:
|
|
446
|
+
return cast(T | None, value)
|
|
447
|
+
|
|
448
|
+
try:
|
|
449
|
+
return decoder(value)
|
|
450
|
+
except Exception as error: # noqa: BLE001
|
|
451
|
+
return ServiceFailure(
|
|
452
|
+
category=ServiceFailureCategory.DECODE,
|
|
453
|
+
code="invalid_graphql_data",
|
|
454
|
+
message="The GraphQL response data could not be decoded.",
|
|
455
|
+
retryable=False,
|
|
456
|
+
transport_id="graphql",
|
|
457
|
+
cause_summary=str(error),
|
|
458
|
+
)
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
def _parse_errors(value: object | None) -> list[GraphqlError]:
|
|
462
|
+
if not isinstance(value, list):
|
|
463
|
+
return []
|
|
464
|
+
|
|
465
|
+
errors: list[GraphqlError] = []
|
|
466
|
+
for entry in value:
|
|
467
|
+
error = entry if isinstance(entry, dict) else {}
|
|
468
|
+
raw_locations = error.get("locations") if isinstance(error, dict) else None
|
|
469
|
+
locations: list[GraphqlErrorLocation] = []
|
|
470
|
+
if isinstance(raw_locations, list):
|
|
471
|
+
for location in raw_locations:
|
|
472
|
+
if isinstance(location, dict):
|
|
473
|
+
line = location.get("line")
|
|
474
|
+
column = location.get("column")
|
|
475
|
+
locations.append(
|
|
476
|
+
GraphqlErrorLocation(
|
|
477
|
+
line=line if isinstance(line, int) else 0,
|
|
478
|
+
column=column if isinstance(column, int) else 0,
|
|
479
|
+
)
|
|
480
|
+
)
|
|
481
|
+
|
|
482
|
+
message = error.get("message", "Unknown GraphQL error") if isinstance(error, dict) else "Unknown GraphQL error"
|
|
483
|
+
errors.append(
|
|
484
|
+
GraphqlError(
|
|
485
|
+
message=str(message),
|
|
486
|
+
path=list(error.get("path", [])) if isinstance(error, dict) and isinstance(error.get("path"), list) else [],
|
|
487
|
+
locations=locations,
|
|
488
|
+
extensions=_parse_extensions(error.get("extensions")) if isinstance(error, dict) else None,
|
|
489
|
+
)
|
|
490
|
+
)
|
|
491
|
+
|
|
492
|
+
return errors
|
|
493
|
+
|
|
494
|
+
|
|
495
|
+
def _parse_extensions(value: object | None) -> dict[str, object] | None:
|
|
496
|
+
if not isinstance(value, dict):
|
|
497
|
+
return None
|
|
498
|
+
return {str(key): item for key, item in value.items()}
|
|
499
|
+
|
|
500
|
+
|
|
501
|
+
def _is_mutation_document(document: str) -> bool:
|
|
502
|
+
return document.lstrip().startswith("mutation ")
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
def _category_for_status(status_code: int) -> ServiceFailureCategory:
|
|
506
|
+
if status_code in {401, 403}:
|
|
507
|
+
return ServiceFailureCategory.AUTH
|
|
508
|
+
if status_code == 429:
|
|
509
|
+
return ServiceFailureCategory.RATE_LIMIT
|
|
510
|
+
return ServiceFailureCategory.PROTOCOL
|
|
511
|
+
|
|
512
|
+
|
|
513
|
+
def _code_for_status(status_code: int) -> str:
|
|
514
|
+
if status_code == 401:
|
|
515
|
+
return "unauthorized"
|
|
516
|
+
if status_code == 403:
|
|
517
|
+
return "forbidden"
|
|
518
|
+
if status_code == 429:
|
|
519
|
+
return "rate_limit"
|
|
520
|
+
return f"http_{status_code}"
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
def _is_retryable_status(status_code: int) -> bool:
|
|
524
|
+
return status_code == 429 or status_code >= 500
|