stablevoy 1.0.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.
- stablevoy/__init__.py +63 -0
- stablevoy/_version.py +1 -0
- stablevoy/client.py +57 -0
- stablevoy/errors/__init__.py +0 -0
- stablevoy/errors/api_error.py +29 -0
- stablevoy/errors/authentication_error.py +5 -0
- stablevoy/errors/configuration_error.py +5 -0
- stablevoy/errors/maintenance_error.py +5 -0
- stablevoy/errors/not_found_error.py +5 -0
- stablevoy/errors/problem_issue.py +9 -0
- stablevoy/errors/rate_limited_error.py +5 -0
- stablevoy/errors/signature_error.py +5 -0
- stablevoy/errors/stablevoy_error.py +2 -0
- stablevoy/errors/transport_error.py +5 -0
- stablevoy/errors/unexpected_response_error.py +5 -0
- stablevoy/errors/validation_error.py +5 -0
- stablevoy/http/__init__.py +0 -0
- stablevoy/http/error_factory.py +59 -0
- stablevoy/http/http_answer.py +9 -0
- stablevoy/http/no_redirects.py +12 -0
- stablevoy/http/opener.py +10 -0
- stablevoy/http/retry_policy.py +26 -0
- stablevoy/http/transport.py +10 -0
- stablevoy/http/urllib_opener.py +22 -0
- stablevoy/http/urllib_transport.py +129 -0
- stablevoy/model/__init__.py +0 -0
- stablevoy/model/created_invoice.py +20 -0
- stablevoy/model/deposit_address.py +19 -0
- stablevoy/model/fields.py +100 -0
- stablevoy/model/invoice.py +52 -0
- stablevoy/model/invoice_page.py +18 -0
- stablevoy/model/invoice_status.py +22 -0
- stablevoy/model/limits.py +17 -0
- stablevoy/model/network.py +35 -0
- stablevoy/model/payment.py +35 -0
- stablevoy/model/pricing.py +18 -0
- stablevoy/model/store.py +37 -0
- stablevoy/model/token.py +18 -0
- stablevoy/py.typed +0 -0
- stablevoy/resources/__init__.py +0 -0
- stablevoy/resources/invoices.py +67 -0
- stablevoy/resources/platform.py +25 -0
- stablevoy/resources/stores.py +12 -0
- stablevoy/time/__init__.py +0 -0
- stablevoy/time/clock.py +7 -0
- stablevoy/time/system_clock.py +6 -0
- stablevoy/webhook/__init__.py +0 -0
- stablevoy/webhook/webhook_event.py +28 -0
- stablevoy/webhook/webhook_verifier.py +62 -0
- stablevoy-1.0.0.dist-info/METADATA +114 -0
- stablevoy-1.0.0.dist-info/RECORD +53 -0
- stablevoy-1.0.0.dist-info/WHEEL +4 -0
- stablevoy-1.0.0.dist-info/licenses/LICENSE +21 -0
stablevoy/__init__.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""Python client for the Stablevoy API: non-custodial USDT and USDC payments, invoices and signed webhooks."""
|
|
2
|
+
|
|
3
|
+
from stablevoy._version import __version__
|
|
4
|
+
from stablevoy.client import Stablevoy
|
|
5
|
+
from stablevoy.errors.api_error import ApiError
|
|
6
|
+
from stablevoy.errors.authentication_error import AuthenticationError
|
|
7
|
+
from stablevoy.errors.configuration_error import ConfigurationError
|
|
8
|
+
from stablevoy.errors.maintenance_error import MaintenanceError
|
|
9
|
+
from stablevoy.errors.not_found_error import NotFoundError
|
|
10
|
+
from stablevoy.errors.problem_issue import ProblemIssue
|
|
11
|
+
from stablevoy.errors.rate_limited_error import RateLimitedError
|
|
12
|
+
from stablevoy.errors.signature_error import SignatureError
|
|
13
|
+
from stablevoy.errors.stablevoy_error import StablevoyError
|
|
14
|
+
from stablevoy.errors.transport_error import TransportError
|
|
15
|
+
from stablevoy.errors.unexpected_response_error import UnexpectedResponseError
|
|
16
|
+
from stablevoy.errors.validation_error import ValidationError
|
|
17
|
+
from stablevoy.http.retry_policy import RetryPolicy
|
|
18
|
+
from stablevoy.http.transport import Transport
|
|
19
|
+
from stablevoy.model.created_invoice import CreatedInvoice
|
|
20
|
+
from stablevoy.model.deposit_address import DepositAddress
|
|
21
|
+
from stablevoy.model.invoice import Invoice
|
|
22
|
+
from stablevoy.model.invoice_page import InvoicePage
|
|
23
|
+
from stablevoy.model.invoice_status import InvoiceStatus
|
|
24
|
+
from stablevoy.model.limits import Limits
|
|
25
|
+
from stablevoy.model.network import Network
|
|
26
|
+
from stablevoy.model.payment import Payment
|
|
27
|
+
from stablevoy.model.pricing import Pricing
|
|
28
|
+
from stablevoy.model.store import Store
|
|
29
|
+
from stablevoy.model.token import Token
|
|
30
|
+
from stablevoy.webhook.webhook_event import WebhookEvent
|
|
31
|
+
from stablevoy.webhook.webhook_verifier import WebhookVerifier
|
|
32
|
+
|
|
33
|
+
__all__ = [
|
|
34
|
+
"ApiError",
|
|
35
|
+
"AuthenticationError",
|
|
36
|
+
"ConfigurationError",
|
|
37
|
+
"CreatedInvoice",
|
|
38
|
+
"DepositAddress",
|
|
39
|
+
"Invoice",
|
|
40
|
+
"InvoicePage",
|
|
41
|
+
"InvoiceStatus",
|
|
42
|
+
"Limits",
|
|
43
|
+
"MaintenanceError",
|
|
44
|
+
"Network",
|
|
45
|
+
"NotFoundError",
|
|
46
|
+
"Payment",
|
|
47
|
+
"Pricing",
|
|
48
|
+
"ProblemIssue",
|
|
49
|
+
"RateLimitedError",
|
|
50
|
+
"RetryPolicy",
|
|
51
|
+
"SignatureError",
|
|
52
|
+
"Stablevoy",
|
|
53
|
+
"StablevoyError",
|
|
54
|
+
"Store",
|
|
55
|
+
"Token",
|
|
56
|
+
"Transport",
|
|
57
|
+
"TransportError",
|
|
58
|
+
"UnexpectedResponseError",
|
|
59
|
+
"ValidationError",
|
|
60
|
+
"WebhookEvent",
|
|
61
|
+
"WebhookVerifier",
|
|
62
|
+
"__version__",
|
|
63
|
+
]
|
stablevoy/_version.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "1.0.0"
|
stablevoy/client.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import platform
|
|
4
|
+
import time
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
|
|
7
|
+
from stablevoy._version import __version__
|
|
8
|
+
from stablevoy.http.error_factory import ErrorFactory
|
|
9
|
+
from stablevoy.http.opener import Opener
|
|
10
|
+
from stablevoy.http.retry_policy import RetryPolicy
|
|
11
|
+
from stablevoy.http.transport import Transport
|
|
12
|
+
from stablevoy.http.urllib_opener import UrllibOpener
|
|
13
|
+
from stablevoy.http.urllib_transport import UrllibTransport
|
|
14
|
+
from stablevoy.resources.invoices import Invoices
|
|
15
|
+
from stablevoy.resources.platform import Platform
|
|
16
|
+
from stablevoy.resources.stores import Stores
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class Stablevoy:
|
|
20
|
+
"""The Stablevoy API: ``stablevoy = Stablevoy.create(os.environ["STABLEVOY_API_KEY"])``."""
|
|
21
|
+
|
|
22
|
+
def __init__(self, invoices: Invoices, stores: Stores, platform: Platform) -> None:
|
|
23
|
+
self.invoices = invoices
|
|
24
|
+
self.stores = stores
|
|
25
|
+
self.platform = platform
|
|
26
|
+
|
|
27
|
+
@classmethod
|
|
28
|
+
def create(
|
|
29
|
+
cls,
|
|
30
|
+
api_key: str,
|
|
31
|
+
*,
|
|
32
|
+
base_url: str = "https://api.stablevoy.com",
|
|
33
|
+
retries: RetryPolicy | None = None,
|
|
34
|
+
timeout_seconds: float = 30.0,
|
|
35
|
+
user_agent_suffix: str | None = None,
|
|
36
|
+
opener: Opener | None = None,
|
|
37
|
+
sleep: Callable[[float], None] = time.sleep,
|
|
38
|
+
) -> Stablevoy:
|
|
39
|
+
user_agent = f"stablevoy-python/{__version__} Python/{platform.python_version()}"
|
|
40
|
+
if user_agent_suffix is not None:
|
|
41
|
+
user_agent += f" {user_agent_suffix}"
|
|
42
|
+
return cls.from_transport(
|
|
43
|
+
UrllibTransport(
|
|
44
|
+
api_key=api_key,
|
|
45
|
+
base_url=base_url,
|
|
46
|
+
user_agent=user_agent,
|
|
47
|
+
retries=retries if retries is not None else RetryPolicy(),
|
|
48
|
+
opener=opener if opener is not None else UrllibOpener(),
|
|
49
|
+
sleep=sleep,
|
|
50
|
+
errors=ErrorFactory(),
|
|
51
|
+
timeout_seconds=timeout_seconds,
|
|
52
|
+
)
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
@classmethod
|
|
56
|
+
def from_transport(cls, transport: Transport) -> Stablevoy:
|
|
57
|
+
return cls(Invoices(transport), Stores(transport), Platform(transport))
|
|
File without changes
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from stablevoy.errors.problem_issue import ProblemIssue
|
|
4
|
+
from stablevoy.errors.stablevoy_error import StablevoyError
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class ApiError(StablevoyError):
|
|
8
|
+
"""
|
|
9
|
+
The API answered with an error: an RFC 7807 problem document with a stable code, a readable detail and a link to the
|
|
10
|
+
code's entry in the error catalog (https://stablevoy.com/docs/api/errors/).
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
def __init__(
|
|
14
|
+
self,
|
|
15
|
+
*,
|
|
16
|
+
status: int,
|
|
17
|
+
code: str,
|
|
18
|
+
detail: str,
|
|
19
|
+
type: str | None,
|
|
20
|
+
issues: tuple[ProblemIssue, ...],
|
|
21
|
+
retry_after_seconds: int | None,
|
|
22
|
+
) -> None:
|
|
23
|
+
super().__init__(f"{detail} (HTTP {status}, {code})")
|
|
24
|
+
self.status = status
|
|
25
|
+
self.code = code
|
|
26
|
+
self.detail = detail
|
|
27
|
+
self.type = type
|
|
28
|
+
self.issues = issues
|
|
29
|
+
self.retry_after_seconds = retry_after_seconds
|
|
File without changes
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
|
|
5
|
+
from stablevoy.errors.api_error import ApiError
|
|
6
|
+
from stablevoy.errors.authentication_error import AuthenticationError
|
|
7
|
+
from stablevoy.errors.maintenance_error import MaintenanceError
|
|
8
|
+
from stablevoy.errors.not_found_error import NotFoundError
|
|
9
|
+
from stablevoy.errors.problem_issue import ProblemIssue
|
|
10
|
+
from stablevoy.errors.rate_limited_error import RateLimitedError
|
|
11
|
+
from stablevoy.errors.validation_error import ValidationError
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class ErrorFactory:
|
|
15
|
+
"""Turns an error answer of the API (an RFC 7807 problem document) into the matching error."""
|
|
16
|
+
|
|
17
|
+
def from_problem(self, status: int, body: bytes, retry_after_seconds: int | None) -> ApiError:
|
|
18
|
+
problem = self._parse(body)
|
|
19
|
+
code = problem.get("code")
|
|
20
|
+
code = code if isinstance(code, str) else f"http_{status}"
|
|
21
|
+
detail = problem.get("detail")
|
|
22
|
+
problem_type = problem.get("type")
|
|
23
|
+
error_class: type[ApiError] = ApiError
|
|
24
|
+
if status == 401:
|
|
25
|
+
error_class = AuthenticationError
|
|
26
|
+
elif status == 404:
|
|
27
|
+
error_class = NotFoundError
|
|
28
|
+
elif status == 429:
|
|
29
|
+
error_class = RateLimitedError
|
|
30
|
+
elif status == 503 and code == "maintenance":
|
|
31
|
+
error_class = MaintenanceError
|
|
32
|
+
elif status in (400, 422):
|
|
33
|
+
error_class = ValidationError
|
|
34
|
+
return error_class(
|
|
35
|
+
status=status,
|
|
36
|
+
code=code,
|
|
37
|
+
detail=detail if isinstance(detail, str) else f"The API answered HTTP {status}",
|
|
38
|
+
type=problem_type if isinstance(problem_type, str) else None,
|
|
39
|
+
issues=self._issues(problem.get("issues")),
|
|
40
|
+
retry_after_seconds=retry_after_seconds,
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
@staticmethod
|
|
44
|
+
def _parse(body: bytes) -> dict[str, object]:
|
|
45
|
+
try:
|
|
46
|
+
value = json.loads(body)
|
|
47
|
+
except ValueError:
|
|
48
|
+
return {}
|
|
49
|
+
return value if isinstance(value, dict) else {}
|
|
50
|
+
|
|
51
|
+
@staticmethod
|
|
52
|
+
def _issues(value: object) -> tuple[ProblemIssue, ...]:
|
|
53
|
+
if not isinstance(value, list):
|
|
54
|
+
return ()
|
|
55
|
+
return tuple(
|
|
56
|
+
ProblemIssue(issue["path"], issue["message"])
|
|
57
|
+
for issue in value
|
|
58
|
+
if isinstance(issue, dict) and isinstance(issue.get("path"), str) and isinstance(issue.get("message"), str)
|
|
59
|
+
)
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from email.message import Message
|
|
4
|
+
from typing import IO
|
|
5
|
+
from urllib.request import HTTPRedirectHandler, Request
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class NoRedirects(HTTPRedirectHandler):
|
|
9
|
+
"""The API never redirects; following one would carry the key wherever it points. The 3xx answer is returned as is."""
|
|
10
|
+
|
|
11
|
+
def redirect_request(self, req: Request, fp: IO[bytes], code: int, msg: str, headers: Message, newurl: str) -> None: # noqa: PLR0917 - urllib defines this signature
|
|
12
|
+
return None
|
stablevoy/http/opener.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
from typing import Protocol
|
|
2
|
+
from urllib.request import Request
|
|
3
|
+
|
|
4
|
+
from stablevoy.http.http_answer import HttpAnswer
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class Opener(Protocol):
|
|
8
|
+
"""Sends a request and returns the answer, whatever its status; raises OSError when there is no answer at all."""
|
|
9
|
+
|
|
10
|
+
def send(self, request: Request, timeout: float) -> HttpAnswer: ...
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class RetryPolicy:
|
|
5
|
+
"""
|
|
6
|
+
When to retry: on 429, 503 and a failed connection, at most max_retries times, waiting what Retry-After asks (or 1, 2,
|
|
7
|
+
4 seconds without it). A wait longer than max_wait_seconds is not slept through: the error goes to the caller with
|
|
8
|
+
retry_after_seconds, so a request never hangs for minutes during maintenance.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
def __init__(self, max_retries: int = 2, max_wait_seconds: int = 10) -> None:
|
|
12
|
+
if max_retries < 0 or max_wait_seconds < 0:
|
|
13
|
+
raise ValueError("max_retries and max_wait_seconds must not be negative")
|
|
14
|
+
self.max_retries = max_retries
|
|
15
|
+
self.max_wait_seconds = max_wait_seconds
|
|
16
|
+
|
|
17
|
+
@classmethod
|
|
18
|
+
def none(cls) -> RetryPolicy:
|
|
19
|
+
return cls(0, 0)
|
|
20
|
+
|
|
21
|
+
def wait_before(self, attempt: int, retry_after_seconds: int | None) -> int | None:
|
|
22
|
+
"""Seconds to wait before the next attempt, or None when the call must not be retried. ``attempt`` counts from 1."""
|
|
23
|
+
if attempt > self.max_retries:
|
|
24
|
+
return None
|
|
25
|
+
wait = retry_after_seconds if retry_after_seconds is not None else 1 << (attempt - 1)
|
|
26
|
+
return wait if wait <= self.max_wait_seconds else None
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
from collections.abc import Mapping
|
|
2
|
+
from typing import Protocol
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class Transport(Protocol):
|
|
6
|
+
"""Sends one API call and returns the decoded JSON answer, or raises the matching error. The resources depend on it only."""
|
|
7
|
+
|
|
8
|
+
def get(self, path: str, query: Mapping[str, str | int] | None = None) -> object: ...
|
|
9
|
+
|
|
10
|
+
def post(self, path: str, body: Mapping[str, object], idempotency_key: str | None = None) -> object: ...
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from urllib.error import HTTPError
|
|
4
|
+
from urllib.request import OpenerDirector, Request, build_opener
|
|
5
|
+
|
|
6
|
+
from stablevoy.http.http_answer import HttpAnswer
|
|
7
|
+
from stablevoy.http.no_redirects import NoRedirects
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class UrllibOpener:
|
|
11
|
+
"""The standard library's HTTP client without redirects. Error statuses come back as answers, not exceptions."""
|
|
12
|
+
|
|
13
|
+
def __init__(self, opener: OpenerDirector | None = None) -> None:
|
|
14
|
+
self._opener = opener if opener is not None else build_opener(NoRedirects)
|
|
15
|
+
|
|
16
|
+
def send(self, request: Request, timeout: float) -> HttpAnswer:
|
|
17
|
+
try:
|
|
18
|
+
with self._opener.open(request, timeout=timeout) as response:
|
|
19
|
+
return HttpAnswer(response.status, response.headers, response.read())
|
|
20
|
+
except HTTPError as error:
|
|
21
|
+
with error:
|
|
22
|
+
return HttpAnswer(error.code, error.headers, error.read())
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import re
|
|
5
|
+
from collections.abc import Callable, Mapping
|
|
6
|
+
from urllib.parse import urlencode, urlsplit
|
|
7
|
+
from urllib.request import Request
|
|
8
|
+
|
|
9
|
+
from stablevoy.errors.api_error import ApiError
|
|
10
|
+
from stablevoy.errors.configuration_error import ConfigurationError
|
|
11
|
+
from stablevoy.errors.transport_error import TransportError
|
|
12
|
+
from stablevoy.errors.unexpected_response_error import UnexpectedResponseError
|
|
13
|
+
from stablevoy.http.error_factory import ErrorFactory
|
|
14
|
+
from stablevoy.http.http_answer import HttpAnswer
|
|
15
|
+
from stablevoy.http.opener import Opener
|
|
16
|
+
from stablevoy.http.retry_policy import RetryPolicy
|
|
17
|
+
|
|
18
|
+
_LOCAL_HOSTS = frozenset({"localhost", "127.0.0.1", "::1"})
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class UrllibTransport:
|
|
22
|
+
"""
|
|
23
|
+
The API over HTTP: Bearer API key, JSON in and out, errors as exceptions, and retries only where a repeat cannot do
|
|
24
|
+
harm (reads, and creates that carry an Idempotency-Key).
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
def __init__(
|
|
28
|
+
self,
|
|
29
|
+
*,
|
|
30
|
+
api_key: str,
|
|
31
|
+
base_url: str,
|
|
32
|
+
user_agent: str,
|
|
33
|
+
retries: RetryPolicy,
|
|
34
|
+
opener: Opener,
|
|
35
|
+
sleep: Callable[[float], None],
|
|
36
|
+
errors: ErrorFactory,
|
|
37
|
+
timeout_seconds: float = 30.0,
|
|
38
|
+
) -> None:
|
|
39
|
+
if not api_key.strip():
|
|
40
|
+
raise ConfigurationError("The API key is empty. Create one in the Stablevoy dashboard.")
|
|
41
|
+
self._api_key = api_key
|
|
42
|
+
self._base_url = self._checked_base_url(base_url)
|
|
43
|
+
self._user_agent = user_agent
|
|
44
|
+
self._retries = retries
|
|
45
|
+
self._opener = opener
|
|
46
|
+
self._sleep = sleep
|
|
47
|
+
self._errors = errors
|
|
48
|
+
self._timeout = timeout_seconds
|
|
49
|
+
|
|
50
|
+
def get(self, path: str, query: Mapping[str, str | int] | None = None) -> object:
|
|
51
|
+
url = self._base_url + path + (f"?{urlencode(query)}" if query else "")
|
|
52
|
+
return self._send(Request(url, method="GET"), retryable=True) # noqa: S310 - the scheme is checked to be http(s)
|
|
53
|
+
|
|
54
|
+
def post(self, path: str, body: Mapping[str, object], idempotency_key: str | None = None) -> object:
|
|
55
|
+
request = Request(self._base_url + path, data=json.dumps(body).encode(), method="POST") # noqa: S310 - checked scheme
|
|
56
|
+
request.add_header("Content-Type", "application/json")
|
|
57
|
+
if idempotency_key is not None:
|
|
58
|
+
request.add_header("Idempotency-Key", idempotency_key)
|
|
59
|
+
return self._send(request, retryable=idempotency_key is not None)
|
|
60
|
+
|
|
61
|
+
def _send(self, request: Request, *, retryable: bool) -> object:
|
|
62
|
+
request.add_header("Authorization", f"Bearer {self._api_key}")
|
|
63
|
+
request.add_header("Accept", "application/json")
|
|
64
|
+
request.add_header("User-Agent", self._user_agent)
|
|
65
|
+
attempt = 1
|
|
66
|
+
while True:
|
|
67
|
+
try:
|
|
68
|
+
answer = self._opener.send(request, self._timeout)
|
|
69
|
+
except OSError as error:
|
|
70
|
+
wait = self._retries.wait_before(attempt, None) if retryable else None
|
|
71
|
+
if wait is None:
|
|
72
|
+
raise TransportError(f"Cannot reach the Stablevoy API: {error}") from error
|
|
73
|
+
self._sleep(wait)
|
|
74
|
+
attempt += 1
|
|
75
|
+
continue
|
|
76
|
+
if 200 <= answer.status < 300:
|
|
77
|
+
return self._decode(answer.body)
|
|
78
|
+
api_error = self._errors.from_problem(answer.status, answer.body, self._retry_after(answer))
|
|
79
|
+
retry = retryable and self._is_retryable(api_error)
|
|
80
|
+
wait = self._retries.wait_before(attempt, api_error.retry_after_seconds) if retry else None
|
|
81
|
+
if wait is None:
|
|
82
|
+
raise api_error
|
|
83
|
+
self._sleep(wait)
|
|
84
|
+
attempt += 1
|
|
85
|
+
|
|
86
|
+
@staticmethod
|
|
87
|
+
def _is_retryable(error: ApiError) -> bool:
|
|
88
|
+
return error.status in (429, 503)
|
|
89
|
+
|
|
90
|
+
@staticmethod
|
|
91
|
+
def _decode(body: bytes) -> object:
|
|
92
|
+
try:
|
|
93
|
+
value: object = json.loads(body)
|
|
94
|
+
except ValueError as error:
|
|
95
|
+
raise UnexpectedResponseError("The API answered with a body that is not JSON") from error
|
|
96
|
+
if not isinstance(value, dict | list):
|
|
97
|
+
raise UnexpectedResponseError("The API answered with JSON that is not an object or a list")
|
|
98
|
+
return value
|
|
99
|
+
|
|
100
|
+
@staticmethod
|
|
101
|
+
def _retry_after(answer: HttpAnswer) -> int | None:
|
|
102
|
+
value = (answer.headers.get("Retry-After") or "").strip()
|
|
103
|
+
return int(value) if re.fullmatch(r"\d{1,9}", value) else None
|
|
104
|
+
|
|
105
|
+
@staticmethod
|
|
106
|
+
def _checked_base_url(base_url: str) -> str:
|
|
107
|
+
"""
|
|
108
|
+
Only a scheme, a host and an optional port. The API key travels in every request, so plain http is refused except
|
|
109
|
+
for a local development server, and so are credentials, paths, queries and fragments in the URL.
|
|
110
|
+
"""
|
|
111
|
+
url = base_url.rstrip("/")
|
|
112
|
+
try:
|
|
113
|
+
parts = urlsplit(url)
|
|
114
|
+
_ = parts.port # raises ValueError on a port that is no number
|
|
115
|
+
except ValueError:
|
|
116
|
+
parts = None
|
|
117
|
+
bad = (
|
|
118
|
+
parts is None
|
|
119
|
+
or not parts.hostname
|
|
120
|
+
or parts.username is not None
|
|
121
|
+
or parts.password is not None
|
|
122
|
+
or bool(parts.path or parts.query or parts.fragment)
|
|
123
|
+
or not (parts.scheme == "https" or (parts.scheme == "http" and parts.hostname in _LOCAL_HOSTS))
|
|
124
|
+
)
|
|
125
|
+
if bad:
|
|
126
|
+
raise ConfigurationError(
|
|
127
|
+
f"The base URL must be https and only a host, like https://api.stablevoy.com (http only for localhost); got {base_url}"
|
|
128
|
+
)
|
|
129
|
+
return url
|
|
File without changes
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
from stablevoy.model.fields import Fields
|
|
6
|
+
from stablevoy.model.invoice import Invoice
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass(frozen=True)
|
|
10
|
+
class CreatedInvoice:
|
|
11
|
+
"""The answer to creating an invoice: the invoice, the hosted payment page to send the buyer to, and what was left out."""
|
|
12
|
+
|
|
13
|
+
invoice: Invoice
|
|
14
|
+
checkout_url: str
|
|
15
|
+
unavailable_networks: tuple[str, ...]
|
|
16
|
+
replayed: bool
|
|
17
|
+
|
|
18
|
+
@classmethod
|
|
19
|
+
def from_fields(cls, f: Fields) -> CreatedInvoice:
|
|
20
|
+
return cls(Invoice.from_fields(f), f.string("checkoutUrl"), f.strings("unavailableNetworks"), f.boolean("replayed"))
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
from stablevoy.model.fields import Fields
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass(frozen=True)
|
|
9
|
+
class DepositAddress:
|
|
10
|
+
"""Where the buyer pays on one network: a one-time deposit address, or on Tron the merchant's own wallet."""
|
|
11
|
+
|
|
12
|
+
network: str
|
|
13
|
+
address: str
|
|
14
|
+
payout_address: str
|
|
15
|
+
amount_due_usd_cents: int
|
|
16
|
+
|
|
17
|
+
@classmethod
|
|
18
|
+
def from_fields(cls, f: Fields) -> DepositAddress:
|
|
19
|
+
return cls(f.string("network"), f.string("address"), f.string("payoutAddress"), f.integer("amountDueUsdCents"))
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable
|
|
4
|
+
from datetime import datetime
|
|
5
|
+
from typing import TypeVar
|
|
6
|
+
|
|
7
|
+
from stablevoy.errors.unexpected_response_error import UnexpectedResponseError
|
|
8
|
+
|
|
9
|
+
T = TypeVar("T")
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Fields:
|
|
13
|
+
"""Strict reads from a decoded JSON object. A missing field or one of the wrong type is an error naming it, never a silent default."""
|
|
14
|
+
|
|
15
|
+
def __init__(self, data: dict[str, object], path: str) -> None:
|
|
16
|
+
self._data = data
|
|
17
|
+
self._path = path
|
|
18
|
+
|
|
19
|
+
@classmethod
|
|
20
|
+
def of(cls, value: object, path: str) -> Fields:
|
|
21
|
+
if not isinstance(value, dict):
|
|
22
|
+
raise UnexpectedResponseError(f"{path} is not a JSON object")
|
|
23
|
+
return cls(value, path)
|
|
24
|
+
|
|
25
|
+
def string(self, key: str) -> str:
|
|
26
|
+
value = self._value(key)
|
|
27
|
+
if not isinstance(value, str):
|
|
28
|
+
raise self._wrong(key, "a string")
|
|
29
|
+
return value
|
|
30
|
+
|
|
31
|
+
def nullable_string(self, key: str) -> str | None:
|
|
32
|
+
value = self._value(key)
|
|
33
|
+
if value is not None and not isinstance(value, str):
|
|
34
|
+
raise self._wrong(key, "a string or null")
|
|
35
|
+
return value
|
|
36
|
+
|
|
37
|
+
def integer(self, key: str) -> int:
|
|
38
|
+
value = self._value(key)
|
|
39
|
+
if not isinstance(value, int) or isinstance(value, bool):
|
|
40
|
+
raise self._wrong(key, "an integer")
|
|
41
|
+
return value
|
|
42
|
+
|
|
43
|
+
def nullable_integer(self, key: str) -> int | None:
|
|
44
|
+
value = self._value(key)
|
|
45
|
+
if value is not None and (not isinstance(value, int) or isinstance(value, bool)):
|
|
46
|
+
raise self._wrong(key, "an integer or null")
|
|
47
|
+
return value
|
|
48
|
+
|
|
49
|
+
def boolean(self, key: str) -> bool:
|
|
50
|
+
value = self._value(key)
|
|
51
|
+
if not isinstance(value, bool):
|
|
52
|
+
raise self._wrong(key, "a boolean")
|
|
53
|
+
return value
|
|
54
|
+
|
|
55
|
+
def date(self, key: str) -> datetime:
|
|
56
|
+
return self._parse_date(key, self.string(key))
|
|
57
|
+
|
|
58
|
+
def nullable_date(self, key: str) -> datetime | None:
|
|
59
|
+
value = self.nullable_string(key)
|
|
60
|
+
return None if value is None else self._parse_date(key, value)
|
|
61
|
+
|
|
62
|
+
def strings(self, key: str) -> tuple[str, ...]:
|
|
63
|
+
items = self.values(key)
|
|
64
|
+
if not all(isinstance(item, str) for item in items):
|
|
65
|
+
raise self._wrong(key, "a list of strings")
|
|
66
|
+
return tuple(str(item) for item in items)
|
|
67
|
+
|
|
68
|
+
def values(self, key: str) -> list[object]:
|
|
69
|
+
value = self._value(key)
|
|
70
|
+
if not isinstance(value, list):
|
|
71
|
+
raise self._wrong(key, "a list")
|
|
72
|
+
return value
|
|
73
|
+
|
|
74
|
+
def objects(self, key: str, parse: Callable[[Fields], T]) -> tuple[T, ...]:
|
|
75
|
+
"""Each item of a list of objects, parsed with ``parse``."""
|
|
76
|
+
return tuple(parse(Fields.of(item, f"{self._path}.{key}[{i}]")) for i, item in enumerate(self.values(key)))
|
|
77
|
+
|
|
78
|
+
def child(self, key: str) -> Fields:
|
|
79
|
+
return Fields.of(self._value(key), f"{self._path}.{key}")
|
|
80
|
+
|
|
81
|
+
def raw(self) -> dict[str, object]:
|
|
82
|
+
"""The object as decoded, for data this library does not model."""
|
|
83
|
+
return self._data
|
|
84
|
+
|
|
85
|
+
def _value(self, key: str) -> object:
|
|
86
|
+
if key not in self._data:
|
|
87
|
+
raise UnexpectedResponseError(f"{self._path}.{key} is missing")
|
|
88
|
+
return self._data[key]
|
|
89
|
+
|
|
90
|
+
def _parse_date(self, key: str, value: str) -> datetime:
|
|
91
|
+
try:
|
|
92
|
+
parsed = datetime.fromisoformat(value)
|
|
93
|
+
except ValueError:
|
|
94
|
+
raise self._wrong(key, "an ISO 8601 date") from None
|
|
95
|
+
if parsed.tzinfo is None:
|
|
96
|
+
raise self._wrong(key, "an ISO 8601 date with a time zone")
|
|
97
|
+
return parsed
|
|
98
|
+
|
|
99
|
+
def _wrong(self, key: str, expected: str) -> UnexpectedResponseError:
|
|
100
|
+
return UnexpectedResponseError(f"{self._path}.{key} is not {expected}")
|