solidping 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.
solidping/__init__.py ADDED
@@ -0,0 +1,29 @@
1
+ """Official Python SDK for SolidPing."""
2
+
3
+ from solidping._client import SolidPing
4
+ from solidping._errors import (
5
+ APIConnectionError,
6
+ APIError,
7
+ APITimeoutError,
8
+ AuthenticationError,
9
+ ConflictError,
10
+ NotFoundError,
11
+ PermissionDeniedError,
12
+ RateLimitError,
13
+ SolidPingError,
14
+ ValidationError,
15
+ )
16
+
17
+ __all__ = [
18
+ "APIConnectionError",
19
+ "APIError",
20
+ "APITimeoutError",
21
+ "AuthenticationError",
22
+ "ConflictError",
23
+ "NotFoundError",
24
+ "PermissionDeniedError",
25
+ "RateLimitError",
26
+ "SolidPing",
27
+ "SolidPingError",
28
+ "ValidationError",
29
+ ]
solidping/_client.py ADDED
@@ -0,0 +1,175 @@
1
+ """The client: configuration, one ``httpx.Client``, auth, retries and error mapping."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import os
7
+ import time
8
+ from importlib import metadata
9
+ from typing import Any, Self
10
+ from urllib.parse import quote
11
+
12
+ import httpx
13
+
14
+ from solidping._errors import (
15
+ APIConnectionError,
16
+ APITimeoutError,
17
+ SolidPingError,
18
+ error_from_response,
19
+ )
20
+ from solidping._generated.operations import OPERATIONS
21
+ from solidping._retry import send_with_retries
22
+ from solidping.resources.channels import Channels
23
+ from solidping.resources.checks import Checks
24
+ from solidping.resources.incidents import Incidents
25
+ from solidping.resources.maintenance_windows import MaintenanceWindows
26
+ from solidping.resources.status_pages import StatusPages
27
+
28
+ DEFAULT_URL = "https://solidping.io"
29
+ logger = logging.getLogger("solidping")
30
+
31
+
32
+ def _version() -> str:
33
+ try:
34
+ return metadata.version("solidping")
35
+ except metadata.PackageNotFoundError: # pragma: no cover - not installed
36
+ return "0.0.0"
37
+
38
+
39
+ def _setup_logging() -> None:
40
+ """``SOLIDPING_LOG=debug`` logs every request and response status to stderr."""
41
+ if os.environ.get("SOLIDPING_LOG", "").lower() != "debug":
42
+ return
43
+ logger.setLevel(logging.DEBUG)
44
+ if not any(getattr(h, "_solidping", False) for h in logger.handlers):
45
+ handler = logging.StreamHandler()
46
+ handler.setFormatter(logging.Formatter("%(asctime)s %(name)s %(message)s"))
47
+ handler._solidping = True # type: ignore[attr-defined]
48
+ logger.addHandler(handler)
49
+
50
+
51
+ class SolidPing:
52
+ """Client of the SolidPing API for one organization.
53
+
54
+ ``url``, ``org`` and ``token`` fall back to ``SOLIDPING_URL`` (default
55
+ ``https://solidping.io``), ``SOLIDPING_ORG`` and ``SOLIDPING_TOKEN``. ``timeout`` is in seconds
56
+ and ``max_retries`` is the number of retries after the first attempt (0 disables them).
57
+ """
58
+
59
+ def __init__(
60
+ self,
61
+ url: str | None = None,
62
+ org: str | None = None,
63
+ token: str | None = None,
64
+ timeout: float = 30,
65
+ max_retries: int = 2,
66
+ ) -> None:
67
+ self.url = (url or os.environ.get("SOLIDPING_URL") or DEFAULT_URL).rstrip("/")
68
+ self.org = org or os.environ.get("SOLIDPING_ORG")
69
+ token = token or os.environ.get("SOLIDPING_TOKEN")
70
+ if not self.org:
71
+ raise SolidPingError("org is required: pass org= or set SOLIDPING_ORG")
72
+ if not token:
73
+ raise SolidPingError("token is required: pass token= or set SOLIDPING_TOKEN")
74
+ self.timeout = timeout
75
+ self.max_retries = max(0, max_retries)
76
+ _setup_logging()
77
+ self._http = httpx.Client(
78
+ timeout=timeout,
79
+ headers={
80
+ "Authorization": f"Bearer {token}",
81
+ "User-Agent": f"solidping-python/{_version()}",
82
+ "Accept": "application/json",
83
+ },
84
+ )
85
+ self.checks = Checks(self)
86
+ self.incidents = Incidents(self)
87
+ self.status_pages = StatusPages(self)
88
+ self.maintenance_windows = MaintenanceWindows(self)
89
+ self.channels = Channels(self)
90
+
91
+ def __enter__(self) -> Self:
92
+ return self
93
+
94
+ def __exit__(self, *exc: object) -> None:
95
+ self.close()
96
+
97
+ def close(self) -> None:
98
+ self._http.close()
99
+
100
+ def request(
101
+ self,
102
+ method: str,
103
+ path: str,
104
+ body: Any = None,
105
+ params: dict[str, Any] | None = None,
106
+ ) -> Any:
107
+ """Call any endpoint with the same auth, retries and errors; return the decoded JSON.
108
+
109
+ ``path`` is relative to the server URL (``/api/v1/orgs/acme/regions``). The result is
110
+ ``None`` when the response has no body.
111
+ """
112
+ method = method.upper()
113
+ url = self.url + (path if path.startswith("/") else "/" + path)
114
+ query = {k: _query_value(v) for k, v in (params or {}).items() if v is not None}
115
+
116
+ def send() -> httpx.Response:
117
+ started = time.monotonic()
118
+ response = self._http.request(method, url, json=body, params=query or None)
119
+ logger.debug(
120
+ "%s %s -> %s (%.0f ms)",
121
+ method,
122
+ path,
123
+ response.status_code,
124
+ (time.monotonic() - started) * 1000,
125
+ )
126
+ return response
127
+
128
+ def on_retry(attempt: int, reason: str) -> None:
129
+ logger.debug(
130
+ "%s %s: %s, retry %d/%d", method, path, reason, attempt + 1, self.max_retries
131
+ )
132
+
133
+ try:
134
+ response = send_with_retries(send, method, self.max_retries, on_retry)
135
+ except httpx.TimeoutException as e:
136
+ logger.debug("%s %s: timeout", method, path)
137
+ raise APITimeoutError(f"{method} {path}: timed out after {self.timeout}s") from e
138
+ except httpx.TransportError as e:
139
+ logger.debug("%s %s: connection error", method, path)
140
+ raise APIConnectionError(f"{method} {path}: {e}") from e
141
+
142
+ data = _decode(response)
143
+ if response.status_code >= 400:
144
+ raise error_from_response(response.status_code, data)
145
+ return data
146
+
147
+ def _call(
148
+ self,
149
+ operation_id: str,
150
+ path_args: dict[str, str] | None = None,
151
+ params: dict[str, Any] | None = None,
152
+ body: Any = None,
153
+ ) -> Any:
154
+ """Call an operation of the generated table, injecting the organization."""
155
+ op = OPERATIONS[operation_id]
156
+ args = {"org": self.org, **(path_args or {})}
157
+ path = op.path.format(**{k: quote(str(v), safe="") for k, v in args.items()})
158
+ return self.request(op.method, path, body=body, params=params)
159
+
160
+
161
+ def _query_value(value: Any) -> Any:
162
+ if isinstance(value, bool):
163
+ return "true" if value else "false"
164
+ if isinstance(value, list | tuple):
165
+ return ",".join(str(v) for v in value)
166
+ return value
167
+
168
+
169
+ def _decode(response: httpx.Response) -> Any:
170
+ if not response.content:
171
+ return None
172
+ try:
173
+ return response.json()
174
+ except ValueError:
175
+ return response.text
solidping/_errors.py ADDED
@@ -0,0 +1,88 @@
1
+ """One exception hierarchy: ``SolidPingError`` is the base of everything the SDK raises."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from solidping._generated.models import ValidationErrorField
8
+
9
+
10
+ class SolidPingError(Exception):
11
+ """Base class of every error raised by the SDK."""
12
+
13
+
14
+ class APIConnectionError(SolidPingError):
15
+ """The server could not be reached (DNS, refused or dropped connection...)."""
16
+
17
+
18
+ class APITimeoutError(APIConnectionError):
19
+ """The server did not answer within ``timeout`` seconds."""
20
+
21
+
22
+ class APIError(SolidPingError):
23
+ """The API answered with an error status, carrying the API error shape."""
24
+
25
+ def __init__(
26
+ self,
27
+ status: int,
28
+ code: str | None = None,
29
+ title: str | None = None,
30
+ detail: str | None = None,
31
+ fields: list[ValidationErrorField] | None = None,
32
+ ) -> None:
33
+ self.status = status
34
+ # The code is an open string: a code this SDK does not know is still kept as is.
35
+ self.code = code
36
+ self.title = title
37
+ self.detail = detail
38
+ self.fields = fields or []
39
+ super().__init__(" - ".join(str(p) for p in (status, code, title, detail) if p))
40
+
41
+
42
+ class AuthenticationError(APIError):
43
+ """401: missing, invalid or expired token."""
44
+
45
+
46
+ class PermissionDeniedError(APIError):
47
+ """403: the token is valid but not allowed to do this."""
48
+
49
+
50
+ class NotFoundError(APIError):
51
+ """404."""
52
+
53
+
54
+ class ValidationError(APIError):
55
+ """400 or 422: the request was rejected, see ``fields``."""
56
+
57
+
58
+ class ConflictError(APIError):
59
+ """409."""
60
+
61
+
62
+ class RateLimitError(APIError):
63
+ """429, after the retries."""
64
+
65
+
66
+ _BY_STATUS: dict[int, type[APIError]] = {
67
+ 400: ValidationError,
68
+ 401: AuthenticationError,
69
+ 403: PermissionDeniedError,
70
+ 404: NotFoundError,
71
+ 409: ConflictError,
72
+ 422: ValidationError,
73
+ 429: RateLimitError,
74
+ }
75
+
76
+
77
+ def error_from_response(status: int, body: Any) -> APIError:
78
+ """Map an error response to an exception by HTTP status, whatever the ``code`` is."""
79
+ data = body if isinstance(body, dict) else {}
80
+ fields = [
81
+ ValidationErrorField.from_dict(f) for f in data.get("fields") or [] if isinstance(f, dict)
82
+ ]
83
+ detail = data.get("detail")
84
+ if detail is None and body is not None and not isinstance(body, dict):
85
+ detail = str(body)[:500]
86
+ return _BY_STATUS.get(status, APIError)(
87
+ status, data.get("code"), data.get("title"), detail, fields
88
+ )
@@ -0,0 +1,5 @@
1
+ """Code generated from SolidPing's OpenAPI spec.
2
+
3
+ Generated by scripts/generate.py from openapi/openapi.yaml. DO NOT EDIT: change the generator
4
+ and run `make generate`.
5
+ """