punchrelay 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.
- punchrelay/__init__.py +48 -0
- punchrelay/_client.py +162 -0
- punchrelay/_convert.py +40 -0
- punchrelay/_core.py +240 -0
- punchrelay/_errors.py +131 -0
- punchrelay/_generated/__init__.py +1 -0
- punchrelay/_generated/models.py +283 -0
- punchrelay/_paging.py +60 -0
- punchrelay/_transport.py +194 -0
- punchrelay/_version.py +2 -0
- punchrelay/models.py +13 -0
- punchrelay/py.typed +0 -0
- punchrelay/resources/__init__.py +19 -0
- punchrelay/resources/attendance.py +220 -0
- punchrelay/resources/devices.py +123 -0
- punchrelay/resources/locations.py +41 -0
- punchrelay/resources/users.py +105 -0
- punchrelay/resources/webhooks.py +179 -0
- punchrelay/webhooks.py +240 -0
- punchrelay-0.1.0.dist-info/METADATA +282 -0
- punchrelay-0.1.0.dist-info/RECORD +23 -0
- punchrelay-0.1.0.dist-info/WHEEL +4 -0
- punchrelay-0.1.0.dist-info/licenses/LICENSE +21 -0
punchrelay/__init__.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""Client for the PunchRelay API.
|
|
2
|
+
|
|
3
|
+
>>> from punchrelay import PunchRelay
|
|
4
|
+
>>> client = PunchRelay(api_key="prk_live_...", base_url="https://adms.example.com")
|
|
5
|
+
|
|
6
|
+
Request and response types are in :mod:`punchrelay.models`; webhook helpers are also in :mod:`punchrelay.webhooks`.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from ._client import AsyncPunchRelay, PunchRelay
|
|
10
|
+
from ._convert import DateInput, DateTimeInput
|
|
11
|
+
from ._errors import PunchRelayError, SubscriptionSuspendedError
|
|
12
|
+
from ._version import __version__
|
|
13
|
+
from .resources import WebhookDeliveryStatus
|
|
14
|
+
from .webhooks import (
|
|
15
|
+
DEFAULT_TOLERANCE,
|
|
16
|
+
AttendanceCreated,
|
|
17
|
+
WebhookEvent,
|
|
18
|
+
WebhookEventTypes,
|
|
19
|
+
WebhookTest,
|
|
20
|
+
WebhookVerificationError,
|
|
21
|
+
compute_signature,
|
|
22
|
+
is_attendance_created,
|
|
23
|
+
is_valid_signature,
|
|
24
|
+
is_webhook_test,
|
|
25
|
+
verify_webhook,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
__all__ = [
|
|
29
|
+
"DEFAULT_TOLERANCE",
|
|
30
|
+
"AsyncPunchRelay",
|
|
31
|
+
"AttendanceCreated",
|
|
32
|
+
"DateInput",
|
|
33
|
+
"DateTimeInput",
|
|
34
|
+
"PunchRelay",
|
|
35
|
+
"PunchRelayError",
|
|
36
|
+
"SubscriptionSuspendedError",
|
|
37
|
+
"WebhookDeliveryStatus",
|
|
38
|
+
"WebhookEvent",
|
|
39
|
+
"WebhookEventTypes",
|
|
40
|
+
"WebhookTest",
|
|
41
|
+
"WebhookVerificationError",
|
|
42
|
+
"__version__",
|
|
43
|
+
"compute_signature",
|
|
44
|
+
"is_attendance_created",
|
|
45
|
+
"is_valid_signature",
|
|
46
|
+
"is_webhook_test",
|
|
47
|
+
"verify_webhook",
|
|
48
|
+
]
|
punchrelay/_client.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import random as _random_module
|
|
4
|
+
import time
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
|
|
7
|
+
import httpx
|
|
8
|
+
|
|
9
|
+
from ._core import AsyncCore, SyncCore
|
|
10
|
+
from ._transport import AsyncSleep, RetryPolicy, Sleep
|
|
11
|
+
from .resources.attendance import AsyncAttendance, Attendance
|
|
12
|
+
from .resources.devices import AsyncDevices, Devices
|
|
13
|
+
from .resources.locations import AsyncLocations, Locations
|
|
14
|
+
from .resources.users import AsyncUsers, Users
|
|
15
|
+
from .resources.webhooks import AsyncWebhooks, Webhooks
|
|
16
|
+
|
|
17
|
+
__all__ = ["AsyncPunchRelay", "PunchRelay"]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _policy(
|
|
21
|
+
max_retries: int,
|
|
22
|
+
retry_base_delay: float,
|
|
23
|
+
max_retry_delay: float,
|
|
24
|
+
timeout: float | None,
|
|
25
|
+
random: Callable[[], float] | None,
|
|
26
|
+
clock: Callable[[], float] | None,
|
|
27
|
+
) -> RetryPolicy:
|
|
28
|
+
return RetryPolicy(
|
|
29
|
+
max_retries=max(0, max_retries),
|
|
30
|
+
retry_base_delay=retry_base_delay,
|
|
31
|
+
max_retry_delay=max_retry_delay,
|
|
32
|
+
timeout=timeout or None,
|
|
33
|
+
random=random or _random_module.random,
|
|
34
|
+
clock=clock or time.monotonic,
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class PunchRelay(SyncCore):
|
|
39
|
+
"""Client for the PunchRelay API, authenticated with a developer API key.
|
|
40
|
+
|
|
41
|
+
The organisation (tenant) is looked up from the key once and cached, so no call takes a tenant id. Keep one
|
|
42
|
+
client per key and reuse it; it is safe to share between threads. Close it with :meth:`close` or a ``with``
|
|
43
|
+
block.
|
|
44
|
+
|
|
45
|
+
Example::
|
|
46
|
+
|
|
47
|
+
from punchrelay import PunchRelay
|
|
48
|
+
|
|
49
|
+
with PunchRelay(api_key=os.environ["PUNCHRELAY_API_KEY"], base_url="https://adms.example.com") as client:
|
|
50
|
+
for punch in client.attendance.list_all(from_=datetime.now(timezone.utc) - timedelta(days=1)):
|
|
51
|
+
print(punch["userId"], punch["punchedAt"])
|
|
52
|
+
|
|
53
|
+
:param api_key: A developer key, ``prk_live_...``, from the dashboard's API keys page.
|
|
54
|
+
:param base_url: The API host, for example ``https://adms.example.com``. There is no default: it differs per
|
|
55
|
+
deployment.
|
|
56
|
+
:param tenant_id: The key's organisation. Set it to skip the one-time ``GET /api/key-info`` call.
|
|
57
|
+
:param max_retries: Retries after a 429, 5xx or network error. Default 3; 0 turns retries off.
|
|
58
|
+
:param retry_base_delay: First backoff ceiling in seconds, doubled each retry. Default 0.5.
|
|
59
|
+
:param max_retry_delay: Longest wait between retries in seconds. A longer ``Retry-After`` raises the 429
|
|
60
|
+
instead. Default 30.
|
|
61
|
+
:param timeout: Seconds per call, including retries. Default 100; None or 0 turns it off. A call that runs
|
|
62
|
+
out of time raises ``httpx.TimeoutException``.
|
|
63
|
+
:param transport: Replaces the httpx transport, for a test stub or custom networking.
|
|
64
|
+
:param proxy: A proxy URL for the default transport.
|
|
65
|
+
"""
|
|
66
|
+
|
|
67
|
+
attendance: Attendance
|
|
68
|
+
"""Attendance punches: list, page through, export, stats, delete."""
|
|
69
|
+
devices: Devices
|
|
70
|
+
"""Devices: register, update, activate, send commands, pull data."""
|
|
71
|
+
users: Users
|
|
72
|
+
"""Employees enrolled on devices, and syncing them to devices."""
|
|
73
|
+
locations: Locations
|
|
74
|
+
"""Locations that group devices."""
|
|
75
|
+
webhooks: Webhooks
|
|
76
|
+
"""Webhook endpoints and their deliveries."""
|
|
77
|
+
|
|
78
|
+
def __init__(
|
|
79
|
+
self,
|
|
80
|
+
*,
|
|
81
|
+
api_key: str,
|
|
82
|
+
base_url: str | httpx.URL,
|
|
83
|
+
tenant_id: str | None = None,
|
|
84
|
+
max_retries: int = 3,
|
|
85
|
+
retry_base_delay: float = 0.5,
|
|
86
|
+
max_retry_delay: float = 30.0,
|
|
87
|
+
timeout: float | None = 100.0,
|
|
88
|
+
transport: httpx.BaseTransport | None = None,
|
|
89
|
+
proxy: str | None = None,
|
|
90
|
+
_sleep: Sleep | None = None,
|
|
91
|
+
_random: Callable[[], float] | None = None,
|
|
92
|
+
_clock: Callable[[], float] | None = None,
|
|
93
|
+
) -> None:
|
|
94
|
+
super().__init__(
|
|
95
|
+
api_key=api_key,
|
|
96
|
+
base_url=base_url,
|
|
97
|
+
tenant_id=tenant_id,
|
|
98
|
+
policy=_policy(max_retries, retry_base_delay, max_retry_delay, timeout, _random, _clock),
|
|
99
|
+
transport=transport,
|
|
100
|
+
proxy=proxy,
|
|
101
|
+
sleep=_sleep,
|
|
102
|
+
)
|
|
103
|
+
self.attendance = Attendance(self)
|
|
104
|
+
self.devices = Devices(self)
|
|
105
|
+
self.users = Users(self)
|
|
106
|
+
self.locations = Locations(self)
|
|
107
|
+
self.webhooks = Webhooks(self)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class AsyncPunchRelay(AsyncCore):
|
|
111
|
+
"""The asyncio client for the PunchRelay API. Same options and methods as :class:`PunchRelay`, awaited.
|
|
112
|
+
|
|
113
|
+
Concurrent first calls share one key-info lookup. Close it with :meth:`aclose` or an ``async with`` block.
|
|
114
|
+
|
|
115
|
+
Example::
|
|
116
|
+
|
|
117
|
+
async with AsyncPunchRelay(api_key=..., base_url="https://adms.example.com") as client:
|
|
118
|
+
async for punch in client.attendance.list_all(from_=since):
|
|
119
|
+
print(punch["userId"], punch["punchedAt"])
|
|
120
|
+
"""
|
|
121
|
+
|
|
122
|
+
attendance: AsyncAttendance
|
|
123
|
+
"""Attendance punches: list, page through, export, stats, delete."""
|
|
124
|
+
devices: AsyncDevices
|
|
125
|
+
"""Devices: register, update, activate, send commands, pull data."""
|
|
126
|
+
users: AsyncUsers
|
|
127
|
+
"""Employees enrolled on devices, and syncing them to devices."""
|
|
128
|
+
locations: AsyncLocations
|
|
129
|
+
"""Locations that group devices."""
|
|
130
|
+
webhooks: AsyncWebhooks
|
|
131
|
+
"""Webhook endpoints and their deliveries."""
|
|
132
|
+
|
|
133
|
+
def __init__(
|
|
134
|
+
self,
|
|
135
|
+
*,
|
|
136
|
+
api_key: str,
|
|
137
|
+
base_url: str | httpx.URL,
|
|
138
|
+
tenant_id: str | None = None,
|
|
139
|
+
max_retries: int = 3,
|
|
140
|
+
retry_base_delay: float = 0.5,
|
|
141
|
+
max_retry_delay: float = 30.0,
|
|
142
|
+
timeout: float | None = 100.0,
|
|
143
|
+
transport: httpx.AsyncBaseTransport | None = None,
|
|
144
|
+
proxy: str | None = None,
|
|
145
|
+
_sleep: AsyncSleep | None = None,
|
|
146
|
+
_random: Callable[[], float] | None = None,
|
|
147
|
+
_clock: Callable[[], float] | None = None,
|
|
148
|
+
) -> None:
|
|
149
|
+
super().__init__(
|
|
150
|
+
api_key=api_key,
|
|
151
|
+
base_url=base_url,
|
|
152
|
+
tenant_id=tenant_id,
|
|
153
|
+
policy=_policy(max_retries, retry_base_delay, max_retry_delay, timeout, _random, _clock),
|
|
154
|
+
transport=transport,
|
|
155
|
+
proxy=proxy,
|
|
156
|
+
sleep=_sleep,
|
|
157
|
+
)
|
|
158
|
+
self.attendance = AsyncAttendance(self)
|
|
159
|
+
self.devices = AsyncDevices(self)
|
|
160
|
+
self.users = AsyncUsers(self)
|
|
161
|
+
self.locations = AsyncLocations(self)
|
|
162
|
+
self.webhooks = AsyncWebhooks(self)
|
punchrelay/_convert.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from datetime import UTC, date, datetime
|
|
4
|
+
|
|
5
|
+
__all__ = ["DateInput", "DateTimeInput", "to_date", "to_datetime"]
|
|
6
|
+
|
|
7
|
+
DateTimeInput = datetime | str
|
|
8
|
+
"""A timestamp: a timezone-aware ``datetime`` or an ISO 8601 string. Sent to the API as UTC ISO 8601."""
|
|
9
|
+
|
|
10
|
+
DateInput = date | str
|
|
11
|
+
"""A calendar date in the organisation's time zone: a ``date`` or ``"YYYY-MM-DD"``."""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def to_datetime(value: DateTimeInput | None, name: str = "value") -> str | None:
|
|
15
|
+
if value is None:
|
|
16
|
+
return None
|
|
17
|
+
if isinstance(value, str):
|
|
18
|
+
return value
|
|
19
|
+
if isinstance(value, datetime):
|
|
20
|
+
if value.tzinfo is None or value.utcoffset() is None:
|
|
21
|
+
raise ValueError(
|
|
22
|
+
f"{name} is a naive datetime, so the instant it means is unknown. Pass a timezone-aware value, "
|
|
23
|
+
"for example datetime.now(timezone.utc) or datetime(2026, 11, 1, tzinfo=timezone.utc)."
|
|
24
|
+
)
|
|
25
|
+
return value.astimezone(UTC).isoformat().replace("+00:00", "Z")
|
|
26
|
+
if isinstance(value, date):
|
|
27
|
+
raise TypeError(f"{name} is a timestamp: pass a timezone-aware datetime or an ISO 8601 string, not a date.")
|
|
28
|
+
raise TypeError(f"{name} must be a datetime or an ISO 8601 string, not {type(value).__name__}.")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def to_date(value: DateInput | None, name: str = "value") -> str | None:
|
|
32
|
+
if value is None:
|
|
33
|
+
return None
|
|
34
|
+
if isinstance(value, str):
|
|
35
|
+
return value
|
|
36
|
+
if isinstance(value, datetime):
|
|
37
|
+
raise TypeError(f"{name} is a calendar date: pass a date or 'YYYY-MM-DD' (for a datetime, use .date()).")
|
|
38
|
+
if isinstance(value, date):
|
|
39
|
+
return value.isoformat()
|
|
40
|
+
raise TypeError(f"{name} must be a date or a 'YYYY-MM-DD' string, not {type(value).__name__}.")
|
punchrelay/_core.py
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import threading
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from types import TracebackType
|
|
8
|
+
from typing import Any, Generic, Literal, Self, TypeVar, cast
|
|
9
|
+
from urllib.parse import quote, urlsplit
|
|
10
|
+
|
|
11
|
+
import httpx
|
|
12
|
+
|
|
13
|
+
from ._generated.models import KeyInfoResponse
|
|
14
|
+
from ._transport import AsyncRetryTransport, AsyncSleep, RetryPolicy, RetryTransport, Sleep
|
|
15
|
+
from ._version import __version__
|
|
16
|
+
|
|
17
|
+
T = TypeVar("T")
|
|
18
|
+
|
|
19
|
+
USER_AGENT = f"PunchRelay-Sdk-Python/{__version__}"
|
|
20
|
+
TENANT = "{tenantId}"
|
|
21
|
+
|
|
22
|
+
QueryValue = str | int | None
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class _NoBody:
|
|
26
|
+
def __repr__(self) -> str:
|
|
27
|
+
return "NO_BODY"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
NO_BODY: Any = _NoBody()
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True)
|
|
34
|
+
class Op(Generic[T]):
|
|
35
|
+
"""One API call, described independently of the sync or async client that sends it.
|
|
36
|
+
|
|
37
|
+
``path`` is the spec's path template; ``{tenantId}`` is filled in from the key when the call is sent.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
method: str
|
|
41
|
+
path: str
|
|
42
|
+
path_params: Mapping[str, str | int] = field(default_factory=dict)
|
|
43
|
+
query: Mapping[str, QueryValue] = field(default_factory=dict)
|
|
44
|
+
json: Any = NO_BODY
|
|
45
|
+
parse: Literal["json", "text", "none"] = "json"
|
|
46
|
+
|
|
47
|
+
def url(self, tenant_id: str | None) -> str:
|
|
48
|
+
params: dict[str, str | int] = dict(self.path_params)
|
|
49
|
+
if tenant_id is not None:
|
|
50
|
+
params["tenantId"] = tenant_id
|
|
51
|
+
return self.path.format_map({k: quote(str(v), safe="") for k, v in params.items()})
|
|
52
|
+
|
|
53
|
+
def params(self) -> dict[str, str | int]:
|
|
54
|
+
return {k: v for k, v in self.query.items() if v is not None}
|
|
55
|
+
|
|
56
|
+
def read(self, response: httpx.Response) -> T:
|
|
57
|
+
if self.parse == "none":
|
|
58
|
+
return cast(T, None)
|
|
59
|
+
if self.parse == "text":
|
|
60
|
+
return cast(T, response.text)
|
|
61
|
+
if response.status_code == 204 or not response.content:
|
|
62
|
+
return cast(T, None)
|
|
63
|
+
return cast(T, response.json())
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def validate(api_key: str, base_url: str | httpx.URL) -> str:
|
|
67
|
+
if not api_key or not isinstance(api_key, str):
|
|
68
|
+
raise ValueError("api_key is required: create one on the dashboard's API keys page.")
|
|
69
|
+
if not api_key.startswith("prk_"):
|
|
70
|
+
raise ValueError(
|
|
71
|
+
"api_key must be a developer key (prk_live_...). The 10-digit device key does not work with the API."
|
|
72
|
+
)
|
|
73
|
+
if not base_url:
|
|
74
|
+
raise ValueError("base_url is required, for example https://adms.example.com.")
|
|
75
|
+
text = str(base_url)
|
|
76
|
+
parts = urlsplit(text)
|
|
77
|
+
if parts.scheme not in ("http", "https") or not parts.netloc:
|
|
78
|
+
raise ValueError(f"base_url must be an http or https URL, for example https://adms.example.com, not {text!r}.")
|
|
79
|
+
return text.rstrip("/")
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def headers(api_key: str) -> dict[str, str]:
|
|
83
|
+
return {"Authorization": f"Bearer {api_key}", "User-Agent": USER_AGENT, "Accept": "application/json"}
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _no_tenant() -> RuntimeError:
|
|
87
|
+
return RuntimeError("The API key info carried no tenant id.")
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class SyncCore:
|
|
91
|
+
"""Request sending and tenant resolution for :class:`punchrelay.PunchRelay`."""
|
|
92
|
+
|
|
93
|
+
http: httpx.Client
|
|
94
|
+
"""The underlying httpx client, for any call the area clients don't wrap yet.
|
|
95
|
+
|
|
96
|
+
It sends the key, retries and raises :class:`PunchRelayError` like the area clients. Paths are relative to
|
|
97
|
+
``base_url``; :meth:`get_tenant_id` supplies the tenant id, e.g.
|
|
98
|
+
``client.http.get(f"/api/tenants/{client.get_tenant_id()}/devices")``.
|
|
99
|
+
"""
|
|
100
|
+
|
|
101
|
+
def __init__(
|
|
102
|
+
self,
|
|
103
|
+
*,
|
|
104
|
+
api_key: str,
|
|
105
|
+
base_url: str | httpx.URL,
|
|
106
|
+
tenant_id: str | None,
|
|
107
|
+
policy: RetryPolicy,
|
|
108
|
+
transport: httpx.BaseTransport | None,
|
|
109
|
+
proxy: str | None,
|
|
110
|
+
sleep: Sleep | None,
|
|
111
|
+
) -> None:
|
|
112
|
+
url = validate(api_key, base_url)
|
|
113
|
+
inner = transport if transport is not None else httpx.HTTPTransport(proxy=proxy)
|
|
114
|
+
retry = RetryTransport(inner, policy) if sleep is None else RetryTransport(inner, policy, sleep)
|
|
115
|
+
self.http = httpx.Client(base_url=url, headers=headers(api_key), transport=retry, timeout=None)
|
|
116
|
+
self._tenant_id = tenant_id or None
|
|
117
|
+
self._key_info: KeyInfoResponse | None = None
|
|
118
|
+
self._lock = threading.Lock()
|
|
119
|
+
|
|
120
|
+
def get_key_info(self) -> KeyInfoResponse:
|
|
121
|
+
"""Details of the API key: its organisation, name, scope and expiry. Fetched once, then cached."""
|
|
122
|
+
# Concurrent first calls share one request; a failure is not cached, so the next call tries again
|
|
123
|
+
with self._lock:
|
|
124
|
+
if self._key_info is None:
|
|
125
|
+
info: KeyInfoResponse = self._send(Op("GET", "/api/key-info"))
|
|
126
|
+
if not isinstance(info, dict):
|
|
127
|
+
raise RuntimeError("The API returned no key info.")
|
|
128
|
+
self._key_info = info
|
|
129
|
+
if self._tenant_id is None:
|
|
130
|
+
self._tenant_id = info.get("tenantId") or None
|
|
131
|
+
return self._key_info
|
|
132
|
+
|
|
133
|
+
def get_tenant_id(self) -> str:
|
|
134
|
+
"""The organisation the key belongs to (from ``tenant_id``, or from :meth:`get_key_info`)."""
|
|
135
|
+
if self._tenant_id is None:
|
|
136
|
+
self.get_key_info()
|
|
137
|
+
if self._tenant_id is None:
|
|
138
|
+
raise _no_tenant()
|
|
139
|
+
return self._tenant_id
|
|
140
|
+
|
|
141
|
+
def _send(self, op: Op[T]) -> T:
|
|
142
|
+
tenant_id = self.get_tenant_id() if TENANT in op.path else None
|
|
143
|
+
if op.json is NO_BODY:
|
|
144
|
+
response = self.http.request(op.method, op.url(tenant_id), params=op.params())
|
|
145
|
+
else:
|
|
146
|
+
response = self.http.request(op.method, op.url(tenant_id), params=op.params(), json=op.json)
|
|
147
|
+
return op.read(response)
|
|
148
|
+
|
|
149
|
+
def close(self) -> None:
|
|
150
|
+
"""Closes the connection pool. The client cannot be used afterwards."""
|
|
151
|
+
self.http.close()
|
|
152
|
+
|
|
153
|
+
def __enter__(self) -> Self:
|
|
154
|
+
return self
|
|
155
|
+
|
|
156
|
+
def __exit__(
|
|
157
|
+
self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None
|
|
158
|
+
) -> None:
|
|
159
|
+
self.close()
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
class AsyncCore:
|
|
163
|
+
"""Request sending and tenant resolution for :class:`punchrelay.AsyncPunchRelay`."""
|
|
164
|
+
|
|
165
|
+
http: httpx.AsyncClient
|
|
166
|
+
"""The underlying httpx client, for any call the area clients don't wrap yet.
|
|
167
|
+
|
|
168
|
+
It sends the key, retries and raises :class:`PunchRelayError` like the area clients. Paths are relative to
|
|
169
|
+
``base_url``; :meth:`get_tenant_id` supplies the tenant id.
|
|
170
|
+
"""
|
|
171
|
+
|
|
172
|
+
def __init__(
|
|
173
|
+
self,
|
|
174
|
+
*,
|
|
175
|
+
api_key: str,
|
|
176
|
+
base_url: str | httpx.URL,
|
|
177
|
+
tenant_id: str | None,
|
|
178
|
+
policy: RetryPolicy,
|
|
179
|
+
transport: httpx.AsyncBaseTransport | None,
|
|
180
|
+
proxy: str | None,
|
|
181
|
+
sleep: AsyncSleep | None,
|
|
182
|
+
) -> None:
|
|
183
|
+
url = validate(api_key, base_url)
|
|
184
|
+
inner = transport if transport is not None else httpx.AsyncHTTPTransport(proxy=proxy)
|
|
185
|
+
retry = AsyncRetryTransport(inner, policy) if sleep is None else AsyncRetryTransport(inner, policy, sleep)
|
|
186
|
+
self.http = httpx.AsyncClient(base_url=url, headers=headers(api_key), transport=retry, timeout=None)
|
|
187
|
+
self._tenant_id = tenant_id or None
|
|
188
|
+
self._key_info: KeyInfoResponse | None = None
|
|
189
|
+
self._lock = asyncio.Lock()
|
|
190
|
+
|
|
191
|
+
async def get_key_info(self) -> KeyInfoResponse:
|
|
192
|
+
"""Details of the API key: its organisation, name, scope and expiry. Fetched once, then cached."""
|
|
193
|
+
# Concurrent first calls wait on the lock and share one request; a failure is not cached
|
|
194
|
+
async with self._lock:
|
|
195
|
+
if self._key_info is None:
|
|
196
|
+
info: KeyInfoResponse = await self._send(Op("GET", "/api/key-info"))
|
|
197
|
+
if not isinstance(info, dict):
|
|
198
|
+
raise RuntimeError("The API returned no key info.")
|
|
199
|
+
self._key_info = info
|
|
200
|
+
if self._tenant_id is None:
|
|
201
|
+
self._tenant_id = info.get("tenantId") or None
|
|
202
|
+
return self._key_info
|
|
203
|
+
|
|
204
|
+
async def get_tenant_id(self) -> str:
|
|
205
|
+
"""The organisation the key belongs to (from ``tenant_id``, or from :meth:`get_key_info`)."""
|
|
206
|
+
if self._tenant_id is None:
|
|
207
|
+
await self.get_key_info()
|
|
208
|
+
if self._tenant_id is None:
|
|
209
|
+
raise _no_tenant()
|
|
210
|
+
return self._tenant_id
|
|
211
|
+
|
|
212
|
+
async def _send(self, op: Op[T]) -> T:
|
|
213
|
+
tenant_id = await self.get_tenant_id() if TENANT in op.path else None
|
|
214
|
+
if op.json is NO_BODY:
|
|
215
|
+
response = await self.http.request(op.method, op.url(tenant_id), params=op.params())
|
|
216
|
+
else:
|
|
217
|
+
response = await self.http.request(op.method, op.url(tenant_id), params=op.params(), json=op.json)
|
|
218
|
+
return op.read(response)
|
|
219
|
+
|
|
220
|
+
async def aclose(self) -> None:
|
|
221
|
+
"""Closes the connection pool. The client cannot be used afterwards."""
|
|
222
|
+
await self.http.aclose()
|
|
223
|
+
|
|
224
|
+
async def __aenter__(self) -> Self:
|
|
225
|
+
return self
|
|
226
|
+
|
|
227
|
+
async def __aexit__(
|
|
228
|
+
self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None
|
|
229
|
+
) -> None:
|
|
230
|
+
await self.aclose()
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
class SyncResource:
|
|
234
|
+
def __init__(self, core: SyncCore) -> None:
|
|
235
|
+
self._call = core._send
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
class AsyncResource:
|
|
239
|
+
def __init__(self, core: AsyncCore) -> None:
|
|
240
|
+
self._call = core._send
|
punchrelay/_errors.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
import httpx
|
|
7
|
+
|
|
8
|
+
__all__ = ["PunchRelayError", "SubscriptionSuspendedError"]
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class PunchRelayError(Exception):
|
|
12
|
+
"""The API answered with an error status.
|
|
13
|
+
|
|
14
|
+
``code`` is the machine-readable ``error`` from the API's ``{"error", "message"}`` body (for example
|
|
15
|
+
``invalid_range``) and ``message`` is its text.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
status: int
|
|
19
|
+
"""The HTTP status, for example 403 for a read-only key on a change."""
|
|
20
|
+
code: str
|
|
21
|
+
"""The ``error`` code from the body, or one derived from the status when the body had none (``unauthorized``)."""
|
|
22
|
+
message: str
|
|
23
|
+
"""The ``message`` from the body, or the status line."""
|
|
24
|
+
body: str | None
|
|
25
|
+
"""The raw response body, when there was one."""
|
|
26
|
+
retry_after: float | None
|
|
27
|
+
"""The server's ``Retry-After`` in seconds, sent with 429."""
|
|
28
|
+
|
|
29
|
+
def __init__(
|
|
30
|
+
self, status: int, code: str, message: str, body: str | None = None, retry_after: float | None = None
|
|
31
|
+
) -> None:
|
|
32
|
+
super().__init__(message)
|
|
33
|
+
self.status = status
|
|
34
|
+
self.code = code
|
|
35
|
+
self.message = message
|
|
36
|
+
self.body = body
|
|
37
|
+
self.retry_after = retry_after
|
|
38
|
+
|
|
39
|
+
def __str__(self) -> str:
|
|
40
|
+
return f"{self.message} ({self.status} {self.code})"
|
|
41
|
+
|
|
42
|
+
def __repr__(self) -> str:
|
|
43
|
+
return f"{type(self).__name__}(status={self.status!r}, code={self.code!r}, message={self.message!r})"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class SubscriptionSuspendedError(PunchRelayError):
|
|
47
|
+
"""402: the organisation's subscription is suspended, usually over an unpaid invoice.
|
|
48
|
+
|
|
49
|
+
Paying it (``pay_url``) restores access.
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
subscription_status: str | None
|
|
53
|
+
"""The subscription status, for example ``suspended``."""
|
|
54
|
+
reason: str | None
|
|
55
|
+
"""Why it was suspended, when known."""
|
|
56
|
+
invoice_number: str | None
|
|
57
|
+
"""The overdue invoice, when there is one."""
|
|
58
|
+
pay_url: str | None
|
|
59
|
+
"""Where an owner can pay the overdue invoice."""
|
|
60
|
+
|
|
61
|
+
def __init__(
|
|
62
|
+
self,
|
|
63
|
+
code: str,
|
|
64
|
+
message: str,
|
|
65
|
+
*,
|
|
66
|
+
subscription_status: str | None = None,
|
|
67
|
+
reason: str | None = None,
|
|
68
|
+
invoice_number: str | None = None,
|
|
69
|
+
pay_url: str | None = None,
|
|
70
|
+
body: str | None = None,
|
|
71
|
+
) -> None:
|
|
72
|
+
super().__init__(402, code, message, body)
|
|
73
|
+
self.subscription_status = subscription_status
|
|
74
|
+
self.reason = reason
|
|
75
|
+
self.invoice_number = invoice_number
|
|
76
|
+
self.pay_url = pay_url
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def to_error(response: httpx.Response, retry_after: float | None) -> PunchRelayError:
|
|
80
|
+
"""Builds the error for a non-2xx response whose body has been read."""
|
|
81
|
+
body = _text(response)
|
|
82
|
+
fields: dict[str, Any] = {}
|
|
83
|
+
if body:
|
|
84
|
+
try:
|
|
85
|
+
parsed = json.loads(body)
|
|
86
|
+
except ValueError:
|
|
87
|
+
parsed = None # Not JSON (a proxy's HTML page, for instance); keep the raw body only
|
|
88
|
+
if isinstance(parsed, dict):
|
|
89
|
+
fields = parsed
|
|
90
|
+
|
|
91
|
+
def field(name: str) -> str | None:
|
|
92
|
+
value = fields.get(name)
|
|
93
|
+
return value if isinstance(value, str) else None
|
|
94
|
+
|
|
95
|
+
status = response.status_code
|
|
96
|
+
code = field("error") or _default_code(status)
|
|
97
|
+
message = field("message") or f"{status} {response.reason_phrase}".rstrip()
|
|
98
|
+
|
|
99
|
+
if status == 402:
|
|
100
|
+
return SubscriptionSuspendedError(
|
|
101
|
+
code,
|
|
102
|
+
message,
|
|
103
|
+
subscription_status=field("status"),
|
|
104
|
+
reason=field("reason"),
|
|
105
|
+
invoice_number=field("invoiceNumber"),
|
|
106
|
+
pay_url=field("payUrl"),
|
|
107
|
+
body=body,
|
|
108
|
+
)
|
|
109
|
+
return PunchRelayError(status, code, message, body, retry_after)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _text(response: httpx.Response) -> str | None:
|
|
113
|
+
try:
|
|
114
|
+
return response.text or None
|
|
115
|
+
except (httpx.ResponseNotRead, UnicodeDecodeError, LookupError):
|
|
116
|
+
return None
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _default_code(status: int) -> str:
|
|
120
|
+
codes = {
|
|
121
|
+
400: "bad_request",
|
|
122
|
+
401: "unauthorized",
|
|
123
|
+
402: "subscription_suspended",
|
|
124
|
+
403: "forbidden",
|
|
125
|
+
404: "not_found",
|
|
126
|
+
409: "conflict",
|
|
127
|
+
429: "rate_limited",
|
|
128
|
+
}
|
|
129
|
+
if status in codes:
|
|
130
|
+
return codes[status]
|
|
131
|
+
return "server_error" if status >= 500 else f"http_{status}"
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# Generated by sdks/generate.sh from sdks/openapi/v1.json. Import the models from punchrelay.models.
|