macss-modular-api-graphql-client 0.4.7__tar.gz
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/PKG-INFO +62 -0
- macss_modular_api_graphql_client-0.4.7/README.md +38 -0
- macss_modular_api_graphql_client-0.4.7/pyproject.toml +46 -0
- macss_modular_api_graphql_client-0.4.7/setup.cfg +4 -0
- macss_modular_api_graphql_client-0.4.7/src/macss_modular_api_graphql_client.egg-info/PKG-INFO +62 -0
- macss_modular_api_graphql_client-0.4.7/src/macss_modular_api_graphql_client.egg-info/SOURCES.txt +10 -0
- macss_modular_api_graphql_client-0.4.7/src/macss_modular_api_graphql_client.egg-info/dependency_links.txt +1 -0
- macss_modular_api_graphql_client-0.4.7/src/macss_modular_api_graphql_client.egg-info/requires.txt +3 -0
- macss_modular_api_graphql_client-0.4.7/src/macss_modular_api_graphql_client.egg-info/top_level.txt +1 -0
- macss_modular_api_graphql_client-0.4.7/src/modular_api_graphql_client/__init__.py +37 -0
- macss_modular_api_graphql_client-0.4.7/src/modular_api_graphql_client/client.py +524 -0
- macss_modular_api_graphql_client-0.4.7/tests/test_graphql_client.py +278 -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,38 @@
|
|
|
1
|
+
# macss-modular-api-graphql-client
|
|
2
|
+
|
|
3
|
+
Official MACSS outbound GraphQL client for Python.
|
|
4
|
+
|
|
5
|
+
## Quick start
|
|
6
|
+
|
|
7
|
+
```python
|
|
8
|
+
from modular_api_graphql_client import GraphqlRequest, ServiceClientConfig, graphql_client
|
|
9
|
+
|
|
10
|
+
result = graphql_client(
|
|
11
|
+
config=ServiceClientConfig(
|
|
12
|
+
service_id="users-graphql",
|
|
13
|
+
base_url="https://api.example.test",
|
|
14
|
+
redacted_summary="users-graphql@example",
|
|
15
|
+
default_headers={"accept": "application/json"},
|
|
16
|
+
),
|
|
17
|
+
request=GraphqlRequest(
|
|
18
|
+
operation_id="users.query",
|
|
19
|
+
document="query GetUsers { users { id } }",
|
|
20
|
+
operation_name="GetUsers",
|
|
21
|
+
),
|
|
22
|
+
decoder=lambda value: dict(value or {}),
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
if result.is_success:
|
|
26
|
+
print(result.value.data)
|
|
27
|
+
print(result.value.errors)
|
|
28
|
+
else:
|
|
29
|
+
print(result.failure.message)
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Current slice
|
|
33
|
+
|
|
34
|
+
- query-only GraphQL POST requests to `/graphql`
|
|
35
|
+
- normalized `GraphqlResponse[T]` with `data`, `errors`, `extensions`, and metadata
|
|
36
|
+
- persistent `GraphqlClient`
|
|
37
|
+
- one-shot `graphql_client()` helper
|
|
38
|
+
- transport failures kept separate from GraphQL error envelopes
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "macss-modular-api-graphql-client"
|
|
7
|
+
version = "0.4.7"
|
|
8
|
+
description = "Official MACSS outbound GraphQL client for Python."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
requires-python = ">=3.11"
|
|
12
|
+
authors = [{ name = "ccisne.dev" }]
|
|
13
|
+
keywords = ["macss", "graphql", "client"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Development Status :: 4 - Beta",
|
|
16
|
+
"Intended Audience :: Developers",
|
|
17
|
+
"Programming Language :: Python :: 3",
|
|
18
|
+
"Programming Language :: Python :: 3.11",
|
|
19
|
+
"Programming Language :: Python :: 3.12",
|
|
20
|
+
"Programming Language :: Python :: 3.13",
|
|
21
|
+
"Topic :: Internet :: WWW/HTTP :: Dynamic Content",
|
|
22
|
+
"Typing :: Typed",
|
|
23
|
+
]
|
|
24
|
+
dependencies = []
|
|
25
|
+
|
|
26
|
+
[project.optional-dependencies]
|
|
27
|
+
dev = [
|
|
28
|
+
"pytest>=8.0",
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
[project.urls]
|
|
32
|
+
Homepage = "https://github.com/macss-dev/modular_api"
|
|
33
|
+
Repository = "https://github.com/macss-dev/modular_api/tree/main/code/py/modular_api_graphql_client"
|
|
34
|
+
Issues = "https://github.com/macss-dev/modular_api/issues"
|
|
35
|
+
Documentation = "https://github.com/macss-dev/modular_api/tree/main/code/py/modular_api_graphql_client#readme"
|
|
36
|
+
|
|
37
|
+
[tool.setuptools.packages.find]
|
|
38
|
+
where = ["src"]
|
|
39
|
+
|
|
40
|
+
[tool.pytest.ini_options]
|
|
41
|
+
testpaths = ["tests"]
|
|
42
|
+
pythonpath = ["src"]
|
|
43
|
+
|
|
44
|
+
[tool.pyright]
|
|
45
|
+
pythonVersion = "3.11"
|
|
46
|
+
typeCheckingMode = "strict"
|
|
@@ -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
|
macss_modular_api_graphql_client-0.4.7/src/macss_modular_api_graphql_client.egg-info/SOURCES.txt
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
README.md
|
|
2
|
+
pyproject.toml
|
|
3
|
+
src/macss_modular_api_graphql_client.egg-info/PKG-INFO
|
|
4
|
+
src/macss_modular_api_graphql_client.egg-info/SOURCES.txt
|
|
5
|
+
src/macss_modular_api_graphql_client.egg-info/dependency_links.txt
|
|
6
|
+
src/macss_modular_api_graphql_client.egg-info/requires.txt
|
|
7
|
+
src/macss_modular_api_graphql_client.egg-info/top_level.txt
|
|
8
|
+
src/modular_api_graphql_client/__init__.py
|
|
9
|
+
src/modular_api_graphql_client/client.py
|
|
10
|
+
tests/test_graphql_client.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
macss_modular_api_graphql_client-0.4.7/src/macss_modular_api_graphql_client.egg-info/top_level.txt
ADDED
|
@@ -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
|
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import threading
|
|
5
|
+
import time
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
8
|
+
|
|
9
|
+
from modular_api_graphql_client import (
|
|
10
|
+
GraphqlClient,
|
|
11
|
+
GraphqlRequest,
|
|
12
|
+
ServiceClientConfig,
|
|
13
|
+
ServiceFailureCategory,
|
|
14
|
+
graphql_client,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(slots=True)
|
|
19
|
+
class _ServerHandle:
|
|
20
|
+
base_url: str
|
|
21
|
+
server: ThreadingHTTPServer
|
|
22
|
+
thread: threading.Thread
|
|
23
|
+
|
|
24
|
+
def close(self) -> None:
|
|
25
|
+
self.server.shutdown()
|
|
26
|
+
self.server.server_close()
|
|
27
|
+
self.thread.join(timeout=2)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def test_graphql_client_sends_a_post_request_and_decodes_the_envelope() -> None:
|
|
31
|
+
def handler(request: BaseHTTPRequestHandler) -> None:
|
|
32
|
+
assert request.command == "POST"
|
|
33
|
+
assert request.path == "/graphql"
|
|
34
|
+
assert request.headers["x-default"] == "package"
|
|
35
|
+
assert request.headers["x-request"] == "test"
|
|
36
|
+
|
|
37
|
+
content_length = int(request.headers.get("Content-Length", "0"))
|
|
38
|
+
payload = json.loads(request.rfile.read(content_length).decode("utf-8"))
|
|
39
|
+
assert payload["query"] == "query GetUsers { users { id } }"
|
|
40
|
+
assert payload["operationName"] == "GetUsers"
|
|
41
|
+
assert payload["variables"] == {"limit": 10}
|
|
42
|
+
|
|
43
|
+
request.send_response(200)
|
|
44
|
+
request.send_header("Content-Type", "application/json")
|
|
45
|
+
request.send_header("X-Request-Id", "req-graphql-1")
|
|
46
|
+
request.end_headers()
|
|
47
|
+
request.wfile.write(
|
|
48
|
+
json.dumps(
|
|
49
|
+
{
|
|
50
|
+
"data": {"users": [{"id": "1"}]},
|
|
51
|
+
"extensions": {"traceId": "trace-1"},
|
|
52
|
+
}
|
|
53
|
+
).encode("utf-8")
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
server = _start_server(handler)
|
|
57
|
+
try:
|
|
58
|
+
result = graphql_client(
|
|
59
|
+
config=ServiceClientConfig(
|
|
60
|
+
service_id="users-graphql",
|
|
61
|
+
base_url=server.base_url,
|
|
62
|
+
redacted_summary="users-graphql@local",
|
|
63
|
+
default_headers={"x-default": "package"},
|
|
64
|
+
),
|
|
65
|
+
request=GraphqlRequest(
|
|
66
|
+
operation_id="users.query",
|
|
67
|
+
document="query GetUsers { users { id } }",
|
|
68
|
+
operation_name="GetUsers",
|
|
69
|
+
variables={"limit": 10},
|
|
70
|
+
headers={"x-request": "test"},
|
|
71
|
+
),
|
|
72
|
+
decoder=lambda value: dict(value or {}),
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
assert result.is_success is True
|
|
76
|
+
assert result.value.data == {"users": [{"id": "1"}]}
|
|
77
|
+
assert result.value.errors == []
|
|
78
|
+
assert result.value.extensions == {"traceId": "trace-1"}
|
|
79
|
+
assert result.value.metadata.status_code == 200
|
|
80
|
+
assert result.value.metadata.transport_id == "graphql"
|
|
81
|
+
assert result.value.metadata.request_id == "req-graphql-1"
|
|
82
|
+
finally:
|
|
83
|
+
server.close()
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def test_graphql_client_preserves_graphql_errors_without_transport_collapse() -> None:
|
|
87
|
+
def handler(request: BaseHTTPRequestHandler) -> None:
|
|
88
|
+
_drain_request_body(request)
|
|
89
|
+
request.send_response(200)
|
|
90
|
+
request.send_header("Content-Type", "application/json")
|
|
91
|
+
request.end_headers()
|
|
92
|
+
request.wfile.write(
|
|
93
|
+
json.dumps(
|
|
94
|
+
{
|
|
95
|
+
"data": None,
|
|
96
|
+
"errors": [
|
|
97
|
+
{
|
|
98
|
+
"message": "Field users is not available",
|
|
99
|
+
"path": ["users"],
|
|
100
|
+
"extensions": {"code": "FIELD_UNAVAILABLE"},
|
|
101
|
+
}
|
|
102
|
+
],
|
|
103
|
+
}
|
|
104
|
+
).encode("utf-8")
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
server = _start_server(handler)
|
|
108
|
+
try:
|
|
109
|
+
result = graphql_client(
|
|
110
|
+
config=ServiceClientConfig(
|
|
111
|
+
service_id="users-graphql",
|
|
112
|
+
base_url=server.base_url,
|
|
113
|
+
redacted_summary="users-graphql@local",
|
|
114
|
+
),
|
|
115
|
+
request=GraphqlRequest(
|
|
116
|
+
operation_id="users.error",
|
|
117
|
+
document="query Broken { users }",
|
|
118
|
+
),
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
assert result.is_success is True
|
|
122
|
+
assert result.value.data is None
|
|
123
|
+
assert len(result.value.errors) == 1
|
|
124
|
+
assert result.value.errors[0].message == "Field users is not available"
|
|
125
|
+
assert result.value.errors[0].path == ["users"]
|
|
126
|
+
assert result.value.errors[0].extensions == {"code": "FIELD_UNAVAILABLE"}
|
|
127
|
+
finally:
|
|
128
|
+
server.close()
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def test_graphql_client_injects_auth_headers_from_the_auth_provider() -> None:
|
|
132
|
+
def handler(request: BaseHTTPRequestHandler) -> None:
|
|
133
|
+
assert request.headers["authorization"] == "Bearer token-123"
|
|
134
|
+
_drain_request_body(request)
|
|
135
|
+
request.send_response(200)
|
|
136
|
+
request.send_header("Content-Type", "application/json")
|
|
137
|
+
request.end_headers()
|
|
138
|
+
request.wfile.write(json.dumps({"data": {"ok": True}}).encode("utf-8"))
|
|
139
|
+
|
|
140
|
+
server = _start_server(handler)
|
|
141
|
+
try:
|
|
142
|
+
result = graphql_client(
|
|
143
|
+
config=ServiceClientConfig(
|
|
144
|
+
service_id="users-graphql",
|
|
145
|
+
base_url=server.base_url,
|
|
146
|
+
redacted_summary="users-graphql@local",
|
|
147
|
+
auth_provider=lambda operation: {"authorization": "Bearer token-123"},
|
|
148
|
+
),
|
|
149
|
+
request=GraphqlRequest(
|
|
150
|
+
operation_id="users.auth",
|
|
151
|
+
document="query Viewer { viewer { id } }",
|
|
152
|
+
),
|
|
153
|
+
decoder=lambda value: dict(value or {}),
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
assert result.is_success is True
|
|
157
|
+
assert result.value.data == {"ok": True}
|
|
158
|
+
finally:
|
|
159
|
+
server.close()
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def test_graphql_client_returns_a_timeout_failure_when_the_request_exceeds_timeout() -> None:
|
|
163
|
+
def handler(request: BaseHTTPRequestHandler) -> None:
|
|
164
|
+
_drain_request_body(request)
|
|
165
|
+
time.sleep(0.2)
|
|
166
|
+
request.send_response(200)
|
|
167
|
+
request.send_header("Content-Type", "application/json")
|
|
168
|
+
request.end_headers()
|
|
169
|
+
request.wfile.write(json.dumps({"data": {"late": True}}).encode("utf-8"))
|
|
170
|
+
|
|
171
|
+
server = _start_server(handler)
|
|
172
|
+
try:
|
|
173
|
+
result = graphql_client(
|
|
174
|
+
config=ServiceClientConfig(
|
|
175
|
+
service_id="slow-graphql",
|
|
176
|
+
base_url=server.base_url,
|
|
177
|
+
redacted_summary="slow-graphql@local",
|
|
178
|
+
timeout=0.02,
|
|
179
|
+
),
|
|
180
|
+
request=GraphqlRequest(
|
|
181
|
+
operation_id="users.timeout",
|
|
182
|
+
document="query Slow { slow }",
|
|
183
|
+
),
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
assert result.is_failure is True
|
|
187
|
+
assert result.failure.category is ServiceFailureCategory.TIMEOUT
|
|
188
|
+
assert result.failure.code == "timeout"
|
|
189
|
+
assert result.failure.retryable is True
|
|
190
|
+
finally:
|
|
191
|
+
server.close()
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def test_graphql_client_keeps_transport_failures_separate_from_graphql_envelopes() -> None:
|
|
195
|
+
def handler(request: BaseHTTPRequestHandler) -> None:
|
|
196
|
+
_drain_request_body(request)
|
|
197
|
+
request.send_response(401)
|
|
198
|
+
request.end_headers()
|
|
199
|
+
request.wfile.write(b"missing token")
|
|
200
|
+
|
|
201
|
+
server = _start_server(handler)
|
|
202
|
+
try:
|
|
203
|
+
result = graphql_client(
|
|
204
|
+
config=ServiceClientConfig(
|
|
205
|
+
service_id="users-graphql",
|
|
206
|
+
base_url=server.base_url,
|
|
207
|
+
redacted_summary="users-graphql@local",
|
|
208
|
+
),
|
|
209
|
+
request=GraphqlRequest(
|
|
210
|
+
operation_id="users.transport",
|
|
211
|
+
document="query Viewer { viewer { id } }",
|
|
212
|
+
),
|
|
213
|
+
)
|
|
214
|
+
|
|
215
|
+
assert result.is_failure is True
|
|
216
|
+
assert result.failure.category is ServiceFailureCategory.AUTH
|
|
217
|
+
assert result.failure.code == "unauthorized"
|
|
218
|
+
assert result.failure.status_code == 401
|
|
219
|
+
finally:
|
|
220
|
+
server.close()
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def test_graphql_client_rejects_mutation_documents_in_v1() -> None:
|
|
224
|
+
result = graphql_client(
|
|
225
|
+
config=ServiceClientConfig(
|
|
226
|
+
service_id="users-graphql",
|
|
227
|
+
base_url="https://example.test",
|
|
228
|
+
redacted_summary="users-graphql@example",
|
|
229
|
+
),
|
|
230
|
+
request=GraphqlRequest(
|
|
231
|
+
operation_id="users.mutation",
|
|
232
|
+
document="mutation UpdateUser { updateUser(id: 1) { id } }",
|
|
233
|
+
),
|
|
234
|
+
)
|
|
235
|
+
|
|
236
|
+
assert result.is_failure is True
|
|
237
|
+
assert result.failure.category is ServiceFailureCategory.GRAPHQL
|
|
238
|
+
assert result.failure.code == "mutation_not_supported"
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def test_graphql_client_describes_its_config_and_closes_cleanly() -> None:
|
|
242
|
+
client = GraphqlClient(
|
|
243
|
+
ServiceClientConfig(
|
|
244
|
+
service_id="users-graphql",
|
|
245
|
+
base_url="https://example.test",
|
|
246
|
+
redacted_summary="users-graphql@example",
|
|
247
|
+
)
|
|
248
|
+
)
|
|
249
|
+
|
|
250
|
+
assert client.describe().service_id == "users-graphql"
|
|
251
|
+
assert client.describe().transport_id == "graphql"
|
|
252
|
+
|
|
253
|
+
closed = client.close()
|
|
254
|
+
assert closed.is_success is True
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def _start_server(handler):
|
|
258
|
+
class _Handler(BaseHTTPRequestHandler):
|
|
259
|
+
def do_POST(self) -> None: # noqa: N802
|
|
260
|
+
handler(self)
|
|
261
|
+
|
|
262
|
+
def log_message(self, format: str, *args) -> None: # noqa: A003
|
|
263
|
+
return None
|
|
264
|
+
|
|
265
|
+
server = ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
|
|
266
|
+
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
|
267
|
+
thread.start()
|
|
268
|
+
return _ServerHandle(
|
|
269
|
+
base_url=f"http://127.0.0.1:{server.server_address[1]}",
|
|
270
|
+
server=server,
|
|
271
|
+
thread=thread,
|
|
272
|
+
)
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def _drain_request_body(request: BaseHTTPRequestHandler) -> None:
|
|
276
|
+
content_length = int(request.headers.get("Content-Length", "0"))
|
|
277
|
+
if content_length > 0:
|
|
278
|
+
request.rfile.read(content_length)
|