watchlogdev 0.1.0__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.
- watchlog/__init__.py +59 -0
- watchlog/_endpoints.py +62 -0
- watchlog/_operations.py +509 -0
- watchlog/_response.py +91 -0
- watchlog/_serialization.py +122 -0
- watchlog/_version.py +1 -0
- watchlog/client.py +452 -0
- watchlog/errors.py +76 -0
- watchlog/models.py +81 -0
- watchlog/py.typed +1 -0
- watchlogdev-0.1.0.dist-info/METADATA +208 -0
- watchlogdev-0.1.0.dist-info/RECORD +14 -0
- watchlogdev-0.1.0.dist-info/WHEEL +4 -0
- watchlogdev-0.1.0.dist-info/licenses/LICENSE +21 -0
watchlog/_response.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""Buffered HTTP response preservation and decoding."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from types import MappingProxyType
|
|
7
|
+
from typing import Any, Literal
|
|
8
|
+
|
|
9
|
+
import httpx
|
|
10
|
+
|
|
11
|
+
from .errors import WatchlogAPIError, WatchlogResponseDecodingError
|
|
12
|
+
from .models import APIResponse, BinaryResponse, JsonResponse, RawResponse
|
|
13
|
+
|
|
14
|
+
_ERROR_MESSAGE_KEYS = ("error", "message", "error_message", "detail")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def create_raw_response(response: httpx.Response, body: bytes) -> RawResponse:
|
|
18
|
+
grouped: dict[str, list[str]] = {}
|
|
19
|
+
for name, value in response.headers.multi_items():
|
|
20
|
+
grouped.setdefault(name.lower(), []).append(value)
|
|
21
|
+
return RawResponse(
|
|
22
|
+
status=response.status_code,
|
|
23
|
+
status_text=response.reason_phrase,
|
|
24
|
+
headers=MappingProxyType({name: tuple(values) for name, values in grouped.items()}),
|
|
25
|
+
content_type=response.headers.get("content-type"),
|
|
26
|
+
body=body,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def create_api_error(raw_response: RawResponse) -> WatchlogAPIError:
|
|
31
|
+
parsed, value = _try_parse_json(raw_response.body)
|
|
32
|
+
message = None
|
|
33
|
+
code: str | None = None
|
|
34
|
+
if parsed and isinstance(value, dict):
|
|
35
|
+
# The API answers {"error": {"code", "message"}}.
|
|
36
|
+
nested = value.get("error")
|
|
37
|
+
if isinstance(nested, dict):
|
|
38
|
+
if isinstance(nested.get("message"), str):
|
|
39
|
+
message = nested["message"]
|
|
40
|
+
if isinstance(nested.get("code"), str):
|
|
41
|
+
code = nested["code"]
|
|
42
|
+
for key in _ERROR_MESSAGE_KEYS:
|
|
43
|
+
candidate = value.get(key)
|
|
44
|
+
if isinstance(candidate, str) and candidate:
|
|
45
|
+
message = candidate
|
|
46
|
+
break
|
|
47
|
+
return WatchlogAPIError(
|
|
48
|
+
raw_response=raw_response,
|
|
49
|
+
response_body=value if parsed else None,
|
|
50
|
+
error_message=message,
|
|
51
|
+
error_code=code,
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def decode_success_response(
|
|
56
|
+
raw_response: RawResponse, expected: Literal["json", "any"]
|
|
57
|
+
) -> APIResponse:
|
|
58
|
+
if not _is_json_media_type(raw_response.content_type):
|
|
59
|
+
if expected == "json":
|
|
60
|
+
raise WatchlogResponseDecodingError(
|
|
61
|
+
"Watchlog returned a successful non-JSON response for a JSON operation.",
|
|
62
|
+
raw_response,
|
|
63
|
+
TypeError(f"Unexpected content type: {raw_response.content_type}."),
|
|
64
|
+
)
|
|
65
|
+
return BinaryResponse(
|
|
66
|
+
bytes=raw_response.body,
|
|
67
|
+
content_type=raw_response.content_type,
|
|
68
|
+
raw_response=raw_response,
|
|
69
|
+
)
|
|
70
|
+
parsed, value = _try_parse_json(raw_response.body)
|
|
71
|
+
if not parsed:
|
|
72
|
+
raise WatchlogResponseDecodingError(
|
|
73
|
+
"Watchlog returned a successful JSON response that could not be decoded.",
|
|
74
|
+
raw_response,
|
|
75
|
+
value if isinstance(value, Exception) else None,
|
|
76
|
+
)
|
|
77
|
+
return JsonResponse(data=value, raw_response=raw_response)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _is_json_media_type(content_type: str | None) -> bool:
|
|
81
|
+
if content_type is None:
|
|
82
|
+
return False
|
|
83
|
+
media_type = content_type.split(";", 1)[0].strip().lower()
|
|
84
|
+
return media_type == "application/json" or media_type.endswith("+json")
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _try_parse_json(body: bytes) -> tuple[bool, Any]:
|
|
88
|
+
try:
|
|
89
|
+
return True, json.loads(body)
|
|
90
|
+
except (UnicodeDecodeError, json.JSONDecodeError) as cause:
|
|
91
|
+
return False, cause
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""Request serialization: path filling, query pairs and JSON bodies."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import math
|
|
7
|
+
import re
|
|
8
|
+
from collections.abc import Mapping
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from typing import Any
|
|
11
|
+
from urllib.parse import quote, urlencode
|
|
12
|
+
|
|
13
|
+
from .errors import WatchlogSerializationError
|
|
14
|
+
from .models import HTTPMethod
|
|
15
|
+
|
|
16
|
+
_PATH_PARAM = re.compile(r"\{([^}]+)\}")
|
|
17
|
+
# The API reads the global parameters from the query string, whatever the method.
|
|
18
|
+
QUERY_STRING_PARAMS = {"/products/{id}/check": ("wait",)}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class _JsonNull:
|
|
22
|
+
__slots__ = ()
|
|
23
|
+
|
|
24
|
+
def __repr__(self) -> str:
|
|
25
|
+
return "JSON_NULL"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
JSON_NULL = _JsonNull()
|
|
29
|
+
"""Internal marker sent as ``null`` in a JSON body, where ``None`` means "not set" and is omitted."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True, slots=True)
|
|
33
|
+
class SerializedRequest:
|
|
34
|
+
path: str
|
|
35
|
+
query: list[tuple[str, str]]
|
|
36
|
+
body: dict[str, Any] | None
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def serialize_request(
|
|
40
|
+
method: HTTPMethod, path_template: str, params: Mapping[str, Any] | None
|
|
41
|
+
) -> SerializedRequest:
|
|
42
|
+
"""Fill ``{name}`` path segments, then send the rest as query pairs (GET, DELETE) or a JSON body (POST, PATCH).
|
|
43
|
+
|
|
44
|
+
``wait`` stays in the query string on POST /products/{id}/check.
|
|
45
|
+
|
|
46
|
+
``None`` values and empty sequences are omitted; ``False`` and ``0`` are sent. ``JSON_NULL`` becomes ``null``
|
|
47
|
+
in a JSON body.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
if params is not None and not isinstance(params, Mapping):
|
|
51
|
+
raise WatchlogSerializationError("Request parameters must be a mapping.")
|
|
52
|
+
remaining = {name: value for name, value in (params or {}).items() if value is not None}
|
|
53
|
+
|
|
54
|
+
def fill(match: re.Match[str]) -> str:
|
|
55
|
+
name = match.group(1)
|
|
56
|
+
if name not in remaining:
|
|
57
|
+
raise WatchlogSerializationError(f'The "{name}" path parameter is required.', name)
|
|
58
|
+
return quote(to_wire_string(name, remaining.pop(name)), safe="")
|
|
59
|
+
|
|
60
|
+
path = _PATH_PARAM.sub(fill, path_template)
|
|
61
|
+
|
|
62
|
+
if method in ("GET", "DELETE"):
|
|
63
|
+
query: list[tuple[str, str]] = []
|
|
64
|
+
for name, value in remaining.items():
|
|
65
|
+
if isinstance(value, (list, tuple)):
|
|
66
|
+
query.extend(
|
|
67
|
+
(name, to_wire_string(name, item)) for item in value if item is not None
|
|
68
|
+
)
|
|
69
|
+
else:
|
|
70
|
+
query.append((name, to_wire_string(name, value)))
|
|
71
|
+
return SerializedRequest(path=path, query=query, body=None)
|
|
72
|
+
|
|
73
|
+
query = [
|
|
74
|
+
(name, to_wire_string(name, remaining.pop(name)))
|
|
75
|
+
for name in QUERY_STRING_PARAMS.get(path_template, ())
|
|
76
|
+
if name in remaining
|
|
77
|
+
]
|
|
78
|
+
for name, value in remaining.items():
|
|
79
|
+
if isinstance(value, float) and not math.isfinite(value):
|
|
80
|
+
raise WatchlogSerializationError(
|
|
81
|
+
f'The "{name}" parameter must be a finite number.', name
|
|
82
|
+
)
|
|
83
|
+
body = {name: None if value is JSON_NULL else value for name, value in remaining.items()}
|
|
84
|
+
return SerializedRequest(path=path, query=query, body=body)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def to_wire_string(name: str, value: Any) -> str:
|
|
88
|
+
if isinstance(value, bool):
|
|
89
|
+
return "true" if value else "false"
|
|
90
|
+
if isinstance(value, str):
|
|
91
|
+
return value
|
|
92
|
+
if isinstance(value, int):
|
|
93
|
+
return str(value)
|
|
94
|
+
if isinstance(value, float):
|
|
95
|
+
if not math.isfinite(value):
|
|
96
|
+
raise WatchlogSerializationError(
|
|
97
|
+
f'The "{name}" parameter must be a finite number.', name
|
|
98
|
+
)
|
|
99
|
+
return str(int(value)) if value.is_integer() else repr(value)
|
|
100
|
+
if isinstance(value, (Mapping, list, tuple)):
|
|
101
|
+
try:
|
|
102
|
+
return json.dumps(value, separators=(",", ":"), ensure_ascii=False)
|
|
103
|
+
except (TypeError, ValueError) as cause:
|
|
104
|
+
raise WatchlogSerializationError(
|
|
105
|
+
f'The "{name}" parameter could not be serialized.', name
|
|
106
|
+
) from cause
|
|
107
|
+
raise WatchlogSerializationError(
|
|
108
|
+
f'The "{name}" parameter has an unsupported type ({type(value).__name__}).', name
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def encode_query(pairs: list[tuple[str, str]]) -> str:
|
|
113
|
+
return urlencode(pairs, quote_via=quote)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def encode_json_body(body: Mapping[str, Any]) -> bytes:
|
|
117
|
+
try:
|
|
118
|
+
return json.dumps(body, ensure_ascii=False, allow_nan=False).encode("utf-8")
|
|
119
|
+
except (TypeError, ValueError) as cause:
|
|
120
|
+
raise WatchlogSerializationError(
|
|
121
|
+
"The request body could not be serialized as JSON."
|
|
122
|
+
) from cause
|
watchlog/_version.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
watchlog/client.py
ADDED
|
@@ -0,0 +1,452 @@
|
|
|
1
|
+
"""Blocking and async-I/O Watchlog clients backed by HTTPX."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import os
|
|
7
|
+
import time
|
|
8
|
+
from collections.abc import Awaitable, Callable, Iterable, Mapping
|
|
9
|
+
from concurrent.futures import Future, ThreadPoolExecutor
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from types import TracebackType
|
|
12
|
+
from typing import Any, Literal, Self, TypeVar
|
|
13
|
+
from urllib.parse import urlsplit
|
|
14
|
+
|
|
15
|
+
import httpx
|
|
16
|
+
|
|
17
|
+
from ._endpoints import ENDPOINTS
|
|
18
|
+
from ._operations import _AsyncOperations, _SyncOperations
|
|
19
|
+
from ._response import create_api_error, create_raw_response, decode_success_response
|
|
20
|
+
from ._serialization import encode_json_body, encode_query, serialize_request
|
|
21
|
+
from ._version import __version__
|
|
22
|
+
from .errors import (
|
|
23
|
+
WatchlogConfigurationError,
|
|
24
|
+
WatchlogSerializationError,
|
|
25
|
+
WatchlogTransportError,
|
|
26
|
+
)
|
|
27
|
+
from .models import APIResponse, BatchResult, HTTPMethod, RawResponse, RequestOptions
|
|
28
|
+
|
|
29
|
+
_I = TypeVar("_I")
|
|
30
|
+
_T = TypeVar("_T")
|
|
31
|
+
|
|
32
|
+
DEFAULT_BASE_URL = "https://www.watchlog.dev/api/v1"
|
|
33
|
+
DEFAULT_TIMEOUT = 120.0
|
|
34
|
+
DEFAULT_CONCURRENCY = 10
|
|
35
|
+
"""Tasks run at the same time by ``batch()``."""
|
|
36
|
+
MAX_RETRIES = 3
|
|
37
|
+
"""Retries after a network error or a 408, 500, 502, 503 or 504 response."""
|
|
38
|
+
RETRY_BACKOFF_FACTOR = 1.5
|
|
39
|
+
"""Each retry waits this many times longer than the previous one (a Retry-After header wins)."""
|
|
40
|
+
DEFAULT_RETRY_DELAY = 1.0
|
|
41
|
+
"""Seconds before the first retry."""
|
|
42
|
+
MAX_RETRY_DELAY = 30.0
|
|
43
|
+
RETRYABLE_STATUSES = frozenset({408, 500, 502, 503, 504})
|
|
44
|
+
API_KEY_ENVIRONMENT_VARIABLE = "WATCHLOG_API_KEY"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass(frozen=True, slots=True)
|
|
48
|
+
class _Configuration:
|
|
49
|
+
api_key: str
|
|
50
|
+
base_url: str
|
|
51
|
+
timeout: float | None
|
|
52
|
+
headers: Mapping[str, str]
|
|
53
|
+
max_retries: int
|
|
54
|
+
retry_delay: float
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@dataclass(frozen=True, slots=True)
|
|
58
|
+
class _PreparedRequest:
|
|
59
|
+
method: HTTPMethod
|
|
60
|
+
url: str
|
|
61
|
+
headers: dict[str, str]
|
|
62
|
+
content: bytes | None
|
|
63
|
+
timeout: float | None
|
|
64
|
+
expected: Literal["json", "any"]
|
|
65
|
+
max_retries: int
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class WatchlogClient(_SyncOperations):
|
|
69
|
+
"""Reusable blocking Watchlog client. Use it as a context manager or call ``close()``."""
|
|
70
|
+
|
|
71
|
+
__slots__ = ("_closed", "_configuration", "_http_client", "_owns_http_client")
|
|
72
|
+
|
|
73
|
+
def __init__(
|
|
74
|
+
self,
|
|
75
|
+
api_key: str | None = None,
|
|
76
|
+
*,
|
|
77
|
+
base_url: str | None = None,
|
|
78
|
+
timeout: float | None = DEFAULT_TIMEOUT,
|
|
79
|
+
headers: Mapping[str, str] | None = None,
|
|
80
|
+
max_retries: int = MAX_RETRIES,
|
|
81
|
+
retry_delay: float = DEFAULT_RETRY_DELAY,
|
|
82
|
+
http_client: httpx.Client | None = None,
|
|
83
|
+
) -> None:
|
|
84
|
+
self._configuration = _build_configuration(
|
|
85
|
+
api_key, base_url, timeout, headers, max_retries, retry_delay
|
|
86
|
+
)
|
|
87
|
+
if http_client is not None and not isinstance(http_client, httpx.Client):
|
|
88
|
+
raise WatchlogConfigurationError("http_client must be an httpx.Client when provided.")
|
|
89
|
+
self._owns_http_client = http_client is None
|
|
90
|
+
self._http_client = http_client or httpx.Client(follow_redirects=False)
|
|
91
|
+
self._closed = False
|
|
92
|
+
|
|
93
|
+
def request(
|
|
94
|
+
self,
|
|
95
|
+
method: HTTPMethod,
|
|
96
|
+
path: str,
|
|
97
|
+
params: Mapping[str, Any] | None = None,
|
|
98
|
+
*,
|
|
99
|
+
timeout: float | None = None,
|
|
100
|
+
headers: Mapping[str, str] | None = None,
|
|
101
|
+
max_retries: int | None = None,
|
|
102
|
+
) -> APIResponse:
|
|
103
|
+
"""Send any request to the Watchlog API, including endpoints newer than this SDK."""
|
|
104
|
+
|
|
105
|
+
options = RequestOptions(
|
|
106
|
+
method=method, timeout=timeout, headers=headers, max_retries=max_retries
|
|
107
|
+
)
|
|
108
|
+
return self._send(_prepare(self._configuration, method, path, params, options, "any"))
|
|
109
|
+
|
|
110
|
+
def batch(
|
|
111
|
+
self,
|
|
112
|
+
items: Iterable[_I],
|
|
113
|
+
task: Callable[[_I], _T],
|
|
114
|
+
*,
|
|
115
|
+
concurrency: int = DEFAULT_CONCURRENCY,
|
|
116
|
+
) -> list[BatchResult[_T]]:
|
|
117
|
+
"""Run ``task`` for every item on ``concurrency`` threads (default 10).
|
|
118
|
+
|
|
119
|
+
Returns one :class:`BatchResult` per item, in input order; a failing item never stops the others.
|
|
120
|
+
The client is thread-safe, so ``task`` can call its methods directly.
|
|
121
|
+
"""
|
|
122
|
+
|
|
123
|
+
_check_concurrency(concurrency)
|
|
124
|
+
values = list(items)
|
|
125
|
+
if not values:
|
|
126
|
+
return []
|
|
127
|
+
with ThreadPoolExecutor(max_workers=min(concurrency, len(values))) as pool:
|
|
128
|
+
futures = [pool.submit(task, value) for value in values]
|
|
129
|
+
return [_settle(index, future) for index, future in enumerate(futures)]
|
|
130
|
+
|
|
131
|
+
def close(self) -> None:
|
|
132
|
+
"""Close transport resources owned by this client."""
|
|
133
|
+
|
|
134
|
+
if self._closed:
|
|
135
|
+
return
|
|
136
|
+
try:
|
|
137
|
+
if self._owns_http_client:
|
|
138
|
+
self._http_client.close()
|
|
139
|
+
finally:
|
|
140
|
+
self._closed = True
|
|
141
|
+
|
|
142
|
+
def __enter__(self) -> Self:
|
|
143
|
+
self._ensure_open()
|
|
144
|
+
return self
|
|
145
|
+
|
|
146
|
+
def __exit__(
|
|
147
|
+
self,
|
|
148
|
+
exc_type: type[BaseException] | None,
|
|
149
|
+
exc_value: BaseException | None,
|
|
150
|
+
traceback: TracebackType | None,
|
|
151
|
+
) -> None:
|
|
152
|
+
self.close()
|
|
153
|
+
|
|
154
|
+
def _call(
|
|
155
|
+
self, name: str, params: dict[str, Any], options: RequestOptions | None
|
|
156
|
+
) -> APIResponse:
|
|
157
|
+
return self._send(_prepare_operation(self._configuration, name, params, options))
|
|
158
|
+
|
|
159
|
+
def _send(self, prepared: _PreparedRequest) -> APIResponse:
|
|
160
|
+
self._ensure_open()
|
|
161
|
+
attempt = 0
|
|
162
|
+
while True:
|
|
163
|
+
try:
|
|
164
|
+
response = self._http_client.request(
|
|
165
|
+
prepared.method,
|
|
166
|
+
prepared.url,
|
|
167
|
+
headers=prepared.headers,
|
|
168
|
+
content=prepared.content,
|
|
169
|
+
timeout=prepared.timeout,
|
|
170
|
+
follow_redirects=False,
|
|
171
|
+
)
|
|
172
|
+
body = response.read()
|
|
173
|
+
except httpx.TimeoutException as cause:
|
|
174
|
+
raise WatchlogTransportError("Watchlog request timed out.", cause) from cause
|
|
175
|
+
except Exception as cause:
|
|
176
|
+
if attempt < prepared.max_retries:
|
|
177
|
+
time.sleep(_retry_delay(self._configuration.retry_delay, attempt, None))
|
|
178
|
+
attempt += 1
|
|
179
|
+
continue
|
|
180
|
+
raise WatchlogTransportError(
|
|
181
|
+
"Watchlog request failed before an HTTP response body was received.", cause
|
|
182
|
+
) from cause
|
|
183
|
+
raw_response = create_raw_response(response, body)
|
|
184
|
+
if _is_retryable(raw_response) and attempt < prepared.max_retries:
|
|
185
|
+
retry_after = (raw_response.headers.get("retry-after") or (None,))[0]
|
|
186
|
+
time.sleep(_retry_delay(self._configuration.retry_delay, attempt, retry_after))
|
|
187
|
+
attempt += 1
|
|
188
|
+
continue
|
|
189
|
+
return _decode(raw_response, prepared)
|
|
190
|
+
|
|
191
|
+
def _ensure_open(self) -> None:
|
|
192
|
+
if self._closed:
|
|
193
|
+
raise WatchlogConfigurationError("This WatchlogClient is closed.")
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
class AsyncWatchlogClient(_AsyncOperations):
|
|
197
|
+
"""Reusable async-I/O Watchlog client. Use it as an async context manager or await ``aclose()``."""
|
|
198
|
+
|
|
199
|
+
__slots__ = ("_closed", "_configuration", "_http_client", "_owns_http_client")
|
|
200
|
+
|
|
201
|
+
def __init__(
|
|
202
|
+
self,
|
|
203
|
+
api_key: str | None = None,
|
|
204
|
+
*,
|
|
205
|
+
base_url: str | None = None,
|
|
206
|
+
timeout: float | None = DEFAULT_TIMEOUT,
|
|
207
|
+
headers: Mapping[str, str] | None = None,
|
|
208
|
+
max_retries: int = MAX_RETRIES,
|
|
209
|
+
retry_delay: float = DEFAULT_RETRY_DELAY,
|
|
210
|
+
http_client: httpx.AsyncClient | None = None,
|
|
211
|
+
) -> None:
|
|
212
|
+
self._configuration = _build_configuration(
|
|
213
|
+
api_key, base_url, timeout, headers, max_retries, retry_delay
|
|
214
|
+
)
|
|
215
|
+
if http_client is not None and not isinstance(http_client, httpx.AsyncClient):
|
|
216
|
+
raise WatchlogConfigurationError(
|
|
217
|
+
"http_client must be an httpx.AsyncClient when provided."
|
|
218
|
+
)
|
|
219
|
+
self._owns_http_client = http_client is None
|
|
220
|
+
self._http_client = http_client or httpx.AsyncClient(follow_redirects=False)
|
|
221
|
+
self._closed = False
|
|
222
|
+
|
|
223
|
+
async def request(
|
|
224
|
+
self,
|
|
225
|
+
method: HTTPMethod,
|
|
226
|
+
path: str,
|
|
227
|
+
params: Mapping[str, Any] | None = None,
|
|
228
|
+
*,
|
|
229
|
+
timeout: float | None = None,
|
|
230
|
+
headers: Mapping[str, str] | None = None,
|
|
231
|
+
max_retries: int | None = None,
|
|
232
|
+
) -> APIResponse:
|
|
233
|
+
"""Send any request to the Watchlog API, including endpoints newer than this SDK."""
|
|
234
|
+
|
|
235
|
+
options = RequestOptions(
|
|
236
|
+
method=method, timeout=timeout, headers=headers, max_retries=max_retries
|
|
237
|
+
)
|
|
238
|
+
return await self._send(_prepare(self._configuration, method, path, params, options, "any"))
|
|
239
|
+
|
|
240
|
+
async def batch(
|
|
241
|
+
self,
|
|
242
|
+
items: Iterable[_I],
|
|
243
|
+
task: Callable[[_I], Awaitable[_T]],
|
|
244
|
+
*,
|
|
245
|
+
concurrency: int = DEFAULT_CONCURRENCY,
|
|
246
|
+
) -> list[BatchResult[_T]]:
|
|
247
|
+
"""Await ``task`` for every item with at most ``concurrency`` in flight (default 10).
|
|
248
|
+
|
|
249
|
+
Returns one :class:`BatchResult` per item, in input order; a failing item never stops the others.
|
|
250
|
+
"""
|
|
251
|
+
|
|
252
|
+
_check_concurrency(concurrency)
|
|
253
|
+
semaphore = asyncio.Semaphore(concurrency)
|
|
254
|
+
|
|
255
|
+
async def run(index: int, value: _I) -> BatchResult[_T]:
|
|
256
|
+
async with semaphore:
|
|
257
|
+
try:
|
|
258
|
+
return BatchResult(index=index, value=await task(value))
|
|
259
|
+
except Exception as error:
|
|
260
|
+
return BatchResult(index=index, error=error)
|
|
261
|
+
|
|
262
|
+
return list(await asyncio.gather(*(run(i, v) for i, v in enumerate(items))))
|
|
263
|
+
|
|
264
|
+
async def aclose(self) -> None:
|
|
265
|
+
"""Close transport resources owned by this client."""
|
|
266
|
+
|
|
267
|
+
if self._closed:
|
|
268
|
+
return
|
|
269
|
+
try:
|
|
270
|
+
if self._owns_http_client:
|
|
271
|
+
await self._http_client.aclose()
|
|
272
|
+
finally:
|
|
273
|
+
self._closed = True
|
|
274
|
+
|
|
275
|
+
async def __aenter__(self) -> Self:
|
|
276
|
+
self._ensure_open()
|
|
277
|
+
return self
|
|
278
|
+
|
|
279
|
+
async def __aexit__(
|
|
280
|
+
self,
|
|
281
|
+
exc_type: type[BaseException] | None,
|
|
282
|
+
exc_value: BaseException | None,
|
|
283
|
+
traceback: TracebackType | None,
|
|
284
|
+
) -> None:
|
|
285
|
+
await self.aclose()
|
|
286
|
+
|
|
287
|
+
async def _call(
|
|
288
|
+
self, name: str, params: dict[str, Any], options: RequestOptions | None
|
|
289
|
+
) -> APIResponse:
|
|
290
|
+
return await self._send(_prepare_operation(self._configuration, name, params, options))
|
|
291
|
+
|
|
292
|
+
async def _send(self, prepared: _PreparedRequest) -> APIResponse:
|
|
293
|
+
self._ensure_open()
|
|
294
|
+
attempt = 0
|
|
295
|
+
while True:
|
|
296
|
+
try:
|
|
297
|
+
response = await self._http_client.request(
|
|
298
|
+
prepared.method,
|
|
299
|
+
prepared.url,
|
|
300
|
+
headers=prepared.headers,
|
|
301
|
+
content=prepared.content,
|
|
302
|
+
timeout=prepared.timeout,
|
|
303
|
+
follow_redirects=False,
|
|
304
|
+
)
|
|
305
|
+
body = await response.aread()
|
|
306
|
+
except httpx.TimeoutException as cause:
|
|
307
|
+
raise WatchlogTransportError("Watchlog request timed out.", cause) from cause
|
|
308
|
+
except Exception as cause:
|
|
309
|
+
if attempt < prepared.max_retries:
|
|
310
|
+
await asyncio.sleep(
|
|
311
|
+
_retry_delay(self._configuration.retry_delay, attempt, None)
|
|
312
|
+
)
|
|
313
|
+
attempt += 1
|
|
314
|
+
continue
|
|
315
|
+
raise WatchlogTransportError(
|
|
316
|
+
"Watchlog request failed before an HTTP response body was received.", cause
|
|
317
|
+
) from cause
|
|
318
|
+
raw_response = create_raw_response(response, body)
|
|
319
|
+
if _is_retryable(raw_response) and attempt < prepared.max_retries:
|
|
320
|
+
retry_after = (raw_response.headers.get("retry-after") or (None,))[0]
|
|
321
|
+
await asyncio.sleep(
|
|
322
|
+
_retry_delay(self._configuration.retry_delay, attempt, retry_after)
|
|
323
|
+
)
|
|
324
|
+
attempt += 1
|
|
325
|
+
continue
|
|
326
|
+
return _decode(raw_response, prepared)
|
|
327
|
+
|
|
328
|
+
def _ensure_open(self) -> None:
|
|
329
|
+
if self._closed:
|
|
330
|
+
raise WatchlogConfigurationError("This AsyncWatchlogClient is closed.")
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def _build_configuration(
|
|
334
|
+
api_key: str | None,
|
|
335
|
+
base_url: str | None,
|
|
336
|
+
timeout: float | None,
|
|
337
|
+
headers: Mapping[str, str] | None,
|
|
338
|
+
max_retries: int = MAX_RETRIES,
|
|
339
|
+
retry_delay: float = DEFAULT_RETRY_DELAY,
|
|
340
|
+
) -> _Configuration:
|
|
341
|
+
key = api_key if api_key is not None else os.environ.get(API_KEY_ENVIRONMENT_VARIABLE)
|
|
342
|
+
if not isinstance(key, str) or not key.strip():
|
|
343
|
+
raise WatchlogConfigurationError(
|
|
344
|
+
f"A non-blank Watchlog API key is required. Pass api_key or set {API_KEY_ENVIRONMENT_VARIABLE}."
|
|
345
|
+
)
|
|
346
|
+
if any(ch in key for ch in "\r\n"):
|
|
347
|
+
raise WatchlogConfigurationError("The Watchlog API key cannot be used in an HTTP header.")
|
|
348
|
+
url = (base_url or DEFAULT_BASE_URL).rstrip("/")
|
|
349
|
+
parts = urlsplit(url)
|
|
350
|
+
if parts.scheme not in ("http", "https") or not parts.netloc:
|
|
351
|
+
raise WatchlogConfigurationError("base_url must be an absolute http or https URL.")
|
|
352
|
+
if timeout is not None and (not isinstance(timeout, (int, float)) or timeout <= 0):
|
|
353
|
+
raise WatchlogConfigurationError("timeout must be a positive number of seconds or None.")
|
|
354
|
+
if isinstance(max_retries, bool) or not isinstance(max_retries, int) or max_retries < 0:
|
|
355
|
+
raise WatchlogConfigurationError("max_retries must be a non-negative integer.")
|
|
356
|
+
if not isinstance(retry_delay, (int, float)) or retry_delay < 0:
|
|
357
|
+
raise WatchlogConfigurationError("retry_delay must be a non-negative number of seconds.")
|
|
358
|
+
return _Configuration(
|
|
359
|
+
api_key=key,
|
|
360
|
+
base_url=url,
|
|
361
|
+
timeout=timeout,
|
|
362
|
+
headers=dict(headers or {}),
|
|
363
|
+
max_retries=max_retries,
|
|
364
|
+
retry_delay=float(retry_delay),
|
|
365
|
+
)
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def _prepare_operation(
|
|
369
|
+
configuration: _Configuration,
|
|
370
|
+
name: str,
|
|
371
|
+
params: Mapping[str, Any],
|
|
372
|
+
options: RequestOptions | None,
|
|
373
|
+
) -> _PreparedRequest:
|
|
374
|
+
endpoint = ENDPOINTS[name]
|
|
375
|
+
method = (options.method if options else None) or endpoint.methods[0]
|
|
376
|
+
if method not in endpoint.methods:
|
|
377
|
+
raise WatchlogConfigurationError(
|
|
378
|
+
f"{endpoint.path} supports {', '.join(endpoint.methods)}, not {method}."
|
|
379
|
+
)
|
|
380
|
+
for required in endpoint.required:
|
|
381
|
+
if params.get(required) is None:
|
|
382
|
+
raise WatchlogSerializationError(f'The "{required}" parameter is required.', required)
|
|
383
|
+
return _prepare(configuration, method, endpoint.path, params, options, endpoint.response)
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def _prepare(
|
|
387
|
+
configuration: _Configuration,
|
|
388
|
+
method: HTTPMethod,
|
|
389
|
+
path: str,
|
|
390
|
+
params: Mapping[str, Any] | None,
|
|
391
|
+
options: RequestOptions | None,
|
|
392
|
+
expected: Literal["json", "any"],
|
|
393
|
+
) -> _PreparedRequest:
|
|
394
|
+
if method not in ("GET", "POST", "PATCH", "DELETE"):
|
|
395
|
+
raise WatchlogConfigurationError(f"Unsupported HTTP method: {method!r}.")
|
|
396
|
+
if not isinstance(path, str) or not path.startswith("/"):
|
|
397
|
+
raise WatchlogConfigurationError('The request path must start with "/".')
|
|
398
|
+
serialized = serialize_request(method, path, params)
|
|
399
|
+
url = configuration.base_url + serialized.path
|
|
400
|
+
if serialized.query:
|
|
401
|
+
url += "?" + encode_query(serialized.query)
|
|
402
|
+
headers = {
|
|
403
|
+
"Accept": "application/json, */*;q=0.8",
|
|
404
|
+
"User-Agent": f"watchlog-python/{__version__}",
|
|
405
|
+
**configuration.headers,
|
|
406
|
+
**dict((options.headers if options else None) or {}),
|
|
407
|
+
"Authorization": f"Bearer {configuration.api_key}",
|
|
408
|
+
}
|
|
409
|
+
content = None
|
|
410
|
+
if serialized.body is not None:
|
|
411
|
+
headers["Content-Type"] = "application/json"
|
|
412
|
+
content = encode_json_body(serialized.body)
|
|
413
|
+
timeout = options.timeout if options and options.timeout is not None else configuration.timeout
|
|
414
|
+
max_retries = (
|
|
415
|
+
options.max_retries
|
|
416
|
+
if options and options.max_retries is not None
|
|
417
|
+
else configuration.max_retries
|
|
418
|
+
)
|
|
419
|
+
return _PreparedRequest(method, url, headers, content, timeout, expected, max_retries)
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def _decode(raw_response: RawResponse, prepared: _PreparedRequest) -> APIResponse:
|
|
423
|
+
if not 200 <= raw_response.status <= 299:
|
|
424
|
+
raise create_api_error(raw_response)
|
|
425
|
+
return decode_success_response(raw_response, prepared.expected)
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
def _check_concurrency(concurrency: int) -> None:
|
|
429
|
+
if isinstance(concurrency, bool) or not isinstance(concurrency, int) or concurrency < 1:
|
|
430
|
+
raise WatchlogConfigurationError("concurrency must be a positive integer.")
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
def _settle(index: int, future: Future[_T]) -> BatchResult[_T]:
|
|
434
|
+
error = future.exception()
|
|
435
|
+
if error is not None:
|
|
436
|
+
return BatchResult(index=index, error=error)
|
|
437
|
+
return BatchResult(index=index, value=future.result())
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def _is_retryable(raw_response: RawResponse) -> bool:
|
|
441
|
+
return raw_response.status in RETRYABLE_STATUSES
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
def _retry_delay(base: float, attempt: int, retry_after: str | None) -> float:
|
|
445
|
+
if retry_after is not None:
|
|
446
|
+
try:
|
|
447
|
+
seconds = float(retry_after)
|
|
448
|
+
except ValueError:
|
|
449
|
+
seconds = -1.0
|
|
450
|
+
if seconds >= 0:
|
|
451
|
+
return min(seconds, 60.0)
|
|
452
|
+
return float(min(base * RETRY_BACKOFF_FACTOR**attempt, MAX_RETRY_DELAY))
|